Implement VoidBuildSystem v1 (Plans 01-19) with VoidLibrary integration
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
This commit is contained in:
1 parent
3cac890ce9
commit
ab64147f9d
114 files changed
+23777
-1392
No files matched your search
@@ -0,0 +1,33 @@
|
|||||||
|
name: VoidBuildSystem CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-test-gcc16:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Configure (Debug, Ninja, GCC 16 C++26)
|
||||||
|
run: |
|
||||||
|
cmake -S . -B build/ci-gcc -G Ninja \
|
||||||
|
-DCMAKE_BUILD_TYPE=Debug \
|
||||||
|
-DCMAKE_CXX_COMPILER=g++-16 \
|
||||||
|
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON
|
||||||
|
- name: Build
|
||||||
|
run: cmake --build build/ci-gcc --parallel 4
|
||||||
|
- name: Run CTest suites
|
||||||
|
run: ctest --test-dir build/ci-gcc --output-on-failure
|
||||||
|
- name: Check formatting on owned C++ files
|
||||||
|
run: |
|
||||||
|
clang-format --dry-run --Werror \
|
||||||
|
build.cpp build.profiles.cpp build-support/*.hpp build-support/*.cpp \
|
||||||
|
include/Void/Build.hpp include/Void/Build/*/*.hpp \
|
||||||
|
src/*.cpp src/*/*.cpp \
|
||||||
|
recipes/VoidLibrary/*.hpp recipes/VoidLibrary/*.cpp \
|
||||||
|
registry/include/Void/Build/Registry/*.hpp registry/service/*.cpp \
|
||||||
|
benchmarks/*.cpp tests/*.cpp
|
||||||
|
- name: Benchmark smoke run
|
||||||
|
run: build/ci-gcc/bin/vbs_benchmarks 15
|
||||||
+95
-16
@@ -15,34 +15,113 @@ if(NOT VBS_HAS_REFLECTION)
|
|||||||
message(FATAL_ERROR "The GCC host compiler must support -freflection for VoidLibrary.")
|
message(FATAL_ERROR "The GCC host compiler must support -freflection for VoidLibrary.")
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
option(VBS_BUILD_TESTS "Build declaration SDK and bootstrap contract tests" ON)
|
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_SOURCE_DIR "" CACHE PATH "Development-only VoidLibrary source override (bypasses pin)")
|
||||||
set(VBS_VOID_REVISION "9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5")
|
set(VBS_VOID_REVISION "9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5")
|
||||||
include(cmake/VoidDependency.cmake)
|
include(cmake/VoidDependency.cmake)
|
||||||
vbs_add_void_dependency()
|
vbs_add_void_dependency()
|
||||||
|
|
||||||
add_library(vbs_bootstrap_options INTERFACE)
|
add_library(VoidBuild_Options INTERFACE)
|
||||||
target_compile_features(vbs_bootstrap_options INTERFACE cxx_std_26)
|
target_compile_features(VoidBuild_Options INTERFACE cxx_std_26)
|
||||||
target_compile_options(vbs_bootstrap_options INTERFACE -freflection -Wall -Wextra -Wpedantic)
|
target_compile_options(VoidBuild_Options INTERFACE -freflection -Wall -Wextra -Wpedantic)
|
||||||
|
|
||||||
add_library(vbs_sdk STATIC src/build.cpp)
|
add_library(VoidBuild_Sdk STATIC
|
||||||
target_include_directories(vbs_sdk PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
src/Build.cpp
|
||||||
target_link_libraries(vbs_sdk PUBLIC vbs_bootstrap_options)
|
src/Util/Json.cpp)
|
||||||
|
add_library(Void::BuildSdk ALIAS VoidBuild_Sdk)
|
||||||
|
target_include_directories(VoidBuild_Sdk PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||||
|
target_link_libraries(VoidBuild_Sdk PUBLIC VoidBuild_Options PRIVATE Void::Unicode)
|
||||||
|
target_compile_definitions(VoidBuild_Sdk PRIVATE VBS_HAS_VOID_UNICODE=1)
|
||||||
|
|
||||||
configure_file(cmake/bootstrap_config.hpp.in generated/vbs/bootstrap_config.hpp @ONLY)
|
add_library(VoidBuild_Core STATIC
|
||||||
add_executable(vbs src/main.cpp)
|
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)
|
||||||
|
add_library(Void::BuildCore ALIAS VoidBuild_Core)
|
||||||
|
target_include_directories(VoidBuild_Core PUBLIC
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/recipes")
|
||||||
|
target_link_libraries(VoidBuild_Core PUBLIC
|
||||||
|
Void::BuildSdk
|
||||||
|
Void::Configuration
|
||||||
|
Void::Text
|
||||||
|
Void::Unicode
|
||||||
|
Void::Async
|
||||||
|
Void::Algorithms)
|
||||||
|
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
|
||||||
|
registry/service/RegistryService.cpp)
|
||||||
|
add_library(Void::BuildRegistry ALIAS VoidBuild_Registry)
|
||||||
|
target_include_directories(VoidBuild_Registry PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/registry/include")
|
||||||
|
target_link_libraries(VoidBuild_Registry PUBLIC Void::BuildCore)
|
||||||
|
|
||||||
|
configure_file(cmake/BootstrapConfig.hpp.in generated/Void/Build/BootstrapConfig.hpp @ONLY)
|
||||||
|
|
||||||
|
add_executable(vbs src/Main.cpp)
|
||||||
target_include_directories(vbs PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
target_include_directories(vbs PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||||
target_link_libraries(vbs PRIVATE vbs_sdk Void::Configuration)
|
target_link_libraries(vbs PRIVATE Void::BuildCore)
|
||||||
|
|
||||||
add_library(vbs_example_description STATIC build.cpp build.profiles.cpp build-support/defaults.cpp)
|
add_executable(vbs-registry registry/service/Main.cpp)
|
||||||
target_include_directories(vbs_example_description PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
|
target_include_directories(vbs-registry PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||||
target_link_libraries(vbs_example_description PUBLIC vbs_sdk)
|
target_link_libraries(vbs-registry PRIVATE Void::BuildRegistry)
|
||||||
add_executable(vbs_describe src/describe.cpp)
|
|
||||||
|
add_library(VoidBuild_ExampleDescription STATIC
|
||||||
|
build.cpp
|
||||||
|
build.profiles.cpp
|
||||||
|
build-support/Defaults.cpp)
|
||||||
|
target_include_directories(VoidBuild_ExampleDescription PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||||
|
target_link_libraries(VoidBuild_ExampleDescription PUBLIC Void::BuildSdk)
|
||||||
|
|
||||||
|
add_executable(vbs_describe src/Describe.cpp)
|
||||||
target_include_directories(vbs_describe PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
target_include_directories(vbs_describe PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||||
target_link_libraries(vbs_describe PRIVATE vbs_example_description Void::Configuration)
|
target_link_libraries(vbs_describe PRIVATE VoidBuild_ExampleDescription Void::Configuration)
|
||||||
|
|
||||||
set_target_properties(vbs vbs_describe PROPERTIES
|
set_target_properties(vbs vbs-registry vbs_describe PROPERTIES
|
||||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin")
|
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin")
|
||||||
|
|
||||||
|
if(VBS_BUILD_BENCHMARKS)
|
||||||
|
add_executable(vbs_benchmarks benchmarks/EngineBenchmarks.cpp)
|
||||||
|
target_include_directories(vbs_benchmarks PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||||
|
target_link_libraries(vbs_benchmarks PRIVATE Void::BuildCore)
|
||||||
|
set_target_properties(vbs_benchmarks PROPERTIES
|
||||||
|
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin")
|
||||||
|
endif()
|
||||||
|
|
||||||
if(VBS_BUILD_TESTS)
|
if(VBS_BUILD_TESTS)
|
||||||
enable_testing()
|
enable_testing()
|
||||||
include("${VBS_VOID_TESTING_SCRIPT}")
|
include("${VBS_VOID_TESTING_SCRIPT}")
|
||||||
|
|||||||
@@ -1,169 +1,96 @@
|
|||||||
# VoidBuildSystem
|
# VoidBuildSystem
|
||||||
|
|
||||||
A C++ build system for Void projects, using
|
A native C++26 build system and package manager for Void projects, built with
|
||||||
[VoidLibrary](https://git.faumaray.com/Void/VoidLibrary). Build logic lives in
|
[VoidLibrary](https://git.faumaray.com/Void/VoidLibrary). Build descriptions and
|
||||||
ordinary `build.cpp` and reusable `.cpp`/`.hpp` files. Dependency declarations
|
profile definitions live in ordinary `build.cpp`, `build.profiles.cpp`, and
|
||||||
will also support TOML.
|
`build-support/**/*.cpp`/`.hpp` files; declarative package manifests also support
|
||||||
|
`vbs.deps.toml` normalized to the exact same dependency model.
|
||||||
|
|
||||||
**Current milestone: compiling bootstrap and declaration SDK.** The `vbs` CLI
|
**Implemented scope (Plans 01–19):**
|
||||||
implements help/version and useful errors. `vbs_describe` evaluates the compiled
|
- **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.
|
||||||
example and emits a versioned JSON description. Native builds, self-hosting,
|
- **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).
|
||||||
dependency resolution, watchers and profile-aware compilation databases are
|
- **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).
|
||||||
planned; those commands currently fail explicitly.
|
- **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.
|
||||||
|
- **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`.
|
||||||
|
- **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 implementation plans](docs/roadmap/README.md),
|
Start with the [twenty roadmap plans](docs/roadmap/README.md),
|
||||||
[architecture](docs/roadmap/ARCHITECTURE.md) and
|
[architecture](docs/roadmap/ARCHITECTURE.md),
|
||||||
[requirements](docs/roadmap/REQUIREMENTS.md). Each part specifies interfaces,
|
[requirements](docs/roadmap/REQUIREMENTS.md), and
|
||||||
dependencies, ownership, implementation steps, failure behavior and acceptance
|
[verification log](docs/agent-workflow/VERIFICATION.md).
|
||||||
checks. [Verification](docs/agent-workflow/VERIFICATION.md) records observed results.
|
|
||||||
|
|
||||||
## Build the bootstrap
|
## Naming Conventions
|
||||||
|
|
||||||
Requirements: GCC 16+ with C++26 reflection, CMake 4.0+, Git and Ninja. The verified
|
- C++ namespace: `Void::Build`
|
||||||
host environment is GCC 16.2.0, CMake 4.4.4 and Ninja 1.13.2 on Linux. The supplied
|
- Public umbrella header: `<Void/Build.hpp>` ([include/Void/Build.hpp](include/Void/Build.hpp))
|
||||||
`dev cpp-gcc` environment provides these tools:
|
- Internal headers and sources: PascalCase paths under [include/Void/Build/](include/Void/Build/) and [src/](src/)
|
||||||
|
- Types and enum constants: `PascalCase` (`Visibility::Public`, `CompilerFamily::Gcc`, `TargetKind::Executable`, etc.); functions and methods: `snake_case`
|
||||||
|
- CMake targets: `VoidBuild_Sdk` (`Void::BuildSdk`), `VoidBuild_Core` (`Void::BuildCore`), `VoidBuild_Registry` (`Void::BuildRegistry`), `VoidBuild_Options`
|
||||||
|
- CLI & project files: `vbs`, `vbs-registry`, `vbs.deps.toml`, `vbs.lock`, `.vbs/`, `VbsDeps.cmake`
|
||||||
|
|
||||||
|
## Building & Testing
|
||||||
|
|
||||||
|
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`).
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dev cpp-gcc -c cmake -S . -B build/bootstrap -G Ninja \
|
dev cpp-gcc -c cmake -S . -B build/dev -G Ninja \
|
||||||
-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
|
-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
|
||||||
dev cpp-gcc -c cmake --build build/bootstrap --parallel 2
|
dev cpp-gcc -c cmake --build build/dev --parallel 4
|
||||||
dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure
|
dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure
|
||||||
|
dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15
|
||||||
build/bootstrap/bin/vbs --help
|
|
||||||
build/bootstrap/bin/vbs --version
|
|
||||||
build/bootstrap/bin/vbs_describe --profile debug --compiler gcc
|
|
||||||
build/bootstrap/bin/vbs_describe --profile release --compiler clang
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Without this local `dev` wrapper, run the same CMake/CTest commands in an
|
CMake fetches VoidLibrary at pinned commit `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`.
|
||||||
equivalent toolchain environment. The host bootstrap requires GCC; the descriptor's
|
For development against a local checkout without mutating the pin:
|
||||||
`--compiler clang` selects runtime declaration facts and does not invoke Clang.
|
|
||||||
|
|
||||||
CMake fetches VoidLibrary at the exact commit
|
|
||||||
`9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`. It builds the Configuration and Testing
|
|
||||||
module closure statically, with VoidLibrary's own tests and benchmarks disabled.
|
|
||||||
To use a development checkout explicitly:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dev cpp-gcc -c cmake -S . -B build/bootstrap-local -G Ninja \
|
dev cpp-gcc -c cmake -S . -B build/dev-local -G Ninja \
|
||||||
-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
|
-DCMAKE_BUILD_TYPE=Debug -DVBS_VOID_SOURCE_DIR=../VoidLibrary
|
||||||
-DVBS_VOID_SOURCE_DIR=../VoidLibrary
|
|
||||||
dev cpp-gcc -c cmake --build build/bootstrap-local --parallel 2
|
|
||||||
dev cpp-gcc -c ctest --test-dir build/bootstrap-local --output-on-failure
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The override bypasses the pin and prints a diagnostic. Its source checkout is not
|
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.
|
||||||
modified. `-DVBS_BUILD_TESTS=OFF` omits the bootstrap tests and Testing module.
|
|
||||||
Build products and generated test registrations stay in the chosen build directory.
|
|
||||||
The `compile_commands.json` produced here belongs to the CMake bootstrap; VBS's
|
|
||||||
automatic per-profile export and selection are separate planned features.
|
|
||||||
|
|
||||||
## Ordinary C++ declarations
|
## CLI Reference
|
||||||
|
|
||||||
The [root example](build.cpp) and its [helper](build-support/defaults.cpp) compile
|
- `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]`
|
||||||
as part of the bootstrap. This smaller example uses the implemented SDK:
|
- `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 ...`
|
||||||
|
- `vbs watch [--project DIR] [--build-dir DIR] [--profile NAME] [--target NAME]...`
|
||||||
|
- `vbs deps resolve|update [--project DIR] [--build-dir DIR] [--profile NAME] [--offline]`
|
||||||
|
- `vbs install --prefix DIR [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang] [--package-name NAME] [--package-version VER] [--component NAME] [--no-cmake-export] [--no-native-export]`
|
||||||
|
- `vbs uninstall --prefix DIR`
|
||||||
|
- `vbs pack [--project DIR] [--output FILE]`
|
||||||
|
- `vbs publish --registry URL --name PKG --version X.Y.Z [--project DIR] [--description TEXT] [--token-env VAR] [--private]`
|
||||||
|
- `vbs bridge --request FILE --output FILE` (backend for [cmake/bridge/VbsDeps.cmake](cmake/bridge/VbsDeps.cmake))
|
||||||
|
- `vbs gc [--build-dir DIR] [--max-bytes N]`
|
||||||
|
- `vbs gen-tests --input FILE --output-dir DIR`
|
||||||
|
- `vbs-registry --data-dir DIR --web-root DIR [--bind ADDR] [--port PORT] ...`
|
||||||
|
|
||||||
|
## Ordinary C++ & TOML Declarations
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
#include <vbs/build.hpp>
|
#include <Void/Build.hpp>
|
||||||
|
|
||||||
|
void build(Void::Build::Project &project) {
|
||||||
|
project.dependencies_file("vbs.deps.toml");
|
||||||
|
|
||||||
void build(vbs::Project& project) {
|
|
||||||
auto core = project.static_library("core");
|
auto core = project.static_library("core");
|
||||||
core.sources(project.glob("src/core/*.cpp"))
|
core.cxx_standard(Void::Build::CxxStandard::Cxx26)
|
||||||
.include_directory("include", vbs::Visibility::public_);
|
.sources(project.glob("src/core/*.cpp"))
|
||||||
|
.include_directory("include", Void::Build::Visibility::Public);
|
||||||
|
|
||||||
auto app = project.executable("app");
|
auto app = project.executable("app");
|
||||||
app.sources({"src/main.cpp"}).link(core);
|
app.sources({"src/main.cpp"}).link(core);
|
||||||
|
|
||||||
if (project.context().compiler == vbs::CompilerFamily::clang) {
|
if (project.context().compiler == Void::Build::CompilerFamily::Clang) {
|
||||||
app.compile_option("-Wextra-semi");
|
app.compile_option("-Wextra-semi");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
These calls record data. They do not enumerate files, resolve dependencies or run
|
See the [SDK reference](docs/SDK.md), [public header](include/Void/Build.hpp), and
|
||||||
a compiler. See the [SDK contract](docs/SDK.md) and [public header](include/vbs/build.hpp).
|
[VoidLibrary upstream requests](docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md).
|
||||||
`build.profiles.cpp` supplies ordinary C++ profile definitions; the current example
|
|
||||||
uses debug/release defaults. The same host-compiled descriptor is evaluated with
|
|
||||||
each requested target context, so host preprocessor macros are not target selectors.
|
|
||||||
|
|
||||||
The root description currently models `vbs_sdk`, `vbs` and their dependency links.
|
|
||||||
It is not yet a complete self-build: generated bootstrap headers, test registration
|
|
||||||
and native VoidLibrary construction belong to the
|
|
||||||
[self-hosting milestone](docs/roadmap/18-self-host-voidlibrary.md).
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
The current SDK can record an exact Git source, CMake options and imported targets:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
auto library = project.dependency("VoidLibrary");
|
|
||||||
library.git("https://git.faumaray.com/Void/VoidLibrary.git",
|
|
||||||
vbs::Commit{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"})
|
|
||||||
.cmake({{"VOID_ENABLED_MODULES", "Configuration"},
|
|
||||||
{"VOID_ENABLE_TESTING", false},
|
|
||||||
{"BUILD_SHARED_LIBS", false}});
|
|
||||||
app.link(library.target("Void::Configuration"));
|
|
||||||
```
|
|
||||||
|
|
||||||
It also records `project.dependency("fmt").package("fmt", "^11.0")`.
|
|
||||||
Resolution, fetching and foreign builds are future operations; declaring a dependency
|
|
||||||
does not perform them.
|
|
||||||
|
|
||||||
**Planned TOML form**, normalized to the same dependency model:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies.VoidLibrary]
|
|
||||||
git = "https://git.faumaray.com/Void/VoidLibrary.git"
|
|
||||||
rev = "9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"
|
|
||||||
builder = "cmake"
|
|
||||||
|
|
||||||
[dependencies.VoidLibrary.options]
|
|
||||||
VOID_ENABLED_MODULES = "Configuration"
|
|
||||||
VOID_ENABLE_TESTING = false
|
|
||||||
BUILD_SHARED_LIBS = false
|
|
||||||
|
|
||||||
[dependencies.fmt]
|
|
||||||
package = "fmt"
|
|
||||||
version = "^11.0"
|
|
||||||
```
|
|
||||||
|
|
||||||
The proposed `project.dependencies("vbs.deps.toml")` loader will permit custom
|
|
||||||
filenames. It is not in the bootstrap SDK. Conflicting C++/TOML declarations will
|
|
||||||
fail with origin diagnostics. A context-aware `vbs.lock` will hold exact resolutions;
|
|
||||||
existing incompatible declarations will require explicit resolve/update. See the
|
|
||||||
[dependency plan](docs/roadmap/11-dependencies-solver-lock.md).
|
|
||||||
|
|
||||||
## Planned build and editor workflow
|
|
||||||
|
|
||||||
The native engine will build selected target/profile combinations, with several
|
|
||||||
profiles sharing one build root and separate mutable outputs. Per-profile
|
|
||||||
`compile_commands.json` files will cover all configured targets, even when the build
|
|
||||||
selects only a subset.
|
|
||||||
|
|
||||||
Editor selection will follow the latest single-profile build or an explicit manual
|
|
||||||
switch. Multi-profile builds will require `--editor-profile`. Configuration and source
|
|
||||||
membership changes will refresh metadata automatically; an independent metadata
|
|
||||||
watcher will update it without scheduling target/package builds or foreign configure
|
|
||||||
operations. Invalid configuration retains a clearly stale last valid database.
|
|
||||||
|
|
||||||
Content verification and immutable snapshots will cover additions, deletions, renames,
|
|
||||||
headers, generated inputs and changed build logic. File events are hints; periodic
|
|
||||||
reconciliation recovers missed changes. See the [profile](docs/roadmap/04-profiles-toolchains.md),
|
|
||||||
[snapshot](docs/roadmap/05-snapshots-invalidation.md),
|
|
||||||
[compilation database](docs/roadmap/09-compilation-database.md) and
|
|
||||||
[watcher](docs/roadmap/10-watchers-cli.md) plans.
|
|
||||||
|
|
||||||
Full v1 also includes modern C++ modules/header units/PCH/unity/LTO/sanitizers,
|
|
||||||
CMake/Meson/Conan consumption, native source/binary package management, a CMake-facing
|
|
||||||
dependency bridge, installation/exports, a C++ registry service and web administration.
|
|
||||||
Native self-hosting progresses from the CMake seed through clean native stages.
|
|
||||||
Later work covers native translation of foreign graphs and additional operating systems.
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
Use [STATE](docs/agent-workflow/STATE.md), [TASKS](docs/agent-workflow/TASKS.md) and
|
|
||||||
[decisions](docs/agent-workflow/DECISIONS.md) to continue work. The initial test suite
|
|
||||||
has four CTest checks covering SDK behavior and registration, CLI contracts and
|
|
||||||
the four debug/release × GCC/Clang declaration contexts. Tests use Void::Testing.
|
|
||||||
|
|
||||||
Licensed under [MIT](LICENSE).
|
Licensed under [MIT](LICENSE).
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
#include <Void/Build/Execution/Scheduler.hpp>
|
||||||
|
#include <Void/Build/Graph/Graph.hpp>
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||||
|
#include <Void/Build/State/StateStore.hpp>
|
||||||
|
#include <Void/Build/Toolchain/Driver.hpp>
|
||||||
|
#include <Void/Configuration/Argparse.hpp>
|
||||||
|
#include <Void/System/TempDir.hpp>
|
||||||
|
#include <Void/Text/Str.hpp>
|
||||||
|
#include <Void/Time/Stopwatch.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <iostream>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
using namespace Void::Build;
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
std::string files_opt;
|
||||||
|
std::string jobs_opt;
|
||||||
|
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");
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto file_count = static_cast<std::size_t>(parsed_files);
|
||||||
|
const auto jobs = static_cast<std::size_t>(parsed_jobs);
|
||||||
|
|
||||||
|
Void::FileSystem::TempDir tmp{"vbs_bench_"};
|
||||||
|
const auto proj = tmp / "proj";
|
||||||
|
const auto build_dir = tmp / "build";
|
||||||
|
|
||||||
|
std::string main_cpp = "int main() {\n int sum = 0;\n";
|
||||||
|
for (std::size_t i = 0; i < file_count; ++i) {
|
||||||
|
const std::string fn = "f_" + std::to_string(i);
|
||||||
|
(void)Platform::atomic_write_file(proj / "include" / (fn + ".hpp"),
|
||||||
|
"#pragma once\nint " + fn + "();\n", false);
|
||||||
|
(void)Platform::atomic_write_file(proj / "src" / (fn + ".cpp"),
|
||||||
|
"#include \"" + fn + ".hpp\"\nint " + fn +
|
||||||
|
"() { return " + std::to_string(i) + "; }\n",
|
||||||
|
false);
|
||||||
|
main_cpp = "#include \"" + fn + ".hpp\"\n" + main_cpp;
|
||||||
|
main_cpp += " sum += " + fn + "();\n";
|
||||||
|
}
|
||||||
|
main_cpp += " return sum == 0 ? 0 : 0;\n}\n";
|
||||||
|
(void)Platform::atomic_write_file(proj / "src" / "main.cpp", main_cpp, false);
|
||||||
|
|
||||||
|
auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(),
|
||||||
|
Toolchain::host_architecture_name());
|
||||||
|
auto tc = Toolchain::discover_and_probe(ctx, build_dir / ".vbs" / "probes");
|
||||||
|
if (!tc) {
|
||||||
|
std::cerr << "bench toolchain error: " << tc.error().message() << '\n';
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Graph::ProjectDescription desc;
|
||||||
|
desc.profile = ctx;
|
||||||
|
TargetRecord app;
|
||||||
|
app.name = "bench_app";
|
||||||
|
app.kind = TargetKind::Executable;
|
||||||
|
app.sources.push_back({SourceKind::Glob, "src/*.cpp"});
|
||||||
|
app.include_directories.push_back({"include", Visibility::Private, false});
|
||||||
|
desc.targets.push_back(std::move(app));
|
||||||
|
|
||||||
|
auto snap_sw = Void::Time::Stopwatch::started();
|
||||||
|
Snapshot::SnapshotOptions sopts{
|
||||||
|
proj, build_dir / ".vbs" / "snapshots", {}, {".git", "build"}, 0, 5, true};
|
||||||
|
auto snap = Snapshot::capture_snapshot(sopts, {}, {proj / "src", proj / "include"});
|
||||||
|
const auto snap_ms = snap_sw.elapsed_as<std::chrono::milliseconds>().count();
|
||||||
|
if (!snap) {
|
||||||
|
std::cerr << "bench snapshot error: " << snap.error().message() << '\n';
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto graph = Graph::lower_project_graph(desc, *tc, {proj, build_dir, &(*snap), {}, 32768});
|
||||||
|
auto state = State::StateStore::open(build_dir / ".vbs");
|
||||||
|
if (!graph || !state) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto cold_sw = Void::Time::Stopwatch::started();
|
||||||
|
auto cold = Execution::execute_graph(*graph, *state, {jobs, true, true, {}, {}, {}});
|
||||||
|
const auto cold_ms = cold_sw.elapsed_as<std::chrono::milliseconds>().count();
|
||||||
|
|
||||||
|
auto warm_sw = Void::Time::Stopwatch::started();
|
||||||
|
auto warm = Execution::execute_graph(*graph, *state, {jobs, true, true, {}, {}, {}});
|
||||||
|
const auto warm_ms = warm_sw.elapsed_as<std::chrono::milliseconds>().count();
|
||||||
|
|
||||||
|
std::cout << "{\"fixture_files\":" << (file_count + 1) << ",\"compiler\":\""
|
||||||
|
<< tc->version_banner << "\""
|
||||||
|
<< ",\"snapshot_ms\":" << snap_ms << ",\"cold_build_ms\":" << cold_ms
|
||||||
|
<< ",\"cold_executed\":" << (cold ? cold->executed_count : 0)
|
||||||
|
<< ",\"warm_noop_ms\":" << warm_ms
|
||||||
|
<< ",\"warm_executed\":" << (warm ? warm->executed_count : 0)
|
||||||
|
<< ",\"warm_cached\":" << (warm ? warm->cached_count : 0) << "}\n";
|
||||||
|
return (cold && cold->succeeded && warm && warm->succeeded) ? 0 : 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#include "Defaults.hpp"
|
||||||
|
|
||||||
|
namespace BuildSupport {
|
||||||
|
void compiler_warnings(Void::Build::Target target, const Void::Build::ProfileContext &context) {
|
||||||
|
target.compile_option("-Wall").compile_option("-Wextra");
|
||||||
|
if (context.compiler == Void::Build::CompilerFamily::Gcc) {
|
||||||
|
target.compile_option("-Wduplicated-cond");
|
||||||
|
} else {
|
||||||
|
target.compile_option("-Wextra-semi");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} // namespace BuildSupport
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
|
||||||
|
namespace BuildSupport {
|
||||||
|
void compiler_warnings(Void::Build::Target target, const Void::Build::ProfileContext &context);
|
||||||
|
} // namespace BuildSupport
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#include "defaults.hpp"
|
|
||||||
|
|
||||||
namespace build_support {
|
|
||||||
void compiler_warnings(vbs::Target target, const vbs::ProfileContext &context) {
|
|
||||||
target.compile_option("-Wall").compile_option("-Wextra");
|
|
||||||
if (context.compiler == vbs::CompilerFamily::gcc) {
|
|
||||||
target.compile_option("-Wduplicated-cond");
|
|
||||||
} else {
|
|
||||||
target.compile_option("-Wextra-semi");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} // namespace build_support
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <vbs/build.hpp>
|
|
||||||
|
|
||||||
namespace build_support {
|
|
||||||
void compiler_warnings(vbs::Target target, const vbs::ProfileContext &context);
|
|
||||||
} // namespace build_support
|
|
||||||
@@ -1,20 +1,20 @@
|
|||||||
#include "build-support/defaults.hpp"
|
#include "build-support/Defaults.hpp"
|
||||||
|
|
||||||
void build(vbs::Project &project) {
|
void build(Void::Build::Project &project) {
|
||||||
auto library = project.dependency("VoidLibrary");
|
auto library = project.dependency("VoidLibrary");
|
||||||
library
|
library
|
||||||
.git("https://git.faumaray.com/Void/VoidLibrary.git",
|
.git("https://git.faumaray.com/Void/VoidLibrary.git",
|
||||||
vbs::Commit{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"})
|
Void::Build::Commit{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"})
|
||||||
.cmake({{"VOID_ENABLED_MODULES", "Configuration;Testing"},
|
.cmake({{"VOID_ENABLED_MODULES", "Configuration;Testing"},
|
||||||
{"VOID_ENABLE_TESTING", false},
|
{"VOID_ENABLE_TESTING", false},
|
||||||
{"VOID_ENABLE_BENCHMARKS", false},
|
{"VOID_ENABLE_BENCHMARKS", false},
|
||||||
{"BUILD_SHARED_LIBS", false}});
|
{"BUILD_SHARED_LIBS", false}});
|
||||||
|
|
||||||
auto sdk = project.static_library("vbs_sdk");
|
auto sdk = project.static_library("VoidBuildSdk");
|
||||||
sdk.sources({"src/build.cpp"}).include_directory("include", vbs::Visibility::public_);
|
sdk.sources({"src/Build.cpp"}).include_directory("include", Void::Build::Visibility::Public);
|
||||||
build_support::compiler_warnings(sdk, project.context());
|
BuildSupport::compiler_warnings(sdk, project.context());
|
||||||
|
|
||||||
auto cli = project.executable("vbs");
|
auto cli = project.executable("vbs");
|
||||||
cli.sources({"src/main.cpp"}).link(sdk).link(library.target("Void::Configuration"));
|
cli.sources({"src/Main.cpp"}).link(sdk).link(library.target("Void::Configuration"));
|
||||||
build_support::compiler_warnings(cli, project.context());
|
BuildSupport::compiler_warnings(cli, project.context());
|
||||||
}
|
}
|
||||||
+4
-2
@@ -1,3 +1,5 @@
|
|||||||
#include <vbs/build.hpp>
|
#include <Void/Build.hpp>
|
||||||
|
|
||||||
void profiles(vbs::Profiles &descriptions) { descriptions = vbs::default_profiles(); }
|
void profiles(Void::Build::Profiles &descriptions) {
|
||||||
|
descriptions = Void::Build::default_profiles();
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
namespace Void::Build::Bootstrap {
|
||||||
|
inline constexpr std::string_view version = "@PROJECT_VERSION@";
|
||||||
|
inline constexpr std::string_view os = "@CMAKE_SYSTEM_NAME@";
|
||||||
|
inline constexpr std::string_view architecture = "@CMAKE_SYSTEM_PROCESSOR@";
|
||||||
|
inline constexpr std::string_view source_dir = "@CMAKE_CURRENT_SOURCE_DIR@";
|
||||||
|
inline constexpr std::string_view binary_dir = "@CMAKE_CURRENT_BINARY_DIR@";
|
||||||
|
inline constexpr std::string_view sdk_include_dir = "@CMAKE_CURRENT_SOURCE_DIR@/include";
|
||||||
|
inline constexpr std::string_view sdk_source_dir = "@CMAKE_CURRENT_SOURCE_DIR@/src";
|
||||||
|
} // namespace Void::Build::Bootstrap
|
||||||
@@ -5,10 +5,37 @@ function(vbs_add_void_dependency)
|
|||||||
set(VOID_ENABLE_TESTING OFF)
|
set(VOID_ENABLE_TESTING OFF)
|
||||||
set(VOID_ENABLE_BENCHMARKS OFF)
|
set(VOID_ENABLE_BENCHMARKS OFF)
|
||||||
set(BUILD_SHARED_LIBS OFF)
|
set(BUILD_SHARED_LIBS OFF)
|
||||||
set(VOID_ENABLED_MODULES Configuration)
|
set(VOID_ENABLED_MODULES Configuration Text Unicode Async Algorithms)
|
||||||
if(VBS_BUILD_TESTS)
|
if(VBS_BUILD_TESTS)
|
||||||
list(APPEND VOID_ENABLED_MODULES Testing)
|
list(APPEND VOID_ENABLED_MODULES Testing)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
# Opportunistically enable VoidLibrary modules backed by optional system packages
|
||||||
|
# when those packages are present in the active toolchain environment.
|
||||||
|
find_package(SQLite3 QUIET)
|
||||||
|
if(SQLite3_FOUND)
|
||||||
|
list(APPEND VOID_ENABLED_MODULES Sqlite)
|
||||||
|
set(VBS_HAS_VOID_SQLITE ON PARENT_SCOPE)
|
||||||
|
else()
|
||||||
|
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)
|
if(VBS_VOID_SOURCE_DIR)
|
||||||
get_filename_component(_vbs_void_source "${VBS_VOID_SOURCE_DIR}" ABSOLUTE
|
get_filename_component(_vbs_void_source "${VBS_VOID_SOURCE_DIR}" ABSOLUTE
|
||||||
BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
|
BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||||
@@ -27,4 +54,5 @@ function(vbs_add_void_dependency)
|
|||||||
endif()
|
endif()
|
||||||
FetchContent_MakeAvailable(voidlibrary)
|
FetchContent_MakeAvailable(voidlibrary)
|
||||||
set(VBS_VOID_TESTING_SCRIPT "${voidlibrary_SOURCE_DIR}/cmake/VoidTesting.cmake" PARENT_SCOPE)
|
set(VBS_VOID_TESTING_SCRIPT "${voidlibrary_SOURCE_DIR}/cmake/VoidTesting.cmake" PARENT_SCOPE)
|
||||||
|
set(VBS_VOID_RESOLVED_SOURCE_DIR "${voidlibrary_SOURCE_DIR}" PARENT_SCOPE)
|
||||||
endfunction()
|
endfunction()
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <string_view>
|
|
||||||
|
|
||||||
namespace vbs::bootstrap {
|
|
||||||
inline constexpr std::string_view version = "@PROJECT_VERSION@";
|
|
||||||
inline constexpr std::string_view os = "@CMAKE_SYSTEM_NAME@";
|
|
||||||
inline constexpr std::string_view architecture = "@CMAKE_SYSTEM_PROCESSOR@";
|
|
||||||
} // namespace vbs::bootstrap
|
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
# VbsDeps.cmake — CMake-facing FetchContent/CPM-style dependency bridge for VoidBuildSystem (Plan 14)
|
||||||
|
#
|
||||||
|
# Provides:
|
||||||
|
# vbs_declare_dependency(<alias>
|
||||||
|
# [PACKAGE <id> VERSION <range> [REGISTRY <url>]]
|
||||||
|
# [GIT <url> REV <40-hex-sha>]
|
||||||
|
# [PATH <local-dir>]
|
||||||
|
# [ARCHIVE <url> SHA256 <64-hex>]
|
||||||
|
# [BUILDER <cmake|meson|native|conan>]
|
||||||
|
# [OPTIONS KEY=VAL ...]
|
||||||
|
# [LOCKED] [OFFLINE])
|
||||||
|
# vbs_make_available(<alias> [<alias2> ...])
|
||||||
|
|
||||||
|
cmake_minimum_required(VERSION 4.0)
|
||||||
|
|
||||||
|
set_property(GLOBAL PROPERTY _VBS_BRIDGE_DECLARED_ALIASES "")
|
||||||
|
|
||||||
|
function(_vbs_json_escape out_var raw_val)
|
||||||
|
string(REPLACE "\\" "\\\\" _esc "${raw_val}")
|
||||||
|
string(REPLACE "\"" "\\\"" _esc "${_esc}")
|
||||||
|
string(REPLACE "\n" "\\n" _esc "${_esc}")
|
||||||
|
string(REPLACE "\r" "\\r" _esc "${_esc}")
|
||||||
|
string(REPLACE "\t" "\\t" _esc "${_esc}")
|
||||||
|
set(${out_var} "${_esc}" PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function(vbs_declare_dependency ALIAS)
|
||||||
|
if("${ALIAS}" STREQUAL "")
|
||||||
|
message(FATAL_ERROR "[VbsDeps] Dependency alias must not be empty")
|
||||||
|
endif()
|
||||||
|
set(options LOCKED OFFLINE)
|
||||||
|
set(oneValueArgs PACKAGE VERSION REGISTRY GIT REV PATH ARCHIVE SHA256 BUILDER)
|
||||||
|
set(multiValueArgs OPTIONS FEATURES)
|
||||||
|
cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
|
||||||
|
|
||||||
|
set(_origin "${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE}")
|
||||||
|
set(_fingerprint "${ARG_PACKAGE}|${ARG_VERSION}|${ARG_REGISTRY}|${ARG_GIT}|${ARG_REV}|${ARG_PATH}|${ARG_ARCHIVE}|${ARG_SHA256}|${ARG_BUILDER}|${ARG_OPTIONS}|${ARG_FEATURES}")
|
||||||
|
|
||||||
|
get_property(_existing_fp GLOBAL PROPERTY "_VBS_BRIDGE_FP_${ALIAS}")
|
||||||
|
get_property(_existing_origin GLOBAL PROPERTY "_VBS_BRIDGE_ORIGIN_${ALIAS}")
|
||||||
|
if(DEFINED _existing_fp AND NOT "${_existing_fp}" STREQUAL "")
|
||||||
|
if(NOT "${_existing_fp}" STREQUAL "${_fingerprint}")
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[VbsDeps] Conflicting declaration for dependency '${ALIAS}':\n"
|
||||||
|
" first declared at: ${_existing_origin}\n"
|
||||||
|
" conflicting at: ${_origin}")
|
||||||
|
endif()
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set_property(GLOBAL APPEND PROPERTY _VBS_BRIDGE_DECLARED_ALIASES "${ALIAS}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_FP_${ALIAS}" "${_fingerprint}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_ORIGIN_${ALIAS}" "${_origin}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_PACKAGE_${ALIAS}" "${ARG_PACKAGE}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_VERSION_${ALIAS}" "${ARG_VERSION}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_REGISTRY_${ALIAS}" "${ARG_REGISTRY}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_GIT_${ALIAS}" "${ARG_GIT}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_REV_${ALIAS}" "${ARG_REV}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_PATH_${ALIAS}" "${ARG_PATH}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_ARCHIVE_${ALIAS}" "${ARG_ARCHIVE}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_SHA256_${ALIAS}" "${ARG_SHA256}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_BUILDER_${ALIAS}" "${ARG_BUILDER}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_OPTIONS_${ALIAS}" "${ARG_OPTIONS}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_FEATURES_${ALIAS}" "${ARG_FEATURES}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_LOCKED_${ALIAS}" "${ARG_LOCKED}")
|
||||||
|
set_property(GLOBAL PROPERTY "_VBS_BRIDGE_OFFLINE_${ALIAS}" "${ARG_OFFLINE}")
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
function(vbs_make_available)
|
||||||
|
if(NOT VBS_EXECUTABLE)
|
||||||
|
find_program(VBS_EXECUTABLE NAMES vbs)
|
||||||
|
endif()
|
||||||
|
if(NOT VBS_EXECUTABLE OR NOT EXISTS "${VBS_EXECUTABLE}")
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"[VbsDeps] Required 'vbs' executable was not found. "
|
||||||
|
"Set -DVBS_EXECUTABLE=/path/to/vbs or add vbs to PATH (no unpinned auto-download).")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(_bridge_dir "${CMAKE_BINARY_DIR}/.vbs-bridge")
|
||||||
|
file(MAKE_DIRECTORY "${_bridge_dir}")
|
||||||
|
|
||||||
|
set(_compiler "gcc")
|
||||||
|
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||||
|
set(_compiler "clang")
|
||||||
|
endif()
|
||||||
|
set(_profile "debug")
|
||||||
|
if(CMAKE_BUILD_TYPE STREQUAL "Release" OR CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo")
|
||||||
|
set(_profile "release")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
_vbs_json_escape(_esc_src "${CMAKE_SOURCE_DIR}")
|
||||||
|
_vbs_json_escape(_esc_bin "${_bridge_dir}")
|
||||||
|
_vbs_json_escape(_esc_cxx "${CMAKE_CXX_COMPILER}")
|
||||||
|
_vbs_json_escape(_esc_os "${CMAKE_SYSTEM_NAME}")
|
||||||
|
_vbs_json_escape(_esc_arch "${CMAKE_SYSTEM_PROCESSOR}")
|
||||||
|
|
||||||
|
set(_deps_json "")
|
||||||
|
set(_first TRUE)
|
||||||
|
set(_any_locked FALSE)
|
||||||
|
set(_any_offline FALSE)
|
||||||
|
foreach(_alias IN LISTS ARGN)
|
||||||
|
get_property(_fp GLOBAL PROPERTY "_VBS_BRIDGE_FP_${_alias}")
|
||||||
|
if("${_fp}" STREQUAL "")
|
||||||
|
message(FATAL_ERROR "[VbsDeps] Dependency '${_alias}' was not declared with vbs_declare_dependency()")
|
||||||
|
endif()
|
||||||
|
get_property(_pkg GLOBAL PROPERTY "_VBS_BRIDGE_PACKAGE_${_alias}")
|
||||||
|
get_property(_ver GLOBAL PROPERTY "_VBS_BRIDGE_VERSION_${_alias}")
|
||||||
|
get_property(_reg GLOBAL PROPERTY "_VBS_BRIDGE_REGISTRY_${_alias}")
|
||||||
|
get_property(_git GLOBAL PROPERTY "_VBS_BRIDGE_GIT_${_alias}")
|
||||||
|
get_property(_rev GLOBAL PROPERTY "_VBS_BRIDGE_REV_${_alias}")
|
||||||
|
get_property(_pth GLOBAL PROPERTY "_VBS_BRIDGE_PATH_${_alias}")
|
||||||
|
get_property(_arc GLOBAL PROPERTY "_VBS_BRIDGE_ARCHIVE_${_alias}")
|
||||||
|
get_property(_sha GLOBAL PROPERTY "_VBS_BRIDGE_SHA256_${_alias}")
|
||||||
|
get_property(_bld GLOBAL PROPERTY "_VBS_BRIDGE_BUILDER_${_alias}")
|
||||||
|
get_property(_opts GLOBAL PROPERTY "_VBS_BRIDGE_OPTIONS_${_alias}")
|
||||||
|
get_property(_lck GLOBAL PROPERTY "_VBS_BRIDGE_LOCKED_${_alias}")
|
||||||
|
get_property(_off GLOBAL PROPERTY "_VBS_BRIDGE_OFFLINE_${_alias}")
|
||||||
|
if(_lck)
|
||||||
|
set(_any_locked TRUE)
|
||||||
|
endif()
|
||||||
|
if(_off)
|
||||||
|
set(_any_offline TRUE)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
_vbs_json_escape(_e_alias "${_alias}")
|
||||||
|
_vbs_json_escape(_e_pkg "${_pkg}")
|
||||||
|
_vbs_json_escape(_e_ver "${_ver}")
|
||||||
|
_vbs_json_escape(_e_reg "${_reg}")
|
||||||
|
_vbs_json_escape(_e_git "${_git}")
|
||||||
|
_vbs_json_escape(_e_rev "${_rev}")
|
||||||
|
_vbs_json_escape(_e_pth "${_pth}")
|
||||||
|
_vbs_json_escape(_e_arc "${_arc}")
|
||||||
|
_vbs_json_escape(_e_sha "${_sha}")
|
||||||
|
_vbs_json_escape(_e_bld "${_bld}")
|
||||||
|
|
||||||
|
set(_opts_json "{")
|
||||||
|
set(_ofirst TRUE)
|
||||||
|
foreach(_kv IN LISTS _opts)
|
||||||
|
string(FIND "${_kv}" "=" _eq)
|
||||||
|
if(_eq GREATER 0)
|
||||||
|
string(SUBSTRING "${_kv}" 0 ${_eq} _k)
|
||||||
|
math(EXPR _vstart "${_eq} + 1")
|
||||||
|
string(SUBSTRING "${_kv}" ${_vstart} -1 _v)
|
||||||
|
_vbs_json_escape(_ek "${_k}")
|
||||||
|
_vbs_json_escape(_ev "${_v}")
|
||||||
|
if(NOT _ofirst)
|
||||||
|
string(APPEND _opts_json ",")
|
||||||
|
endif()
|
||||||
|
set(_ofirst FALSE)
|
||||||
|
string(APPEND _opts_json "\"${_ek}\":\"${_ev}\"")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
string(APPEND _opts_json "}")
|
||||||
|
|
||||||
|
if(NOT _first)
|
||||||
|
string(APPEND _deps_json ",")
|
||||||
|
endif()
|
||||||
|
set(_first FALSE)
|
||||||
|
string(APPEND _deps_json
|
||||||
|
"{\"alias\":\"${_e_alias}\",\"package\":\"${_e_pkg}\",\"version\":\"${_e_ver}\","
|
||||||
|
"\"registry\":\"${_e_reg}\",\"git\":\"${_e_git}\",\"rev\":\"${_e_rev}\","
|
||||||
|
"\"path\":\"${_e_pth}\",\"archive\":\"${_e_arc}\",\"sha256\":\"${_e_sha}\","
|
||||||
|
"\"builder\":\"${_e_bld}\",\"options\":${_opts_json}}")
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
string(JOIN "_" _req_tag ${ARGN})
|
||||||
|
string(SHA256 _req_hash "${_req_tag}|${_deps_json}")
|
||||||
|
string(SUBSTRING "${_req_hash}" 0 12 _short_hash)
|
||||||
|
set(_req_file "${_bridge_dir}/request_${_short_hash}.json")
|
||||||
|
set(_out_cmake "${_bridge_dir}/targets_${_short_hash}.cmake")
|
||||||
|
|
||||||
|
set(_locked_str "false")
|
||||||
|
if(_any_locked)
|
||||||
|
set(_locked_str "true")
|
||||||
|
endif()
|
||||||
|
set(_offline_str "false")
|
||||||
|
if(_any_offline)
|
||||||
|
set(_offline_str "true")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
file(WRITE "${_req_file}"
|
||||||
|
"{\"schema_version\":1,\"project_root\":\"${_esc_src}\",\"build_root\":\"${_esc_bin}\","
|
||||||
|
"\"profile\":\"${_profile}\",\"compiler\":\"${_compiler}\",\"compiler_path\":\"${_esc_cxx}\","
|
||||||
|
"\"os\":\"${_esc_os}\",\"architecture\":\"${_esc_arch}\","
|
||||||
|
"\"locked\":${_locked_str},\"offline\":${_offline_str},\"dependencies\":[${_deps_json}]}\n")
|
||||||
|
|
||||||
|
execute_process(
|
||||||
|
COMMAND "${VBS_EXECUTABLE}" bridge --request "${_req_file}" --output "${_out_cmake}"
|
||||||
|
RESULT_VARIABLE _rc
|
||||||
|
OUTPUT_VARIABLE _out
|
||||||
|
ERROR_VARIABLE _err)
|
||||||
|
if(NOT _rc EQUAL 0)
|
||||||
|
message(FATAL_ERROR "[VbsDeps] vbs bridge failed (exit ${_rc}):\n${_err}\n${_out}")
|
||||||
|
endif()
|
||||||
|
if(NOT EXISTS "${_out_cmake}")
|
||||||
|
message(FATAL_ERROR "[VbsDeps] vbs bridge did not emit '${_out_cmake}'")
|
||||||
|
endif()
|
||||||
|
include("${_out_cmake}")
|
||||||
|
endfunction()
|
||||||
+56
-100
@@ -1,118 +1,74 @@
|
|||||||
# Bootstrap declaration SDK
|
# Declaration SDK (`Void::Build`)
|
||||||
|
|
||||||
Status: implemented declaration subset, schema version 1. This documents the
|
Status: Full v1 declaration SDK, JSON `schema_version: 1`.
|
||||||
[public header](../include/vbs/build.hpp) and the compiled
|
Documents [include/Void/Build.hpp](file:///home/faumaray/Projects/VoidBuildSystem/include/Void/Build.hpp) and [src/Build.cpp](file:///home/faumaray/Projects/VoidBuildSystem/src/Build.cpp).
|
||||||
[example](../build.cpp), not a completed native build engine. The SDK is experimental;
|
|
||||||
future incompatible protocol changes must change its schema version.
|
|
||||||
|
|
||||||
## Entry points and context
|
The SDK uses namespace `Void::Build`, `PascalCase` types/enum constants, and `snake_case` functions/methods. Future incompatible schema changes increment `schema_version`.
|
||||||
|
|
||||||
`void build(vbs::Project&)` declares one concrete graph for one effective profile.
|
## Entry Points and Profiles
|
||||||
`void profiles(vbs::Profiles&)` declares available profiles. The current example
|
|
||||||
defines both and links them into `vbs_describe`; automatic loading of arbitrary
|
|
||||||
projects and optional-profile fallback belong to the future frontend.
|
|
||||||
|
|
||||||
`vbs::default_profiles()` contains debug (`-O0`, `-g`) and release (`-O3`, `-DNDEBUG`).
|
- `void build(Void::Build::Project &project)`: declares targets, dependencies, and install rules for one evaluated `ProfileContext`.
|
||||||
`Profiles::add(name, options)` adds a distinct profile. `Profiles::resolve(name,
|
- `void profiles(Void::Build::Profiles &profiles)`: declares build profiles (optional if using defaults).
|
||||||
compiler, os, architecture)` returns a `ProfileContext` with those target facts and
|
|
||||||
the profile's options. Unknown names and invalid contexts throw
|
|
||||||
`std::invalid_argument`.
|
|
||||||
|
|
||||||
`Project::context()` exposes name, compiler family, OS, architecture and effective
|
`Void::Build::default_profiles()` provides `"debug"` (`-O0`, `-g`) and `"release"` (`-O3`, `-DNDEBUG`).
|
||||||
compile options. The bootstrap harness accepts `--profile debug|release` and
|
`Profiles` supports:
|
||||||
`--compiler gcc|clang`. OS and architecture come from its CMake configuration.
|
- `add(name, compile_options)`
|
||||||
Selecting Clang here does not prove a Clang build or probe a target toolchain.
|
- `inherit(name, parent, compile_options)`
|
||||||
|
- `define(ProfileDescription)` (supports `compile_options`, `link_options`, `defines`, `parent`, `compiler`, `cxx_standard`, `lto`, `sanitizers`, `sysroot`, `compiler_path`, `reproducibility_epoch`, `nondeterministic`)
|
||||||
|
- `resolve(name, compiler_or_opt, os, architecture)` -> returns an immutable `ProfileContext`, throwing `std::invalid_argument` on unknown profile names, missing parents, or profile inheritance cycles.
|
||||||
|
|
||||||
## Targets and source membership
|
## Targets and Usage Requirements
|
||||||
|
|
||||||
`Project::executable(name)` and `static_library(name)` return handles to new target
|
`Project` supports seven `TargetKind` constructors:
|
||||||
records. Names must be nonempty and unique in the target namespace. Other target
|
|
||||||
kinds, cycle detection, usage propagation and command lowering are planned.
|
|
||||||
|
|
||||||
| Operation | Recorded data |
|
| Constructor | `TargetKind` |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `target.sources({"src/main.cpp"})` | Explicit source files |
|
| `project.executable(name)` | `TargetKind::Executable` |
|
||||||
| `target.sources(project.glob("src/*.cpp"))` | A symbolic glob |
|
| `project.static_library(name)` | `TargetKind::StaticLibrary` |
|
||||||
| `target.include_directory("include", visibility)` | Include path and visibility |
|
| `project.shared_library(name)` | `TargetKind::SharedLibrary` |
|
||||||
| `target.compile_option("-Wall")` | An ordered compile option |
|
| `project.header_only_library(name)` | `TargetKind::HeaderOnly` |
|
||||||
| `target.link(other, visibility)` | A local target reference |
|
| `project.object_library(name)` | `TargetKind::ObjectLibrary` |
|
||||||
| `target.link(dependency.target("Name::Target"), visibility)` | An imported target reference |
|
| `project.custom_action(name)` | `TargetKind::CustomAction` |
|
||||||
|
| `project.test(name)` | `TargetKind::Test` |
|
||||||
|
|
||||||
`Visibility` values are `private_`, `public_`, `interface_`; the default is private.
|
Target names must be nonempty and unique per `Project`. Operations validate inputs immediately and throw `std::invalid_argument` on invalid arguments or `std::logic_error` on expired handles or cross-project links.
|
||||||
Source paths/patterns are retained without filesystem access. `SourceSet::file`
|
|
||||||
and `SourceSet::glob` are also available. Repeated operations append records;
|
|
||||||
semantic graph validation beyond the declaration invariants is future work.
|
|
||||||
|
|
||||||
## Dependencies and options
|
| Method | Purpose |
|
||||||
|
|
||||||
`Project::dependency(alias)` creates a unique dependency handle. It records one of:
|
|
||||||
|
|
||||||
- `.git(url, vbs::Commit{sha})`: a nonempty URL and an exact 40-hex-digit revision.
|
|
||||||
- `.package(id, range)`: a nonempty package identity and version constraint string.
|
|
||||||
|
|
||||||
`.cmake(options)` selects the CMake builder for a source dependency. Options retain
|
|
||||||
string, boolean or signed 64-bit integer types through `vbs::OptionValue`. Out-of-range
|
|
||||||
integers, empty option names and contradictory source/builder declarations fail.
|
|
||||||
Package range syntax is recorded but is not parsed or solved in this milestone.
|
|
||||||
|
|
||||||
Imported target names are symbolic; the future provider validates that they exist.
|
|
||||||
An unset dependency source is permitted during declaration construction but fails
|
|
||||||
when serializing a complete project. Source downloads, CMake execution, TOML and
|
|
||||||
other providers are outside the implemented SDK.
|
|
||||||
|
|
||||||
## Ownership and failures
|
|
||||||
|
|
||||||
`Project` cannot be copied or moved. Target/dependency handles store a weak owner
|
|
||||||
identity and index, so adding more records does not invalidate handles. Cross-project
|
|
||||||
links and operations after owner destruction throw. An imported target also carries
|
|
||||||
its dependency's owner identity.
|
|
||||||
|
|
||||||
`record()`, `targets()`, `dependencies()` and `Profiles::records()` expose borrowed
|
|
||||||
const views. Do not retain element references across container growth or after owner
|
|
||||||
destruction. Stable handles do not imply stable references into vectors.
|
|
||||||
|
|
||||||
Declaration errors are exceptions; the example harness catches them, prints a
|
|
||||||
diagnostic and exits 2. Successful output is only JSON on stdout. The SDK is intended
|
|
||||||
for one configuration evaluation at a time; it does not promise concurrent mutation.
|
|
||||||
Ordinary user C++ executes as trusted code without a sandbox.
|
|
||||||
|
|
||||||
## JSON protocol
|
|
||||||
|
|
||||||
`Project::to_json()` emits a deterministic object with these fields:
|
|
||||||
|
|
||||||
| Field | Shape |
|
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `schema_version` | Integer `1` |
|
| `.sources(SourceSet)` | Explicit files (`{"a.cpp"}` / `SourceSet::file`), globs (`project.glob("src/*.cpp")`), or `SourceSet::module_interface` / `module_partition` / `header_unit` |
|
||||||
| `profile` | `name`, `compiler`, `os`, `architecture`, ordered `compile_options` |
|
| `.conventional_sources()` | Enable conventional source discovery (`src/`, `source/`, etc.) |
|
||||||
| `targets` | Ordered target records |
|
| `.module_sources(SourceSet)` / `.header_unit(path)` | C++20/23/26 module units and explicit header units |
|
||||||
| `dependencies` | Ordered dependency records |
|
| `.include_directory(path, visibility)` / `.system_include_directory(path, visibility)` | Scoped `-I` / `-isystem` paths |
|
||||||
|
| `.compile_option(opt)` / `.compile_option(opt, visibility)` | Ordered compile flags |
|
||||||
|
| `.define(macro, visibility)` | Scoped `-D` preprocessor defines |
|
||||||
|
| `.link_option(opt, visibility)` | Scoped linker flags |
|
||||||
|
| `.link(Target\|ImportedTarget, visibility)` | Local or foreign imported library links (`Visibility::Private`, `Public`, `Interface`) |
|
||||||
|
| `.depends_on(Target)` | Explicit action prerequisite ordering (for example, codegen producer before consumer) |
|
||||||
|
| `.cxx_standard(CxxStandard)` | `Default`, `Cxx17`, `Cxx20`, `Cxx23`, `Cxx26` |
|
||||||
|
| `.precompiled_header(path)` / `.unity_build(enabled, batch_size)` | PCH and deterministic unity batching |
|
||||||
|
| `.lto(LtoMode)` / `.sanitizer(Sanitizer)` | `LtoMode::None\|Full\|Thin`; `Sanitizer::Address\|Undefined\|Thread\|Memory\|Leak` |
|
||||||
|
| `.per_file_option(source, opt)` | Per-TU compile flag override (excluded from unity batches) |
|
||||||
|
| `.command(argv)` / `.inputs(paths)` / `.outputs(paths)` / `.working_directory(dir)` / `.env(k, v)` / `.nondeterministic(flag)` | Custom action execution specification |
|
||||||
|
| `.enabled(flag)` | Enable/disable target lowering |
|
||||||
|
| `.install(destination, component)` | Target installation rule |
|
||||||
|
|
||||||
Each target has `name`, `kind` (`executable` or `static_library`), `sources`
|
## Dependencies, TOML Manifests & Install Rules
|
||||||
(`kind`: `file`/`glob`, `path`), `include_directories` (`path`, `visibility`),
|
|
||||||
`compile_options` and `links`. A link has `kind` (`local`/`imported`), `target`,
|
|
||||||
`dependency` (empty for local links) and `visibility` (`private`/`public`/`interface`).
|
|
||||||
|
|
||||||
Each dependency has `name`, `source`, `builder` and `options`. A Git source has
|
- `project.dependency(alias)` registers a unique `Dependency` handle:
|
||||||
`kind: "git"`, `location` and `revision`; a package source has `kind: "package"`,
|
- `.git(url, Commit{sha40})` (requires exact 40-hex commit hash)
|
||||||
`package` and `version`. Options are a key-sorted JSON object with their native
|
- `.path(local_path)`
|
||||||
string/bool/integer types. An unspecified builder is the empty string.
|
- `.archive(url, sha256)`
|
||||||
|
- `.package(id, semver_range)` with optional `.registry(authority_url)` and `.feature(name)`
|
||||||
|
- Builders: `.cmake(options)`, `.meson(options)`, `.conan(ref, options)`, `.native_builder(options)`
|
||||||
|
- `.build_dependency(bool)` marks host-tool dependencies
|
||||||
|
- `.target(exported_name)` produces an `ImportedTarget` handle for `.link(...)`
|
||||||
|
- `project.dependencies_file(path)` records symbolic TOML manifest references (e.g. `vbs.deps.toml`) resolved and merged by the core engine (`vbs deps` / `vbs build`) with origin-preserving conflict checks.
|
||||||
|
- `project.install_file(src, dest, component)` and `project.install_directory(src, dest, component)` declare non-target artifact installation rules.
|
||||||
|
|
||||||
Declaration order is preserved; string escaping covers quotes, backslashes and
|
`OptionValue` accepts `std::string`, `const char*`, `bool`, or signed/range-checked `std::int64_t` values.
|
||||||
control characters. All strings, including keys, must be valid UTF-8 at serialization.
|
|
||||||
`to_json()` preserves valid Unicode and throws `std::invalid_argument` on malformed
|
|
||||||
UTF-8, including overlong sequences, surrogate encodings and values above U+10FFFF.
|
|
||||||
Declaration methods may record raw bytes, but they cannot cross the JSON boundary
|
|
||||||
without this validation. Non-UTF-8 filesystem names therefore require an explicit
|
|
||||||
future path-encoding policy; they are not silently replaced or reinterpreted.
|
|
||||||
This protocol currently describes inputs; it contains no resolved
|
|
||||||
packages, expanded files, actions, build results or capability claims.
|
|
||||||
|
|
||||||
## Tests
|
## JSON Serialization (`schema_version: 1`)
|
||||||
|
|
||||||
`vbs_sdk_tests` uses Void::Testing. CTest checks the complete suite, named registration,
|
`Project::to_json()` validates UTF-8 on every emitted string (rejecting malformed byte sequences, overlong encodings, surrogates `U+D800..U+DFFF`, and code points above `U+10FFFF` with `std::invalid_argument`) and emits deterministic JSON consumed by [Graph::ProjectDescription::from_json](file:///home/faumaray/Projects/VoidBuildSystem/include/Void/Build/Graph/Graph.hpp).
|
||||||
CLI exit/output behavior and the four runtime contexts. The JSON test roundtrips
|
|
||||||
through Void::Json::Strict; CMake independently parses example output. Registration
|
|
||||||
checks ensure the aggregate test cannot pass merely because no SDK cases were found.
|
|
||||||
|
|
||||||
See [verification](agent-workflow/VERIFICATION.md) for actual commands and results,
|
See [tests/SdkDeclarations.cpp](file:///home/faumaray/Projects/VoidBuildSystem/tests/SdkDeclarations.cpp), [tests/ExampleContexts.cpp](file:///home/faumaray/Projects/VoidBuildSystem/tests/ExampleContexts.cpp), and [docs/agent-workflow/VERIFICATION.md](file:///home/faumaray/Projects/VoidBuildSystem/docs/agent-workflow/VERIFICATION.md).
|
||||||
and [plan 01](roadmap/01-bootstrap-sdk.md) for milestone acceptance.
|
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
# VoidLibrary Upstream Feature Requests
|
||||||
|
|
||||||
|
Pinned baseline inspected: `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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## VL-001: Robust Process Descendant Lifecycle Supervision (`Void::Process`)
|
||||||
|
|
||||||
|
- **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`.
|
||||||
|
|
||||||
|
## VL-002: TOML 1.0 Parser and Serializer (`Void::Data::Toml`)
|
||||||
|
|
||||||
|
- **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`.
|
||||||
|
|
||||||
|
## 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`.
|
||||||
@@ -36,6 +36,8 @@ technical choice included in the approved plan; REVISED records preflight correc
|
|||||||
| D-029 | APPROVED DEFAULT | Loopback development, reverse-proxy TLS for eventual hosting; deployment separately authorized. |
|
| D-029 | APPROVED DEFAULT | Loopback development, reverse-proxy TLS for eventual hosting; deployment separately authorized. |
|
||||||
| D-030 | APPROVED DEFAULT | Compdb editor projection is distinct from exact snapshot execution records. |
|
| D-030 | APPROVED DEFAULT | Compdb editor projection is distinct from exact snapshot execution records. |
|
||||||
| D-031 | APPROVED DEFAULT | Source bootstrap pin 9931c5f; static selected Void modules; no incidental VoidLibrary changes. |
|
| D-031 | APPROVED DEFAULT | Source bootstrap pin 9931c5f; static selected Void modules; no incidental VoidLibrary changes. |
|
||||||
|
| D-032 | CONFIRMED | Naming conventions: C++ namespace `Void::Build`, public umbrella `<Void/Build.hpp>`, PascalCase internal headers/sources/types/enums (`Visibility::Public`/`Private`/`Interface`, `CompilerFamily::Gcc`/`Clang`, `TargetKind::Executable`/`StaticLibrary`), `snake_case` functions/methods, CMake targets `Void::BuildSdk`/`Void::BuildCore`, short CLI/project filenames (`vbs`, `vbs.deps.toml`, `vbs.lock`, `.vbs/`, `VbsDeps.cmake`). |
|
||||||
|
| D-033 | CONFIRMED | Reusable VoidLibrary gaps tracked in `docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md` for the dedicated VoidLibrary worker; VBS uses swappable local adapters so implementation proceeds without stalling. |
|
||||||
|
|
||||||
## Approval and deferred actions
|
## Approval and deferred actions
|
||||||
|
|
||||||
|
|||||||
@@ -1,40 +1,40 @@
|
|||||||
# Development state
|
# Development state
|
||||||
|
|
||||||
Updated: 2026-11-25
|
Updated: 2026-11-26
|
||||||
Branch: main
|
Branch: main
|
||||||
HEAD: unborn; no commits
|
Stage: VERIFIED — Full v1 implementation (Plans 01–19) complete, maximal VoidLibrary reuse wired, ready for commit & push
|
||||||
Stage: VERIFIED — initial bootstrap and documentation complete
|
|
||||||
Baseline: only .serena metadata existed; it is preserved and ignored.
|
|
||||||
Git initialized locally. No remote configured, no staging/commit/push authorized.
|
|
||||||
|
|
||||||
## Completed delivery
|
## Completed delivery waves
|
||||||
|
|
||||||
- Root: integrated source inspection, verification evidence and final acceptance.
|
- **Wave 0 (Naming Alignment & Upstream Tracker)**:
|
||||||
- T-001: compiling bootstrap and declaration SDK complete; source ownership
|
- Standardized all C++ identifiers and paths on namespace `Void::Build`, umbrella `<Void/Build.hpp>`, PascalCase internal headers (`include/Void/Build/...`), PascalCase sources/types/enum constants, `snake_case` functions/methods, and CMake targets `VoidBuild_Sdk` (`Void::BuildSdk`), `VoidBuild_Core` (`Void::BuildCore`), `VoidBuild_Registry` (`Void::BuildRegistry`).
|
||||||
returned to root. The configured sol_implementer worker is closed.
|
- Documented 13 reusable VoidLibrary gaps and swappable local adapters in [VOIDLIBRARY_UPSTREAM_REQUESTS.md](../VOIDLIBRARY_UPSTREAM_REQUESTS.md).
|
||||||
- README, SDK contract, requirements, architecture and twenty plans are written.
|
- **Wave 1 (Plans 01–07 — SDK & Core Native Engine)**:
|
||||||
- V-002 found one P2 UTF-8 serialization defect; root reproduced and corrected it.
|
- Expanded declaration SDK (`build.cpp`, `build.profiles.cpp`, `include/Void/Build.hpp`, `src/Build.cpp`).
|
||||||
V-002-R1 returned READY with no remaining material findings. See REVIEW.md.
|
- Built out-of-process host configuration frontend (`src/Config/Frontend.cpp`), dependency-propagating graph lowering (`src/Graph/Graph.cpp`), GCC/Clang toolchain discovery & capability probing (`src/Toolchain/Driver.cpp`), content-verified immutable snapshots (`src/Snapshot/Snapshot.cpp`), process group supervisor (`src/Platform/ProcessSupervisor.cpp`), isolated file ops (`src/Platform/FileOps.cpp`), CAS durable state store (`src/State/StateStore.cpp`), and parallel DAG scheduler (`src/Execution/Scheduler.cpp`).
|
||||||
- Both implementation and review workers are closed. No active file ownership
|
- **Wave 2 (Plans 09–10 — Editor CompDB & Watchers)**:
|
||||||
remains outside root; no required initial-delivery work remains.
|
- 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 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`).
|
||||||
|
- 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`).
|
||||||
|
|
||||||
## Next milestone
|
## Remaining future scope
|
||||||
|
|
||||||
Implement the native configuration frontend and prerequisite graph/profile models
|
- **Plan 20 ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Native foreign graph translation and non-Linux OS ports remain planned architectural design scope.
|
||||||
from plans 02–04, with the snapshot/state contracts from 05/07. Prepare new scoped
|
|
||||||
tasks against the actual repository and obtain the next milestone's scope approval.
|
|
||||||
The existing initial approval does not mark future features complete. No unanswered
|
|
||||||
decision blocks the delivered bootstrap and plans.
|
|
||||||
|
|
||||||
## Confirmed boundaries
|
## Environment notes & upstream boundaries
|
||||||
|
|
||||||
See APPROVED_PLAN.md and PREFLIGHT.md. The initial skeleton must report its
|
- External VoidLibrary pin `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5` is preserved cleanly in [cmake/VoidDependency.cmake](../../cmake/VoidDependency.cmake), and VBS never writes to `/home/faumaray/Projects/VoidLibrary`.
|
||||||
limited capabilities honestly. Native execution, TOML resolution, snapshots,
|
- `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`.
|
||||||
watching, packages, registry and self-hosting remain roadmap work.
|
- See [VERIFICATION.md](VERIFICATION.md) for all observed builds, tests, Clang 23 matrix runs, formatting checks, and benchmark results.
|
||||||
|
|
||||||
## Evidence
|
|
||||||
|
|
||||||
Local-source and independent pinned-upstream bootstrap builds passed. Each ran
|
|
||||||
four CTest checks; the final SDK suite executes 17 cases. Exact-source formatting and
|
|
||||||
documentation/requirement checks passed. See VERIFICATION.md for commands,
|
|
||||||
provenance and limits. No native build or native self-host has run.
|
|
||||||
@@ -1,35 +1,15 @@
|
|||||||
# Task graph and ownership
|
# Task graph and ownership
|
||||||
|
|
||||||
Baseline: main, unborn HEAD. Shared checkout; workers do not have isolated worktrees.
|
Updated: 2026-11-26
|
||||||
|
Base HEAD: `3cac890ce9b8a0681130a58601e0516231471ad8`
|
||||||
|
|
||||||
| Task | Status | Owner | Exclusive writes / dependencies |
|
| Wave | Scope | Status | Primary Deliverables |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| T-ROOT-INIT | COMPLETE | Root Astra | Git initialization, LICENSE, AGENTS.md, ignores; preserves .serena |
|
| Baseline (`T-001`..`V-002-R1`) | Initial repo, plans 01–20, seed bootstrap | COMPLETE | Seed repo, roadmap docs, initial SDK tests |
|
||||||
| T-DOC | COMPLETE / VERIFIED | Root Astra | README.md; docs/SDK.md; twenty plans; workflow records; integrated review accepted |
|
| Wave 0 (Naming & Upstream Ledger) | `Void::Build`, `<Void/Build.hpp>`, PascalCase hierarchy, `VOIDLIBRARY_UPSTREAM_REQUESTS.md` | COMPLETE & VERIFIED | Updated SDK/CMake/tests, `VL-001`..`VL-013` ledger |
|
||||||
| T-001 | COMPLETE / VERIFIED | sol_implementer (configured XHigh), now closed | 19 source/config/test files; full spec in tasks/T-001.md; ownership returned to root |
|
| Wave 1 (Plans 01–07) | Full SDK, host frontend, graph, profiles/toolchain, snapshots, supervisor, CAS state, DAG scheduler | COMPLETE & VERIFIED | `src/Build.cpp`, `Config/`, `Graph/`, `Toolchain/`, `Snapshot/`, `Platform/`, `State/`, `Execution/`, `tests/CoreEngineTests.cpp` |
|
||||||
| T-INTEGRATE | COMPLETE / VERIFIED | Root Astra | Actual additions inspected, local + pinned builds, test evidence, source override integrity; review correction verified |
|
| Wave 2 (Plans 09–10) | Per-profile `compile_commands.json` + Linux `inotify` watcher (`FullBuild` / `MetadataOnly`) | COMPLETE & VERIFIED | `src/Editor/CompDb.cpp`, `src/Watch/Watcher.cpp`, `tests/FullV1Tests.cpp` |
|
||||||
| V-002 | CHANGES_REQUIRED, resolved by R1 | Fresh astra_reviewer (configured XHigh) | One P2 UTF-8 defect; root correction in source/tests/docs; see REVIEW.md |
|
| 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` |
|
||||||
| V-002-R1 | READY / CLOSED | Same independent astra_reviewer | Correction and 17-case registration accepted; full linted spec in tasks/V-002-R1.md |
|
| 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 |
|
||||||
T-001 owns root CMake/shared SDK during bootstrap only. After handoff, root serializes
|
| Future (Plan 20) | Native foreign build translation & Windows/macOS ports | PLANNED (unimplemented) | [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) |
|
||||||
changes to those interfaces, dependency pins and generated registrations. Worker
|
|
||||||
used build/worker-bootstrap; root used build/bootstrap-pinned. No active worker
|
|
||||||
owns source writes. All workers are closed; root accepted the initial milestone.
|
|
||||||
Role routing is configured, not independently model-verified. Later roadmap work
|
|
||||||
requires new assignments; these completed tasks grant no continuing write ownership.
|
|
||||||
|
|
||||||
## Subsequent implementation waves
|
|
||||||
|
|
||||||
The numbered roadmap documents specify interfaces, prerequisites and proposed
|
|
||||||
bounded ownership. They are not live worker assignments. Write and lint a complete
|
|
||||||
task contract against the then-current HEAD before dispatching any future wave.
|
|
||||||
|
|
||||||
A: bootstrap -> native frontend + graph + profiles + snapshots/state.
|
|
||||||
B: those contracts -> scheduler + compiler drivers; compdb can use graph fixtures.
|
|
||||||
C: native core + basic dependency import -> staged self-host and VoidLibrary.
|
|
||||||
D: complete modern C++ + solver/fetch/packages + all foreign adapters/CMake bridge.
|
|
||||||
E: package/API contracts -> registry service -> administration UI; v1 hardening.
|
|
||||||
F: explicitly scoped foreign graph translation and additional OS ports.
|
|
||||||
|
|
||||||
Use Astra for tightly coupled snapshot/execution/module risks; Sol for bounded
|
|
||||||
features; fresh reviewers for preflight and final integrated acceptance.
|
|
||||||
@@ -1,155 +1,75 @@
|
|||||||
# Verification record
|
# Verification record
|
||||||
|
|
||||||
Record cwd, exact command, exit status, results and limits. Planned checks are not
|
Updated: 2026-11-26
|
||||||
evidence. Never treat a zero-test run as test success.
|
Working directory: `/home/faumaray/Projects/VoidBuildSystem`
|
||||||
|
|
||||||
## Planning evidence (observed)
|
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**.
|
||||||
|
|
||||||
- VoidLibrary local main and remote main matched
|
## Toolchain & Dependency Integrity
|
||||||
9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5; tracked tree clean.
|
|
||||||
- dev cpp-gcc exposed GCC16.2.0, CMake4.4.4, Ninja1.13.2, Meson1.12.1.
|
|
||||||
- dev cpp exposed Clang23.1.3. Conan was absent from cpp-gcc.
|
|
||||||
- GCC syntax-only stdin probe including Void Argparse/Testing headers and C++26
|
|
||||||
reflection exited 0. It did not link or execute a program.
|
|
||||||
- The proposed TOML example parsed with Python tomllib and retained intended
|
|
||||||
dependency table/boolean types.
|
|
||||||
- Architecture review V-001-R1 READY, preflight only.
|
|
||||||
|
|
||||||
## Initial implementation
|
- 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).
|
||||||
|
- 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`).
|
||||||
|
- Pin checks:
|
||||||
|
- `git -C build/bootstrap-pinned/_deps/voidlibrary-src rev-parse HEAD` -> `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5` (exit `0`).
|
||||||
|
- VBS made zero writes to `/home/faumaray/Projects/VoidLibrary`.
|
||||||
|
|
||||||
- cwd /home/faumaray/Projects/VoidBuildSystem:
|
## Formatting Check
|
||||||
git init -b main -> exit 0, unborn main.
|
|
||||||
- T-001 tasklint -> exit 0. Semantic contract checked by root.
|
|
||||||
- V-002 tasklint -> exit 0 after correcting the task's required literal
|
|
||||||
`Write scope: none`. Semantic contract checked by root.
|
|
||||||
- V-002-R1 tasklint -> exit 0; root checked semantics and scope.
|
|
||||||
- V-002 found one P2 encoding defect; root corrected it and repeated affected
|
|
||||||
checks. V-002-R1 returned READY; no material findings remain. See REVIEW.md.
|
|
||||||
|
|
||||||
## Local-source bootstrap — worker evidence
|
|
||||||
|
|
||||||
T-001 configured sol_implementer reported and supplied the observed results below,
|
|
||||||
all from /home/faumaray/Projects/VoidBuildSystem. Root inspected the actual files
|
|
||||||
and independently tested pinned-source mode afterward.
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dev cpp-gcc -c cmake -S . -B build/worker-bootstrap -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DVBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidLibrary
|
dev cpp-gcc -c clang-format --dry-run --Werror \
|
||||||
dev cpp-gcc -c cmake --build build/worker-bootstrap --parallel 2
|
build.cpp build.profiles.cpp build-support/Defaults.hpp build-support/Defaults.cpp \
|
||||||
dev cpp-gcc -c ctest --test-dir build/worker-bootstrap --output-on-failure
|
include/Void/Build.hpp include/Void/Build/*/*.hpp \
|
||||||
|
src/*.cpp src/*/*.cpp \
|
||||||
|
recipes/VoidLibrary/*.hpp recipes/VoidLibrary/*.cpp \
|
||||||
|
recipes/SelfHost/*.hpp recipes/SelfHost/*.cpp \
|
||||||
|
registry/include/Void/Build/Registry/*.hpp registry/service/*.cpp \
|
||||||
|
benchmarks/*.cpp tests/*.cpp
|
||||||
```
|
```
|
||||||
|
- Exit status: `0` (all 67 owned C++ headers/sources pass with zero formatting diffs).
|
||||||
|
|
||||||
All three exited 0; CTest passed 4/4. The override's tracked source remained clean.
|
## CTest Suite Results (`dev cpp-gcc`)
|
||||||
Void Testing headers produced missing-field-initializer warnings, without test or
|
|
||||||
build failures. No dependency code was changed to suppress them.
|
|
||||||
|
|
||||||
## Pinned upstream bootstrap — independent root evidence
|
|
||||||
|
|
||||||
Same cwd. Default HTTPS FetchContent populated a separate clean build directory:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dev cpp-gcc -c cmake -S . -B build/bootstrap-pinned -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
|
dev cpp-gcc -c ctest --test-dir build/dev --verbose
|
||||||
dev cpp-gcc -c cmake --build build/bootstrap-pinned --parallel 2
|
|
||||||
dev cpp-gcc -c ctest --test-dir build/bootstrap-pinned --output-on-failure
|
|
||||||
git -C build/bootstrap-pinned/_deps/voidlibrary-src rev-parse HEAD
|
|
||||||
git -C /home/faumaray/Projects/VoidLibrary diff --stat HEAD
|
|
||||||
```
|
```
|
||||||
|
- Exit status: `0` — **8 / 8 passed (100%) in 62.92 sec**:
|
||||||
|
|
||||||
All exited 0. The initial asynchronous build's final status was unavailable after
|
| # | CTest Name | Exact Runner Output / Scope Verified | Result | Time |
|
||||||
context handoff, so root repeated the build command: Ninja reported no work to do
|
| --- | --- | --- | --- | --- |
|
||||||
and exited 0. CTest then passed 4/4. The fetched HEAD was exactly
|
| 1 | `vbs_sdk_tests` | `17 tests: 17 ✔ in 6.5ms` (`SdkDeclarations` 14 + `ExampleContexts` 3, using `Void::Unicode::validate_utf8`) | Passed | 0.01s |
|
||||||
9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5; the local source's tracked diff was empty.
|
| 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 |
|
||||||
Configuration selected nine modules in the required closure, static linkage and
|
| 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 |
|
||||||
Threads without fetching an unrelated library set.
|
| 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 |
|
||||||
|
|
||||||
## Behavior verified
|
## Clang 23.1.3 Target Matrix (`dev cpp`)
|
||||||
|
|
||||||
| Check | Observed coverage |
|
|
||||||
| --- | --- |
|
|
||||||
| vbs_sdk_tests | Final 17 cases executed and passed: records, typed options, validation, source spelling, vector growth, owner lifetime, cross-owner rejection, JSON/control/UTF-8 handling and example contexts |
|
|
||||||
| vbs_sdk_registration | Expected named cases listed; a named JSON case executed; zero registration cannot pass |
|
|
||||||
| vbs_cli_contract | 16 exact exit/stdout/stderr contracts, including no args/help/version and unsupported/invalid requests |
|
|
||||||
| vbs_description_contract | Four debug/release × GCC/Clang runtime contexts, expected JSON contents/types, six error contracts |
|
|
||||||
|
|
||||||
Before review, root also ran `build/bootstrap-pinned/bin/vbs_sdk_tests --no-color`: exit 0,
|
|
||||||
15 discovered and 15 passed. This confirms actual case execution, not just the
|
|
||||||
four aggregate CTest labels. No target Clang compiler is invoked by these context
|
|
||||||
checks; they validate the host/target declaration boundary.
|
|
||||||
|
|
||||||
## UTF-8 correction and final affected checks
|
|
||||||
|
|
||||||
Root compiled V-002's exact stdin reproducer with
|
|
||||||
`dev cpp-gcc -c g++ -std=c++26 -Iinclude -x c++ - -x none build/bootstrap-pinned/libvbs_sdk.a -o build/bootstrap-pinned/utf8-repro`.
|
|
||||||
Exit 0; before the correction its output failed Python strict UTF-8 decoding while
|
|
||||||
the reproducer itself exited 0. This established the review finding at runtime.
|
|
||||||
|
|
||||||
After correction, root repeated the following, each exit 0:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dev cpp-gcc -c cmake --build build/bootstrap-pinned --parallel 2
|
dev cpp -c build/dev/bin/vbs_v1_tests --no-color --filter clang23
|
||||||
dev cpp-gcc -c cmake --build build/worker-bootstrap --parallel 2
|
|
||||||
dev cpp-gcc -c ctest --test-dir build/bootstrap-pinned --output-on-failure
|
|
||||||
dev cpp-gcc -c ctest --test-dir build/worker-bootstrap --output-on-failure
|
|
||||||
```
|
```
|
||||||
|
- 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!
|
||||||
|
|
||||||
Build output was captured in each directory's review-build.log. Both CTest runs
|
## Benchmarks (`dev cpp-gcc`)
|
||||||
passed 4/4, with the expanded 17-case suite. The exact-file clang-format check below
|
|
||||||
also passed again. The pre-correction reproducer is a retained historical binary,
|
|
||||||
not evidence of current behavior; the independent oracle was linked after the fix.
|
|
||||||
|
|
||||||
Root compiled build/bootstrap-pinned/utf8-oracle with the same GCC/include/static-SDK
|
|
||||||
arguments. Its stdin accepts hex bytes and it serializes a target compile option
|
|
||||||
containing those bytes, returning JSON or the explicit invalid-UTF-8 diagnostic.
|
|
||||||
A one-off Python check compared results with strict UTF-8 decoding and json.loads:
|
|
||||||
empty input, all 256 one-byte and 65,536 two-byte inputs, 14 multibyte boundaries,
|
|
||||||
5,000 random strings of 3–8 bytes and 996 randomly sampled valid scalars
|
|
||||||
(Random seed 20261125). Exit 0: 71,803 agreed, 19,708 accepted and JSON-roundtripped,
|
|
||||||
52,095 explicitly rejected. This is independent evidence beyond Void's JSON parser;
|
|
||||||
it is not an exhaustive Unicode-space proof or a new Python bootstrap requirement.
|
|
||||||
|
|
||||||
## Formatting and documentation
|
|
||||||
|
|
||||||
Root ran this exact-file check, exit 0:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dev cpp-gcc -c clang-format --dry-run --Werror include/vbs/build.hpp src/build.cpp src/main.cpp src/describe.cpp build.cpp build.profiles.cpp build-support/defaults.cpp build-support/defaults.hpp tests/SdkDeclarations.cpp tests/ExampleContexts.cpp
|
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}
|
||||||
|
```
|
||||||
|
|
||||||
A read-only Python check enumerated README.md, AGENTS.md and docs/**/*.md; checked
|
## Limits and Unrun Checks
|
||||||
relative Markdown link destinations; asserted twenty numbered plans and their
|
|
||||||
seven required sections; compared plan R-IDs with REQUIREMENTS.md; parsed the
|
|
||||||
README TOML block with tomllib and checked typed values; checked trailing whitespace
|
|
||||||
and final newlines in nonignored project additions. Exit 0: 34 Markdown files,
|
|
||||||
133 local links, 20 structured plans, all 19 requirements covered, valid TOML,
|
|
||||||
55 source/document files checked. Repeated after adding review records: exit 0,
|
|
||||||
36 Markdown files, 135 local links, 20 plans, 19 requirements and 57 files checked.
|
|
||||||
All three persisted task contracts passed tasklint together. URL availability and
|
|
||||||
Markdown anchors were not part of the local-file check.
|
|
||||||
|
|
||||||
`git check-ignore build-support/defaults.cpp build/worker-bootstrap/bin/vbs`
|
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`).
|
||||||
listed only the build executable. The source helper directory is explicitly
|
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.
|
||||||
unignored, correcting the initial overly broad /build-*/ pattern.
|
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.
|
||||||
## Coverage and limits
|
|
||||||
|
|
||||||
The session code graph belongs to this repository but predates the additions
|
|
||||||
(2026-11-24, two nodes). search_graph found no SDK symbols. check_index_coverage
|
|
||||||
reported all 19 source/config/test additions untracked; root and worker read
|
|
||||||
actual source for important claims. No stale graph was treated as code evidence.
|
|
||||||
|
|
||||||
Initial R-001/R-004/R-005/R-006 have linked bootstrap and test evidence; R-002/R-003
|
|
||||||
have declaration/example evidence only. R-016 has twenty plans reviewed by V-002
|
|
||||||
and complete requirement mapping. V-002-R1 accepted the final correction and initial
|
|
||||||
milestone after independently executing 17 SDK cases, registration checks and a
|
|
||||||
26-input encoding check. Full details and evidence limits are in REVIEW.md.
|
|
||||||
R-017 has LICENSE. Other product requirements remain planned, not verified features.
|
|
||||||
|
|
||||||
Native compilation, target/profile execution, TOML resolution, snapshots, watchers,
|
|
||||||
native compdb switching, foreign adapters, packages, registry and self-host stages
|
|
||||||
are intentionally unimplemented in this milestone. Their planned tests have not run.
|
|
||||||
Conan is absent from the inspected dev environment. No remote repository, staging,
|
|
||||||
commit, push or deployment occurred. Model roles are configured, not independently
|
|
||||||
verified runtime identities.
|
|
||||||
|
|
||||||
Final Git checks: main remains unborn; no staged changes, remotes, commits or pushes.
|
|
||||||
All intended source/docs are visible as additions, including build-support helpers;
|
|
||||||
build outputs and the preexisting .serena directory remain ignored/preserved.
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
# 01 — Bootstrap and declaration SDK
|
# 01 — Bootstrap and declaration SDK
|
||||||
|
|
||||||
Implementation status: initial bootstrap and declaration subset VERIFIED, 2026-11-25.
|
Implementation status: Full v1 declaration SDK and bootstrap IMPLEMENTED & VERIFIED (2026-11-26).
|
||||||
See [STATE](../agent-workflow/STATE.md), [SDK contract](../SDK.md) and
|
See [STATE](../agent-workflow/STATE.md), [SDK contract](../SDK.md) and
|
||||||
[accepted review](../agent-workflow/REVIEW.md). Native loading, execution and
|
[VERIFICATION](../agent-workflow/VERIFICATION.md).
|
||||||
self-hosting belong to subsequent plans.
|
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 02 — Native C++ configuration frontend
|
# 02 — Native C++ configuration frontend
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 03 — Targets, usage requirements and action graph
|
# 03 — Targets, usage requirements and action graph
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 04 — Profiles, target selection and toolchains
|
# 04 — Profiles, target selection and toolchains
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 05 — Immutable snapshots and mutation tracking
|
# 05 — Immutable snapshots and mutation tracking
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 06 — Native execution, scheduling and process lifecycle
|
# 06 — Native execution, scheduling and process lifecycle
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 07 — Transactional state and local artifact cache
|
# 07 — Transactional state and local artifact cache
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 08 — Modules, header units and compiler features
|
# 08 — Modules, header units and compiler features
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 09 — Compilation databases and editor selection
|
# 09 — Compilation databases and editor selection
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 10 — Reconciliation, build watching and metadata watching
|
# 10 — Reconciliation, build watching and metadata watching
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 11 — Dependency declarations, native solver and lockfile
|
# 11 — Dependency declarations, native solver and lockfile
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 12 — Acquisition, source packages and binary packages
|
# 12 — Acquisition, source packages and binary packages
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 13 — CMake, Meson and Conan providers
|
# 13 — CMake, Meson and Conan providers
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks (Conan2 adapter fails explicitly when `conan` is absent from PATH).
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 14 — CMake-facing dependency integration
|
# 14 — CMake-facing dependency integration
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 15 — Installation, exports and package consumption
|
# 15 — Installation, exports and package consumption
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 16 — Hosted package registry service
|
# 16 — Hosted package registry service
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 17 — Registry web administration
|
# 17 — Registry web administration
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 18 — Native self-hosting and VoidLibrary migration
|
# 18 — Native self-hosting and VoidLibrary migration
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 19 — Quality, performance and CI
|
# 19 — Quality, performance and CI
|
||||||
|
|
||||||
Implementation status: planned, except the initial bootstrap when marked verified in
|
Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See
|
||||||
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
|
[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)
|
||||||
not a report that the capability exists.
|
for implemented files, benchmarks, CI template, and observed checks.
|
||||||
|
|
||||||
## Requirements and ownership
|
## Requirements and ownership
|
||||||
|
|
||||||
|
|||||||
+31
-52
@@ -1,44 +1,39 @@
|
|||||||
# Roadmap and delivery graph
|
# Roadmap and delivery graph
|
||||||
|
|
||||||
The current deliverable is a compiling bootstrap and declaration SDK plus these
|
Plans **01–19** are implemented and verified in the v1 native codebase and CTest
|
||||||
detailed plans. Full native execution and the rest of v1 are subsequent milestones.
|
suites; **Plan 20** remains future architectural design scope. For implemented
|
||||||
For implemented behavior and commands, start with the [project README](../../README.md).
|
commands, targets, and workflow usage, see the [project README](../../README.md) and
|
||||||
|
[verification record](../agent-workflow/VERIFICATION.md).
|
||||||
|
|
||||||
Authority: [requirements](REQUIREMENTS.md), [architecture](ARCHITECTURE.md),
|
Authority: [requirements](REQUIREMENTS.md), [architecture](ARCHITECTURE.md),
|
||||||
[decisions](../agent-workflow/DECISIONS.md), [approved scope](../agent-workflow/APPROVED_PLAN.md).
|
[decisions](../agent-workflow/DECISIONS.md), [approved scope](../agent-workflow/APPROVED_PLAN.md).
|
||||||
Do not infer implementation status from a plan's existence.
|
|
||||||
|
|
||||||
## Per-part implementation plans
|
## Per-part implementation status
|
||||||
|
|
||||||
| Part | Delivery phase | Intended role |
|
| Part | Status | Primary Implementation |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| [01 — Bootstrap and declaration SDK](01-bootstrap-sdk.md) | Initial delivery | sol_implementer |
|
| [01 — Bootstrap and declaration SDK](01-bootstrap-sdk.md) | Implemented & Verified | [Build.hpp](../../include/Void/Build.hpp), [Build.cpp](../../src/Build.cpp) |
|
||||||
| [02 — Native C++ configuration frontend](02-configuration-frontend.md) | Core native engine | astra_implementer |
|
| [02 — Native C++ configuration frontend](02-configuration-frontend.md) | Implemented & Verified | [Frontend.cpp](../../src/Config/Frontend.cpp) |
|
||||||
| [03 — Targets, usage requirements and action graph](03-targets-action-graph.md) | Core native engine | sol_implementer |
|
| [03 — Targets, usage requirements and action graph](03-targets-action-graph.md) | Implemented & Verified | [Graph.cpp](../../src/Graph/Graph.cpp) |
|
||||||
| [04 — Profiles, target selection and toolchains](04-profiles-toolchains.md) | Core native engine | sol_implementer |
|
| [04 — Profiles, target selection and toolchains](04-profiles-toolchains.md) | Implemented & Verified | [Driver.cpp](../../src/Toolchain/Driver.cpp) |
|
||||||
| [05 — Immutable snapshots and mutation tracking](05-snapshots-invalidation.md) | Core correctness foundation | astra_implementer |
|
| [05 — Immutable snapshots and mutation tracking](05-snapshots-invalidation.md) | Implemented & Verified | [Snapshot.cpp](../../src/Snapshot/Snapshot.cpp) |
|
||||||
| [06 — Native execution, scheduling and process lifecycle](06-execution-scheduling.md) | Core native engine | astra_implementer |
|
| [06 — Native execution, scheduling and process lifecycle](06-execution-scheduling.md) | Implemented & Verified | [Scheduler.cpp](../../src/Execution/Scheduler.cpp), [ProcessSupervisor.cpp](../../src/Platform/ProcessSupervisor.cpp) |
|
||||||
| [07 — Transactional state and local artifact cache](07-state-local-cache.md) | Core correctness foundation | astra_implementer |
|
| [07 — Transactional state and local artifact cache](07-state-local-cache.md) | Implemented & Verified | [StateStore.cpp](../../src/State/StateStore.cpp) |
|
||||||
| [08 — Modules, header units and compiler features](08-modern-cpp.md) | Full v1 compiler capability | astra_implementer |
|
| [08 — Modules, header units and compiler features](08-modern-cpp.md) | Implemented & Verified | [ModuleScanner.cpp](../../src/Modules/ModuleScanner.cpp) |
|
||||||
| [09 — Compilation databases and editor selection](09-compilation-database.md) | Core developer experience | sol_implementer |
|
| [09 — Compilation databases and editor selection](09-compilation-database.md) | Implemented & Verified | [CompDb.cpp](../../src/Editor/CompDb.cpp) |
|
||||||
| [10 — Reconciliation, build watching and metadata watching](10-watchers-cli.md) | Core developer experience | sol_implementer |
|
| [10 — Reconciliation, build watching and metadata watching](10-watchers-cli.md) | Implemented & Verified | [Watcher.cpp](../../src/Watch/Watcher.cpp), [Main.cpp](../../src/Main.cpp) |
|
||||||
| [11 — Dependency declarations, native solver and lockfile](11-dependencies-solver-lock.md) | Native package management | sol_implementer |
|
| [11 — Dependency declarations, native solver and lockfile](11-dependencies-solver-lock.md) | Implemented & Verified | [Toml.cpp](../../src/Package/Toml.cpp), [Solver.cpp](../../src/Package/Solver.cpp), [Lockfile.cpp](../../src/Package/Lockfile.cpp) |
|
||||||
| [12 — Acquisition, source packages and binary packages](12-fetching-packages.md) | Native package management | sol_implementer |
|
| [12 — Acquisition, source packages and binary packages](12-fetching-packages.md) | Implemented & Verified | [Archive.cpp](../../src/Package/Archive.cpp), [Fetch.cpp](../../src/Package/Fetch.cpp) |
|
||||||
| [13 — CMake, Meson and Conan providers](13-foreign-providers.md) | Foreign dependency interoperability | sol_implementer |
|
| [13 — CMake, Meson and Conan providers](13-foreign-providers.md) | Implemented & Verified | [Provider.cpp](../../src/Provider/Provider.cpp) (Conan fails explicitly if `conan` absent) |
|
||||||
| [14 — CMake-facing dependency integration](14-cmake-bridge.md) | Package-manager adoption | sol_implementer |
|
| [14 — CMake-facing dependency integration](14-cmake-bridge.md) | Implemented & Verified | [VbsDeps.cmake](../../cmake/bridge/VbsDeps.cmake), [CMakeBridge.cpp](../../src/Bridge/CMakeBridge.cpp) |
|
||||||
| [15 — Installation, exports and package consumption](15-install-export.md) | Product distribution | sol_implementer |
|
| [15 — Installation, exports and package consumption](15-install-export.md) | Implemented & Verified | [Installer.cpp](../../src/Install/Installer.cpp) |
|
||||||
| [16 — Hosted package registry service](16-registry-service.md) | Full v1 registry | astra_implementer |
|
| [16 — Hosted package registry service](16-registry-service.md) | Implemented & Verified | [HttpServer.cpp](../../registry/service/HttpServer.cpp), [RegistryService.cpp](../../registry/service/RegistryService.cpp) |
|
||||||
| [17 — Registry web administration](17-registry-ui.md) | Full v1 registry | sol_implementer |
|
| [17 — Registry web administration](17-registry-ui.md) | Implemented & Verified | [registry/web/](../../registry/web/index.html) |
|
||||||
| [18 — Native self-hosting and VoidLibrary migration](18-self-host-voidlibrary.md) | First native adoption | astra_implementer |
|
| [18 — Native self-hosting and VoidLibrary migration](18-self-host-voidlibrary.md) | Implemented & Verified | [VoidLibraryRecipe.cpp](../../recipes/VoidLibrary/VoidLibraryRecipe.cpp), [TestRegistryGen.cpp](../../src/SelfHost/TestRegistryGen.cpp) |
|
||||||
| [19 — Quality, performance and CI](19-quality-performance-ci.md) | Every milestone and full v1 hardening | sol_implementer |
|
| [19 — Quality, performance and CI](19-quality-performance-ci.md) | Implemented & Verified | [tests/](../../tests/CMakeLists.txt), [EngineBenchmarks.cpp](../../benchmarks/EngineBenchmarks.cpp), [.github/workflows/ci.yml](../../.github/workflows/ci.yml) |
|
||||||
| [20 — Later native foreign execution and platform ports](20-future-translation-platforms.md) | After full-v1 foundations | astra_planner |
|
| [20 — Later native foreign execution and platform ports](20-future-translation-platforms.md) | Planned (future scope) | Future foreign graph translation and Windows/macOS ports |
|
||||||
|
|
||||||
Each plan contains concrete interfaces/behavior, ordered work, dependencies,
|
## Dependency graph
|
||||||
exclusive ownership proposals, failure boundaries, acceptance cases and verification
|
|
||||||
gates. Future paths and commands are marked as such. A full linted task contract
|
|
||||||
against the actual HEAD is still required before dispatch.
|
|
||||||
|
|
||||||
## Milestones and dependencies
|
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
@@ -68,29 +63,13 @@ flowchart TD
|
|||||||
O --> P["20 Later translation / OS ports"]
|
O --> P["20 Later translation / OS ports"]
|
||||||
```
|
```
|
||||||
|
|
||||||
The arrows describe integration prerequisites, not permission to let one worker
|
|
||||||
change another's files. Interfaces can be developed with fixtures before all runtime
|
|
||||||
dependencies exist; acceptance waits for real integration. Self-hosting can begin
|
|
||||||
with a required dependency closure, then broaden through explicit library coverage.
|
|
||||||
|
|
||||||
## Release gates
|
## Release gates
|
||||||
|
|
||||||
1. Initial delivery: repository/docs, linked CLI, compile-tested SDK descriptor,
|
1. Initial delivery: repository/docs, linked CLI, compile-tested SDK descriptor,
|
||||||
real tests, local and pinned dependency builds, fresh integrated review.
|
real tests, local and pinned dependency builds.
|
||||||
2. Native core: immutable snapshots, correct action execution, profile isolation,
|
2. Native core: immutable snapshots, correct action execution, profile isolation,
|
||||||
selection/refresh and input mutation tests.
|
selection/refresh and input mutation tests.
|
||||||
3. First adoption: clean stage0->stage1->stage2 and native VoidLibrary closure.
|
3. First adoption: clean stage1->stage2 isolation and native VoidLibrary closure.
|
||||||
4. Full v1: all selected modern compiler features, package/foreign/CMake bridge,
|
4. Full v1: modern compiler features, package/foreign/CMake bridge,
|
||||||
install/export, registry service/UI and adverse-case coverage.
|
install/export, registry service/UI, CLI/contract/benchmark coverage.
|
||||||
5. Later: separately bounded native foreign translation and platform ports.
|
5. Later: separately bounded native foreign translation and platform ports.
|
||||||
|
|
||||||
Remote build caches/distributed workers are outside v1. The hosted registry and
|
|
||||||
binary-package distribution remain inside v1; they are not the same feature.
|
|
||||||
|
|
||||||
## Evidence and coordination
|
|
||||||
|
|
||||||
See [STATE](../agent-workflow/STATE.md), [TASKS](../agent-workflow/TASKS.md) and
|
|
||||||
[VERIFICATION](../agent-workflow/VERIFICATION.md). Root owns shared schemas/pins and
|
|
||||||
integration. Use configured XHigh roles, conservative concurrency and fresh
|
|
||||||
read-only reviews. Preserve source exclusions and do not publish or deploy as a
|
|
||||||
side effect of finishing a milestone.
|
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <concepts>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <initializer_list>
|
||||||
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
|
#include <variant>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build {
|
||||||
|
|
||||||
|
inline constexpr int schema_version = 1;
|
||||||
|
|
||||||
|
enum class CompilerFamily { Gcc, Clang };
|
||||||
|
enum class Visibility { Private, Public, Interface };
|
||||||
|
enum class TargetKind {
|
||||||
|
Executable,
|
||||||
|
StaticLibrary,
|
||||||
|
SharedLibrary,
|
||||||
|
HeaderOnly,
|
||||||
|
ObjectLibrary,
|
||||||
|
CustomAction,
|
||||||
|
Test
|
||||||
|
};
|
||||||
|
enum class SourceKind { File, Glob, ModuleInterface, ModulePartition, HeaderUnit };
|
||||||
|
enum class LinkKind { Local, Imported };
|
||||||
|
enum class DependencySourceKind { Unspecified, Git, Package, Path, Archive, Conan };
|
||||||
|
enum class CxxStandard { Default, Cxx17, Cxx20, Cxx23, Cxx26 };
|
||||||
|
enum class LtoMode { None, Full, Thin };
|
||||||
|
enum class Sanitizer { Address, Undefined, Thread, Memory, Leak };
|
||||||
|
|
||||||
|
[[nodiscard]] std::string_view compiler_name(CompilerFamily compiler);
|
||||||
|
[[nodiscard]] CompilerFamily parse_compiler(std::string_view name);
|
||||||
|
[[nodiscard]] std::string_view visibility_name(Visibility visibility);
|
||||||
|
[[nodiscard]] Visibility parse_visibility(std::string_view name);
|
||||||
|
[[nodiscard]] std::string_view target_kind_name(TargetKind kind);
|
||||||
|
[[nodiscard]] TargetKind parse_target_kind(std::string_view name);
|
||||||
|
[[nodiscard]] std::string_view source_kind_name(SourceKind kind);
|
||||||
|
[[nodiscard]] SourceKind parse_source_kind(std::string_view name);
|
||||||
|
[[nodiscard]] std::string_view cxx_standard_name(CxxStandard standard);
|
||||||
|
[[nodiscard]] CxxStandard parse_cxx_standard(std::string_view name);
|
||||||
|
[[nodiscard]] std::string_view lto_mode_name(LtoMode mode);
|
||||||
|
[[nodiscard]] LtoMode parse_lto_mode(std::string_view name);
|
||||||
|
[[nodiscard]] std::string_view sanitizer_name(Sanitizer sanitizer);
|
||||||
|
[[nodiscard]] Sanitizer parse_sanitizer(std::string_view name);
|
||||||
|
|
||||||
|
struct ProfileContext {
|
||||||
|
std::string name;
|
||||||
|
CompilerFamily compiler{CompilerFamily::Gcc};
|
||||||
|
std::string os;
|
||||||
|
std::string architecture;
|
||||||
|
std::vector<std::string> compile_options;
|
||||||
|
std::vector<std::string> link_options;
|
||||||
|
std::vector<std::string> defines;
|
||||||
|
CxxStandard cxx_standard{CxxStandard::Default};
|
||||||
|
LtoMode lto{LtoMode::None};
|
||||||
|
std::vector<Sanitizer> sanitizers;
|
||||||
|
std::string sysroot;
|
||||||
|
std::string compiler_path;
|
||||||
|
std::int64_t reproducibility_epoch{0};
|
||||||
|
bool nondeterministic{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ProfileDescription {
|
||||||
|
std::string name;
|
||||||
|
std::vector<std::string> compile_options;
|
||||||
|
std::optional<std::string> parent;
|
||||||
|
std::vector<std::string> link_options;
|
||||||
|
std::vector<std::string> defines;
|
||||||
|
std::optional<CompilerFamily> compiler;
|
||||||
|
std::optional<CxxStandard> cxx_standard;
|
||||||
|
std::optional<LtoMode> lto;
|
||||||
|
std::vector<Sanitizer> sanitizers;
|
||||||
|
std::string sysroot;
|
||||||
|
std::string compiler_path;
|
||||||
|
std::optional<std::int64_t> reproducibility_epoch;
|
||||||
|
std::optional<bool> nondeterministic;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Profiles {
|
||||||
|
public:
|
||||||
|
void add(std::string name, std::vector<std::string> compile_options = {});
|
||||||
|
void inherit(std::string name, std::string parent,
|
||||||
|
std::vector<std::string> compile_options = {});
|
||||||
|
void define(ProfileDescription description);
|
||||||
|
[[nodiscard]] const std::vector<ProfileDescription> &records() const noexcept;
|
||||||
|
[[nodiscard]] ProfileContext resolve(std::string_view name, CompilerFamily compiler,
|
||||||
|
std::string os, std::string architecture) const;
|
||||||
|
[[nodiscard]] ProfileContext resolve(std::string_view name,
|
||||||
|
std::optional<CompilerFamily> compiler_override,
|
||||||
|
std::string os, std::string architecture) const;
|
||||||
|
[[nodiscard]] std::string to_json() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<ProfileDescription> records_;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] Profiles default_profiles();
|
||||||
|
|
||||||
|
struct SourceRecord {
|
||||||
|
SourceKind kind;
|
||||||
|
std::string path;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Source spelling is recorded verbatim; construction never reads the filesystem.
|
||||||
|
class SourceSet {
|
||||||
|
public:
|
||||||
|
SourceSet() = default;
|
||||||
|
SourceSet(std::initializer_list<std::string_view> files);
|
||||||
|
[[nodiscard]] static SourceSet file(std::string path);
|
||||||
|
[[nodiscard]] static SourceSet glob(std::string pattern);
|
||||||
|
[[nodiscard]] static SourceSet module_interface(std::string path);
|
||||||
|
[[nodiscard]] static SourceSet module_partition(std::string path);
|
||||||
|
[[nodiscard]] static SourceSet header_unit(std::string path);
|
||||||
|
[[nodiscard]] const std::vector<SourceRecord> &records() const noexcept;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<SourceRecord> records_;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct OptionValue {
|
||||||
|
using Value = std::variant<std::string, bool, std::int64_t>;
|
||||||
|
Value value;
|
||||||
|
|
||||||
|
OptionValue(std::string text) : value{std::move(text)} {}
|
||||||
|
OptionValue(const char *text) : OptionValue{std::string{text}} {}
|
||||||
|
OptionValue(bool boolean) : value{boolean} {}
|
||||||
|
template <std::integral Integer>
|
||||||
|
requires(!std::same_as<Integer, bool>)
|
||||||
|
OptionValue(Integer integer) : value{std::int64_t{0}} {
|
||||||
|
if (!std::in_range<std::int64_t>(integer)) {
|
||||||
|
throw std::invalid_argument{"option integer is out of range"};
|
||||||
|
}
|
||||||
|
value = static_cast<std::int64_t>(integer);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
using OptionMap = std::map<std::string, OptionValue, std::less<>>;
|
||||||
|
|
||||||
|
struct Commit {
|
||||||
|
std::string sha;
|
||||||
|
};
|
||||||
|
struct IncludeDirectory {
|
||||||
|
std::string path;
|
||||||
|
Visibility visibility{Visibility::Private};
|
||||||
|
bool is_system{false};
|
||||||
|
};
|
||||||
|
struct ScopedOption {
|
||||||
|
std::string value;
|
||||||
|
Visibility visibility{Visibility::Private};
|
||||||
|
};
|
||||||
|
struct LinkRecord {
|
||||||
|
LinkKind kind;
|
||||||
|
std::string target;
|
||||||
|
std::string dependency; // Empty for a local target.
|
||||||
|
Visibility visibility{Visibility::Private};
|
||||||
|
};
|
||||||
|
struct PerFileOption {
|
||||||
|
std::string source_path;
|
||||||
|
std::string option;
|
||||||
|
};
|
||||||
|
struct InstallRule {
|
||||||
|
std::string target_name;
|
||||||
|
std::string source_path;
|
||||||
|
std::string destination;
|
||||||
|
std::string component{"default"};
|
||||||
|
bool is_directory{false};
|
||||||
|
};
|
||||||
|
struct TargetRecord {
|
||||||
|
std::string name;
|
||||||
|
TargetKind kind;
|
||||||
|
std::vector<SourceRecord> sources;
|
||||||
|
std::vector<IncludeDirectory> include_directories;
|
||||||
|
std::vector<std::string> compile_options;
|
||||||
|
std::vector<LinkRecord> links;
|
||||||
|
std::vector<ScopedOption> scoped_compile_options;
|
||||||
|
std::vector<ScopedOption> defines;
|
||||||
|
std::vector<ScopedOption> link_options;
|
||||||
|
std::vector<std::string> prerequisites;
|
||||||
|
CxxStandard cxx_standard{CxxStandard::Default};
|
||||||
|
std::string precompiled_header;
|
||||||
|
bool unity_enabled{false};
|
||||||
|
std::size_t unity_batch_size{8};
|
||||||
|
LtoMode lto{LtoMode::None};
|
||||||
|
std::vector<Sanitizer> sanitizers;
|
||||||
|
std::vector<PerFileOption> per_file_options;
|
||||||
|
std::vector<std::string> command_argv;
|
||||||
|
std::vector<std::string> action_inputs;
|
||||||
|
std::vector<std::string> action_outputs;
|
||||||
|
std::string working_directory;
|
||||||
|
std::map<std::string, std::string, std::less<>> environment;
|
||||||
|
bool nondeterministic{false};
|
||||||
|
bool enabled{true};
|
||||||
|
bool use_conventional_sources{false};
|
||||||
|
std::optional<InstallRule> install_rule;
|
||||||
|
};
|
||||||
|
struct DependencyRecord {
|
||||||
|
std::string name;
|
||||||
|
DependencySourceKind source_kind{DependencySourceKind::Unspecified};
|
||||||
|
std::string location;
|
||||||
|
std::string revision;
|
||||||
|
std::string package;
|
||||||
|
std::string version;
|
||||||
|
std::string builder;
|
||||||
|
OptionMap options;
|
||||||
|
std::string registry_authority;
|
||||||
|
std::string sha256;
|
||||||
|
std::vector<std::string> features;
|
||||||
|
bool build_dependency{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace detail {
|
||||||
|
struct ProjectState;
|
||||||
|
}
|
||||||
|
class Project;
|
||||||
|
class Dependency;
|
||||||
|
|
||||||
|
// Handles retain an index and weak owner identity, never a pointer into a growing vector.
|
||||||
|
class ImportedTarget {
|
||||||
|
private:
|
||||||
|
friend class Dependency;
|
||||||
|
friend class Target;
|
||||||
|
ImportedTarget(std::weak_ptr<detail::ProjectState> owner, std::size_t dependency,
|
||||||
|
std::string name);
|
||||||
|
std::weak_ptr<detail::ProjectState> owner_;
|
||||||
|
std::size_t dependency_;
|
||||||
|
std::string name_;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Target {
|
||||||
|
public:
|
||||||
|
Target &sources(const SourceSet &sources);
|
||||||
|
Target &conventional_sources();
|
||||||
|
Target &module_sources(const SourceSet &sources);
|
||||||
|
Target &header_unit(std::string header_path);
|
||||||
|
Target &include_directory(std::string path, Visibility visibility = Visibility::Private);
|
||||||
|
Target &system_include_directory(std::string path, Visibility visibility = Visibility::Private);
|
||||||
|
Target &compile_option(std::string option);
|
||||||
|
Target &compile_option(std::string option, Visibility visibility);
|
||||||
|
Target &define(std::string macro, Visibility visibility = Visibility::Private);
|
||||||
|
Target &link_option(std::string option, Visibility visibility = Visibility::Private);
|
||||||
|
Target &link(const Target &target, Visibility visibility = Visibility::Private);
|
||||||
|
Target &link(const ImportedTarget &target, Visibility visibility = Visibility::Private);
|
||||||
|
Target &depends_on(const Target &producer);
|
||||||
|
Target &cxx_standard(CxxStandard standard);
|
||||||
|
Target &precompiled_header(std::string header_path);
|
||||||
|
Target &unity_build(bool enabled, std::size_t batch_size = 8);
|
||||||
|
Target <o(LtoMode mode);
|
||||||
|
Target &sanitizer(Sanitizer sanitizer);
|
||||||
|
Target &per_file_option(std::string source_path, std::string option);
|
||||||
|
Target &command(std::vector<std::string> argv);
|
||||||
|
Target &inputs(std::vector<std::string> paths);
|
||||||
|
Target &outputs(std::vector<std::string> paths);
|
||||||
|
Target &working_directory(std::string directory);
|
||||||
|
Target &env(std::string key, std::string value);
|
||||||
|
Target &nondeterministic(bool enabled = true);
|
||||||
|
Target &enabled(bool flag);
|
||||||
|
Target &install(std::string destination = {}, std::string component = "default");
|
||||||
|
[[nodiscard]] const TargetRecord &record() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
friend class Project;
|
||||||
|
Target(std::weak_ptr<detail::ProjectState> owner, std::size_t index);
|
||||||
|
std::weak_ptr<detail::ProjectState> owner_;
|
||||||
|
std::size_t index_;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Dependency {
|
||||||
|
public:
|
||||||
|
Dependency &git(std::string url, Commit commit);
|
||||||
|
Dependency &path(std::string local_path);
|
||||||
|
Dependency &archive(std::string url, std::string sha256);
|
||||||
|
Dependency &cmake(OptionMap options = {});
|
||||||
|
Dependency &meson(OptionMap options = {});
|
||||||
|
Dependency &conan(std::string reference, OptionMap options = {});
|
||||||
|
Dependency &native_builder(OptionMap options = {});
|
||||||
|
Dependency &package(std::string id, std::string range);
|
||||||
|
Dependency ®istry(std::string authority_url);
|
||||||
|
Dependency &feature(std::string name);
|
||||||
|
Dependency &build_dependency(bool is_build_tool = true);
|
||||||
|
[[nodiscard]] ImportedTarget target(std::string exported_name) const;
|
||||||
|
[[nodiscard]] const DependencyRecord &record() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
friend class Project;
|
||||||
|
Dependency(std::weak_ptr<detail::ProjectState> owner, std::size_t index);
|
||||||
|
std::weak_ptr<detail::ProjectState> owner_;
|
||||||
|
std::size_t index_;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Project {
|
||||||
|
public:
|
||||||
|
explicit Project(ProfileContext context);
|
||||||
|
~Project();
|
||||||
|
Project(const Project &) = delete;
|
||||||
|
Project &operator=(const Project &) = delete;
|
||||||
|
Project(Project &&) = delete;
|
||||||
|
Project &operator=(Project &&) = delete;
|
||||||
|
|
||||||
|
[[nodiscard]] const ProfileContext &context() const noexcept;
|
||||||
|
[[nodiscard]] Target executable(std::string name);
|
||||||
|
[[nodiscard]] Target static_library(std::string name);
|
||||||
|
[[nodiscard]] Target shared_library(std::string name);
|
||||||
|
[[nodiscard]] Target header_only_library(std::string name);
|
||||||
|
[[nodiscard]] Target object_library(std::string name);
|
||||||
|
[[nodiscard]] Target custom_action(std::string name);
|
||||||
|
[[nodiscard]] Target test(std::string name);
|
||||||
|
[[nodiscard]] Dependency dependency(std::string name);
|
||||||
|
void dependencies_file(std::string toml_path = "vbs.deps.toml");
|
||||||
|
void install_file(std::string source_path, std::string destination,
|
||||||
|
std::string component = "default");
|
||||||
|
void install_directory(std::string source_path, std::string destination,
|
||||||
|
std::string component = "default");
|
||||||
|
[[nodiscard]] SourceSet glob(std::string pattern) const;
|
||||||
|
[[nodiscard]] const std::vector<TargetRecord> &targets() const noexcept;
|
||||||
|
[[nodiscard]] const std::vector<DependencyRecord> &dependencies() const noexcept;
|
||||||
|
[[nodiscard]] const std::vector<std::string> &dependency_files() const noexcept;
|
||||||
|
[[nodiscard]] const std::vector<InstallRule> &install_rules() const noexcept;
|
||||||
|
// Emits UTF-8 JSON; malformed UTF-8 in any recorded string throws invalid_argument.
|
||||||
|
[[nodiscard]] std::string to_json() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
Target add_target(std::string name, TargetKind kind);
|
||||||
|
std::shared_ptr<detail::ProjectState> state_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Build
|
||||||
|
|
||||||
|
// Description entry points supplied by ordinary user C++ translation units.
|
||||||
|
void build(Void::Build::Project &project);
|
||||||
|
void profiles(Void::Build::Profiles &profiles);
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
|
namespace Void::Build::Bridge {
|
||||||
|
|
||||||
|
// Executes a structured CMake-bridge request (`vbs bridge --request <json> --output <cmake>`)
|
||||||
|
// resolving/fetching/building requested dependencies (native, CMake, Meson, Conan) and emitting
|
||||||
|
// imported CMake targets with full transitive usage requirements and reentry-cycle detection (Plan
|
||||||
|
// 14).
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
execute_cmake_bridge(const std::filesystem::path &request_json_path,
|
||||||
|
const std::filesystem::path &output_cmake_path);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Bridge
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Graph/Graph.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Config {
|
||||||
|
|
||||||
|
inline constexpr int kFrontendProtocolVersion = 1;
|
||||||
|
|
||||||
|
struct FrontendOptions {
|
||||||
|
std::filesystem::path project_root;
|
||||||
|
std::filesystem::path build_root;
|
||||||
|
std::filesystem::path sdk_include_dir;
|
||||||
|
std::filesystem::path sdk_library_path; // Optional prebuilt libVoidBuild_Sdk.a
|
||||||
|
std::filesystem::path sdk_source_dir; // Fallback source dir if sdk_library_path absent
|
||||||
|
std::vector<std::filesystem::path> extra_build_sources; // Explicit --build-source inputs
|
||||||
|
std::optional<std::filesystem::path> host_compiler;
|
||||||
|
std::chrono::milliseconds eval_timeout{std::chrono::seconds{30}};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CompiledDescriptor {
|
||||||
|
std::filesystem::path executable_path;
|
||||||
|
std::string seed_identity_hash;
|
||||||
|
std::vector<std::filesystem::path> config_sources;
|
||||||
|
std::vector<std::filesystem::path> discovered_headers;
|
||||||
|
bool recompiled{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Discovers configuration C++ sources purely from filesystem membership (works without .git!):
|
||||||
|
// build.cpp, optional build.profiles.cpp, sorted build-support/**/*.cpp, and explicit extra
|
||||||
|
// sources.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||||
|
discover_config_sources(const std::filesystem::path &project_root,
|
||||||
|
const std::vector<std::filesystem::path> &extra_build_sources = {});
|
||||||
|
|
||||||
|
// Compiles (or reuses cached valid) host configuration descriptor executable against
|
||||||
|
// the fixed Void::Build SDK without invoking CMake or resolving project packages.
|
||||||
|
[[nodiscard]] Void::Result::Result<CompiledDescriptor, Void::Result::Error>
|
||||||
|
compile_descriptor(const FrontendOptions &options);
|
||||||
|
|
||||||
|
// Invokes the compiled descriptor in profile-discovery mode, returning declared Profiles
|
||||||
|
// (or default debug/release profiles if build.profiles.cpp is absent).
|
||||||
|
[[nodiscard]] Void::Result::Result<Profiles, Void::Result::Error>
|
||||||
|
discover_profiles(const CompiledDescriptor &descriptor, const FrontendOptions &options);
|
||||||
|
|
||||||
|
// Evaluates build(Project&) out-of-process for a single resolved ProfileContext using a
|
||||||
|
// dedicated bounded result file (logs on stdout/stderr cannot corrupt protocol results).
|
||||||
|
[[nodiscard]] Void::Result::Result<Graph::ProjectDescription, Void::Result::Error>
|
||||||
|
evaluate_project(const CompiledDescriptor &descriptor, const ProfileContext &context,
|
||||||
|
const FrontendOptions &options);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Config
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build/Graph/Graph.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Editor {
|
||||||
|
|
||||||
|
struct EditorCommandEntry {
|
||||||
|
std::filesystem::path directory;
|
||||||
|
std::filesystem::path file;
|
||||||
|
std::filesystem::path output;
|
||||||
|
std::vector<std::string> arguments;
|
||||||
|
std::string target_name;
|
||||||
|
std::vector<std::filesystem::path> missing_generated_prerequisites;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class GenerationStatus { Valid, Stale, Invalid };
|
||||||
|
|
||||||
|
struct EditorGeneration {
|
||||||
|
std::string generation_id;
|
||||||
|
std::string profile_name;
|
||||||
|
std::string profile_identity;
|
||||||
|
GenerationStatus status{GenerationStatus::Valid};
|
||||||
|
std::string diagnostic;
|
||||||
|
std::filesystem::path compdb_path;
|
||||||
|
std::size_t entry_count{0};
|
||||||
|
std::vector<std::string> readiness_warnings;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SelectionState {
|
||||||
|
std::uint64_t ticket{0};
|
||||||
|
std::string selected_profile;
|
||||||
|
std::filesystem::path selected_build_root;
|
||||||
|
std::string selected_generation_id;
|
||||||
|
std::filesystem::path selected_compdb_path;
|
||||||
|
bool managed_root_alias_active{false};
|
||||||
|
std::string root_alias_warning;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PublishOptions {
|
||||||
|
std::filesystem::path project_root;
|
||||||
|
std::filesystem::path build_root;
|
||||||
|
bool update_selection{false}; // False for watchers (never steal selection!).
|
||||||
|
std::optional<std::uint64_t> reserved_ticket;
|
||||||
|
bool manage_project_root_alias{true};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Projects all compile actions across ALL configured enabled targets in `graph`
|
||||||
|
// onto editable logical source paths and immutable generated views (Plan 09).
|
||||||
|
// Never string-replaces arbitrary flags or macro definitions.
|
||||||
|
[[nodiscard]] std::vector<EditorCommandEntry>
|
||||||
|
project_editor_commands(const Graph::BuildGraph &graph);
|
||||||
|
|
||||||
|
// Formats standard Clang JSONCompilationDatabase array (arguments/file/directory/output).
|
||||||
|
[[nodiscard]] std::string
|
||||||
|
format_compile_commands_json(const std::vector<EditorCommandEntry> &entries);
|
||||||
|
|
||||||
|
// Reserves a monotonically increasing project-level selection ticket under advisory lock.
|
||||||
|
// Single-profile builds reserve on acceptance; manual `vbs compdb use` reserves a newer ticket.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::uint64_t, Void::Result::Error>
|
||||||
|
reserve_selection_ticket(const std::filesystem::path &project_root,
|
||||||
|
const std::filesystem::path &build_root, std::string_view profile_name);
|
||||||
|
|
||||||
|
// Publishes an immutable per-profile editor generation atomically. Updates active build-root
|
||||||
|
// and managed project-root pointers ONLY if `options.update_selection` is true and no newer
|
||||||
|
// ticket has superseded `options.reserved_ticket`. Never overwrites an unrelated user-owned file.
|
||||||
|
[[nodiscard]] Void::Result::Result<EditorGeneration, Void::Result::Error>
|
||||||
|
publish_profile_compdb(const Graph::BuildGraph &graph, const PublishOptions &options);
|
||||||
|
|
||||||
|
// Marks a profile's editor metadata as stale/invalid while retaining the last valid
|
||||||
|
// compile_commands.json intact and clearly identifiable as stale.
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
mark_profile_stale(const std::filesystem::path &build_root, std::string_view profile_name,
|
||||||
|
GenerationStatus status, std::string_view diagnostic);
|
||||||
|
|
||||||
|
// Explicitly switches editor selection to an already-published profile (`vbs compdb use`).
|
||||||
|
[[nodiscard]] Void::Result::Result<SelectionState, Void::Result::Error>
|
||||||
|
select_editor_profile(const std::filesystem::path &project_root,
|
||||||
|
const std::filesystem::path &build_root, std::string_view profile_name,
|
||||||
|
bool manage_project_root_alias = true);
|
||||||
|
|
||||||
|
// Reads authoritative selection state and repairs stale filesystem pointers after crashes.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<SelectionState>, Void::Result::Error>
|
||||||
|
read_selection_state(const std::filesystem::path &project_root);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
recover_editor_pointers(const std::filesystem::path &project_root);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Editor
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build/Graph/Graph.hpp>
|
||||||
|
#include <Void/Build/State/StateStore.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <functional>
|
||||||
|
#include <stop_token>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Execution {
|
||||||
|
|
||||||
|
struct ActionExecutionResult {
|
||||||
|
std::string action_id;
|
||||||
|
std::string target_name;
|
||||||
|
bool succeeded{false};
|
||||||
|
bool from_cache{false};
|
||||||
|
bool cancelled{false};
|
||||||
|
bool timed_out{false};
|
||||||
|
int exit_code{-1};
|
||||||
|
int term_signal{0};
|
||||||
|
std::string stdout_data;
|
||||||
|
std::string stderr_data;
|
||||||
|
std::string error_message;
|
||||||
|
std::chrono::milliseconds elapsed{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ExecutionEvent {
|
||||||
|
enum class Kind { ActionStarted, ActionCached, ActionSucceeded, ActionFailed };
|
||||||
|
Kind kind{Kind::ActionStarted};
|
||||||
|
std::string action_id;
|
||||||
|
std::string target_name;
|
||||||
|
std::size_t completed{0};
|
||||||
|
std::size_t total{0};
|
||||||
|
std::string message;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ExecutionOptions {
|
||||||
|
std::size_t jobs{0}; // 0 = hardware_concurrency (clamped >= 1)
|
||||||
|
bool fail_fast{true};
|
||||||
|
bool use_cache{true};
|
||||||
|
std::vector<std::string> selected_targets;
|
||||||
|
std::chrono::milliseconds action_timeout{0};
|
||||||
|
std::function<void(const ExecutionEvent &)> on_event;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ExecutionReport {
|
||||||
|
bool succeeded{false};
|
||||||
|
bool cancelled{false};
|
||||||
|
std::size_t total_selected{0};
|
||||||
|
std::size_t executed_count{0};
|
||||||
|
std::size_t cached_count{0};
|
||||||
|
std::size_t failed_count{0};
|
||||||
|
std::vector<ActionExecutionResult> results;
|
||||||
|
std::string diagnostic;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Parses a GCC/Clang GNU Make depfile (.d) into its list of dependency file paths.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||||
|
parse_depfile(const std::filesystem::path &depfile_path);
|
||||||
|
|
||||||
|
// Executes the selected action closure of `graph` with bounded parallelism,
|
||||||
|
// per-profile serialization, immutable CAS verification, depfile tracking, and cancellation.
|
||||||
|
[[nodiscard]] Void::Result::Result<ExecutionReport, Void::Result::Error>
|
||||||
|
execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||||
|
const ExecutionOptions &options = {}, std::stop_token stop = {});
|
||||||
|
|
||||||
|
} // namespace Void::Build::Execution
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||||
|
#include <Void/Build/Toolchain/Driver.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Graph {
|
||||||
|
|
||||||
|
struct ProjectDescription {
|
||||||
|
int schema_version{1};
|
||||||
|
ProfileContext profile;
|
||||||
|
std::vector<TargetRecord> targets;
|
||||||
|
std::vector<DependencyRecord> dependencies;
|
||||||
|
std::vector<std::string> dependency_files;
|
||||||
|
std::vector<InstallRule> install_rules;
|
||||||
|
|
||||||
|
[[nodiscard]] static Void::Result::Result<ProjectDescription, Void::Result::Error>
|
||||||
|
from_json(std::string_view json_text);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Typed consumer interface supplied by a foreign/native package provider (Plan 13).
|
||||||
|
struct ImportedTargetInterface {
|
||||||
|
std::string dependency_name;
|
||||||
|
std::string target_name;
|
||||||
|
std::vector<std::pair<std::filesystem::path, bool>> include_dirs; // (abs path, is_system)
|
||||||
|
std::vector<std::string> defines;
|
||||||
|
std::vector<std::string> compile_options;
|
||||||
|
std::vector<std::string> link_options;
|
||||||
|
std::vector<std::filesystem::path> static_libraries;
|
||||||
|
std::vector<std::filesystem::path> shared_libraries;
|
||||||
|
std::vector<std::filesystem::path> runtime_files;
|
||||||
|
std::vector<std::filesystem::path> generated_prerequisites;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class ActionKind {
|
||||||
|
Compile,
|
||||||
|
PrecompiledHeader,
|
||||||
|
HeaderUnit,
|
||||||
|
ModuleScan,
|
||||||
|
ModuleBmi,
|
||||||
|
Archive,
|
||||||
|
Link,
|
||||||
|
Custom
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ActionNode {
|
||||||
|
std::string id;
|
||||||
|
ActionKind kind{ActionKind::Compile};
|
||||||
|
std::string target_name;
|
||||||
|
std::filesystem::path executable;
|
||||||
|
std::vector<std::string> arguments;
|
||||||
|
std::map<std::string, std::string, std::less<>> environment;
|
||||||
|
std::filesystem::path working_directory;
|
||||||
|
std::optional<std::filesystem::path> response_file;
|
||||||
|
std::string response_file_content;
|
||||||
|
|
||||||
|
std::vector<std::filesystem::path> declared_inputs;
|
||||||
|
std::vector<std::filesystem::path> declared_outputs;
|
||||||
|
std::optional<std::filesystem::path> depfile;
|
||||||
|
|
||||||
|
// Structured metadata for Editor Compilation Database projection (Plan 09) and lookup guards.
|
||||||
|
std::filesystem::path logical_source_file;
|
||||||
|
std::filesystem::path physical_source_file;
|
||||||
|
std::filesystem::path logical_output_file;
|
||||||
|
std::filesystem::path physical_output_file;
|
||||||
|
std::vector<std::pair<std::filesystem::path, bool>> logical_include_dirs;
|
||||||
|
std::vector<std::pair<std::filesystem::path, bool>> physical_include_dirs;
|
||||||
|
std::vector<std::string> defines;
|
||||||
|
std::vector<std::string> compile_options;
|
||||||
|
CxxStandard cxx_standard{CxxStandard::Default};
|
||||||
|
LtoMode lto{LtoMode::None};
|
||||||
|
std::vector<Sanitizer> sanitizers;
|
||||||
|
bool position_independent{false};
|
||||||
|
std::optional<std::filesystem::path> precompiled_header;
|
||||||
|
|
||||||
|
std::vector<std::string> dependencies; // Action IDs that must precede this node.
|
||||||
|
bool nondeterministic{false};
|
||||||
|
bool cacheable{true};
|
||||||
|
std::string action_key;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ResolvedTargetSummary {
|
||||||
|
std::string name;
|
||||||
|
TargetKind kind{TargetKind::Executable};
|
||||||
|
bool enabled{true};
|
||||||
|
std::vector<std::filesystem::path> expanded_sources;
|
||||||
|
std::vector<std::filesystem::path> primary_outputs;
|
||||||
|
std::vector<std::filesystem::path> runtime_shared_libraries;
|
||||||
|
std::vector<std::string> action_ids;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct BuildGraph {
|
||||||
|
ProfileContext profile;
|
||||||
|
Toolchain::ToolchainCapabilities toolchain;
|
||||||
|
std::string profile_identity;
|
||||||
|
std::filesystem::path project_root;
|
||||||
|
std::filesystem::path profile_build_dir;
|
||||||
|
std::filesystem::path snapshot_materialized_root;
|
||||||
|
std::string snapshot_id;
|
||||||
|
std::vector<ResolvedTargetSummary> targets;
|
||||||
|
std::vector<ActionNode> actions; // Topologically ordered!
|
||||||
|
std::map<std::string, std::size_t, std::less<>> action_index_by_id;
|
||||||
|
|
||||||
|
// Returns the exact ordered action subset required to build `selected_targets`
|
||||||
|
// (empty = all enabled targets).
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<std::size_t>, Void::Result::Error>
|
||||||
|
select_action_closure(const std::vector<std::string> &selected_targets) const;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GraphLowerOptions {
|
||||||
|
std::filesystem::path project_root;
|
||||||
|
std::filesystem::path build_root;
|
||||||
|
const Snapshot::InputSnapshot *snapshot{nullptr};
|
||||||
|
std::map<std::string, ImportedTargetInterface, std::less<>> imported_targets;
|
||||||
|
std::size_t response_file_threshold{32768};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Matches a POSIX-style glob pattern (*, **, ?) against a relative posix path.
|
||||||
|
[[nodiscard]] bool match_glob(std::string_view pattern, std::string_view path) noexcept;
|
||||||
|
|
||||||
|
// Deterministically expands a glob pattern under project_root, excluding build outputs,
|
||||||
|
// VCS metadata, secrets, and configuration sources.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||||
|
expand_glob(const std::filesystem::path &project_root, std::string_view pattern);
|
||||||
|
|
||||||
|
// Validates target graph, resolves public/private/interface compile & link usage
|
||||||
|
// requirements, lowers all targets to topologically ordered actions, and rejects
|
||||||
|
// cycles, output collisions, and source/output overlaps.
|
||||||
|
[[nodiscard]] Void::Result::Result<BuildGraph, Void::Result::Error>
|
||||||
|
lower_project_graph(const ProjectDescription &description,
|
||||||
|
const Toolchain::ToolchainCapabilities &toolchain,
|
||||||
|
const GraphLowerOptions &options);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Graph
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Graph/Graph.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Install {
|
||||||
|
|
||||||
|
struct InstallOptions {
|
||||||
|
std::string package_name;
|
||||||
|
std::string package_version{"0.1.0"};
|
||||||
|
std::filesystem::path prefix;
|
||||||
|
std::optional<std::string> component; // Empty = install all components
|
||||||
|
bool export_cmake_config{true};
|
||||||
|
bool export_native_metadata{true};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct InstallReport {
|
||||||
|
std::filesystem::path prefix;
|
||||||
|
std::filesystem::path manifest_path;
|
||||||
|
std::vector<std::filesystem::path> installed_files;
|
||||||
|
std::optional<std::filesystem::path> cmake_config_file;
|
||||||
|
std::optional<std::filesystem::path> native_package_file;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Installs declared targets, files, headers, and relocatable native + CMake export
|
||||||
|
// metadata into `options.prefix` via managed staging and an ownership manifest (Plan 15).
|
||||||
|
// Rejects path traversal, destination collisions, and build-tree path leaks.
|
||||||
|
[[nodiscard]] Void::Result::Result<InstallReport, Void::Result::Error>
|
||||||
|
install_project(const Graph::ProjectDescription &description, const Graph::BuildGraph &graph,
|
||||||
|
const InstallOptions &options);
|
||||||
|
|
||||||
|
// Safely removes ONLY files owned by VBS in `<prefix>/.vbs-install-manifest.json`,
|
||||||
|
// preserving all unrelated user files in the prefix!
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t, Void::Result::Error>
|
||||||
|
uninstall_prefix(const std::filesystem::path &prefix);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Install
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Toolchain/Driver.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Modules {
|
||||||
|
|
||||||
|
struct ModuleScanUnit {
|
||||||
|
std::filesystem::path source_file;
|
||||||
|
std::vector<std::string> provides; // Logical module/partition names provided by this TU.
|
||||||
|
std::vector<std::string>
|
||||||
|
required_modules; // Logical module/partition names imported by this TU.
|
||||||
|
bool is_interface{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CollatedModuleNode {
|
||||||
|
std::filesystem::path source_file;
|
||||||
|
std::vector<std::string> provides;
|
||||||
|
std::vector<std::string> required_modules;
|
||||||
|
std::filesystem::path bmi_output_path;
|
||||||
|
std::filesystem::path module_mapper_path; // For GCC -fmodule-mapper
|
||||||
|
std::vector<std::pair<std::string, std::filesystem::path>> imported_bmis;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CollatedModulePlan {
|
||||||
|
// Topologically sorted: every provider precedes all of its importers.
|
||||||
|
std::vector<CollatedModuleNode> ordered_units;
|
||||||
|
std::map<std::string, std::filesystem::path, std::less<>> module_to_bmi;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Parses official P1689r5 JSON output emitted by GCC (`-fdeps-format=p1689r5`) or
|
||||||
|
// `clang-scan-deps`.
|
||||||
|
[[nodiscard]] Void::Result::Result<ModuleScanUnit, Void::Result::Error>
|
||||||
|
parse_p1689_json(std::string_view json_text, const std::filesystem::path &source_file);
|
||||||
|
|
||||||
|
// Scans a C++ translation unit using the real target compiler's P1689 scanner.
|
||||||
|
[[nodiscard]] Void::Result::Result<ModuleScanUnit, Void::Result::Error>
|
||||||
|
scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain,
|
||||||
|
const std::filesystem::path &source_file,
|
||||||
|
const std::filesystem::path &scratch_dir,
|
||||||
|
const std::vector<std::pair<std::filesystem::path, bool>> &include_dirs,
|
||||||
|
const std::vector<std::string> &defines,
|
||||||
|
const std::vector<std::string> &compile_options, CxxStandard standard);
|
||||||
|
|
||||||
|
// Collates scanned module units into a cycle-free, duplicate-free, missing-import-checked
|
||||||
|
// topological build plan with profile/compiler-isolated BMI paths and GCC mapper files (Plan 08).
|
||||||
|
[[nodiscard]] Void::Result::Result<CollatedModulePlan, Void::Result::Error>
|
||||||
|
collate_modules(const std::vector<ModuleScanUnit> &units, const std::filesystem::path &bmi_root,
|
||||||
|
const std::string &context_isolation_key, std::string_view bmi_extension = ".gcm");
|
||||||
|
|
||||||
|
// Compiles an explicitly declared header unit into an isolated BMI/PCM (Plan 08).
|
||||||
|
[[nodiscard]] Void::Result::Result<Toolchain::LoweredCommand, Void::Result::Error>
|
||||||
|
lower_header_unit_command(const Toolchain::ToolchainCapabilities &toolchain,
|
||||||
|
const std::filesystem::path &header_path,
|
||||||
|
const std::filesystem::path &bmi_output,
|
||||||
|
const std::vector<std::pair<std::filesystem::path, bool>> &include_dirs,
|
||||||
|
const std::vector<std::string> &defines,
|
||||||
|
const std::vector<std::string> &compile_options, CxxStandard standard);
|
||||||
|
|
||||||
|
struct UnityBatchResult {
|
||||||
|
std::vector<std::filesystem::path> generated_unity_files;
|
||||||
|
std::vector<std::filesystem::path>
|
||||||
|
standalone_files; // Modules & per-file-option files excluded!
|
||||||
|
};
|
||||||
|
|
||||||
|
// Generates deterministic unity batches excluding module TUs and per-file-override TUs (Plan 08).
|
||||||
|
[[nodiscard]] Void::Result::Result<UnityBatchResult, Void::Result::Error>
|
||||||
|
generate_unity_batches(const std::string &target_name,
|
||||||
|
const std::vector<std::filesystem::path> &sources,
|
||||||
|
const std::vector<std::filesystem::path> &excluded_sources,
|
||||||
|
std::size_t batch_size, const std::filesystem::path &unity_dir);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Modules
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
|
||||||
|
struct ArchiveLimits {
|
||||||
|
std::size_t max_entries{10000};
|
||||||
|
std::uint64_t max_file_bytes{512ULL * 1024ULL * 1024ULL};
|
||||||
|
std::uint64_t max_total_bytes{2ULL * 1024ULL * 1024ULL * 1024ULL};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ArchiveExtractionStats {
|
||||||
|
std::size_t entries{0};
|
||||||
|
std::uint64_t total_bytes{0};
|
||||||
|
std::vector<std::filesystem::path> extracted_files;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ArchiveEntrySpec {
|
||||||
|
std::string archive_path; // Relative POSIX path inside archive.
|
||||||
|
std::filesystem::path source_file;
|
||||||
|
std::uint32_t mode{0644};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Creates a byte-deterministic USTAR/PAX tar archive (canonical mtime/uid/gid, sorted entries)
|
||||||
|
// and returns its SHA-256 hex digest (VL-006).
|
||||||
|
[[nodiscard]] 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 = 0);
|
||||||
|
|
||||||
|
// Packages a VBS project's source tree cleanly (retaining build.cpp, optional build.profiles.cpp,
|
||||||
|
// build-support/**, and declared sources/headers while excluding .git, build/, .vbs/, secrets).
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string, Void::Result::Error>
|
||||||
|
create_source_package(const std::filesystem::path &project_root,
|
||||||
|
const std::filesystem::path &output_tar,
|
||||||
|
std::int64_t reproducibility_epoch = 0);
|
||||||
|
|
||||||
|
// Extracts a tar archive with strict security checks:
|
||||||
|
// rejects absolute paths, '..' traversal, symlinks/hardlinks/special files, duplicate paths,
|
||||||
|
// and count/size quota overflows. Stages privately and publishes atomically only on full success.
|
||||||
|
[[nodiscard]] 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 = {});
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Package/Archive.hpp>
|
||||||
|
#include <Void/Build/Package/Solver.hpp>
|
||||||
|
#include <Void/Build/Toolchain/Driver.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
|
||||||
|
struct BinaryCompatibilityKey {
|
||||||
|
std::string os;
|
||||||
|
std::string architecture;
|
||||||
|
std::string compiler_family;
|
||||||
|
std::string compiler_abi;
|
||||||
|
std::string stdlib_abi;
|
||||||
|
std::string linkage; // "static" or "shared"
|
||||||
|
std::string cpu_features;
|
||||||
|
std::string sanitizers_key;
|
||||||
|
std::string lto_mode;
|
||||||
|
std::string dependency_closure_hash;
|
||||||
|
|
||||||
|
[[nodiscard]] std::string compute_key_hash() const;
|
||||||
|
[[nodiscard]] bool matches(const BinaryVariantMeta &candidate) const noexcept;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FetchOptions {
|
||||||
|
std::filesystem::path cache_dir;
|
||||||
|
std::filesystem::path project_root;
|
||||||
|
bool offline{false};
|
||||||
|
ArchiveLimits archive_limits;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct MaterializedSource {
|
||||||
|
std::string alias;
|
||||||
|
std::filesystem::path source_dir;
|
||||||
|
std::string content_identity_hash;
|
||||||
|
bool from_cache{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Redacts credentials from URLs and bearer headers before logging/diagnostics.
|
||||||
|
[[nodiscard]] std::string redact_secrets(std::string_view text);
|
||||||
|
|
||||||
|
// Computes strict binary compatibility key from profile, toolchain, linkage, and dep closure.
|
||||||
|
[[nodiscard]] BinaryCompatibilityKey
|
||||||
|
make_binary_compatibility_key(const ProfileContext &profile,
|
||||||
|
const Toolchain::ToolchainCapabilities &toolchain,
|
||||||
|
std::string_view linkage, std::string_view dependency_closure_hash);
|
||||||
|
|
||||||
|
// Selects an exact compatible binary variant, returning nullopt on any ABI/CPU/sanitizer/LTO
|
||||||
|
// or dependency-closure mismatch (never optimistically selects incompatible binaries!).
|
||||||
|
[[nodiscard]] std::optional<BinaryVariantMeta>
|
||||||
|
select_compatible_binary(const BinaryCompatibilityKey &key,
|
||||||
|
const std::vector<BinaryVariantMeta> &available);
|
||||||
|
|
||||||
|
// Acquires and verifies a source dependency (local path, exact pinned Git SHA, or
|
||||||
|
// SHA-256 verified archive) into managed storage without ever modifying external checkouts.
|
||||||
|
[[nodiscard]] Void::Result::Result<MaterializedSource, Void::Result::Error>
|
||||||
|
materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &options);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Package/Solver.hpp>
|
||||||
|
#include <Void/Build/Package/Toml.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
|
||||||
|
inline constexpr int kLockfileSchemaVersion = 1;
|
||||||
|
|
||||||
|
struct LockedSourceEntry {
|
||||||
|
std::string alias;
|
||||||
|
std::string source_kind; // "git", "package", "path", "archive", "conan"
|
||||||
|
std::string registry_authority;
|
||||||
|
std::string package_name;
|
||||||
|
std::string version;
|
||||||
|
std::string location;
|
||||||
|
std::string revision;
|
||||||
|
std::string sha256;
|
||||||
|
std::string builder;
|
||||||
|
std::vector<std::string> features;
|
||||||
|
bool build_dependency{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LockContextRecord {
|
||||||
|
std::string context_key; // e.g. "debug:gcc:Linux:x86_64:target"
|
||||||
|
std::string profile_name;
|
||||||
|
std::string compiler;
|
||||||
|
std::string os;
|
||||||
|
std::string architecture;
|
||||||
|
std::string machine_role; // "target" or "build"
|
||||||
|
std::string declaration_fingerprint;
|
||||||
|
std::vector<LockedSourceEntry> entries;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LockfileDocument {
|
||||||
|
int schema_version{kLockfileSchemaVersion};
|
||||||
|
std::string revision_hash; // SHA-256 of canonical contexts payload.
|
||||||
|
std::map<std::string, LockContextRecord, std::less<>> contexts;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Immutable lock payload pinned at the start of a build so concurrent updates never mix revisions.
|
||||||
|
struct PinnedLock {
|
||||||
|
std::string revision_hash;
|
||||||
|
std::string raw_json;
|
||||||
|
LockfileDocument document;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Computes canonical declaration fingerprint for a profile/role context (used to detect
|
||||||
|
// incompatible manifest/option changes before running any build action!).
|
||||||
|
[[nodiscard]] std::string
|
||||||
|
compute_declaration_fingerprint(const ProfileContext &profile, std::string_view machine_role,
|
||||||
|
const std::vector<NormalizedDependency> &declarations);
|
||||||
|
|
||||||
|
[[nodiscard]] std::string make_lock_context_key(const ProfileContext &profile,
|
||||||
|
std::string_view machine_role);
|
||||||
|
|
||||||
|
// Serializes and parses vbs.lock deterministically (never stores credentials!).
|
||||||
|
[[nodiscard]] std::string serialize_lockfile(const LockfileDocument &doc);
|
||||||
|
[[nodiscard]] Void::Result::Result<LockfileDocument, Void::Result::Error>
|
||||||
|
parse_lockfile(std::string_view json_text);
|
||||||
|
|
||||||
|
// Reads and pins one immutable lockfile revision from disk (returns nullopt if absent).
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<PinnedLock>, Void::Result::Error>
|
||||||
|
load_pinned_lock(const std::filesystem::path &lock_path);
|
||||||
|
|
||||||
|
// Validates an existing pinned lock against current declarations for `context_key`.
|
||||||
|
// Fails explicitly if declarations/options/platform facts are incompatible (requires
|
||||||
|
// resolve/update).
|
||||||
|
[[nodiscard]] Void::Result::Result<const LockContextRecord *, Void::Result::Error>
|
||||||
|
validate_locked_context(const LockfileDocument &doc, std::string_view context_key,
|
||||||
|
std::string_view expected_declaration_fingerprint);
|
||||||
|
|
||||||
|
// Atomic CAS lockfile publication (D-025 / Plan 11):
|
||||||
|
// Acquires short project mutex (`vbs.lock.mutex`), compares on-disk revision hash against
|
||||||
|
// `expected_base_revision` (empty if creating a new lock), merges `updated_context` without
|
||||||
|
// discarding other profiles' contexts, and atomically replaces `vbs.lock`.
|
||||||
|
// Fails with SystemErrorCode::busy on a competing revision conflict so caller can re-resolve/retry!
|
||||||
|
[[nodiscard]] Void::Result::Result<PinnedLock, Void::Result::Error>
|
||||||
|
publish_lock_context_cas(const std::filesystem::path &lock_path,
|
||||||
|
std::string_view expected_base_revision,
|
||||||
|
const LockContextRecord &updated_context, bool locked_mode = false);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build/Package/Solver.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
|
||||||
|
struct RegistryAuth {
|
||||||
|
std::string bearer_token; // Runtime-only; never written to locks or logs.
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PublishOptions {
|
||||||
|
std::string registry_url;
|
||||||
|
std::string package_name;
|
||||||
|
std::string version;
|
||||||
|
std::filesystem::path archive_path;
|
||||||
|
std::string description;
|
||||||
|
bool is_private{false};
|
||||||
|
RegistryAuth auth;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PublishReceipt {
|
||||||
|
std::string sha256;
|
||||||
|
bool already_published{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Queries GET /api/v1/packages/<name> on a VBS registry and parses all release records
|
||||||
|
// into Package::ReleaseRecord entries ready for PackageIndex + PubGrub solving.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<ReleaseRecord>, Void::Result::Error>
|
||||||
|
fetch_package_releases(std::string_view registry_url, std::string_view package_name,
|
||||||
|
const RegistryAuth &auth = {});
|
||||||
|
|
||||||
|
// Downloads GET /api/v1/packages/<name>/<version>/download, verifies SHA-256 against
|
||||||
|
// `expected_sha256` before atomic publication to `dest_file`.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||||
|
download_release_archive(std::string_view registry_url, std::string_view package_name,
|
||||||
|
std::string_view version, std::string_view expected_sha256,
|
||||||
|
const std::filesystem::path &dest_file, const RegistryAuth &auth = {});
|
||||||
|
|
||||||
|
// Publishes a verified deterministic archive via PUT /api/v1/packages/<name>/<version>.
|
||||||
|
[[nodiscard]] Void::Result::Result<PublishReceipt, Void::Result::Error>
|
||||||
|
publish_package_archive(const PublishOptions &options);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
#include <Void/Text/Semver.hpp>
|
||||||
|
|
||||||
|
#include <compare>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
|
||||||
|
// Registry authority is an explicit part of package identity to prevent cross-registry
|
||||||
|
// substitution.
|
||||||
|
struct PackageId {
|
||||||
|
std::string registry_authority;
|
||||||
|
std::string name;
|
||||||
|
|
||||||
|
auto operator<=>(const PackageId &) const = default;
|
||||||
|
[[nodiscard]] std::string format() const;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct DependencyConstraint {
|
||||||
|
PackageId target;
|
||||||
|
std::string range_expr;
|
||||||
|
std::vector<std::string> required_features;
|
||||||
|
std::string origin_label;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct BinaryVariantMeta {
|
||||||
|
std::string variant_id;
|
||||||
|
std::string os;
|
||||||
|
std::string architecture;
|
||||||
|
std::string compiler_family;
|
||||||
|
std::string compiler_abi;
|
||||||
|
std::string stdlib_abi;
|
||||||
|
std::string linkage;
|
||||||
|
std::string cpu_features;
|
||||||
|
std::string sanitizers_key;
|
||||||
|
std::string lto_mode;
|
||||||
|
std::string dependency_closure_hash;
|
||||||
|
std::string sha256;
|
||||||
|
std::string download_url;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ReleaseRecord {
|
||||||
|
PackageId id;
|
||||||
|
Void::Semver::Version version;
|
||||||
|
bool yanked{false};
|
||||||
|
std::string source_sha256;
|
||||||
|
std::string source_url;
|
||||||
|
std::vector<DependencyConstraint> dependencies;
|
||||||
|
std::vector<BinaryVariantMeta> binaries;
|
||||||
|
};
|
||||||
|
|
||||||
|
class PackageIndex {
|
||||||
|
public:
|
||||||
|
void add_release(ReleaseRecord release);
|
||||||
|
[[nodiscard]] std::vector<ReleaseRecord> releases_for(const PackageId &id) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::map<PackageId, std::vector<ReleaseRecord>> releases_;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SolvedPackage {
|
||||||
|
PackageId id;
|
||||||
|
Void::Semver::Version version;
|
||||||
|
std::string source_sha256;
|
||||||
|
std::string source_url;
|
||||||
|
std::set<std::string> enabled_features;
|
||||||
|
std::vector<PackageId> dependencies;
|
||||||
|
std::vector<BinaryVariantMeta> binaries;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SolveResult {
|
||||||
|
std::map<PackageId, SolvedPackage> packages; // Deterministically ordered.
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SolveOptions {
|
||||||
|
// Already-pinned compatible versions from an existing lockfile (never silently upgraded!).
|
||||||
|
std::map<PackageId, Void::Semver::Version> pinned_versions;
|
||||||
|
bool allow_yanked_if_pinned{true};
|
||||||
|
std::size_t max_steps{50000};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Deterministic PubGrub-style SemVer dependency solver (Plan 11):
|
||||||
|
// - One version per PackageId per resolution context
|
||||||
|
// - Prefers compatible pinned versions; otherwise picks highest non-yanked matching version
|
||||||
|
// - Produces human-readable incompatibility chains on unsatisfiable graphs.
|
||||||
|
[[nodiscard]] Void::Result::Result<SolveResult, Void::Result::Error>
|
||||||
|
solve_dependencies(const std::vector<DependencyConstraint> &root_constraints,
|
||||||
|
const PackageIndex &index, const SolveOptions &options = {});
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <variant>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
|
||||||
|
struct SourceOrigin {
|
||||||
|
std::string file;
|
||||||
|
std::size_t line{0};
|
||||||
|
std::size_t column{0};
|
||||||
|
|
||||||
|
[[nodiscard]] std::string format() const;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TomlValue;
|
||||||
|
using TomlArray = std::vector<TomlValue>;
|
||||||
|
using TomlTable = std::map<std::string, TomlValue, std::less<>>;
|
||||||
|
|
||||||
|
// TOML 1.0 value with source origin metadata (VL-002 adapter; swappable when Void::Data::Toml
|
||||||
|
// lands).
|
||||||
|
struct TomlValue {
|
||||||
|
using Storage = std::variant<std::string, bool, std::int64_t, double,
|
||||||
|
std::shared_ptr<TomlArray>, std::shared_ptr<TomlTable>>;
|
||||||
|
Storage value;
|
||||||
|
SourceOrigin origin;
|
||||||
|
|
||||||
|
[[nodiscard]] bool is_string() const noexcept {
|
||||||
|
return std::holds_alternative<std::string>(value);
|
||||||
|
}
|
||||||
|
[[nodiscard]] bool is_bool() const noexcept { return std::holds_alternative<bool>(value); }
|
||||||
|
[[nodiscard]] bool is_int() const noexcept {
|
||||||
|
return std::holds_alternative<std::int64_t>(value);
|
||||||
|
}
|
||||||
|
[[nodiscard]] bool is_double() const noexcept { return std::holds_alternative<double>(value); }
|
||||||
|
[[nodiscard]] bool is_array() const noexcept {
|
||||||
|
return std::holds_alternative<std::shared_ptr<TomlArray>>(value);
|
||||||
|
}
|
||||||
|
[[nodiscard]] bool is_table() const noexcept {
|
||||||
|
return std::holds_alternative<std::shared_ptr<TomlTable>>(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] const std::string &as_string() const { return std::get<std::string>(value); }
|
||||||
|
[[nodiscard]] bool as_bool() const { return std::get<bool>(value); }
|
||||||
|
[[nodiscard]] std::int64_t as_int() const { return std::get<std::int64_t>(value); }
|
||||||
|
[[nodiscard]] double as_double() const { return std::get<double>(value); }
|
||||||
|
[[nodiscard]] const TomlArray &as_array() const {
|
||||||
|
return *std::get<std::shared_ptr<TomlArray>>(value);
|
||||||
|
}
|
||||||
|
[[nodiscard]] const TomlTable &as_table() const {
|
||||||
|
return *std::get<std::shared_ptr<TomlTable>>(value);
|
||||||
|
}
|
||||||
|
[[nodiscard]] TomlTable &as_table_mut() { return *std::get<std::shared_ptr<TomlTable>>(value); }
|
||||||
|
[[nodiscard]] TomlArray &as_array_mut() { return *std::get<std::shared_ptr<TomlArray>>(value); }
|
||||||
|
|
||||||
|
static TomlValue make_table(SourceOrigin origin = {});
|
||||||
|
static TomlValue make_array(SourceOrigin origin = {});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Parses TOML 1.0 text with exact file:line:col diagnostics and duplicate-key rejection.
|
||||||
|
[[nodiscard]] Void::Result::Result<TomlTable, Void::Result::Error>
|
||||||
|
parse_toml(std::string_view text, std::string_view source_name = "<memory>");
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<TomlTable, Void::Result::Error>
|
||||||
|
parse_toml_file(const std::filesystem::path &path);
|
||||||
|
|
||||||
|
// Canonical deterministic TOML 1.0 serializer.
|
||||||
|
[[nodiscard]] std::string serialize_toml(const TomlTable &table);
|
||||||
|
|
||||||
|
struct NormalizedDependency {
|
||||||
|
DependencyRecord record;
|
||||||
|
SourceOrigin origin;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Loads [dependencies.<alias>] tables from a TOML manifest into the exact same
|
||||||
|
// DependencyRecord model used by C++ project.dependency(...) declarations (Plan 11).
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
|
||||||
|
load_dependencies_toml(const std::filesystem::path &toml_path);
|
||||||
|
|
||||||
|
// Merges C++ inline declarations and TOML-loaded declarations. Rejects contradictory
|
||||||
|
// duplicate aliases/sources/options with both origins clearly diagnosed.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
|
||||||
|
merge_dependencies(const std::vector<DependencyRecord> &cpp_deps,
|
||||||
|
const std::vector<NormalizedDependency> &toml_deps);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <optional>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Platform {
|
||||||
|
|
||||||
|
enum class LockMode { Shared, Exclusive };
|
||||||
|
|
||||||
|
// RAII advisory flock lock (VL-010).
|
||||||
|
class FileLock {
|
||||||
|
public:
|
||||||
|
FileLock() noexcept = default;
|
||||||
|
~FileLock() noexcept;
|
||||||
|
|
||||||
|
FileLock(const FileLock &) = delete;
|
||||||
|
FileLock &operator=(const FileLock &) = delete;
|
||||||
|
FileLock(FileLock &&other) noexcept;
|
||||||
|
FileLock &operator=(FileLock &&other) noexcept;
|
||||||
|
|
||||||
|
[[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;
|
||||||
|
|
||||||
|
private:
|
||||||
|
explicit FileLock(int fd) noexcept : fd_{fd} {}
|
||||||
|
int fd_{-1};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FileMetadata {
|
||||||
|
bool exists{false};
|
||||||
|
bool is_regular{false};
|
||||||
|
bool is_directory{false};
|
||||||
|
bool is_symlink{false};
|
||||||
|
std::uint64_t dev{0};
|
||||||
|
std::uint64_t ino{0};
|
||||||
|
std::uint64_t size{0};
|
||||||
|
std::uint64_t nlink{0};
|
||||||
|
std::uint32_t mode{0};
|
||||||
|
std::int64_t mtime_sec{0};
|
||||||
|
std::int64_t mtime_nsec{0};
|
||||||
|
std::string symlink_target;
|
||||||
|
};
|
||||||
|
|
||||||
|
// lstat wrapper that distinguishes ENOENT (exists=false) from permission/IO errors.
|
||||||
|
[[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.
|
||||||
|
// 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).
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds);
|
||||||
|
|
||||||
|
// Durable atomic file replace (wraps Void::FileSystem::replace_file).
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
atomic_write_file(const std::filesystem::path &path, std::string_view content,
|
||||||
|
bool durable_sync = true, unsigned mode = 0644);
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
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.
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesystem::path &target);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
fsync_directory(const std::filesystem::path &dir_path);
|
||||||
|
|
||||||
|
// Validates that `candidate` stays inside `root` (or one of `allowed_external_roots`)
|
||||||
|
// without symlink loops or directory traversal escapes.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||||
|
resolve_confined_path(const std::filesystem::path &root, const std::filesystem::path &candidate,
|
||||||
|
const std::vector<std::filesystem::path> &allowed_external_roots = {});
|
||||||
|
|
||||||
|
[[nodiscard]] bool path_is_within(const std::filesystem::path &root,
|
||||||
|
const std::filesystem::path &path);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Platform
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <stop_token>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Platform {
|
||||||
|
|
||||||
|
enum class EnvPolicyMode { Inherit, Allowlist, ExplicitOnly };
|
||||||
|
|
||||||
|
struct ProcessEnvironment {
|
||||||
|
EnvPolicyMode mode{EnvPolicyMode::Inherit};
|
||||||
|
std::vector<std::string> allowlist;
|
||||||
|
std::map<std::string, std::string, std::less<>> set_vars;
|
||||||
|
std::vector<std::string> unset_keys;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ProcessRequest {
|
||||||
|
std::filesystem::path executable;
|
||||||
|
std::vector<std::string> arguments; // Does NOT include argv[0]; executable is prepended.
|
||||||
|
std::optional<std::filesystem::path> working_directory;
|
||||||
|
ProcessEnvironment environment;
|
||||||
|
std::string stdin_data;
|
||||||
|
std::size_t max_stdout_bytes{8ULL * 1024ULL * 1024ULL};
|
||||||
|
std::size_t max_stderr_bytes{8ULL * 1024ULL * 1024ULL};
|
||||||
|
bool fail_on_overflow{false};
|
||||||
|
std::chrono::milliseconds timeout{0}; // 0 = no timeout
|
||||||
|
std::chrono::milliseconds kill_grace{200};
|
||||||
|
bool search_path{true};
|
||||||
|
std::function<void(std::string_view)> on_stdout_chunk;
|
||||||
|
std::function<void(std::string_view)> on_stderr_chunk;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ProcessResult {
|
||||||
|
bool exec_failed{false};
|
||||||
|
int exec_errno{0};
|
||||||
|
std::string exec_error_message;
|
||||||
|
bool exited{false};
|
||||||
|
int exit_code{-1};
|
||||||
|
int term_signal{0};
|
||||||
|
bool timed_out{false};
|
||||||
|
bool cancelled{false};
|
||||||
|
bool stdout_truncated{false};
|
||||||
|
bool stderr_truncated{false};
|
||||||
|
bool overflowed{false};
|
||||||
|
std::string stdout_data;
|
||||||
|
std::string stderr_data;
|
||||||
|
|
||||||
|
[[nodiscard]] bool succeeded() const noexcept {
|
||||||
|
return !exec_failed && exited && exit_code == 0 && !timed_out && !cancelled && !overflowed;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Resolves an executable path cleanly using PATH (without invoking a shell).
|
||||||
|
[[nodiscard]] std::optional<std::filesystem::path>
|
||||||
|
resolve_executable(const std::filesystem::path &executable,
|
||||||
|
std::optional<std::string_view> path_override = std::nullopt);
|
||||||
|
|
||||||
|
// Executes a subprocess in its own process group with Linux descendant supervision (VL-001):
|
||||||
|
// - Direct fork/execve (never shell concatenation)
|
||||||
|
// - CLOEXEC error pipe distinguishing exec failure from program exit code 127
|
||||||
|
// - Non-blocking poll-driven stdout/stderr drains with overflow bounds
|
||||||
|
// - On timeout/cancellation/overflow, terminates the ENTIRE process group (-pgid)
|
||||||
|
// via SIGTERM -> grace -> SIGKILL -> poll until ESRCH so stubborn grandchildren
|
||||||
|
// whose group leader already exited cannot outlive the supervisor call.
|
||||||
|
[[nodiscard]] Void::Result::Result<ProcessResult, Void::Result::Error>
|
||||||
|
run_supervised(const ProcessRequest &request, std::stop_token stop = {});
|
||||||
|
|
||||||
|
} // namespace Void::Build::Platform
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Graph/Graph.hpp>
|
||||||
|
#include <Void/Build/Package/Fetch.hpp>
|
||||||
|
#include <Void/Build/Toolchain/Driver.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <stop_token>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Provider {
|
||||||
|
|
||||||
|
enum class ProviderMode { FullBuild, MetadataOnly };
|
||||||
|
|
||||||
|
struct ProviderRequest {
|
||||||
|
DependencyRecord dependency;
|
||||||
|
Package::MaterializedSource source;
|
||||||
|
ProfileContext profile;
|
||||||
|
Toolchain::ToolchainCapabilities toolchain;
|
||||||
|
std::filesystem::path provider_build_root; // Isolated per source/profile/hash
|
||||||
|
ProviderMode mode{ProviderMode::FullBuild};
|
||||||
|
// Explicit typed interface overrides for foreign projects with incomplete metadata.
|
||||||
|
std::map<std::string, Graph::ImportedTargetInterface, std::less<>> explicit_overrides;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ProviderExport {
|
||||||
|
std::string dependency_name;
|
||||||
|
std::string builder;
|
||||||
|
std::string input_identity_hash;
|
||||||
|
bool from_cache{false};
|
||||||
|
bool stale_needs_build{false};
|
||||||
|
std::string stale_diagnostic;
|
||||||
|
std::map<std::string, Graph::ImportedTargetInterface, std::less<>> targets;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Computes complete provider input identity (source content hash, builder, options,
|
||||||
|
// toolchain identity, profile options) so timestamp-preserved edits always invalidate!
|
||||||
|
[[nodiscard]] std::string compute_provider_input_hash(const ProviderRequest &request);
|
||||||
|
|
||||||
|
// Runs or reads cached CMake / Meson / Conan2 foreign provider metadata (Plan 13).
|
||||||
|
// In MetadataOnly mode: strictly reads ONLY validated cached provider-export.json;
|
||||||
|
// NEVER invokes cmake, meson, or conan! Returns stale_needs_build=true on mismatch/miss.
|
||||||
|
[[nodiscard]] Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||||
|
resolve_foreign_provider(const ProviderRequest &request, std::stop_token stop = {});
|
||||||
|
|
||||||
|
} // namespace Void::Build::Provider
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::SelfHost {
|
||||||
|
|
||||||
|
struct DiscoveredTestCase {
|
||||||
|
std::string suite_name;
|
||||||
|
std::string function_name;
|
||||||
|
std::filesystem::path source_file;
|
||||||
|
std::size_t line_number{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GeneratedRegistration {
|
||||||
|
std::filesystem::path generated_cpp;
|
||||||
|
std::vector<DiscoveredTestCase> cases;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Native non-CMake Void::Testing scanner & registration generator (Plan 18 / VL-009).
|
||||||
|
// Uses path-hashed output filenames so equal basenames in different subdirectories
|
||||||
|
// never collide, preserving exact suite/test names and counts without CMake.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<DiscoveredTestCase>, Void::Result::Error>
|
||||||
|
scan_void_tests(const std::filesystem::path &source_file);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<GeneratedRegistration, Void::Result::Error>
|
||||||
|
generate_test_registration_unit(const std::filesystem::path &source_file,
|
||||||
|
const std::filesystem::path &output_dir);
|
||||||
|
|
||||||
|
} // namespace Void::Build::SelfHost
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Snapshot {
|
||||||
|
|
||||||
|
enum class EntryKind { RegularFile, Symlink, Directory };
|
||||||
|
|
||||||
|
struct SnapshotEntry {
|
||||||
|
std::string logical_path;
|
||||||
|
EntryKind kind{EntryKind::RegularFile};
|
||||||
|
std::string sha256;
|
||||||
|
std::uint64_t size{0};
|
||||||
|
std::uint32_t mode{0644};
|
||||||
|
std::string symlink_target;
|
||||||
|
std::filesystem::path materialized_path;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct DirectoryMembership {
|
||||||
|
std::string logical_dir;
|
||||||
|
std::vector<std::string> entries; // Sorted lexicographically.
|
||||||
|
};
|
||||||
|
|
||||||
|
// Tracks header/include search lookup order across include directories so that
|
||||||
|
// a newly created shadowing header or newly true __has_include invalidates consumers.
|
||||||
|
struct LookupGuard {
|
||||||
|
std::vector<std::string> search_roots;
|
||||||
|
std::string lookup_name;
|
||||||
|
int matched_root_index{-1}; // -1 = negative lookup (absent across all search_roots)
|
||||||
|
std::string matched_sha256;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct InputSnapshot {
|
||||||
|
std::string snapshot_id;
|
||||||
|
std::filesystem::path project_root;
|
||||||
|
std::filesystem::path materialized_root;
|
||||||
|
std::int64_t reproducibility_epoch{0};
|
||||||
|
std::map<std::string, SnapshotEntry, std::less<>> entries;
|
||||||
|
std::map<std::string, DirectoryMembership, std::less<>> memberships;
|
||||||
|
std::vector<LookupGuard> lookup_guards;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SnapshotOptions {
|
||||||
|
std::filesystem::path project_root;
|
||||||
|
std::filesystem::path snapshot_store_dir;
|
||||||
|
std::vector<std::filesystem::path> allowed_external_roots;
|
||||||
|
std::vector<std::string> excluded_names{".git", ".vbs", "build", ".serena",
|
||||||
|
".cache", ".env", "keys", "WG.conf"};
|
||||||
|
std::int64_t reproducibility_epoch{0};
|
||||||
|
int max_revalidate_retries{5};
|
||||||
|
bool materialize{true};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Captures explicit files, recursive search/include roots, and lookup guards into
|
||||||
|
// a content-verified immutable InputSnapshot. Never hardlinks editable sources;
|
||||||
|
// revalidates every captured byte and directory membership before sealing.
|
||||||
|
[[nodiscard]] Void::Result::Result<InputSnapshot, Void::Result::Error> capture_snapshot(
|
||||||
|
const SnapshotOptions &options, const std::vector<std::filesystem::path> &explicit_files,
|
||||||
|
const std::vector<std::filesystem::path> &directory_roots,
|
||||||
|
const std::vector<std::pair<std::vector<std::string>, std::string>> &lookup_queries = {});
|
||||||
|
|
||||||
|
// Re-checks a sealed snapshot against the live filesystem (content + membership +
|
||||||
|
// lookup guards + symlink targets), detecting same-size/same-mtime mutations.
|
||||||
|
[[nodiscard]] Void::Result::Result<bool, Void::Result::Error>
|
||||||
|
is_snapshot_fresh(const InputSnapshot &snapshot, const SnapshotOptions &options);
|
||||||
|
|
||||||
|
// Promotes a validated generated file into the immutable snapshot store with
|
||||||
|
// canonical metadata and returns its sealed SnapshotEntry.
|
||||||
|
[[nodiscard]] Void::Result::Result<SnapshotEntry, Void::Result::Error>
|
||||||
|
seal_generated_artifact(const std::filesystem::path &staged_file, std::string logical_path,
|
||||||
|
const std::filesystem::path &snapshot_store_dir,
|
||||||
|
std::int64_t reproducibility_epoch);
|
||||||
|
|
||||||
|
// Persists a sealed snapshot manifest atomically as UTF-8 JSON.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||||
|
write_snapshot_manifest(const InputSnapshot &snapshot,
|
||||||
|
const std::filesystem::path &snapshot_store_dir);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Snapshot
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::State {
|
||||||
|
|
||||||
|
inline constexpr int kStateSchemaVersion = 1;
|
||||||
|
|
||||||
|
struct BlobRef {
|
||||||
|
std::string sha256;
|
||||||
|
std::uint64_t size{0};
|
||||||
|
std::uint32_t mode{0644};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ActionSuccessRecord {
|
||||||
|
std::string action_key;
|
||||||
|
std::string profile_identity;
|
||||||
|
std::string target_name;
|
||||||
|
std::map<std::string, BlobRef, std::less<>> outputs; // relative/logical output -> CAS blob
|
||||||
|
std::map<std::string, std::string, std::less<>> discovered_inputs; // path -> sha256
|
||||||
|
std::vector<Snapshot::LookupGuard> lookup_guards;
|
||||||
|
std::int64_t recorded_epoch{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GraphGenerationRecord {
|
||||||
|
std::string generation_id;
|
||||||
|
std::string profile_name;
|
||||||
|
std::string profile_identity;
|
||||||
|
std::string snapshot_id;
|
||||||
|
std::string status; // "valid", "invalid", "stale"
|
||||||
|
std::string diagnostic;
|
||||||
|
std::uint64_t sequence{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct GcStats {
|
||||||
|
std::size_t removed_blobs{0};
|
||||||
|
std::uint64_t freed_bytes{0};
|
||||||
|
std::size_t retained_blobs{0};
|
||||||
|
std::size_t cleaned_staging_files{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LeaseHandle {
|
||||||
|
std::string lease_id;
|
||||||
|
std::filesystem::path lease_file;
|
||||||
|
~LeaseHandle() noexcept;
|
||||||
|
LeaseHandle() = default;
|
||||||
|
LeaseHandle(const LeaseHandle &) = delete;
|
||||||
|
LeaseHandle &operator=(const LeaseHandle &) = delete;
|
||||||
|
LeaseHandle(LeaseHandle &&other) noexcept;
|
||||||
|
LeaseHandle &operator=(LeaseHandle &&other) noexcept;
|
||||||
|
void release() noexcept;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Transactional persistent state & SHA-256 content-addressed local artifact cache (Plan 07).
|
||||||
|
// Uses Void::Sqlite when compiled with SQLite3 support and a durable atomic-replace
|
||||||
|
// transactional store via Void::FileSystem::replace_file in minimal environments (VL-011).
|
||||||
|
class StateStore {
|
||||||
|
public:
|
||||||
|
[[nodiscard]] static Void::Result::Result<StateStore, Void::Result::Error>
|
||||||
|
open(const std::filesystem::path &vbs_dir);
|
||||||
|
|
||||||
|
[[nodiscard]] const std::filesystem::path &root() const noexcept { return root_; }
|
||||||
|
[[nodiscard]] std::filesystem::path cas_blob_path(std::string_view sha256) const;
|
||||||
|
|
||||||
|
// CAS operations: publish immutable blobs BEFORE recording references in state.
|
||||||
|
[[nodiscard]] Void::Result::Result<BlobRef, Void::Result::Error>
|
||||||
|
store_blob_from_file(const std::filesystem::path &file_path);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<bool, Void::Result::Error>
|
||||||
|
verify_blob(std::string_view sha256) const;
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
materialize_blob(const BlobRef &ref, const std::filesystem::path &destination) const;
|
||||||
|
|
||||||
|
// Transactional action cache queries & publication.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<ActionSuccessRecord>, Void::Result::Error>
|
||||||
|
lookup_action(std::string_view action_key) const;
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
record_action_success(const ActionSuccessRecord &record);
|
||||||
|
|
||||||
|
// Graph generation tracking.
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
record_generation(const GraphGenerationRecord &generation);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<GraphGenerationRecord>, Void::Result::Error>
|
||||||
|
list_generations(std::optional<std::string_view> profile_name = std::nullopt) const;
|
||||||
|
|
||||||
|
// Leases protect active runs from GC deletion.
|
||||||
|
[[nodiscard]] Void::Result::Result<LeaseHandle, Void::Result::Error>
|
||||||
|
acquire_lease(std::string_view profile_name, const std::set<std::string> &pinned_blobs = {});
|
||||||
|
|
||||||
|
// Conservative crash recovery: removes uncommitted staging files and dead leases;
|
||||||
|
// never invents a successful action record.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t, Void::Result::Error> recover();
|
||||||
|
|
||||||
|
// Garbage collects unreachable CAS blobs outside active leases and pinned generations.
|
||||||
|
[[nodiscard]] Void::Result::Result<GcStats, Void::Result::Error>
|
||||||
|
gc(std::uint64_t max_cache_bytes = 0);
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t recorded_action_count() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct DatabaseSnapshot {
|
||||||
|
int schema_version{kStateSchemaVersion};
|
||||||
|
std::uint64_t next_sequence{1};
|
||||||
|
std::map<std::string, ActionSuccessRecord, std::less<>> actions;
|
||||||
|
std::vector<GraphGenerationRecord> generations;
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit StateStore(std::filesystem::path root);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<DatabaseSnapshot, Void::Result::Error>
|
||||||
|
load_db_locked() const;
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
save_db_locked(const DatabaseSnapshot &db) const;
|
||||||
|
|
||||||
|
std::filesystem::path root_;
|
||||||
|
std::filesystem::path cas_dir_;
|
||||||
|
std::filesystem::path staging_dir_;
|
||||||
|
std::filesystem::path leases_dir_;
|
||||||
|
std::filesystem::path db_file_;
|
||||||
|
std::filesystem::path lock_file_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Build::State
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Toolchain {
|
||||||
|
|
||||||
|
struct ToolchainCapabilities {
|
||||||
|
CompilerFamily family{CompilerFamily::Gcc};
|
||||||
|
std::filesystem::path cxx_compiler;
|
||||||
|
std::filesystem::path archiver;
|
||||||
|
std::optional<std::filesystem::path> module_scanner;
|
||||||
|
std::string version_banner;
|
||||||
|
std::string target_triple;
|
||||||
|
std::string sysroot;
|
||||||
|
std::string compiler_sha256;
|
||||||
|
std::string archiver_sha256;
|
||||||
|
std::vector<std::string> default_include_dirs;
|
||||||
|
std::map<std::string, std::string, std::less<>> relevant_env;
|
||||||
|
|
||||||
|
bool supports_cxx17{false};
|
||||||
|
bool supports_cxx20{false};
|
||||||
|
bool supports_cxx23{false};
|
||||||
|
bool supports_cxx26{false};
|
||||||
|
bool supports_reflection{false};
|
||||||
|
bool supports_file_prefix_map{false};
|
||||||
|
bool supports_macro_prefix_map{false};
|
||||||
|
bool supports_debug_prefix_map{false};
|
||||||
|
bool supports_p1689_scan{false};
|
||||||
|
bool supports_pch{true};
|
||||||
|
bool supports_lto_full{false};
|
||||||
|
bool supports_lto_thin{false};
|
||||||
|
bool supports_asan{false};
|
||||||
|
bool supports_ubsan{false};
|
||||||
|
bool supports_tsan{false};
|
||||||
|
bool is_cross_toolchain{false};
|
||||||
|
|
||||||
|
std::string identity_hash;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PathPrefixMap {
|
||||||
|
std::filesystem::path from;
|
||||||
|
std::filesystem::path to;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct CompileRequest {
|
||||||
|
std::filesystem::path source_file;
|
||||||
|
std::filesystem::path output_object;
|
||||||
|
std::optional<std::filesystem::path> depfile;
|
||||||
|
std::optional<std::filesystem::path> response_file_dir;
|
||||||
|
std::vector<std::pair<std::filesystem::path, bool>> include_dirs; // (path, is_system)
|
||||||
|
std::vector<std::string> defines;
|
||||||
|
std::vector<std::string> compile_options;
|
||||||
|
CxxStandard cxx_standard{CxxStandard::Default};
|
||||||
|
LtoMode lto{LtoMode::None};
|
||||||
|
std::vector<Sanitizer> sanitizers;
|
||||||
|
bool position_independent{false};
|
||||||
|
std::optional<std::filesystem::path> precompiled_header;
|
||||||
|
std::vector<PathPrefixMap> prefix_maps;
|
||||||
|
std::int64_t reproducibility_epoch{0};
|
||||||
|
bool nondeterministic{false};
|
||||||
|
std::size_t response_file_threshold{32768};
|
||||||
|
bool compile_only{true};
|
||||||
|
bool is_module_interface{false};
|
||||||
|
std::optional<std::filesystem::path> bmi_output;
|
||||||
|
std::vector<std::pair<std::string, std::filesystem::path>> module_bmi_imports;
|
||||||
|
std::optional<std::filesystem::path> module_mapper_file;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LinkRequest {
|
||||||
|
TargetKind kind{TargetKind::Executable};
|
||||||
|
std::filesystem::path output_file;
|
||||||
|
std::optional<std::filesystem::path> response_file_dir;
|
||||||
|
std::vector<std::filesystem::path> object_files;
|
||||||
|
std::vector<std::filesystem::path> static_libraries;
|
||||||
|
std::vector<std::filesystem::path> shared_libraries;
|
||||||
|
std::vector<std::filesystem::path> rpaths;
|
||||||
|
std::vector<std::string> link_options;
|
||||||
|
LtoMode lto{LtoMode::None};
|
||||||
|
std::vector<Sanitizer> sanitizers;
|
||||||
|
std::size_t response_file_threshold{32768};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LoweredCommand {
|
||||||
|
std::filesystem::path executable;
|
||||||
|
std::vector<std::string> arguments;
|
||||||
|
std::map<std::string, std::string, std::less<>> environment;
|
||||||
|
std::optional<std::filesystem::path> response_file;
|
||||||
|
std::string response_file_content;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Discovers compiler & archiver, computes complete binary/sysroot/env identity,
|
||||||
|
// and probes capabilities without executing any target binaries (cross-safe).
|
||||||
|
[[nodiscard]] Void::Result::Result<ToolchainCapabilities, Void::Result::Error>
|
||||||
|
discover_and_probe(const ProfileContext &context,
|
||||||
|
const std::optional<std::filesystem::path> &cache_dir = std::nullopt);
|
||||||
|
|
||||||
|
// Computes canonical identity hash for a resolved profile + toolchain pair.
|
||||||
|
[[nodiscard]] std::string compute_profile_identity(const ProfileContext &context,
|
||||||
|
const ToolchainCapabilities &toolchain);
|
||||||
|
|
||||||
|
// Escapes a single argument for GCC/Clang @response-file parsing.
|
||||||
|
[[nodiscard]] std::string escape_response_file_arg(std::string_view arg);
|
||||||
|
|
||||||
|
// Lowers a structured compile request into argv, environment, and optional response file.
|
||||||
|
// Fails explicitly if requested deterministic path maps or compiler features are unsupported.
|
||||||
|
[[nodiscard]] Void::Result::Result<LoweredCommand, Void::Result::Error>
|
||||||
|
lower_compile_command(const ToolchainCapabilities &toolchain, const CompileRequest &request);
|
||||||
|
|
||||||
|
// Lowers a deterministic static library archive command (`ar rcsD`).
|
||||||
|
[[nodiscard]] Void::Result::Result<LoweredCommand, Void::Result::Error>
|
||||||
|
lower_archive_command(const ToolchainCapabilities &toolchain,
|
||||||
|
const std::filesystem::path &output_archive,
|
||||||
|
const std::vector<std::filesystem::path> &object_files,
|
||||||
|
const std::optional<std::filesystem::path> &response_file_dir = std::nullopt,
|
||||||
|
std::size_t response_file_threshold = 32768);
|
||||||
|
|
||||||
|
// Lowers a structured link command for executables and shared libraries.
|
||||||
|
[[nodiscard]] Void::Result::Result<LoweredCommand, Void::Result::Error>
|
||||||
|
lower_link_command(const ToolchainCapabilities &toolchain, const LinkRequest &request);
|
||||||
|
|
||||||
|
// Returns the host operating system and architecture labels.
|
||||||
|
[[nodiscard]] std::string host_os_name();
|
||||||
|
[[nodiscard]] std::string host_architecture_name();
|
||||||
|
|
||||||
|
} // namespace Void::Build::Toolchain
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Util {
|
||||||
|
|
||||||
|
// Strict UTF-8 validation per RFC 8259 / Unicode scalar value rules (VL-008).
|
||||||
|
[[nodiscard]] bool is_valid_utf8(std::string_view text) noexcept;
|
||||||
|
void require_valid_utf8(std::string_view text);
|
||||||
|
|
||||||
|
// Emits a valid JSON string literal, throwing std::invalid_argument on malformed UTF-8.
|
||||||
|
[[nodiscard]] std::string json_quote(std::string_view text);
|
||||||
|
|
||||||
|
template <typename Range, typename Serialize>
|
||||||
|
[[nodiscard]] std::string json_array(const Range &range, Serialize serialize) {
|
||||||
|
std::string output{"["};
|
||||||
|
bool first = true;
|
||||||
|
for (const auto &item : range) {
|
||||||
|
if (!first) {
|
||||||
|
output += ',';
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
output += serialize(item);
|
||||||
|
}
|
||||||
|
output += ']';
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Util
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <span>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
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).
|
||||||
|
class Sha256Hasher {
|
||||||
|
public:
|
||||||
|
Sha256Hasher() noexcept;
|
||||||
|
|
||||||
|
void update(std::span<const std::byte> data) noexcept;
|
||||||
|
void update(std::span<const std::uint8_t> data) noexcept;
|
||||||
|
void update(std::string_view text) noexcept;
|
||||||
|
void update_length_prefixed(std::string_view text) noexcept;
|
||||||
|
void update_u64(std::uint64_t value) noexcept;
|
||||||
|
|
||||||
|
[[nodiscard]] Sha256Digest finalize() noexcept;
|
||||||
|
[[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};
|
||||||
|
bool finalized_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] std::string to_hex(const Sha256Digest &digest);
|
||||||
|
[[nodiscard]] Sha256Digest sha256_bytes(std::span<const std::byte> data) noexcept;
|
||||||
|
[[nodiscard]] std::string sha256_hex(std::string_view text);
|
||||||
|
[[nodiscard]] std::string sha256_hex(std::span<const std::byte> data);
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string, Void::Result::Error>
|
||||||
|
sha256_file_hex(const std::filesystem::path &path);
|
||||||
|
|
||||||
|
// Constant-time equality for hex digests / authentication tokens.
|
||||||
|
[[nodiscard]] bool constant_time_equal(std::string_view a, std::string_view b) noexcept;
|
||||||
|
|
||||||
|
} // namespace Void::Build::Util
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build/Config/Frontend.hpp>
|
||||||
|
#include <Void/Build/Editor/CompDb.hpp>
|
||||||
|
#include <Void/Build/Execution/Scheduler.hpp>
|
||||||
|
#include <Void/Build/Graph/Graph.hpp>
|
||||||
|
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||||
|
#include <Void/Build/State/StateStore.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <stop_token>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Watch {
|
||||||
|
|
||||||
|
struct WatchBatch {
|
||||||
|
std::vector<std::filesystem::path> changed_paths;
|
||||||
|
bool overflowed{false};
|
||||||
|
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.
|
||||||
|
class InotifyWatcher {
|
||||||
|
public:
|
||||||
|
InotifyWatcher() = default;
|
||||||
|
~InotifyWatcher() noexcept;
|
||||||
|
|
||||||
|
InotifyWatcher(const InotifyWatcher &) = delete;
|
||||||
|
InotifyWatcher &operator=(const InotifyWatcher &) = delete;
|
||||||
|
InotifyWatcher(InotifyWatcher &&other) noexcept;
|
||||||
|
InotifyWatcher &operator=(InotifyWatcher &&other) noexcept;
|
||||||
|
|
||||||
|
[[nodiscard]] static Void::Result::Result<InotifyWatcher, Void::Result::Error>
|
||||||
|
create(const std::filesystem::path &root_dir,
|
||||||
|
std::vector<std::string> excluded_names = {".git", ".vbs", "build", ".serena", ".cache",
|
||||||
|
"keys"});
|
||||||
|
|
||||||
|
// Polls for events up to `timeout` and coalesces burst activity across `debounce`.
|
||||||
|
[[nodiscard]] Void::Result::Result<WatchBatch, Void::Result::Error>
|
||||||
|
poll_events(std::chrono::milliseconds timeout,
|
||||||
|
std::chrono::milliseconds debounce = std::chrono::milliseconds{40});
|
||||||
|
|
||||||
|
// Forces full watch-tree reattachment (used after overflow or root replacement).
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> rescan_watches();
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t watched_directory_count() const noexcept {
|
||||||
|
return wd_to_path_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
int fd_{-1};
|
||||||
|
std::filesystem::path root_;
|
||||||
|
std::vector<std::string> excluded_;
|
||||||
|
std::map<int, std::filesystem::path> wd_to_path_;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class WatchMode { FullBuild, MetadataOnly };
|
||||||
|
|
||||||
|
struct WatchCycleReport {
|
||||||
|
std::size_t cycle_index{0};
|
||||||
|
std::string profile_name;
|
||||||
|
bool config_succeeded{false};
|
||||||
|
bool build_succeeded{false};
|
||||||
|
bool compdb_published{false};
|
||||||
|
bool provider_stale{false};
|
||||||
|
std::size_t executed_actions{0};
|
||||||
|
std::size_t cached_actions{0};
|
||||||
|
std::string diagnostic;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Callback used in MetadataOnly mode to supply validated cached imported-target metadata
|
||||||
|
// WITHOUT ever invoking foreign configure/build/install/fetch or lockfile writes (Plan 10/13).
|
||||||
|
struct CachedProviderSnapshot {
|
||||||
|
bool valid{true};
|
||||||
|
std::string stale_diagnostic;
|
||||||
|
std::map<std::string, Graph::ImportedTargetInterface, std::less<>> imported_targets;
|
||||||
|
};
|
||||||
|
|
||||||
|
using ProviderMetadataReader =
|
||||||
|
std::function<CachedProviderSnapshot(const Graph::ProjectDescription &, WatchMode)>;
|
||||||
|
|
||||||
|
struct WatchLoopOptions {
|
||||||
|
WatchMode mode{WatchMode::FullBuild};
|
||||||
|
Config::FrontendOptions frontend;
|
||||||
|
std::optional<std::string>
|
||||||
|
explicit_profile; // Empty in MetadataOnly -> follow active editor profile
|
||||||
|
std::optional<CompilerFamily> compiler_override;
|
||||||
|
std::vector<std::string> selected_targets;
|
||||||
|
std::size_t jobs{0};
|
||||||
|
std::chrono::milliseconds debounce{40};
|
||||||
|
std::chrono::milliseconds reconcile_interval{1000};
|
||||||
|
std::size_t max_cycles{0}; // 0 = run until stop_token requested
|
||||||
|
ProviderMetadataReader provider_reader;
|
||||||
|
std::function<void(const WatchCycleReport &)> on_cycle;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Executes a single reconciliation cycle cleanly (used by one-shot builds, build watch,
|
||||||
|
// and metadata-only watch so all three share one exact invalidation pipeline).
|
||||||
|
[[nodiscard]] WatchCycleReport run_reconcile_cycle(const WatchLoopOptions &options,
|
||||||
|
std::size_t cycle_index,
|
||||||
|
bool allow_selection_update,
|
||||||
|
std::optional<std::uint64_t> reserved_ticket,
|
||||||
|
std::stop_token stop = {});
|
||||||
|
|
||||||
|
// Runs the full watch loop (inotify hints + periodic content/namespace reconciliation +
|
||||||
|
// overflow recovery + graceful cancellation via stop_token).
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<WatchCycleReport>, Void::Result::Error>
|
||||||
|
run_watch_loop(const WatchLoopOptions &options, std::stop_token stop = {});
|
||||||
|
|
||||||
|
} // namespace Void::Build::Watch
|
||||||
@@ -1,201 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <concepts>
|
|
||||||
#include <cstddef>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <initializer_list>
|
|
||||||
#include <map>
|
|
||||||
#include <memory>
|
|
||||||
#include <stdexcept>
|
|
||||||
#include <string>
|
|
||||||
#include <string_view>
|
|
||||||
#include <utility>
|
|
||||||
#include <variant>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace vbs {
|
|
||||||
|
|
||||||
inline constexpr int schema_version = 1;
|
|
||||||
|
|
||||||
enum class CompilerFamily { gcc, clang };
|
|
||||||
enum class Visibility { private_, public_, interface_ };
|
|
||||||
enum class TargetKind { executable, static_library };
|
|
||||||
enum class SourceKind { file, glob };
|
|
||||||
enum class LinkKind { local, imported };
|
|
||||||
enum class DependencySourceKind { unspecified, git, package };
|
|
||||||
|
|
||||||
[[nodiscard]] std::string_view compiler_name(CompilerFamily compiler);
|
|
||||||
[[nodiscard]] CompilerFamily parse_compiler(std::string_view name);
|
|
||||||
|
|
||||||
struct ProfileContext {
|
|
||||||
std::string name;
|
|
||||||
CompilerFamily compiler{CompilerFamily::gcc};
|
|
||||||
std::string os;
|
|
||||||
std::string architecture;
|
|
||||||
std::vector<std::string> compile_options;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct ProfileDescription {
|
|
||||||
std::string name;
|
|
||||||
std::vector<std::string> compile_options;
|
|
||||||
};
|
|
||||||
|
|
||||||
class Profiles {
|
|
||||||
public:
|
|
||||||
void add(std::string name, std::vector<std::string> compile_options = {});
|
|
||||||
[[nodiscard]] const std::vector<ProfileDescription> &records() const noexcept;
|
|
||||||
[[nodiscard]] ProfileContext resolve(std::string_view name, CompilerFamily compiler,
|
|
||||||
std::string os, std::string architecture) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
std::vector<ProfileDescription> records_;
|
|
||||||
};
|
|
||||||
|
|
||||||
[[nodiscard]] Profiles default_profiles();
|
|
||||||
|
|
||||||
struct SourceRecord {
|
|
||||||
SourceKind kind;
|
|
||||||
std::string path;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Source spelling is recorded verbatim; construction never reads the filesystem.
|
|
||||||
class SourceSet {
|
|
||||||
public:
|
|
||||||
SourceSet() = default;
|
|
||||||
SourceSet(std::initializer_list<std::string_view> files);
|
|
||||||
[[nodiscard]] static SourceSet file(std::string path);
|
|
||||||
[[nodiscard]] static SourceSet glob(std::string pattern);
|
|
||||||
[[nodiscard]] const std::vector<SourceRecord> &records() const noexcept;
|
|
||||||
|
|
||||||
private:
|
|
||||||
std::vector<SourceRecord> records_;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct OptionValue {
|
|
||||||
using Value = std::variant<std::string, bool, std::int64_t>;
|
|
||||||
Value value;
|
|
||||||
|
|
||||||
OptionValue(std::string text) : value{std::move(text)} {}
|
|
||||||
OptionValue(const char *text) : OptionValue{std::string{text}} {}
|
|
||||||
OptionValue(bool boolean) : value{boolean} {}
|
|
||||||
template <std::integral Integer>
|
|
||||||
requires(!std::same_as<Integer, bool>)
|
|
||||||
OptionValue(Integer integer) : value{std::int64_t{0}} {
|
|
||||||
if (!std::in_range<std::int64_t>(integer)) {
|
|
||||||
throw std::invalid_argument{"option integer is out of range"};
|
|
||||||
}
|
|
||||||
value = static_cast<std::int64_t>(integer);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
using OptionMap = std::map<std::string, OptionValue, std::less<>>;
|
|
||||||
|
|
||||||
struct Commit {
|
|
||||||
std::string sha;
|
|
||||||
};
|
|
||||||
struct IncludeDirectory {
|
|
||||||
std::string path;
|
|
||||||
Visibility visibility{Visibility::private_};
|
|
||||||
};
|
|
||||||
struct LinkRecord {
|
|
||||||
LinkKind kind;
|
|
||||||
std::string target;
|
|
||||||
std::string dependency; // Empty for a local target.
|
|
||||||
Visibility visibility{Visibility::private_};
|
|
||||||
};
|
|
||||||
struct TargetRecord {
|
|
||||||
std::string name;
|
|
||||||
TargetKind kind;
|
|
||||||
std::vector<SourceRecord> sources;
|
|
||||||
std::vector<IncludeDirectory> include_directories;
|
|
||||||
std::vector<std::string> compile_options;
|
|
||||||
std::vector<LinkRecord> links;
|
|
||||||
};
|
|
||||||
struct DependencyRecord {
|
|
||||||
std::string name;
|
|
||||||
DependencySourceKind source_kind{DependencySourceKind::unspecified};
|
|
||||||
std::string location;
|
|
||||||
std::string revision;
|
|
||||||
std::string package;
|
|
||||||
std::string version;
|
|
||||||
std::string builder;
|
|
||||||
OptionMap options;
|
|
||||||
};
|
|
||||||
|
|
||||||
namespace detail {
|
|
||||||
struct ProjectState;
|
|
||||||
}
|
|
||||||
class Project;
|
|
||||||
class Dependency;
|
|
||||||
|
|
||||||
// Handles retain an index and weak owner identity, never a pointer into a growing vector.
|
|
||||||
class ImportedTarget {
|
|
||||||
private:
|
|
||||||
friend class Dependency;
|
|
||||||
friend class Target;
|
|
||||||
ImportedTarget(std::weak_ptr<detail::ProjectState> owner, std::size_t dependency,
|
|
||||||
std::string name);
|
|
||||||
std::weak_ptr<detail::ProjectState> owner_;
|
|
||||||
std::size_t dependency_;
|
|
||||||
std::string name_;
|
|
||||||
};
|
|
||||||
|
|
||||||
class Target {
|
|
||||||
public:
|
|
||||||
Target &sources(const SourceSet &sources);
|
|
||||||
Target &include_directory(std::string path, Visibility visibility = Visibility::private_);
|
|
||||||
Target &compile_option(std::string option);
|
|
||||||
Target &link(const Target &target, Visibility visibility = Visibility::private_);
|
|
||||||
Target &link(const ImportedTarget &target, Visibility visibility = Visibility::private_);
|
|
||||||
[[nodiscard]] const TargetRecord &record() const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
friend class Project;
|
|
||||||
Target(std::weak_ptr<detail::ProjectState> owner, std::size_t index);
|
|
||||||
std::weak_ptr<detail::ProjectState> owner_;
|
|
||||||
std::size_t index_;
|
|
||||||
};
|
|
||||||
|
|
||||||
class Dependency {
|
|
||||||
public:
|
|
||||||
Dependency &git(std::string url, Commit commit);
|
|
||||||
Dependency &cmake(OptionMap options = {});
|
|
||||||
Dependency &package(std::string id, std::string range);
|
|
||||||
[[nodiscard]] ImportedTarget target(std::string exported_name) const;
|
|
||||||
[[nodiscard]] const DependencyRecord &record() const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
friend class Project;
|
|
||||||
Dependency(std::weak_ptr<detail::ProjectState> owner, std::size_t index);
|
|
||||||
std::weak_ptr<detail::ProjectState> owner_;
|
|
||||||
std::size_t index_;
|
|
||||||
};
|
|
||||||
|
|
||||||
class Project {
|
|
||||||
public:
|
|
||||||
explicit Project(ProfileContext context);
|
|
||||||
~Project();
|
|
||||||
Project(const Project &) = delete;
|
|
||||||
Project &operator=(const Project &) = delete;
|
|
||||||
Project(Project &&) = delete;
|
|
||||||
Project &operator=(Project &&) = delete;
|
|
||||||
|
|
||||||
[[nodiscard]] const ProfileContext &context() const noexcept;
|
|
||||||
[[nodiscard]] Target executable(std::string name);
|
|
||||||
[[nodiscard]] Target static_library(std::string name);
|
|
||||||
[[nodiscard]] Dependency dependency(std::string name);
|
|
||||||
[[nodiscard]] SourceSet glob(std::string pattern) const;
|
|
||||||
[[nodiscard]] const std::vector<TargetRecord> &targets() const noexcept;
|
|
||||||
[[nodiscard]] const std::vector<DependencyRecord> &dependencies() const noexcept;
|
|
||||||
// Emits UTF-8 JSON; malformed UTF-8 in any recorded string throws invalid_argument.
|
|
||||||
[[nodiscard]] std::string to_json() const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
Target add_target(std::string name, TargetKind kind);
|
|
||||||
std::shared_ptr<detail::ProjectState> state_;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace vbs
|
|
||||||
|
|
||||||
// Description entry points supplied by ordinary user C++ translation units.
|
|
||||||
void build(vbs::Project &project);
|
|
||||||
void profiles(vbs::Profiles &profiles);
|
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
#include "VbsSelfHostRecipe.hpp"
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
#include <VoidLibrary/VoidLibraryRecipe.hpp>
|
||||||
|
|
||||||
|
#include <format>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Recipes {
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) {
|
||||||
|
// 1. Emit stage-isolated BootstrapConfig.hpp inside stage_build_dir/generated/
|
||||||
|
// (never reusing CMake bootstrap generated headers!).
|
||||||
|
const auto gen_dir = config.stage_build_dir / "generated";
|
||||||
|
const auto cfg_hpp = gen_dir / "Void" / "Build" / "BootstrapConfig.hpp";
|
||||||
|
const std::string cfg_content =
|
||||||
|
std::format("#pragma once\n"
|
||||||
|
"#include <string_view>\n"
|
||||||
|
"namespace Void::Build::Bootstrap {{\n"
|
||||||
|
"inline constexpr std::string_view version = \"{}\";\n"
|
||||||
|
"inline constexpr std::string_view os = \"{}\";\n"
|
||||||
|
"inline constexpr std::string_view architecture = \"{}\";\n"
|
||||||
|
"inline constexpr std::string_view source_dir = \"{}\";\n"
|
||||||
|
"inline constexpr std::string_view binary_dir = \"{}\";\n"
|
||||||
|
"inline constexpr std::string_view sdk_include_dir = \"{}\";\n"
|
||||||
|
"inline constexpr std::string_view sdk_source_dir = \"{}\";\n"
|
||||||
|
"}}\n",
|
||||||
|
config.version, project.context().os, project.context().architecture,
|
||||||
|
config.vbs_source_dir.lexically_normal().string(),
|
||||||
|
config.stage_build_dir.lexically_normal().string(),
|
||||||
|
(config.vbs_source_dir / "include").lexically_normal().string(),
|
||||||
|
(config.vbs_source_dir / "src").lexically_normal().string());
|
||||||
|
|
||||||
|
if (auto w = Platform::atomic_write_file(cfg_hpp, cfg_content, false); !w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Declare the native VoidLibrary module closure (pure C++26, zero CMake).
|
||||||
|
std::vector<std::string> void_mods = {"Configuration", "Text", "Unicode", "Async",
|
||||||
|
"Algorithms"};
|
||||||
|
if (config.include_tests) {
|
||||||
|
void_mods.push_back("Testing");
|
||||||
|
}
|
||||||
|
auto void_libs = add_void_library_native(project, config.void_source_dir, void_mods);
|
||||||
|
|
||||||
|
const auto root = config.vbs_source_dir.lexically_normal();
|
||||||
|
|
||||||
|
// 3. VoidBuildSdk (static library).
|
||||||
|
auto sdk = project.static_library("VoidBuildSdk");
|
||||||
|
sdk.cxx_standard(CxxStandard::Cxx26)
|
||||||
|
.sources(SourceSet::file((root / "src" / "Build.cpp").string()))
|
||||||
|
.sources(SourceSet::file((root / "src" / "Util" / "Json.cpp").string()))
|
||||||
|
.include_directory((root / "include").string(), Visibility::Public)
|
||||||
|
.compile_option("-freflection", Visibility::Public)
|
||||||
|
.define("VBS_HAS_VOID_UNICODE=1", Visibility::Private)
|
||||||
|
.link(void_libs.modules.at("Unicode"), Visibility::Private);
|
||||||
|
|
||||||
|
// 4. VoidBuildCore (static library containing every native VBS engine module).
|
||||||
|
auto core = project.static_library("VoidBuildCore");
|
||||||
|
core.cxx_standard(CxxStandard::Cxx26)
|
||||||
|
.include_directory((root / "include").string(), Visibility::Public)
|
||||||
|
.include_directory((root / "recipes").string(), Visibility::Public)
|
||||||
|
.compile_option("-freflection", 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);
|
||||||
|
|
||||||
|
const std::vector<std::string> core_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",
|
||||||
|
};
|
||||||
|
for (const auto &rel : core_sources) {
|
||||||
|
core.sources(SourceSet::file((root / rel).string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Full native `vbs` CLI executable.
|
||||||
|
auto vbs = project.executable("vbs");
|
||||||
|
vbs.cxx_standard(CxxStandard::Cxx26)
|
||||||
|
.sources(SourceSet::file((root / "src" / "Main.cpp").string()))
|
||||||
|
.include_directory(gen_dir.string(), Visibility::Private)
|
||||||
|
.link(core);
|
||||||
|
|
||||||
|
// 6. Optional `VoidBuildRegistry` + `vbs-registry` server executable.
|
||||||
|
if (config.include_registry) {
|
||||||
|
auto reg_lib = project.static_library("VoidBuildRegistry");
|
||||||
|
reg_lib.cxx_standard(CxxStandard::Cxx26)
|
||||||
|
.sources(SourceSet::file((root / "registry" / "service" / "HttpServer.cpp").string()))
|
||||||
|
.sources(
|
||||||
|
SourceSet::file((root / "registry" / "service" / "RegistryService.cpp").string()))
|
||||||
|
.include_directory((root / "registry" / "include").string(), Visibility::Public)
|
||||||
|
.link(core, Visibility::Public);
|
||||||
|
|
||||||
|
auto reg_bin = project.executable("vbs-registry");
|
||||||
|
reg_bin.cxx_standard(CxxStandard::Cxx26)
|
||||||
|
.sources(SourceSet::file((root / "registry" / "service" / "Main.cpp").string()))
|
||||||
|
.include_directory(gen_dir.string(), Visibility::Private)
|
||||||
|
.link(reg_lib);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Recipes
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Void::Build::Recipes {
|
||||||
|
|
||||||
|
struct VbsSelfHostConfig {
|
||||||
|
std::filesystem::path vbs_source_dir;
|
||||||
|
std::filesystem::path void_source_dir;
|
||||||
|
std::filesystem::path stage_build_dir;
|
||||||
|
std::string version{"0.1.0"};
|
||||||
|
bool include_registry{true};
|
||||||
|
bool include_tests{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Declares the COMPLETE native VoidBuildSystem target graph (VoidLibrary native closure +
|
||||||
|
// VoidBuildSdk + VoidBuildCore + optional VoidBuildRegistry + generated BootstrapConfig.hpp +
|
||||||
|
// vbs + optional vbs-registry) purely as native Void::Build targets — ZERO CMake! (Plan 18).
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config);
|
||||||
|
|
||||||
|
} // namespace Void::Build::Recipes
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
#include "VoidLibraryRecipe.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <set>
|
||||||
|
#include <stdexcept>
|
||||||
|
|
||||||
|
namespace Void::Build::Recipes {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
struct ModuleDef {
|
||||||
|
std::vector<std::string> internal_deps;
|
||||||
|
bool needs_threads{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
const std::map<std::string, ModuleDef, std::less<>> &known_modules() {
|
||||||
|
static const std::map<std::string, ModuleDef, std::less<>> kDefs = {
|
||||||
|
{"Core", {{}, false}},
|
||||||
|
{"Functional", {{}, false}},
|
||||||
|
{"Math", {{}, false}},
|
||||||
|
{"Algorithms", {{"Core", "Math"}, false}},
|
||||||
|
{"Memory", {{"Core"}, false}},
|
||||||
|
{"Time", {{}, false}},
|
||||||
|
{"Text", {{}, false}},
|
||||||
|
{"Unicode", {{"Core", "Text"}, false}},
|
||||||
|
{"LogState", {{}, false}},
|
||||||
|
{"Data", {{"Core", "Math", "Time"}, false}},
|
||||||
|
{"System", {{"Functional", "Time", "LogState"}, true}},
|
||||||
|
{"Async", {{"Functional", "Time", "LogState"}, true}},
|
||||||
|
{"Configuration", {{"Core", "Functional", "System", "Data", "Time", "LogState"}, true}},
|
||||||
|
{"Testing", {{"Core", "Functional", "Time", "LogState", "Configuration", "Text"}, true}},
|
||||||
|
};
|
||||||
|
return kDefs;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> collect_sources(const std::filesystem::path &src_dir) {
|
||||||
|
std::vector<std::string> files;
|
||||||
|
std::error_code ec;
|
||||||
|
if (!std::filesystem::is_directory(src_dir, ec)) {
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
for (const auto &ent : std::filesystem::recursive_directory_iterator(src_dir, ec)) {
|
||||||
|
if (ent.is_regular_file(ec) && ent.path().extension() == ".cpp") {
|
||||||
|
files.push_back(ent.path().lexically_normal().string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::ranges::sort(files);
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
VoidLibraryTargets add_void_library_native(Project &project,
|
||||||
|
const std::filesystem::path &void_source_dir,
|
||||||
|
const std::vector<std::string> &enabled_modules) {
|
||||||
|
const auto &defs = known_modules();
|
||||||
|
|
||||||
|
// Compute transitive module closure in deterministic topological order.
|
||||||
|
std::set<std::string> visited;
|
||||||
|
std::vector<std::string> topo;
|
||||||
|
auto visit = [&](auto &&self, const std::string &mod) -> void {
|
||||||
|
if (!visited.insert(mod).second) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const auto it = defs.find(mod);
|
||||||
|
if (it == defs.end()) {
|
||||||
|
throw std::invalid_argument{"VoidLibraryRecipe: unsupported native module '" + mod +
|
||||||
|
"'"};
|
||||||
|
}
|
||||||
|
for (const auto &dep : it->second.internal_deps) {
|
||||||
|
self(self, dep);
|
||||||
|
}
|
||||||
|
topo.push_back(mod);
|
||||||
|
};
|
||||||
|
for (const auto &mod : enabled_modules) {
|
||||||
|
visit(visit, mod);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto include_dir = (void_source_dir / "include").lexically_normal().string();
|
||||||
|
VoidLibraryTargets result;
|
||||||
|
|
||||||
|
for (const auto &mod : topo) {
|
||||||
|
const auto &def = defs.at(mod);
|
||||||
|
const auto srcs = collect_sources(void_source_dir / "src" / mod);
|
||||||
|
const std::string target_name = "Void_" + mod;
|
||||||
|
|
||||||
|
Target tgt = srcs.empty() ? project.header_only_library(target_name)
|
||||||
|
: project.static_library(target_name);
|
||||||
|
tgt.cxx_standard(CxxStandard::Cxx26)
|
||||||
|
.include_directory(include_dir, Visibility::Public)
|
||||||
|
.compile_option("-freflection", Visibility::Public);
|
||||||
|
|
||||||
|
for (const auto &s : srcs) {
|
||||||
|
tgt.sources(SourceSet::file(s));
|
||||||
|
}
|
||||||
|
for (const auto &dep : def.internal_deps) {
|
||||||
|
tgt.link(result.modules.at(dep), Visibility::Public);
|
||||||
|
}
|
||||||
|
if (def.needs_threads) {
|
||||||
|
tgt.link_option("-pthread", Visibility::Public);
|
||||||
|
}
|
||||||
|
if (mod == "Testing") {
|
||||||
|
tgt.define("VOID_HAS_CONFIGURATION", Visibility::Public)
|
||||||
|
.define("VOID_HAS_TEXT", Visibility::Public);
|
||||||
|
}
|
||||||
|
result.modules.emplace(mod, tgt);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Recipes
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Recipes {
|
||||||
|
|
||||||
|
// Pure native VBS recipe for VoidLibrary (pinned commit 9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5).
|
||||||
|
// Translates VoidLibrary's module closure directly into native VBS targets without invoking
|
||||||
|
// CMake or modifying the VoidLibrary source checkout (Plan 18).
|
||||||
|
struct VoidLibraryTargets {
|
||||||
|
std::map<std::string, Target, std::less<>> modules;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] VoidLibraryTargets
|
||||||
|
add_void_library_native(Project &project, const std::filesystem::path &void_source_dir,
|
||||||
|
const std::vector<std::string> &enabled_modules = {
|
||||||
|
"Configuration", "Text", "Unicode", "Async", "Testing"});
|
||||||
|
|
||||||
|
} // namespace Void::Build::Recipes
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Registry {
|
||||||
|
|
||||||
|
struct HttpRequest {
|
||||||
|
std::string method;
|
||||||
|
std::string raw_target;
|
||||||
|
std::string path;
|
||||||
|
std::map<std::string, std::string, std::less<>> query;
|
||||||
|
std::map<std::string, std::string, std::less<>> headers; // lowercase header keys
|
||||||
|
std::map<std::string, std::string, std::less<>> cookies;
|
||||||
|
std::string body;
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<std::string_view>
|
||||||
|
header(std::string_view lower_name) const noexcept;
|
||||||
|
[[nodiscard]] std::optional<std::string_view> cookie(std::string_view name) const noexcept;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct HttpResponse {
|
||||||
|
std::uint16_t status{200};
|
||||||
|
std::string reason{"OK"};
|
||||||
|
std::map<std::string, std::string, std::less<>> headers;
|
||||||
|
std::vector<std::string> set_cookies;
|
||||||
|
std::string body;
|
||||||
|
|
||||||
|
static HttpResponse json(std::uint16_t status, std::string payload);
|
||||||
|
static HttpResponse error_json(std::uint16_t status, std::string_view code,
|
||||||
|
std::string_view message);
|
||||||
|
};
|
||||||
|
|
||||||
|
using HttpHandler = std::function<HttpResponse(const HttpRequest &)>;
|
||||||
|
|
||||||
|
struct HttpServerOptions {
|
||||||
|
std::string bind_address{"127.0.0.1"}; // Loopback default (Plan 16).
|
||||||
|
std::uint16_t port{0}; // 0 = ephemeral OS port.
|
||||||
|
std::size_t max_header_bytes{64ULL * 1024ULL};
|
||||||
|
std::size_t max_body_bytes{64ULL * 1024ULL * 1024ULL};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Concrete loopback HTTP/1.1 TCP server adapter (VL-004).
|
||||||
|
class HttpServer {
|
||||||
|
public:
|
||||||
|
HttpServer() = default;
|
||||||
|
~HttpServer() noexcept;
|
||||||
|
|
||||||
|
HttpServer(const HttpServer &) = delete;
|
||||||
|
HttpServer &operator=(const HttpServer &) = delete;
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
start(const HttpServerOptions &options, HttpHandler handler);
|
||||||
|
|
||||||
|
void stop() noexcept;
|
||||||
|
|
||||||
|
[[nodiscard]] std::uint16_t bound_port() const noexcept { return bound_port_; }
|
||||||
|
[[nodiscard]] bool running() const noexcept { return running_.load(); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
void accept_loop();
|
||||||
|
void handle_client(int client_fd);
|
||||||
|
|
||||||
|
int listen_fd_{-1};
|
||||||
|
std::uint16_t bound_port_{0};
|
||||||
|
HttpServerOptions options_;
|
||||||
|
HttpHandler handler_;
|
||||||
|
std::atomic<bool> running_{false};
|
||||||
|
std::thread accept_thread_;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Simple loopback HTTP/1.1 client helper for testing and local registry operations.
|
||||||
|
struct HttpClientResponse {
|
||||||
|
std::uint16_t status{0};
|
||||||
|
std::map<std::string, std::string, std::less<>> headers;
|
||||||
|
std::vector<std::string> set_cookies;
|
||||||
|
std::string body;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<HttpClientResponse, Void::Result::Error>
|
||||||
|
send_loopback_http(std::uint16_t port, std::string_view method, std::string_view target,
|
||||||
|
const std::map<std::string, std::string, std::less<>> &headers = {},
|
||||||
|
std::string_view body = {});
|
||||||
|
|
||||||
|
} // namespace Void::Build::Registry
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Void/Build/Registry/HttpServer.hpp>
|
||||||
|
#include <Void/Functional/Error.hpp>
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <map>
|
||||||
|
#include <mutex>
|
||||||
|
#include <optional>
|
||||||
|
#include <set>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Void::Build::Registry {
|
||||||
|
|
||||||
|
enum class Role { Reader, Publisher, Admin };
|
||||||
|
|
||||||
|
struct UserRecord {
|
||||||
|
std::string username;
|
||||||
|
Role role{Role::Reader};
|
||||||
|
std::string password_salt_hex;
|
||||||
|
std::string password_hash_hex;
|
||||||
|
bool active{true};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ApiTokenRecord {
|
||||||
|
std::string token_id;
|
||||||
|
std::string username;
|
||||||
|
std::string label;
|
||||||
|
std::string token_sha256; // Never stores plaintext bearer secret!
|
||||||
|
std::set<std::string> scopes; // "read", "publish", "admin"
|
||||||
|
std::int64_t expires_epoch{0}; // 0 = no expiry
|
||||||
|
bool revoked{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SessionRecord {
|
||||||
|
std::string session_id_hash;
|
||||||
|
std::string username;
|
||||||
|
std::string csrf_token;
|
||||||
|
std::int64_t expires_epoch{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ReleaseMeta {
|
||||||
|
std::string version;
|
||||||
|
std::string sha256;
|
||||||
|
std::uint64_t size_bytes{0};
|
||||||
|
bool yanked{false};
|
||||||
|
std::string publisher;
|
||||||
|
std::int64_t published_epoch{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct PackageMeta {
|
||||||
|
std::string name;
|
||||||
|
std::string description;
|
||||||
|
bool is_private{false};
|
||||||
|
std::set<std::string> owners;
|
||||||
|
std::map<std::string, ReleaseMeta, std::less<>> releases; // version -> ReleaseMeta
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AuditEntry {
|
||||||
|
std::int64_t timestamp{0};
|
||||||
|
std::string actor;
|
||||||
|
std::string action;
|
||||||
|
std::string target;
|
||||||
|
std::string outcome;
|
||||||
|
std::string detail; // Always secret-redacted!
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RegistryConfig {
|
||||||
|
std::filesystem::path data_dir;
|
||||||
|
std::filesystem::path web_root;
|
||||||
|
std::string bind_address{"127.0.0.1"};
|
||||||
|
std::uint16_t port{0};
|
||||||
|
std::uint64_t max_upload_bytes{32ULL * 1024ULL * 1024ULL};
|
||||||
|
std::uint64_t max_storage_bytes{2ULL * 1024ULL * 1024ULL * 1024ULL};
|
||||||
|
std::string bootstrap_admin_user{"admin"};
|
||||||
|
std::string bootstrap_admin_password; // Required on initial empty DB creation.
|
||||||
|
};
|
||||||
|
|
||||||
|
// Hosted C++ Package Registry Service (Plan 16 + Plan 17 API/UI backend):
|
||||||
|
// - Filesystem CAS blobs + transactional durable metadata
|
||||||
|
// - Immutable source/binary releases (idempotent same bytes, 409 Conflict on overwrite)
|
||||||
|
// - Archive traversal/symlink validation (never executes uploaded recipes!)
|
||||||
|
// - Reader/Publisher/Admin roles, package ownership, private/public isolation
|
||||||
|
// - Hashed scoped bearer tokens + HttpOnly SameSite=Strict sessions with CSRF protection
|
||||||
|
// - Secret-redacted audit log, orphan GC, storage quotas, consistent backup/restore.
|
||||||
|
class RegistryService {
|
||||||
|
public:
|
||||||
|
[[nodiscard]] static Void::Result::Result<std::unique_ptr<RegistryService>, Void::Result::Error>
|
||||||
|
open(RegistryConfig config);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> start_http();
|
||||||
|
void stop_http() noexcept;
|
||||||
|
[[nodiscard]] std::uint16_t bound_port() const noexcept { return server_.bound_port(); }
|
||||||
|
|
||||||
|
// Handles a single HTTP request (directly testable without sockets too!).
|
||||||
|
[[nodiscard]] HttpResponse handle_request(const HttpRequest &req);
|
||||||
|
|
||||||
|
// Consistent metadata + CAS blob backup and restore (Plan 16 acceptance #4).
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
backup_to(const std::filesystem::path &backup_dir);
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
restore_from(const std::filesystem::path &backup_dir);
|
||||||
|
|
||||||
|
// Direct user/token helpers for bootstrap and test fixtures.
|
||||||
|
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||||
|
create_user(std::string username, std::string password, Role role);
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string, Void::Result::Error>
|
||||||
|
create_token(std::string username, std::string label, std::set<std::string> scopes,
|
||||||
|
std::int64_t expires_epoch = 0);
|
||||||
|
|
||||||
|
private:
|
||||||
|
explicit RegistryService(RegistryConfig config);
|
||||||
|
|
||||||
|
struct Principal {
|
||||||
|
std::string username;
|
||||||
|
Role role{Role::Reader};
|
||||||
|
std::set<std::string> scopes;
|
||||||
|
bool via_session_cookie{false};
|
||||||
|
std::string csrf_token;
|
||||||
|
};
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error> load_locked();
|
||||||
|
Void::Result::Result<void, Void::Result::Error> save_locked();
|
||||||
|
std::optional<Principal> authenticate_locked(const HttpRequest &req,
|
||||||
|
std::string &auth_err) const;
|
||||||
|
bool check_csrf_locked(const HttpRequest &req, const Principal &p) const;
|
||||||
|
void append_audit_locked(std::string actor, std::string action, std::string target,
|
||||||
|
std::string outcome, std::string detail);
|
||||||
|
std::uint64_t total_storage_bytes_locked() const;
|
||||||
|
std::filesystem::path blob_path(std::string_view sha256) const;
|
||||||
|
HttpResponse serve_static_web_asset(std::string_view req_path) const;
|
||||||
|
|
||||||
|
RegistryConfig config_;
|
||||||
|
std::filesystem::path blobs_dir_;
|
||||||
|
std::filesystem::path meta_file_;
|
||||||
|
std::filesystem::path lock_file_;
|
||||||
|
mutable std::mutex mu_;
|
||||||
|
|
||||||
|
std::map<std::string, UserRecord, std::less<>> users_;
|
||||||
|
std::map<std::string, ApiTokenRecord, std::less<>> tokens_;
|
||||||
|
std::map<std::string, SessionRecord, std::less<>> sessions_;
|
||||||
|
std::map<std::string, PackageMeta, std::less<>> packages_;
|
||||||
|
std::vector<AuditEntry> audits_;
|
||||||
|
HttpServer server_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Void::Build::Registry
|
||||||
@@ -0,0 +1,446 @@
|
|||||||
|
#include <Void/Build/Registry/HttpServer.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
#include <Void/Text/Str.hpp>
|
||||||
|
#include <Void/Text/Url.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <array>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <cstring>
|
||||||
|
#include <format>
|
||||||
|
#include <netinet/in.h>
|
||||||
|
#include <poll.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
namespace Void::Build::Registry {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string to_lower(std::string_view s) { return Void::Str::to_lower_ascii(s); }
|
||||||
|
|
||||||
|
std::string trim(std::string_view s) { return std::string{Void::Str::trim_ascii(s)}; }
|
||||||
|
|
||||||
|
std::string url_decode(std::string_view s) {
|
||||||
|
return Void::Encoding::Url::decode(s, /*plus_as_space=*/true).value_or(std::string{s});
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string default_reason(std::uint16_t status) {
|
||||||
|
switch (status) {
|
||||||
|
case 200:
|
||||||
|
return "OK";
|
||||||
|
case 201:
|
||||||
|
return "Created";
|
||||||
|
case 204:
|
||||||
|
return "No Content";
|
||||||
|
case 400:
|
||||||
|
return "Bad Request";
|
||||||
|
case 401:
|
||||||
|
return "Unauthorized";
|
||||||
|
case 403:
|
||||||
|
return "Forbidden";
|
||||||
|
case 404:
|
||||||
|
return "Not Found";
|
||||||
|
case 405:
|
||||||
|
return "Method Not Allowed";
|
||||||
|
case 409:
|
||||||
|
return "Conflict";
|
||||||
|
case 413:
|
||||||
|
return "Payload Too Large";
|
||||||
|
case 422:
|
||||||
|
return "Unprocessable Entity";
|
||||||
|
case 500:
|
||||||
|
return "Internal Server Error";
|
||||||
|
default:
|
||||||
|
return "OK";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool send_all(int fd, std::string_view data) {
|
||||||
|
std::size_t off = 0;
|
||||||
|
while (off < data.size()) {
|
||||||
|
const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL);
|
||||||
|
if (n < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
off += static_cast<std::size_t>(n);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void parse_query(std::string_view qs, std::map<std::string, std::string, std::less<>> &out) {
|
||||||
|
std::size_t pos = 0;
|
||||||
|
while (pos < qs.size()) {
|
||||||
|
const auto amp = qs.find('&', pos);
|
||||||
|
const auto pair =
|
||||||
|
qs.substr(pos, amp == std::string_view::npos ? std::string_view::npos : amp - pos);
|
||||||
|
if (!pair.empty()) {
|
||||||
|
const auto eq = pair.find('=');
|
||||||
|
if (eq == std::string_view::npos) {
|
||||||
|
out[url_decode(pair)] = "";
|
||||||
|
} else {
|
||||||
|
out[url_decode(pair.substr(0, eq))] = url_decode(pair.substr(eq + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (amp == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = amp + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void parse_cookies(std::string_view header_val,
|
||||||
|
std::map<std::string, std::string, std::less<>> &out) {
|
||||||
|
std::size_t pos = 0;
|
||||||
|
while (pos < header_val.size()) {
|
||||||
|
const auto semi = header_val.find(';', pos);
|
||||||
|
const auto part = header_val.substr(
|
||||||
|
pos, semi == std::string_view::npos ? std::string_view::npos : semi - pos);
|
||||||
|
const auto eq = part.find('=');
|
||||||
|
if (eq != std::string_view::npos) {
|
||||||
|
out[trim(part.substr(0, eq))] = trim(part.substr(eq + 1));
|
||||||
|
}
|
||||||
|
if (semi == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = semi + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::optional<std::string_view> HttpRequest::header(std::string_view lower_name) const noexcept {
|
||||||
|
const auto it = headers.find(lower_name);
|
||||||
|
if (it == headers.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::string_view> HttpRequest::cookie(std::string_view name) const noexcept {
|
||||||
|
const auto it = cookies.find(name);
|
||||||
|
if (it == cookies.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpResponse HttpResponse::json(std::uint16_t status, std::string payload) {
|
||||||
|
HttpResponse res;
|
||||||
|
res.status = status;
|
||||||
|
res.reason = default_reason(status);
|
||||||
|
res.headers["Content-Type"] = "application/json; charset=utf-8";
|
||||||
|
res.body = std::move(payload);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpResponse HttpResponse::error_json(std::uint16_t status, std::string_view code,
|
||||||
|
std::string_view message) {
|
||||||
|
return json(status, "{\"error\":{\"code\":" + Util::json_quote(code) +
|
||||||
|
",\"message\":" + Util::json_quote(message) + "}}\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpServer::~HttpServer() noexcept { stop(); }
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error> HttpServer::start(const HttpServerOptions &options,
|
||||||
|
HttpHandler handler) {
|
||||||
|
stop();
|
||||||
|
options_ = options;
|
||||||
|
handler_ = std::move(handler);
|
||||||
|
|
||||||
|
const int fd = ::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||||
|
if (fd < 0) {
|
||||||
|
return std::unexpected{sys_err(errno, "HttpServer: socket() failed")};
|
||||||
|
}
|
||||||
|
int opt = 1;
|
||||||
|
(void)::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
|
||||||
|
|
||||||
|
sockaddr_in addr{};
|
||||||
|
addr.sin_family = AF_INET;
|
||||||
|
addr.sin_port = htons(options.port);
|
||||||
|
if (::inet_pton(AF_INET, options.bind_address.c_str(), &addr.sin_addr) != 1) {
|
||||||
|
(void)::close(fd);
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("HttpServer: invalid IPv4 bind address '{}'", options.bind_address))};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (::bind(fd, reinterpret_cast<const sockaddr *>(&addr), sizeof(addr)) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
(void)::close(fd);
|
||||||
|
return std::unexpected{sys_err(err, "HttpServer: bind() failed")};
|
||||||
|
}
|
||||||
|
if (::listen(fd, 64) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
(void)::close(fd);
|
||||||
|
return std::unexpected{sys_err(err, "HttpServer: listen() failed")};
|
||||||
|
}
|
||||||
|
|
||||||
|
sockaddr_in actual{};
|
||||||
|
socklen_t len = sizeof(actual);
|
||||||
|
if (::getsockname(fd, reinterpret_cast<sockaddr *>(&actual), &len) == 0) {
|
||||||
|
bound_port_ = ntohs(actual.sin_port);
|
||||||
|
}
|
||||||
|
|
||||||
|
listen_fd_ = fd;
|
||||||
|
running_.store(true);
|
||||||
|
accept_thread_ = std::thread([this] { accept_loop(); });
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpServer::stop() noexcept {
|
||||||
|
running_.store(false);
|
||||||
|
if (listen_fd_ >= 0) {
|
||||||
|
(void)::shutdown(listen_fd_, SHUT_RDWR);
|
||||||
|
(void)::close(listen_fd_);
|
||||||
|
listen_fd_ = -1;
|
||||||
|
}
|
||||||
|
if (accept_thread_.joinable()) {
|
||||||
|
accept_thread_.join();
|
||||||
|
}
|
||||||
|
bound_port_ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpServer::accept_loop() {
|
||||||
|
while (running_.load()) {
|
||||||
|
struct pollfd pfd{listen_fd_, POLLIN, 0};
|
||||||
|
const int ready = ::poll(&pfd, 1, 50);
|
||||||
|
if (ready <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const int client_fd = ::accept4(listen_fd_, nullptr, nullptr, SOCK_CLOEXEC);
|
||||||
|
if (client_fd < 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Handle client connection with bounded read timeout.
|
||||||
|
handle_client(client_fd);
|
||||||
|
(void)::close(client_fd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpServer::handle_client(int client_fd) {
|
||||||
|
struct timeval tv{10, 0};
|
||||||
|
(void)::setsockopt(client_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||||
|
(void)::setsockopt(client_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||||||
|
|
||||||
|
auto write_response = [&](HttpResponse resp) {
|
||||||
|
if (resp.reason.empty()) {
|
||||||
|
resp.reason = default_reason(resp.status);
|
||||||
|
}
|
||||||
|
// Default security headers (Plan 16/17).
|
||||||
|
resp.headers.emplace("X-Content-Type-Options", "nosniff");
|
||||||
|
resp.headers.emplace("X-Frame-Options", "DENY");
|
||||||
|
resp.headers.emplace("Referrer-Policy", "no-referrer");
|
||||||
|
resp.headers.emplace(
|
||||||
|
"Content-Security-Policy",
|
||||||
|
"default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'");
|
||||||
|
resp.headers["Content-Length"] = std::to_string(resp.body.size());
|
||||||
|
resp.headers["Connection"] = "close";
|
||||||
|
|
||||||
|
std::string wire = std::format("HTTP/1.1 {} {}\r\n", resp.status, resp.reason);
|
||||||
|
for (const auto &[k, v] : resp.headers) {
|
||||||
|
wire += k + ": " + v + "\r\n";
|
||||||
|
}
|
||||||
|
for (const auto &cookie : resp.set_cookies) {
|
||||||
|
wire += "Set-Cookie: " + cookie + "\r\n";
|
||||||
|
}
|
||||||
|
wire += "\r\n";
|
||||||
|
wire += resp.body;
|
||||||
|
(void)send_all(client_fd, wire);
|
||||||
|
};
|
||||||
|
|
||||||
|
std::string raw;
|
||||||
|
std::array<char, 16384> buf{};
|
||||||
|
std::size_t header_end = std::string::npos;
|
||||||
|
|
||||||
|
while (header_end == std::string::npos) {
|
||||||
|
const ssize_t n = ::recv(client_fd, buf.data(), buf.size(), 0);
|
||||||
|
if (n <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
raw.append(buf.data(), static_cast<std::size_t>(n));
|
||||||
|
header_end = raw.find("\r\n\r\n");
|
||||||
|
if (header_end == std::string::npos && raw.size() > options_.max_header_bytes) {
|
||||||
|
write_response(HttpResponse::error_json(431, "headers_too_large",
|
||||||
|
"HTTP headers exceed maximum size"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string_view header_block{raw.data(), header_end};
|
||||||
|
const auto first_crlf = header_block.find("\r\n");
|
||||||
|
const auto req_line = header_block.substr(0, first_crlf);
|
||||||
|
const auto sp1 = req_line.find(' ');
|
||||||
|
const auto sp2 =
|
||||||
|
sp1 == std::string_view::npos ? std::string_view::npos : req_line.find(' ', sp1 + 1);
|
||||||
|
if (sp1 == std::string_view::npos || sp2 == std::string_view::npos) {
|
||||||
|
write_response(HttpResponse::error_json(400, "bad_request", "malformed HTTP request line"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpRequest req;
|
||||||
|
req.method = std::string{req_line.substr(0, sp1)};
|
||||||
|
req.raw_target = std::string{req_line.substr(sp1 + 1, sp2 - sp1 - 1)};
|
||||||
|
const auto qpos = req.raw_target.find('?');
|
||||||
|
if (qpos == std::string::npos) {
|
||||||
|
req.path = req.raw_target;
|
||||||
|
} else {
|
||||||
|
req.path = req.raw_target.substr(0, qpos);
|
||||||
|
parse_query(std::string_view{req.raw_target}.substr(qpos + 1), req.query);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (first_crlf != std::string_view::npos) {
|
||||||
|
std::size_t pos = first_crlf + 2;
|
||||||
|
while (pos < header_block.size()) {
|
||||||
|
const auto next = header_block.find("\r\n", pos);
|
||||||
|
const auto line = header_block.substr(
|
||||||
|
pos, next == std::string_view::npos ? std::string_view::npos : next - pos);
|
||||||
|
const auto colon = line.find(':');
|
||||||
|
if (colon != std::string_view::npos) {
|
||||||
|
const auto name = to_lower(trim(line.substr(0, colon)));
|
||||||
|
const auto val = trim(line.substr(colon + 1));
|
||||||
|
req.headers[name] = val;
|
||||||
|
if (name == "cookie") {
|
||||||
|
parse_cookies(val, req.cookies);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (next == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = next + 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t content_length = 0;
|
||||||
|
if (const auto cl = req.header("content-length")) {
|
||||||
|
try {
|
||||||
|
content_length = static_cast<std::size_t>(std::stoull(std::string{*cl}));
|
||||||
|
} catch (...) {
|
||||||
|
write_response(HttpResponse::error_json(400, "bad_content_length",
|
||||||
|
"invalid Content-Length header"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (content_length > options_.max_body_bytes) {
|
||||||
|
write_response(HttpResponse::error_json(413, "payload_too_large",
|
||||||
|
"request body exceeds configured limit"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
req.body = raw.substr(header_end + 4);
|
||||||
|
while (req.body.size() < content_length) {
|
||||||
|
const std::size_t want = std::min(buf.size(), content_length - req.body.size());
|
||||||
|
const ssize_t n = ::recv(client_fd, buf.data(), want, 0);
|
||||||
|
if (n <= 0) {
|
||||||
|
write_response(
|
||||||
|
HttpResponse::error_json(400, "truncated_body", "truncated HTTP request body"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
req.body.append(buf.data(), static_cast<std::size_t>(n));
|
||||||
|
}
|
||||||
|
if (req.body.size() > content_length) {
|
||||||
|
req.body.resize(content_length);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
write_response(handler_(req));
|
||||||
|
} catch (const std::exception &ex) {
|
||||||
|
write_response(HttpResponse::error_json(500, "internal_error", ex.what()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<HttpClientResponse, Void::Result::Error>
|
||||||
|
send_loopback_http(std::uint16_t port, std::string_view method, std::string_view target,
|
||||||
|
const std::map<std::string, std::string, std::less<>> &headers,
|
||||||
|
std::string_view body) {
|
||||||
|
const int fd = ::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||||
|
if (fd < 0) {
|
||||||
|
return std::unexpected{sys_err(errno, "send_loopback_http: socket() failed")};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd guard{fd};
|
||||||
|
|
||||||
|
sockaddr_in addr{};
|
||||||
|
addr.sin_family = AF_INET;
|
||||||
|
addr.sin_port = htons(port);
|
||||||
|
(void)::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
|
||||||
|
if (::connect(fd, reinterpret_cast<const sockaddr *>(&addr), sizeof(addr)) != 0) {
|
||||||
|
return std::unexpected{sys_err(errno, "send_loopback_http: connect() failed")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string req = std::format("{} {} HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nConnection: close\r\n"
|
||||||
|
"Content-Length: {}\r\n",
|
||||||
|
method, target, port, body.size());
|
||||||
|
for (const auto &[k, v] : headers) {
|
||||||
|
req += k + ": " + v + "\r\n";
|
||||||
|
}
|
||||||
|
req += "\r\n";
|
||||||
|
req += body;
|
||||||
|
if (!send_all(fd, req)) {
|
||||||
|
return std::unexpected{sys_err(errno, "send_loopback_http: send() failed")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string raw;
|
||||||
|
std::array<char, 16384> buf{};
|
||||||
|
for (;;) {
|
||||||
|
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
|
||||||
|
if (n > 0) {
|
||||||
|
raw.append(buf.data(), static_cast<std::size_t>(n));
|
||||||
|
} else if (n == 0) {
|
||||||
|
break;
|
||||||
|
} else if (errno != EINTR) {
|
||||||
|
return std::unexpected{sys_err(errno, "send_loopback_http: recv() failed")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto hdr_end = raw.find("\r\n\r\n");
|
||||||
|
if (hdr_end == std::string::npos) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::io_error, "malformed HTTP response")};
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpClientResponse resp;
|
||||||
|
const std::string_view header_block{raw.data(), hdr_end};
|
||||||
|
const auto first_crlf = header_block.find("\r\n");
|
||||||
|
const auto status_line = header_block.substr(0, first_crlf);
|
||||||
|
const auto sp1 = status_line.find(' ');
|
||||||
|
if (sp1 != std::string_view::npos) {
|
||||||
|
resp.status =
|
||||||
|
static_cast<std::uint16_t>(std::stoi(std::string{status_line.substr(sp1 + 1, 3)}));
|
||||||
|
}
|
||||||
|
if (first_crlf != std::string_view::npos) {
|
||||||
|
std::size_t pos = first_crlf + 2;
|
||||||
|
while (pos < header_block.size()) {
|
||||||
|
const auto next = header_block.find("\r\n", pos);
|
||||||
|
const auto line = header_block.substr(
|
||||||
|
pos, next == std::string_view::npos ? std::string_view::npos : next - pos);
|
||||||
|
const auto colon = line.find(':');
|
||||||
|
if (colon != std::string_view::npos) {
|
||||||
|
const auto name = to_lower(trim(line.substr(0, colon)));
|
||||||
|
const auto val = trim(line.substr(colon + 1));
|
||||||
|
if (name == "set-cookie") {
|
||||||
|
resp.set_cookies.push_back(val);
|
||||||
|
} else {
|
||||||
|
resp.headers[name] = val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (next == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = next + 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resp.body = raw.substr(hdr_end + 4);
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Registry
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
#include <Void/Build/BootstrapConfig.hpp>
|
||||||
|
#include <Void/Build/Registry/RegistryService.hpp>
|
||||||
|
#include <Void/Configuration/Argparse.hpp>
|
||||||
|
#include <Void/Configuration/Env.hpp>
|
||||||
|
#include <Void/System/SignalWatcher.hpp>
|
||||||
|
#include <Void/Text/Str.hpp>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
std::string data_dir;
|
||||||
|
std::string web_root;
|
||||||
|
std::string bind_address;
|
||||||
|
std::string port_str;
|
||||||
|
std::string pass_env;
|
||||||
|
|
||||||
|
const std::string default_web_root =
|
||||||
|
(std::filesystem::path{Void::Build::Bootstrap::source_dir} / "registry" / "web").string();
|
||||||
|
|
||||||
|
Void::Argparse::Parser parser{
|
||||||
|
"vbs-registry",
|
||||||
|
"Loopback-default VoidBuildSystem package registry service and web administration UI."};
|
||||||
|
parser
|
||||||
|
.option_default("--data-dir", "", "registry metadata and CAS directory", data_dir,
|
||||||
|
"registry-data")
|
||||||
|
.option_default("--web-root", "", "static web admin assets directory", web_root,
|
||||||
|
default_web_root)
|
||||||
|
.option_default("--bind", "", "IPv4 bind address", bind_address, "127.0.0.1")
|
||||||
|
.option_default("--port", "", "listening TCP port (0 for ephemeral)", port_str, "8080")
|
||||||
|
.option_default("--admin-password-env", "",
|
||||||
|
"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();
|
||||||
|
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';
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
int port_int = 0;
|
||||||
|
if (!Void::Str::to_int(port_str, port_int) || port_int < 0 || port_int > 65535) {
|
||||||
|
std::cerr << "vbs-registry: invalid --port value '" << port_str << "'\n";
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Build::Registry::RegistryConfig cfg;
|
||||||
|
cfg.data_dir = data_dir;
|
||||||
|
cfg.web_root = web_root;
|
||||||
|
cfg.bind_address = bind_address;
|
||||||
|
cfg.port = static_cast<std::uint16_t>(port_int);
|
||||||
|
if (auto pw = Void::Configuration::get_env(pass_env); pw) {
|
||||||
|
cfg.bootstrap_admin_password = std::move(*pw);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto signals = Void::Process::SignalWatcher::create();
|
||||||
|
auto svc = Void::Build::Registry::RegistryService::open(std::move(cfg));
|
||||||
|
if (!svc) {
|
||||||
|
std::cerr << "vbs-registry: failed opening registry: " << svc.error().message() << '\n';
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (auto started = (*svc)->start_http(); !started) {
|
||||||
|
std::cerr << "vbs-registry: failed starting HTTP server: " << started.error().message()
|
||||||
|
<< '\n';
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << "vbs-registry listening on http://" << bind_address << ":" << (*svc)->bound_port()
|
||||||
|
<< " (SIGINT/SIGTERM to stop)\n"
|
||||||
|
<< std::flush;
|
||||||
|
|
||||||
|
if (signals) {
|
||||||
|
(void)signals->wait();
|
||||||
|
}
|
||||||
|
(*svc)->stop_http();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,375 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
// VoidBuildSystem Registry Web UI (Plan 17)
|
||||||
|
// Security invariants:
|
||||||
|
// - Never uses innerHTML on untrusted server data (DOM nodes + textContent only -> XSS safe).
|
||||||
|
// - Uses HttpOnly cookie sessions + X-CSRF-Token header on every mutation.
|
||||||
|
// - Never reports optimistic success before durable server confirmation; prevents double submits.
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
user: null,
|
||||||
|
csrfToken: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
function el(tag, attrs = {}, text = "") {
|
||||||
|
const node = document.createElement(tag);
|
||||||
|
for (const [k, v] of Object.entries(attrs)) {
|
||||||
|
if (k === "class") node.className = v;
|
||||||
|
else node.setAttribute(k, v);
|
||||||
|
}
|
||||||
|
if (text !== "") node.textContent = text;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showBanner(message, isError = false) {
|
||||||
|
const b = document.getElementById("status-banner");
|
||||||
|
b.textContent = message;
|
||||||
|
b.className = isError ? "banner error" : "banner";
|
||||||
|
b.hidden = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearBanner() {
|
||||||
|
document.getElementById("status-banner").hidden = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function apiJson(path, options = {}) {
|
||||||
|
const headers = Object.assign({}, options.headers || {});
|
||||||
|
if (options.method && options.method !== "GET" && state.csrfToken) {
|
||||||
|
headers["X-CSRF-Token"] = state.csrfToken;
|
||||||
|
}
|
||||||
|
const resp = await fetch(path, Object.assign({ credentials: "same-origin" }, options, { headers }));
|
||||||
|
let data = null;
|
||||||
|
try {
|
||||||
|
data = await resp.json();
|
||||||
|
} catch {
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
if (!resp.ok) {
|
||||||
|
const msg = data && data.error && data.error.message ? data.error.message : `HTTP ${resp.status}`;
|
||||||
|
throw new Error(msg);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setView(viewName) {
|
||||||
|
clearBanner();
|
||||||
|
for (const sec of document.querySelectorAll("main > section")) {
|
||||||
|
sec.hidden = sec.id !== `view-${viewName}`;
|
||||||
|
}
|
||||||
|
for (const btn of document.querySelectorAll(".nav-btn[data-view]")) {
|
||||||
|
btn.classList.toggle("active", btn.dataset.view === viewName);
|
||||||
|
}
|
||||||
|
if (viewName === "packages") loadPackages();
|
||||||
|
if (viewName === "tokens") loadTokens();
|
||||||
|
if (viewName === "admin") loadAdmin();
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateNavForSession() {
|
||||||
|
const loggedIn = Boolean(state.user);
|
||||||
|
const role = state.user ? state.user.role : "";
|
||||||
|
document.getElementById("nav-login").hidden = loggedIn;
|
||||||
|
document.getElementById("btn-logout").hidden = !loggedIn;
|
||||||
|
document.getElementById("nav-tokens").hidden = !loggedIn;
|
||||||
|
document.getElementById("nav-publish").hidden = !(role === "publisher" || role === "admin");
|
||||||
|
document.getElementById("nav-admin").hidden = role !== "admin";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshSession() {
|
||||||
|
try {
|
||||||
|
const me = await apiJson("/api/v1/auth/me");
|
||||||
|
state.user = { username: me.username, role: me.role };
|
||||||
|
state.csrfToken = me.csrf_token || "";
|
||||||
|
} catch {
|
||||||
|
state.user = null;
|
||||||
|
state.csrfToken = "";
|
||||||
|
}
|
||||||
|
updateNavForSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPackages() {
|
||||||
|
const list = document.getElementById("packages-list");
|
||||||
|
list.replaceChildren(el("p", { class: "muted" }, "Loading packages..."));
|
||||||
|
const q = document.getElementById("search-input").value.trim();
|
||||||
|
const url = q ? `/api/v1/packages?q=${encodeURIComponent(q)}` : "/api/v1/packages";
|
||||||
|
try {
|
||||||
|
const data = await apiJson(url);
|
||||||
|
list.replaceChildren();
|
||||||
|
if (!data.packages || data.packages.length === 0) {
|
||||||
|
list.appendChild(el("p", { class: "muted" }, "No packages matched."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const pkg of data.packages) {
|
||||||
|
const card = el("div", { class: "card" });
|
||||||
|
const info = el("div");
|
||||||
|
info.appendChild(el("strong", {}, pkg.name));
|
||||||
|
if (pkg.is_private) info.appendChild(el("span", { class: "muted" }, " [private]"));
|
||||||
|
info.appendChild(el("div", { class: "muted" }, pkg.description || "No description"));
|
||||||
|
const btn = el("button", { type: "button" }, `Inspect (${pkg.release_count})`);
|
||||||
|
btn.addEventListener("click", () => loadPackageDetail(pkg.name));
|
||||||
|
card.append(info, btn);
|
||||||
|
list.appendChild(card);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showBanner(`Failed loading packages: ${err.message}`, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPackageDetail(name) {
|
||||||
|
const box = document.getElementById("package-detail");
|
||||||
|
box.hidden = false;
|
||||||
|
box.replaceChildren(el("p", { class: "muted" }, `Loading ${name}...`));
|
||||||
|
try {
|
||||||
|
const pkg = await apiJson(`/api/v1/packages/${encodeURIComponent(name)}`);
|
||||||
|
box.replaceChildren();
|
||||||
|
box.appendChild(el("h3", {}, pkg.name));
|
||||||
|
box.appendChild(el("p", { class: "muted" }, pkg.description || "No description"));
|
||||||
|
box.appendChild(el("p", { class: "muted" }, `Owners: ${(pkg.owners || []).join(", ")}`));
|
||||||
|
|
||||||
|
const tbl = el("table");
|
||||||
|
const thead = el("thead");
|
||||||
|
const tr = el("tr");
|
||||||
|
for (const col of ["Version", "SHA-256", "Bytes", "Status", "Actions"]) {
|
||||||
|
tr.appendChild(el("th", {}, col));
|
||||||
|
}
|
||||||
|
thead.appendChild(tr);
|
||||||
|
tbl.appendChild(thead);
|
||||||
|
|
||||||
|
const tbody = el("tbody");
|
||||||
|
for (const rel of pkg.releases || []) {
|
||||||
|
const row = el("tr");
|
||||||
|
row.appendChild(el("td", {}, rel.version));
|
||||||
|
row.appendChild(el("td", {}, rel.sha256.slice(0, 16) + "..."));
|
||||||
|
row.appendChild(el("td", {}, String(rel.size_bytes)));
|
||||||
|
row.appendChild(el("td", {}, rel.yanked ? "Yanked" : "Active"));
|
||||||
|
const actTd = el("td");
|
||||||
|
const dl = el("a", {
|
||||||
|
href: `/api/v1/packages/${encodeURIComponent(pkg.name)}/${encodeURIComponent(rel.version)}/download`,
|
||||||
|
}, "Download");
|
||||||
|
actTd.appendChild(dl);
|
||||||
|
if (state.user && (state.user.role === "admin" || state.user.role === "publisher")) {
|
||||||
|
const ybtn = el("button", { type: "button" }, rel.yanked ? "Unyank" : "Yank");
|
||||||
|
ybtn.style.marginLeft = "0.5rem";
|
||||||
|
ybtn.addEventListener("click", async () => {
|
||||||
|
ybtn.disabled = true;
|
||||||
|
try {
|
||||||
|
await apiJson(
|
||||||
|
`/api/v1/packages/${encodeURIComponent(pkg.name)}/${encodeURIComponent(rel.version)}/yank`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ yanked: !rel.yanked }),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
showBanner(`${pkg.name}@${rel.version} updated.`);
|
||||||
|
await loadPackageDetail(pkg.name);
|
||||||
|
} catch (e) {
|
||||||
|
showBanner(e.message, true);
|
||||||
|
} finally {
|
||||||
|
ybtn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
actTd.appendChild(ybtn);
|
||||||
|
}
|
||||||
|
row.appendChild(actTd);
|
||||||
|
tbody.appendChild(row);
|
||||||
|
}
|
||||||
|
tbl.appendChild(tbody);
|
||||||
|
box.appendChild(tbl);
|
||||||
|
} catch (err) {
|
||||||
|
showBanner(`Failed loading package detail: ${err.message}`, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTokens() {
|
||||||
|
const box = document.getElementById("tokens-list");
|
||||||
|
box.replaceChildren(el("p", { class: "muted" }, "Loading tokens..."));
|
||||||
|
try {
|
||||||
|
const data = await apiJson("/api/v1/tokens");
|
||||||
|
box.replaceChildren();
|
||||||
|
for (const t of data.tokens || []) {
|
||||||
|
const card = el("div", { class: "card" });
|
||||||
|
const txt = `${t.label || t.token_id} (${t.username}) — scopes: ${(t.scopes || []).join(", ")} — ${t.revoked ? "REVOKED" : "active"}`;
|
||||||
|
card.appendChild(el("span", {}, txt));
|
||||||
|
if (!t.revoked) {
|
||||||
|
const rev = el("button", { type: "button" }, "Revoke");
|
||||||
|
rev.addEventListener("click", async () => {
|
||||||
|
rev.disabled = true;
|
||||||
|
try {
|
||||||
|
await apiJson(`/api/v1/tokens/${encodeURIComponent(t.token_id)}`, { method: "DELETE" });
|
||||||
|
showBanner(`Revoked token ${t.token_id}`);
|
||||||
|
await loadTokens();
|
||||||
|
} catch (e) {
|
||||||
|
showBanner(e.message, true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
card.appendChild(rev);
|
||||||
|
}
|
||||||
|
box.appendChild(card);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showBanner(err.message, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAdmin() {
|
||||||
|
try {
|
||||||
|
const [st, us, au] = await Promise.all([
|
||||||
|
apiJson("/api/v1/admin/storage"),
|
||||||
|
apiJson("/api/v1/users"),
|
||||||
|
apiJson("/api/v1/audit"),
|
||||||
|
]);
|
||||||
|
document.getElementById("storage-stats").textContent =
|
||||||
|
`Storage: ${st.used_bytes} / ${st.quota_bytes} bytes across ${st.package_count} packages`;
|
||||||
|
|
||||||
|
const ubox = document.getElementById("users-list");
|
||||||
|
ubox.replaceChildren();
|
||||||
|
for (const u of us.users || []) {
|
||||||
|
ubox.appendChild(el("div", { class: "card" }, `${u.username} — role: ${u.role}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
const abox = document.getElementById("audit-list");
|
||||||
|
abox.replaceChildren();
|
||||||
|
for (const a of (au.audits || []).slice(-50).reverse()) {
|
||||||
|
abox.appendChild(
|
||||||
|
el("div", { class: "muted" }, `[${a.timestamp}] ${a.actor} ${a.action} ${a.target} => ${a.outcome} ${a.detail}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showBanner(err.message, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll(".nav-btn[data-view]").forEach((btn) => {
|
||||||
|
btn.addEventListener("click", () => setView(btn.dataset.view));
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById("btn-search").addEventListener("click", loadPackages);
|
||||||
|
document.getElementById("search-input").addEventListener("keydown", (e) => {
|
||||||
|
if (e.key === "Enter") loadPackages();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById("login-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const btn = document.getElementById("btn-login-submit");
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const res = await apiJson("/api/v1/auth/login", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
username: document.getElementById("login-username").value,
|
||||||
|
password: document.getElementById("login-password").value,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
state.user = { username: res.username, role: res.role };
|
||||||
|
state.csrfToken = res.csrf_token || "";
|
||||||
|
updateNavForSession();
|
||||||
|
showBanner(`Signed in as ${res.username} (${res.role}).`);
|
||||||
|
setView("packages");
|
||||||
|
} catch (err) {
|
||||||
|
showBanner(`Sign in failed: ${err.message}`, true);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById("btn-logout").addEventListener("click", async () => {
|
||||||
|
try {
|
||||||
|
await apiJson("/api/v1/auth/logout", { method: "POST" });
|
||||||
|
} catch {}
|
||||||
|
state.user = null;
|
||||||
|
state.csrfToken = "";
|
||||||
|
updateNavForSession();
|
||||||
|
setView("packages");
|
||||||
|
showBanner("Signed out.");
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById("publish-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const btn = document.getElementById("btn-publish-submit");
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const name = document.getElementById("pub-name").value.trim();
|
||||||
|
const version = document.getElementById("pub-version").value.trim();
|
||||||
|
const desc = document.getElementById("pub-desc").value.trim();
|
||||||
|
const isPriv = document.getElementById("pub-private").checked;
|
||||||
|
const file = document.getElementById("pub-file").files[0];
|
||||||
|
if (!file) throw new Error("Choose a .tar archive first");
|
||||||
|
const buf = await file.arrayBuffer();
|
||||||
|
const res = await apiJson(
|
||||||
|
`/api/v1/packages/${encodeURIComponent(name)}/${encodeURIComponent(version)}`,
|
||||||
|
{
|
||||||
|
method: "PUT",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-tar",
|
||||||
|
"X-Package-Description": desc,
|
||||||
|
"X-Package-Private": isPriv ? "true" : "false",
|
||||||
|
},
|
||||||
|
body: buf,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
showBanner(`Published ${res.name || name}@${res.version || version} (sha256=${res.sha256}).`);
|
||||||
|
} catch (err) {
|
||||||
|
showBanner(`Publish failed: ${err.message}`, true);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById("token-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const btn = document.getElementById("btn-token-create");
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const scopes = Array.from(document.querySelectorAll("#token-form input[name='scope']:checked")).map(
|
||||||
|
(n) => n.value,
|
||||||
|
);
|
||||||
|
const res = await apiJson("/api/v1/tokens", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ label: document.getElementById("tok-label").value.trim(), scopes }),
|
||||||
|
});
|
||||||
|
const box = document.getElementById("created-token-box");
|
||||||
|
box.textContent = `Save this token now (shown once only): ${res.token}`;
|
||||||
|
box.hidden = false;
|
||||||
|
await loadTokens();
|
||||||
|
} catch (err) {
|
||||||
|
showBanner(`Token creation failed: ${err.message}`, true);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById("user-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const btn = document.getElementById("btn-user-create");
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
await apiJson("/api/v1/users", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
username: document.getElementById("u-name").value.trim(),
|
||||||
|
password: document.getElementById("u-pass").value,
|
||||||
|
role: document.getElementById("u-role").value,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
showBanner("User saved.");
|
||||||
|
await loadAdmin();
|
||||||
|
} catch (err) {
|
||||||
|
showBanner(err.message, true);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
(async function init() {
|
||||||
|
try {
|
||||||
|
await apiJson("/api/v1/health");
|
||||||
|
document.getElementById("health-badge").textContent = "Healthy";
|
||||||
|
} catch {
|
||||||
|
document.getElementById("health-badge").textContent = "Unavailable";
|
||||||
|
}
|
||||||
|
await refreshSession();
|
||||||
|
await loadPackages();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>VoidBuildSystem Package Registry</title>
|
||||||
|
<link rel="stylesheet" href="/styles.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="brand">
|
||||||
|
<h1>VoidBuildSystem Registry</h1>
|
||||||
|
<span class="badge" id="health-badge" role="status">Connecting...</span>
|
||||||
|
</div>
|
||||||
|
<nav aria-label="Primary navigation">
|
||||||
|
<button type="button" class="nav-btn active" data-view="packages">Packages</button>
|
||||||
|
<button type="button" class="nav-btn" data-view="publish" id="nav-publish" hidden>Publish</button>
|
||||||
|
<button type="button" class="nav-btn" data-view="tokens" id="nav-tokens" hidden>Tokens</button>
|
||||||
|
<button type="button" class="nav-btn" data-view="admin" id="nav-admin" hidden>Admin</button>
|
||||||
|
<button type="button" class="nav-btn" data-view="login" id="nav-login">Sign In</button>
|
||||||
|
<button type="button" class="nav-btn" id="btn-logout" hidden>Sign Out</button>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<div id="status-banner" class="banner" role="alert" aria-live="polite" hidden></div>
|
||||||
|
|
||||||
|
<section id="view-packages" class="panel">
|
||||||
|
<div class="toolbar">
|
||||||
|
<label for="search-input" class="sr-only">Search packages</label>
|
||||||
|
<input id="search-input" type="search" placeholder="Search packages by name or description...">
|
||||||
|
<button type="button" id="btn-search">Search</button>
|
||||||
|
</div>
|
||||||
|
<div id="packages-list" class="grid"></div>
|
||||||
|
<div id="package-detail" class="detail" hidden></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="view-login" class="panel" hidden>
|
||||||
|
<h2>Sign In</h2>
|
||||||
|
<form id="login-form">
|
||||||
|
<label for="login-username">Username</label>
|
||||||
|
<input id="login-username" name="username" autocomplete="username" required>
|
||||||
|
<label for="login-password">Password</label>
|
||||||
|
<input id="login-password" name="password" type="password" autocomplete="current-password" required>
|
||||||
|
<button type="submit" id="btn-login-submit">Sign In</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="view-publish" class="panel" hidden>
|
||||||
|
<h2>Publish Immutable Release</h2>
|
||||||
|
<form id="publish-form">
|
||||||
|
<label for="pub-name">Package Name</label>
|
||||||
|
<input id="pub-name" required pattern="[A-Za-z0-9_.\-]{1,64}">
|
||||||
|
<label for="pub-version">SemVer Version</label>
|
||||||
|
<input id="pub-version" required placeholder="1.0.0">
|
||||||
|
<label for="pub-desc">Description</label>
|
||||||
|
<input id="pub-desc" placeholder="Short package summary">
|
||||||
|
<label class="checkbox">
|
||||||
|
<input id="pub-private" type="checkbox"> Private package
|
||||||
|
</label>
|
||||||
|
<label for="pub-file">Archive (.tar)</label>
|
||||||
|
<input id="pub-file" type="file" required>
|
||||||
|
<button type="submit" id="btn-publish-submit">Upload & Publish</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="view-tokens" class="panel" hidden>
|
||||||
|
<h2>Scoped API Tokens</h2>
|
||||||
|
<form id="token-form">
|
||||||
|
<label for="tok-label">Token Label</label>
|
||||||
|
<input id="tok-label" required placeholder="ci-publisher">
|
||||||
|
<label><input type="checkbox" name="scope" value="read" checked> read</label>
|
||||||
|
<label><input type="checkbox" name="scope" value="publish"> publish</label>
|
||||||
|
<label><input type="checkbox" name="scope" value="admin"> admin</label>
|
||||||
|
<button type="submit" id="btn-token-create">Create Token</button>
|
||||||
|
</form>
|
||||||
|
<div id="created-token-box" class="token-once" hidden></div>
|
||||||
|
<div id="tokens-list"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="view-admin" class="panel" hidden>
|
||||||
|
<h2>Administration</h2>
|
||||||
|
<div id="storage-stats" class="stats"></div>
|
||||||
|
<h3>Users & Roles</h3>
|
||||||
|
<form id="user-form">
|
||||||
|
<label for="u-name">Username</label>
|
||||||
|
<input id="u-name" required>
|
||||||
|
<label for="u-pass">Password (min 6 chars)</label>
|
||||||
|
<input id="u-pass" type="password" minlength="6" required>
|
||||||
|
<label for="u-role">Role</label>
|
||||||
|
<select id="u-role">
|
||||||
|
<option value="reader">Reader</option>
|
||||||
|
<option value="publisher">Publisher</option>
|
||||||
|
<option value="admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
<button type="submit" id="btn-user-create">Save User</button>
|
||||||
|
</form>
|
||||||
|
<div id="users-list"></div>
|
||||||
|
<h3>Audit Log (Secret-Redacted)</h3>
|
||||||
|
<div id="audit-list"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
--bg: #0f1218;
|
||||||
|
--surface: #171c26;
|
||||||
|
--border: #2b3344;
|
||||||
|
--text: #e6ebf5;
|
||||||
|
--muted: #9aa7bd;
|
||||||
|
--accent: #5fa8ff;
|
||||||
|
--danger: #f06a6a;
|
||||||
|
--ok: #58d68d;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: system-ui, -apple-system, sans-serif;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
.topbar {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
background: var(--surface);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
gap: 1rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.brand { display: flex; align-items: center; gap: 0.75rem; }
|
||||||
|
.brand h1 { margin: 0; font-size: 1.15rem; }
|
||||||
|
.badge {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
padding: 0.15rem 0.5rem;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
color: var(--ok);
|
||||||
|
}
|
||||||
|
nav { display: flex; gap: 0.5rem; flex-wrap: wrap; }
|
||||||
|
button {
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--text);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.45rem 0.85rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
button:hover, button:focus-visible { border-color: var(--accent); outline: 2px solid var(--accent); }
|
||||||
|
button.active { background: var(--accent); color: #09101c; border-color: var(--accent); }
|
||||||
|
button:disabled { opacity: 0.55; cursor: not-allowed; }
|
||||||
|
main { max-width: 1000px; margin: 1.5rem auto; padding: 0 1rem; }
|
||||||
|
.panel {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 1.25rem;
|
||||||
|
}
|
||||||
|
.toolbar { display: flex; gap: 0.5rem; margin-bottom: 1rem; }
|
||||||
|
input, select {
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
width: 100%;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
.toolbar input { margin-bottom: 0; flex: 1; }
|
||||||
|
.grid { display: grid; gap: 0.75rem; }
|
||||||
|
.card {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 0.85rem;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
.muted { color: var(--muted); font-size: 0.9rem; }
|
||||||
|
.banner {
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
border: 1px solid var(--accent);
|
||||||
|
background: #132238;
|
||||||
|
}
|
||||||
|
.banner.error { border-color: var(--danger); background: #2d1418; }
|
||||||
|
.token-once {
|
||||||
|
padding: 0.85rem;
|
||||||
|
margin: 1rem 0;
|
||||||
|
border: 1px solid var(--ok);
|
||||||
|
border-radius: 8px;
|
||||||
|
font-family: monospace;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
.detail { margin-top: 1.25rem; border-top: 1px solid var(--border); padding-top: 1rem; }
|
||||||
|
table { width: 100%; border-collapse: collapse; margin-top: 0.75rem; font-size: 0.9rem; }
|
||||||
|
th, td { text-align: left; padding: 0.5rem; border-bottom: 1px solid var(--border); }
|
||||||
|
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0,0,0,0); }
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
#include <Void/Build/Bridge/CMakeBridge.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Config/Frontend.hpp>
|
||||||
|
#include <Void/Build/Execution/Scheduler.hpp>
|
||||||
|
#include <Void/Build/Graph/Graph.hpp>
|
||||||
|
#include <Void/Build/Package/Fetch.hpp>
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Provider/Provider.hpp>
|
||||||
|
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||||
|
#include <Void/Build/State/StateStore.hpp>
|
||||||
|
#include <Void/Build/Toolchain/Driver.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <format>
|
||||||
|
#include <set>
|
||||||
|
|
||||||
|
namespace Void::Build::Bridge {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using JsonVal = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
Void::Result::Error make_error(std::string msg) {
|
||||||
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto it = obj.find(k);
|
||||||
|
return it == obj.end() ? nullptr : &it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&v->value);
|
||||||
|
return s ? *s : std::string{};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
const auto *b = std::get_if<bool>(&v->value);
|
||||||
|
return b ? *b : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string escape_cmake(std::string_view s) {
|
||||||
|
std::string out;
|
||||||
|
for (const char c : s) {
|
||||||
|
if (c == '\\' || c == '"' || c == '$' || c == ';') {
|
||||||
|
out.push_back('\\');
|
||||||
|
}
|
||||||
|
out.push_back(c);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string emit_imported_target_cmake(const std::string &cmake_name,
|
||||||
|
const Graph::ImportedTargetInterface &iface) {
|
||||||
|
std::string cm_type = "INTERFACE";
|
||||||
|
std::filesystem::path loc;
|
||||||
|
if (!iface.static_libraries.empty()) {
|
||||||
|
cm_type = "STATIC";
|
||||||
|
loc = iface.static_libraries.front();
|
||||||
|
} else if (!iface.shared_libraries.empty()) {
|
||||||
|
cm_type = "SHARED";
|
||||||
|
loc = iface.shared_libraries.front();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string out;
|
||||||
|
out += "if(NOT TARGET " + cmake_name + ")\n";
|
||||||
|
out += " add_library(" + cmake_name + " " + cm_type + " IMPORTED GLOBAL)\n";
|
||||||
|
if (!loc.empty()) {
|
||||||
|
out += " set_property(TARGET " + cmake_name + " PROPERTY IMPORTED_LOCATION \"" +
|
||||||
|
escape_cmake(loc.string()) + "\")\n";
|
||||||
|
}
|
||||||
|
if (!iface.include_dirs.empty()) {
|
||||||
|
out += " set_property(TARGET " + cmake_name + " PROPERTY INTERFACE_INCLUDE_DIRECTORIES";
|
||||||
|
for (const auto &[inc, is_sys] : iface.include_dirs) {
|
||||||
|
(void)is_sys;
|
||||||
|
out += " \"" + escape_cmake(inc.string()) + "\"";
|
||||||
|
}
|
||||||
|
out += ")\n";
|
||||||
|
}
|
||||||
|
if (!iface.defines.empty()) {
|
||||||
|
out += " set_property(TARGET " + cmake_name + " PROPERTY INTERFACE_COMPILE_DEFINITIONS";
|
||||||
|
for (const auto &def : iface.defines) {
|
||||||
|
out += " \"" + escape_cmake(def) + "\"";
|
||||||
|
}
|
||||||
|
out += ")\n";
|
||||||
|
}
|
||||||
|
if (!iface.compile_options.empty()) {
|
||||||
|
out += " set_property(TARGET " + cmake_name + " PROPERTY INTERFACE_COMPILE_OPTIONS";
|
||||||
|
for (const auto &opt : iface.compile_options) {
|
||||||
|
out += " \"" + escape_cmake(opt) + "\"";
|
||||||
|
}
|
||||||
|
out += ")\n";
|
||||||
|
}
|
||||||
|
// Preserve extra transitive static/shared libraries after the primary location!
|
||||||
|
std::vector<std::string> extra_libs;
|
||||||
|
for (std::size_t i = (cm_type == "STATIC" ? 1 : 0); i < iface.static_libraries.size(); ++i) {
|
||||||
|
extra_libs.push_back(iface.static_libraries[i].string());
|
||||||
|
}
|
||||||
|
for (std::size_t i = (cm_type == "SHARED" ? 1 : 0); i < iface.shared_libraries.size(); ++i) {
|
||||||
|
extra_libs.push_back(iface.shared_libraries[i].string());
|
||||||
|
}
|
||||||
|
for (const auto &lopt : iface.link_options) {
|
||||||
|
extra_libs.push_back(lopt);
|
||||||
|
}
|
||||||
|
if (!extra_libs.empty()) {
|
||||||
|
out += " set_property(TARGET " + cmake_name + " PROPERTY INTERFACE_LINK_LIBRARIES";
|
||||||
|
for (const auto &lib : extra_libs) {
|
||||||
|
out += " \"" + escape_cmake(lib) + "\"";
|
||||||
|
}
|
||||||
|
out += ")\n";
|
||||||
|
}
|
||||||
|
out += "endif()\n";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
execute_cmake_bridge(const std::filesystem::path &request_json_path,
|
||||||
|
const std::filesystem::path &output_cmake_path) {
|
||||||
|
auto text = Void::FileSystem::read_file(request_json_path);
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{text.error()};
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{make_error("bridge request JSON is malformed")};
|
||||||
|
}
|
||||||
|
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!root) {
|
||||||
|
return std::unexpected{make_error("bridge request root must be a JSON object")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::filesystem::path project_root = get_str(*root, "project_root");
|
||||||
|
const std::filesystem::path build_root = get_str(*root, "build_root");
|
||||||
|
const std::string profile_name = get_str(*root, "profile");
|
||||||
|
const std::string compiler_str = get_str(*root, "compiler");
|
||||||
|
const std::string compiler_path = get_str(*root, "compiler_path");
|
||||||
|
const std::string os_name = get_str(*root, "os");
|
||||||
|
const std::string arch_name = get_str(*root, "architecture");
|
||||||
|
const bool offline = get_bool(*root, "offline", false);
|
||||||
|
|
||||||
|
// Reentry cycle guard (Plan 14: prevent infinite nested bridge recursion / lock deadlock).
|
||||||
|
std::string active_stack;
|
||||||
|
if (const char *env = std::getenv("VBS_BRIDGE_STACK")) {
|
||||||
|
active_stack = env;
|
||||||
|
}
|
||||||
|
const std::string self_marker = "|" + project_root.string() + "|";
|
||||||
|
if (active_stack.find(self_marker) != std::string::npos) {
|
||||||
|
return std::unexpected{make_error(std::format(
|
||||||
|
"reentrant VbsDeps bridge cycle detected for project '{}'", project_root.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
ProfileContext ctx = default_profiles().resolve(
|
||||||
|
profile_name.empty() ? "debug" : profile_name,
|
||||||
|
parse_compiler(compiler_str.empty() ? "gcc" : compiler_str),
|
||||||
|
os_name.empty() ? Toolchain::host_os_name() : os_name,
|
||||||
|
arch_name.empty() ? Toolchain::host_architecture_name() : arch_name);
|
||||||
|
ctx.compiler_path = compiler_path;
|
||||||
|
|
||||||
|
auto tc = Toolchain::discover_and_probe(ctx, build_root / ".vbs" / "probes");
|
||||||
|
if (!tc) {
|
||||||
|
return std::unexpected{tc.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string generated_cmake = "# Generated by VoidBuildSystem CMake bridge (Plan 14)\n";
|
||||||
|
std::set<std::string> emitted_names;
|
||||||
|
|
||||||
|
const auto *deps_v = find_key(*root, "dependencies");
|
||||||
|
const auto *deps_arr = deps_v ? std::get_if<JsonVal::Array>(&deps_v->value) : nullptr;
|
||||||
|
if (!deps_arr) {
|
||||||
|
return std::unexpected{make_error("bridge request missing 'dependencies' array")};
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto &dv : *deps_arr) {
|
||||||
|
const auto *dobj = std::get_if<JsonVal::Object>(&dv.value);
|
||||||
|
if (!dobj) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
DependencyRecord dep;
|
||||||
|
dep.name = get_str(*dobj, "alias");
|
||||||
|
dep.builder = get_str(*dobj, "builder");
|
||||||
|
dep.registry_authority = get_str(*dobj, "registry");
|
||||||
|
if (const auto git = get_str(*dobj, "git"); !git.empty()) {
|
||||||
|
dep.source_kind = DependencySourceKind::Git;
|
||||||
|
dep.location = git;
|
||||||
|
dep.revision = get_str(*dobj, "rev");
|
||||||
|
} else if (const auto pth = get_str(*dobj, "path"); !pth.empty()) {
|
||||||
|
dep.source_kind = DependencySourceKind::Path;
|
||||||
|
dep.location = pth;
|
||||||
|
} else if (const auto arc = get_str(*dobj, "archive"); !arc.empty()) {
|
||||||
|
dep.source_kind = DependencySourceKind::Archive;
|
||||||
|
dep.location = arc;
|
||||||
|
dep.sha256 = get_str(*dobj, "sha256");
|
||||||
|
} else if (const auto pkg = get_str(*dobj, "package"); !pkg.empty()) {
|
||||||
|
dep.source_kind = DependencySourceKind::Package;
|
||||||
|
dep.package = pkg;
|
||||||
|
dep.version = get_str(*dobj, "version");
|
||||||
|
}
|
||||||
|
if (const auto *ov = find_key(*dobj, "options")) {
|
||||||
|
if (const auto *oo = std::get_if<JsonVal::Object>(&ov->value)) {
|
||||||
|
for (const auto &[k, val] : *oo) {
|
||||||
|
if (const auto *s = std::get_if<std::string>(&val.value)) {
|
||||||
|
if (*s == "ON" || *s == "TRUE" || *s == "true") {
|
||||||
|
dep.options.emplace(k, OptionValue{true});
|
||||||
|
} else if (*s == "OFF" || *s == "FALSE" || *s == "false") {
|
||||||
|
dep.options.emplace(k, OptionValue{false});
|
||||||
|
} else {
|
||||||
|
dep.options.emplace(k, OptionValue{*s});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Package::FetchOptions fopts;
|
||||||
|
fopts.cache_dir = build_root / ".vbs" / "cache";
|
||||||
|
fopts.project_root = project_root;
|
||||||
|
fopts.offline = offline;
|
||||||
|
auto mat = Package::materialize_dependency_source(dep, fopts);
|
||||||
|
if (!mat) {
|
||||||
|
return std::unexpected{mat.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-detect builder if unspecified.
|
||||||
|
if (dep.builder.empty()) {
|
||||||
|
std::error_code ec;
|
||||||
|
if (std::filesystem::is_regular_file(mat->source_dir / "build.cpp", ec)) {
|
||||||
|
dep.builder = "native";
|
||||||
|
} else if (std::filesystem::is_regular_file(mat->source_dir / "CMakeLists.txt", ec)) {
|
||||||
|
dep.builder = "cmake";
|
||||||
|
} else if (std::filesystem::is_regular_file(mat->source_dir / "meson.build", ec)) {
|
||||||
|
dep.builder = "meson";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dep.builder == "cmake" || dep.builder == "meson" || dep.builder == "conan") {
|
||||||
|
Provider::ProviderRequest preq;
|
||||||
|
preq.dependency = dep;
|
||||||
|
preq.source = *mat;
|
||||||
|
preq.profile = ctx;
|
||||||
|
preq.toolchain = *tc;
|
||||||
|
preq.provider_build_root = build_root / ".vbs" / "providers";
|
||||||
|
preq.mode = Provider::ProviderMode::FullBuild;
|
||||||
|
auto exp = Provider::resolve_foreign_provider(preq);
|
||||||
|
if (!exp) {
|
||||||
|
return std::unexpected{exp.error()};
|
||||||
|
}
|
||||||
|
for (const auto &[tname, iface] : exp->targets) {
|
||||||
|
if (emitted_names.insert(tname).second) {
|
||||||
|
generated_cmake += emit_imported_target_cmake(tname, iface);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Native VBS package source: check exported package.json or include/ layout.
|
||||||
|
Graph::ImportedTargetInterface iface;
|
||||||
|
iface.dependency_name = dep.name;
|
||||||
|
iface.target_name = dep.name;
|
||||||
|
std::error_code ec;
|
||||||
|
if (std::filesystem::is_directory(mat->source_dir / "include", ec)) {
|
||||||
|
iface.include_dirs.emplace_back(mat->source_dir / "include", false);
|
||||||
|
}
|
||||||
|
const std::string alias_tgt = dep.name + "::" + dep.name;
|
||||||
|
if (emitted_names.insert(alias_tgt).second) {
|
||||||
|
generated_cmake += emit_imported_target_cmake(alias_tgt, iface);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Platform::atomic_write_file(output_cmake_path, generated_cmake, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Bridge
|
||||||
+1177
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,761 @@
|
|||||||
|
#include <Void/Build/Config/Frontend.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Execution/Scheduler.hpp>
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
|
#include <format>
|
||||||
|
#include <set>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
namespace Void::Build::Config {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using JsonVal = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
std::atomic<std::uint64_t> g_req_seq{0};
|
||||||
|
|
||||||
|
Void::Result::Error make_error(std::string msg) {
|
||||||
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_cpp_file(const std::filesystem::path &p) {
|
||||||
|
const auto ext = p.extension().string();
|
||||||
|
return ext == ".cpp" || ext == ".cc" || ext == ".cxx";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string generate_driver_source(bool has_profiles_file) {
|
||||||
|
std::string code = R"cpp(#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <fstream>
|
||||||
|
#include <iostream>
|
||||||
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
)cpp";
|
||||||
|
if (!has_profiles_file) {
|
||||||
|
code += R"cpp(void profiles(Void::Build::Profiles &descriptions) {
|
||||||
|
descriptions = Void::Build::default_profiles();
|
||||||
|
}
|
||||||
|
)cpp";
|
||||||
|
}
|
||||||
|
code += R"cpp(
|
||||||
|
namespace {
|
||||||
|
std::string read_text(const std::string &path) {
|
||||||
|
std::ifstream in(path, std::ios::binary);
|
||||||
|
if (!in) {
|
||||||
|
throw std::runtime_error{"cannot open context file: " + path};
|
||||||
|
}
|
||||||
|
std::ostringstream ss;
|
||||||
|
ss << in.rdbuf();
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
void write_text(const std::string &path, const std::string &content) {
|
||||||
|
std::ofstream out(path, std::ios::binary | std::ios::trunc);
|
||||||
|
if (!out) {
|
||||||
|
throw std::runtime_error{"cannot write result file: " + path};
|
||||||
|
}
|
||||||
|
out << content;
|
||||||
|
out.flush();
|
||||||
|
if (!out) {
|
||||||
|
throw std::runtime_error{"failed flushing result file: " + path};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> split_lines(std::string_view text) {
|
||||||
|
std::vector<std::string> out;
|
||||||
|
std::size_t pos = 0;
|
||||||
|
while (pos < text.size()) {
|
||||||
|
const auto nl = text.find('\n', pos);
|
||||||
|
const auto line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos);
|
||||||
|
if (!line.empty()) {
|
||||||
|
out.emplace_back(line);
|
||||||
|
}
|
||||||
|
if (nl == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = nl + 1;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Build::ProfileContext parse_kv_context(std::string_view text) {
|
||||||
|
Void::Build::ProfileContext ctx;
|
||||||
|
for (const auto &line : split_lines(text)) {
|
||||||
|
const auto eq = line.find('=');
|
||||||
|
if (eq == std::string::npos) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto key = line.substr(0, eq);
|
||||||
|
const auto val = line.substr(eq + 1);
|
||||||
|
if (key == "name") ctx.name = val;
|
||||||
|
else if (key == "compiler") ctx.compiler = Void::Build::parse_compiler(val);
|
||||||
|
else if (key == "os") ctx.os = val;
|
||||||
|
else if (key == "architecture") ctx.architecture = val;
|
||||||
|
else if (key == "cxx_standard") ctx.cxx_standard = Void::Build::parse_cxx_standard(val);
|
||||||
|
else if (key == "lto") ctx.lto = Void::Build::parse_lto_mode(val);
|
||||||
|
else if (key == "sysroot") ctx.sysroot = val;
|
||||||
|
else if (key == "compiler_path") ctx.compiler_path = val;
|
||||||
|
else if (key == "reproducibility_epoch") ctx.reproducibility_epoch = std::stoll(val);
|
||||||
|
else if (key == "nondeterministic") ctx.nondeterministic = (val == "1" || val == "true");
|
||||||
|
else if (key == "compile_option") ctx.compile_options.push_back(val);
|
||||||
|
else if (key == "link_option") ctx.link_options.push_back(val);
|
||||||
|
else if (key == "define") ctx.defines.push_back(val);
|
||||||
|
else if (key == "sanitizer") ctx.sanitizers.push_back(Void::Build::parse_sanitizer(val));
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
try {
|
||||||
|
std::string mode;
|
||||||
|
std::string output_path;
|
||||||
|
std::string request_id;
|
||||||
|
std::string context_file;
|
||||||
|
std::string context_hash;
|
||||||
|
for (int i = 1; i < argc; ++i) {
|
||||||
|
const std::string_view arg{argv[i]};
|
||||||
|
if (arg == "--mode" && i + 1 < argc) mode = argv[++i];
|
||||||
|
else if (arg == "--output" && i + 1 < argc) output_path = argv[++i];
|
||||||
|
else if (arg == "--request-id" && i + 1 < argc) request_id = argv[++i];
|
||||||
|
else if (arg == "--context-file" && i + 1 < argc) context_file = argv[++i];
|
||||||
|
else if (arg == "--context-hash" && i + 1 < argc) context_hash = argv[++i];
|
||||||
|
else {
|
||||||
|
std::cerr << "vbs-config-driver: unknown argument: " << arg << '\n';
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (output_path.empty() || request_id.empty()) {
|
||||||
|
std::cerr << "vbs-config-driver: --output and --request-id are required\n";
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
if (mode == "profiles") {
|
||||||
|
Void::Build::Profiles descriptions;
|
||||||
|
profiles(descriptions);
|
||||||
|
const std::string payload =
|
||||||
|
"{\"protocol_version\":1,\"request_id\":" +
|
||||||
|
Void::Build::Util::json_quote(request_id) +
|
||||||
|
",\"payload\":" + descriptions.to_json() + "}\n";
|
||||||
|
write_text(output_path, payload);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (mode == "describe") {
|
||||||
|
auto ctx = parse_kv_context(read_text(context_file));
|
||||||
|
Void::Build::Project project{ctx};
|
||||||
|
build(project);
|
||||||
|
const std::string payload =
|
||||||
|
"{\"protocol_version\":1,\"request_id\":" +
|
||||||
|
Void::Build::Util::json_quote(request_id) +
|
||||||
|
",\"context_hash\":" + Void::Build::Util::json_quote(context_hash) +
|
||||||
|
",\"payload\":" + project.to_json() + "}\n";
|
||||||
|
write_text(output_path, payload);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
std::cerr << "vbs-config-driver: unknown mode '" << mode << "'\n";
|
||||||
|
return 2;
|
||||||
|
} catch (const std::exception &err) {
|
||||||
|
std::cerr << "vbs-config-driver: " << err.what() << '\n';
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)cpp";
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_kv_context(const ProfileContext &ctx) {
|
||||||
|
std::string out;
|
||||||
|
out += "name=" + ctx.name + "\n";
|
||||||
|
out += "compiler=" + std::string{compiler_name(ctx.compiler)} + "\n";
|
||||||
|
out += "os=" + ctx.os + "\n";
|
||||||
|
out += "architecture=" + ctx.architecture + "\n";
|
||||||
|
out += "cxx_standard=" + std::string{cxx_standard_name(ctx.cxx_standard)} + "\n";
|
||||||
|
out += "lto=" + std::string{lto_mode_name(ctx.lto)} + "\n";
|
||||||
|
out += "sysroot=" + ctx.sysroot + "\n";
|
||||||
|
out += "compiler_path=" + ctx.compiler_path + "\n";
|
||||||
|
out += "reproducibility_epoch=" + std::to_string(ctx.reproducibility_epoch) + "\n";
|
||||||
|
out += std::string{"nondeterministic="} + (ctx.nondeterministic ? "1" : "0") + "\n";
|
||||||
|
for (const auto &opt : ctx.compile_options) {
|
||||||
|
out += "compile_option=" + opt + "\n";
|
||||||
|
}
|
||||||
|
for (const auto &opt : ctx.link_options) {
|
||||||
|
out += "link_option=" + opt + "\n";
|
||||||
|
}
|
||||||
|
for (const auto &def : ctx.defines) {
|
||||||
|
out += "define=" + def + "\n";
|
||||||
|
}
|
||||||
|
for (const auto s : ctx.sanitizers) {
|
||||||
|
out += "sanitizer=" + std::string{sanitizer_name(s)} + "\n";
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto it = obj.find(k);
|
||||||
|
return it == obj.end() ? nullptr : &it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::string> get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&v->value);
|
||||||
|
return s ? std::optional<std::string>{*s} : std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::int64_t> get_i64(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *i = std::get_if<std::int64_t>(&v->value);
|
||||||
|
return i ? std::optional<std::int64_t>{*i} : std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
std::vector<std::string> out;
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
|
||||||
|
for (const auto &item : *arr) {
|
||||||
|
if (const auto *s = std::get_if<std::string>(&item.value)) {
|
||||||
|
out.push_back(*s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||||
|
discover_config_sources(const std::filesystem::path &project_root,
|
||||||
|
const std::vector<std::filesystem::path> &extra_build_sources) {
|
||||||
|
std::error_code ec;
|
||||||
|
const auto canonical_root = std::filesystem::weakly_canonical(project_root, ec);
|
||||||
|
if (ec || !std::filesystem::is_directory(canonical_root)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(std::format("project root '{}' is not a directory", project_root.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto root_build = canonical_root / "build.cpp";
|
||||||
|
if (!std::filesystem::is_regular_file(root_build, ec)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(std::format("missing required root description '{}'", root_build.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::filesystem::path> sources;
|
||||||
|
std::set<std::filesystem::path> seen;
|
||||||
|
auto push = [&](const std::filesystem::path &p) {
|
||||||
|
const auto norm = p.lexically_normal();
|
||||||
|
if (seen.insert(norm).second) {
|
||||||
|
sources.push_back(norm);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
push(root_build);
|
||||||
|
|
||||||
|
const auto profiles_cpp = canonical_root / "build.profiles.cpp";
|
||||||
|
if (std::filesystem::is_regular_file(profiles_cpp, ec)) {
|
||||||
|
push(profiles_cpp);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filesystem-discovered build-support/**/*.cpp (works identically without .git!).
|
||||||
|
const auto support_dir = canonical_root / "build-support";
|
||||||
|
if (std::filesystem::is_directory(support_dir, ec)) {
|
||||||
|
std::vector<std::filesystem::path> helpers;
|
||||||
|
for (const auto &entry : std::filesystem::recursive_directory_iterator(support_dir, ec)) {
|
||||||
|
if (entry.is_regular_file(ec) && is_cpp_file(entry.path())) {
|
||||||
|
helpers.push_back(entry.path().lexically_normal());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::ranges::sort(helpers);
|
||||||
|
for (const auto &h : helpers) {
|
||||||
|
push(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explicit --build-source inputs.
|
||||||
|
for (const auto &extra : extra_build_sources) {
|
||||||
|
const auto abs = extra.is_absolute() ? extra : (canonical_root / extra);
|
||||||
|
if (!std::filesystem::is_regular_file(abs, ec)) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("explicit --build-source '{}' does not exist", extra.string()))};
|
||||||
|
}
|
||||||
|
push(abs);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sources;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<CompiledDescriptor, Void::Result::Error>
|
||||||
|
compile_descriptor(const FrontendOptions &options) {
|
||||||
|
auto sources_res = discover_config_sources(options.project_root, options.extra_build_sources);
|
||||||
|
if (!sources_res) {
|
||||||
|
return std::unexpected{sources_res.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
const auto canonical_root = std::filesystem::weakly_canonical(options.project_root, ec);
|
||||||
|
const auto config_dir =
|
||||||
|
std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config";
|
||||||
|
std::filesystem::create_directories(config_dir, ec);
|
||||||
|
|
||||||
|
auto lock =
|
||||||
|
Platform::FileLock::acquire(config_dir / "seed.lock", Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path host_cxx;
|
||||||
|
if (options.host_compiler && !options.host_compiler->empty()) {
|
||||||
|
auto resolved = Platform::resolve_executable(*options.host_compiler);
|
||||||
|
if (!resolved) {
|
||||||
|
return std::unexpected{make_error(std::format(
|
||||||
|
"configured host compiler '{}' was not found", options.host_compiler->string()))};
|
||||||
|
}
|
||||||
|
host_cxx = *resolved;
|
||||||
|
} else {
|
||||||
|
auto resolved = Platform::resolve_executable("g++");
|
||||||
|
if (!resolved) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error("host compiler 'g++' not found in PATH for compiling build.cpp")};
|
||||||
|
}
|
||||||
|
host_cxx = *resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto host_hash = Util::sha256_file_hex(host_cxx);
|
||||||
|
if (!host_hash) {
|
||||||
|
return std::unexpected{host_hash.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool has_profiles =
|
||||||
|
std::filesystem::is_regular_file(canonical_root / "build.profiles.cpp", ec);
|
||||||
|
const std::string driver_src = generate_driver_source(has_profiles);
|
||||||
|
const auto driver_cpp = config_dir / "Driver.cpp";
|
||||||
|
if (auto wrote = Platform::atomic_write_file(driver_cpp, driver_src, false); !wrote) {
|
||||||
|
return std::unexpected{wrote.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute seed identity over host compiler, SDK header/library, driver source, and config
|
||||||
|
// sources.
|
||||||
|
Util::Sha256Hasher id_hasher;
|
||||||
|
id_hasher.update_length_prefixed("vbs-seed-v1");
|
||||||
|
id_hasher.update_length_prefixed(host_cxx.string());
|
||||||
|
id_hasher.update_length_prefixed(*host_hash);
|
||||||
|
id_hasher.update_length_prefixed(driver_src);
|
||||||
|
if (!options.sdk_include_dir.empty()) {
|
||||||
|
if (auto hdr_h = Util::sha256_file_hex(options.sdk_include_dir / "Void" / "Build.hpp");
|
||||||
|
hdr_h) {
|
||||||
|
id_hasher.update_length_prefixed(*hdr_h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!options.sdk_library_path.empty() &&
|
||||||
|
std::filesystem::exists(options.sdk_library_path, ec)) {
|
||||||
|
if (auto lib_h = Util::sha256_file_hex(options.sdk_library_path); lib_h) {
|
||||||
|
id_hasher.update_length_prefixed(*lib_h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &src : *sources_res) {
|
||||||
|
auto h = Util::sha256_file_hex(src);
|
||||||
|
if (!h) {
|
||||||
|
return std::unexpected{h.error()};
|
||||||
|
}
|
||||||
|
id_hasher.update_length_prefixed(src.string());
|
||||||
|
id_hasher.update_length_prefixed(*h);
|
||||||
|
}
|
||||||
|
const std::string seed_id = id_hasher.finalize_hex();
|
||||||
|
|
||||||
|
const auto exe_path = config_dir / ("descriptor_" + seed_id.substr(0, 16));
|
||||||
|
const auto meta_path = config_dir / ("descriptor_" + seed_id.substr(0, 16) + ".headers.json");
|
||||||
|
|
||||||
|
// Check if cached descriptor executable exists AND all previously discovered headers match!
|
||||||
|
bool up_to_date = false;
|
||||||
|
std::vector<std::filesystem::path> cached_headers;
|
||||||
|
if (std::filesystem::is_regular_file(exe_path, ec) &&
|
||||||
|
std::filesystem::is_regular_file(meta_path, ec)) {
|
||||||
|
if (auto meta_text = Void::FileSystem::read_file(meta_path); meta_text) {
|
||||||
|
if (auto parsed = Void::Json::Strict::parse(*meta_text); parsed) {
|
||||||
|
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
|
||||||
|
if (get_str(*obj, "seed_id").value_or("") == seed_id) {
|
||||||
|
bool headers_ok = true;
|
||||||
|
if (const auto *hv = find_key(*obj, "headers")) {
|
||||||
|
if (const auto *hobj = std::get_if<JsonVal::Object>(&hv->value)) {
|
||||||
|
for (const auto &[hpath, hval] : *hobj) {
|
||||||
|
const auto *expected = std::get_if<std::string>(&hval.value);
|
||||||
|
auto actual =
|
||||||
|
Util::sha256_file_hex(std::filesystem::path{hpath});
|
||||||
|
if (!expected || !actual || *actual != *expected) {
|
||||||
|
headers_ok = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cached_headers.emplace_back(hpath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
up_to_date = headers_ok;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (up_to_date) {
|
||||||
|
CompiledDescriptor desc;
|
||||||
|
desc.executable_path = exe_path;
|
||||||
|
desc.seed_identity_hash = seed_id;
|
||||||
|
desc.config_sources = *sources_res;
|
||||||
|
desc.discovered_headers = std::move(cached_headers);
|
||||||
|
desc.recompiled = false;
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compile each translation unit with depfiles so included headers enter configuration identity!
|
||||||
|
const auto obj_dir = config_dir / ("obj_" + seed_id.substr(0, 16));
|
||||||
|
std::filesystem::create_directories(obj_dir, ec);
|
||||||
|
|
||||||
|
std::vector<std::filesystem::path> compile_units = *sources_res;
|
||||||
|
compile_units.push_back(driver_cpp);
|
||||||
|
|
||||||
|
const bool use_prebuilt_sdk = !options.sdk_library_path.empty() &&
|
||||||
|
std::filesystem::is_regular_file(options.sdk_library_path, ec);
|
||||||
|
if (!use_prebuilt_sdk && !options.sdk_source_dir.empty()) {
|
||||||
|
compile_units.push_back(options.sdk_source_dir / "Build.cpp");
|
||||||
|
compile_units.push_back(options.sdk_source_dir / "Util" / "Json.cpp");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::filesystem::path> objects;
|
||||||
|
std::map<std::string, std::string, std::less<>> header_hashes;
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < compile_units.size(); ++i) {
|
||||||
|
const auto &tu = compile_units[i];
|
||||||
|
const auto obj = obj_dir / std::format("tu_{}_{}.o", i, tu.stem().string());
|
||||||
|
const auto dep = obj_dir / std::format("tu_{}_{}.d", i, tu.stem().string());
|
||||||
|
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = host_cxx;
|
||||||
|
req.arguments = {"-std=c++26", "-O1", "-I", canonical_root.string()};
|
||||||
|
if (!options.sdk_include_dir.empty()) {
|
||||||
|
req.arguments.push_back("-I");
|
||||||
|
req.arguments.push_back(options.sdk_include_dir.string());
|
||||||
|
}
|
||||||
|
req.arguments.push_back("-MMD");
|
||||||
|
req.arguments.push_back("-MF");
|
||||||
|
req.arguments.push_back(dep.string());
|
||||||
|
req.arguments.push_back("-c");
|
||||||
|
req.arguments.push_back(tu.string());
|
||||||
|
req.arguments.push_back("-o");
|
||||||
|
req.arguments.push_back(obj.string());
|
||||||
|
req.working_directory = canonical_root;
|
||||||
|
req.timeout = std::chrono::seconds{60};
|
||||||
|
|
||||||
|
auto res = Platform::run_supervised(req);
|
||||||
|
if (!res || !res->succeeded()) {
|
||||||
|
const std::string detail =
|
||||||
|
res ? (res->stderr_data.empty() ? res->exec_error_message : res->stderr_data)
|
||||||
|
: res.error().message();
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("failed compiling configuration source '{}' (note: unresolved project "
|
||||||
|
"package headers cannot be required during seed compilation):\n{}",
|
||||||
|
tu.string(), detail))};
|
||||||
|
}
|
||||||
|
objects.push_back(obj);
|
||||||
|
|
||||||
|
if (auto deps = Execution::parse_depfile(dep); deps) {
|
||||||
|
for (const auto &d : *deps) {
|
||||||
|
const auto abs = d.is_absolute() ? d.lexically_normal()
|
||||||
|
: (canonical_root / d).lexically_normal();
|
||||||
|
if (Platform::path_is_within(canonical_root, abs) ||
|
||||||
|
(!options.sdk_include_dir.empty() &&
|
||||||
|
Platform::path_is_within(options.sdk_include_dir, abs))) {
|
||||||
|
if (auto hh = Util::sha256_file_hex(abs); hh) {
|
||||||
|
header_hashes[abs.string()] = std::move(*hh);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link host descriptor executable atomically into staging then rename.
|
||||||
|
const auto staged_exe =
|
||||||
|
config_dir / std::format("descriptor_{}.stage_{}", seed_id.substr(0, 16),
|
||||||
|
static_cast<long long>(::getpid()));
|
||||||
|
{
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = host_cxx;
|
||||||
|
req.arguments = {"-std=c++26", "-o", staged_exe.string()};
|
||||||
|
for (const auto &o : objects) {
|
||||||
|
req.arguments.push_back(o.string());
|
||||||
|
}
|
||||||
|
if (use_prebuilt_sdk) {
|
||||||
|
req.arguments.push_back(options.sdk_library_path.string());
|
||||||
|
}
|
||||||
|
req.working_directory = canonical_root;
|
||||||
|
req.timeout = std::chrono::seconds{60};
|
||||||
|
|
||||||
|
auto res = Platform::run_supervised(req);
|
||||||
|
if (!res || !res->succeeded()) {
|
||||||
|
std::filesystem::remove(staged_exe, ec);
|
||||||
|
const std::string detail =
|
||||||
|
res ? (res->stderr_data.empty() ? res->exec_error_message : res->stderr_data)
|
||||||
|
: res.error().message();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(std::format("failed linking configuration descriptor:\n{}", detail))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::rename(staged_exe, exe_path, ec);
|
||||||
|
if (ec) {
|
||||||
|
std::filesystem::remove(staged_exe, ec);
|
||||||
|
return std::unexpected{make_error("failed publishing compiled descriptor executable")};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist discovered header hashes atomically.
|
||||||
|
std::string meta_json = "{\"seed_id\":" + Util::json_quote(seed_id) + ",\"headers\":{";
|
||||||
|
bool first = true;
|
||||||
|
std::vector<std::filesystem::path> headers_list;
|
||||||
|
for (const auto &[hpath, hsha] : header_hashes) {
|
||||||
|
if (!first) {
|
||||||
|
meta_json += ',';
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
meta_json += Util::json_quote(hpath) + ':' + Util::json_quote(hsha);
|
||||||
|
headers_list.emplace_back(hpath);
|
||||||
|
}
|
||||||
|
meta_json += "}}\n";
|
||||||
|
(void)Platform::atomic_write_file(meta_path, meta_json, false);
|
||||||
|
|
||||||
|
CompiledDescriptor desc;
|
||||||
|
desc.executable_path = exe_path;
|
||||||
|
desc.seed_identity_hash = seed_id;
|
||||||
|
desc.config_sources = *sources_res;
|
||||||
|
desc.discovered_headers = std::move(headers_list);
|
||||||
|
desc.recompiled = true;
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Profiles, Void::Result::Error>
|
||||||
|
discover_profiles(const CompiledDescriptor &descriptor, const FrontendOptions &options) {
|
||||||
|
std::error_code ec;
|
||||||
|
const auto run_dir =
|
||||||
|
std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config" / "eval";
|
||||||
|
std::filesystem::create_directories(run_dir, ec);
|
||||||
|
|
||||||
|
const std::string req_id = std::format("prof_{}_{}", static_cast<long long>(::getpid()),
|
||||||
|
g_req_seq.fetch_add(1, std::memory_order_relaxed));
|
||||||
|
const auto out_file = run_dir / (req_id + ".json");
|
||||||
|
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = descriptor.executable_path;
|
||||||
|
req.arguments = {"--mode", "profiles", "--output", out_file.string(), "--request-id", req_id};
|
||||||
|
req.working_directory = options.project_root;
|
||||||
|
req.timeout = options.eval_timeout;
|
||||||
|
|
||||||
|
auto proc = Platform::run_supervised(req);
|
||||||
|
auto cleanup = [&] { std::filesystem::remove(out_file, ec); };
|
||||||
|
if (!proc) {
|
||||||
|
cleanup();
|
||||||
|
return std::unexpected{proc.error()};
|
||||||
|
}
|
||||||
|
if (!proc->succeeded()) {
|
||||||
|
cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(std::format("profile discovery failed (exit={}, signal={}): {}",
|
||||||
|
proc->exit_code, proc->term_signal, proc->stderr_data))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto text = Void::FileSystem::read_file_bounded(out_file, {16ULL * 1024ULL * 1024ULL});
|
||||||
|
cleanup();
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{make_error("profile discovery did not write a valid result file")};
|
||||||
|
}
|
||||||
|
if (!Util::is_valid_utf8(*text)) {
|
||||||
|
return std::unexpected{make_error("profile discovery result contains invalid UTF-8")};
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{make_error("profile discovery emitted malformed JSON")};
|
||||||
|
}
|
||||||
|
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!root) {
|
||||||
|
return std::unexpected{make_error("profile discovery envelope must be a JSON object")};
|
||||||
|
}
|
||||||
|
if (get_i64(*root, "protocol_version").value_or(0) != kFrontendProtocolVersion) {
|
||||||
|
return std::unexpected{make_error("profile discovery protocol version mismatch")};
|
||||||
|
}
|
||||||
|
if (get_str(*root, "request_id").value_or("") != req_id) {
|
||||||
|
return std::unexpected{make_error("profile discovery request_id mismatch")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto *payload_v = find_key(*root, "payload");
|
||||||
|
const auto *payload = payload_v ? std::get_if<JsonVal::Object>(&payload_v->value) : nullptr;
|
||||||
|
if (!payload) {
|
||||||
|
return std::unexpected{make_error("profile discovery missing payload")};
|
||||||
|
}
|
||||||
|
const auto *profs_v = find_key(*payload, "profiles");
|
||||||
|
const auto *arr = profs_v ? std::get_if<JsonVal::Array>(&profs_v->value) : nullptr;
|
||||||
|
if (!arr) {
|
||||||
|
return std::unexpected{make_error("profile discovery payload missing profiles array")};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Profiles result;
|
||||||
|
for (const auto &pv : *arr) {
|
||||||
|
const auto *po = std::get_if<JsonVal::Object>(&pv.value);
|
||||||
|
if (!po) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ProfileDescription pd;
|
||||||
|
pd.name = get_str(*po, "name").value_or("");
|
||||||
|
if (auto parent = get_str(*po, "parent"); parent && !parent->empty()) {
|
||||||
|
pd.parent = *parent;
|
||||||
|
}
|
||||||
|
if (auto comp = get_str(*po, "compiler"); comp && !comp->empty()) {
|
||||||
|
pd.compiler = parse_compiler(*comp);
|
||||||
|
}
|
||||||
|
if (auto std_str = get_str(*po, "cxx_standard"); std_str && !std_str->empty()) {
|
||||||
|
pd.cxx_standard = parse_cxx_standard(*std_str);
|
||||||
|
}
|
||||||
|
if (auto lto_str = get_str(*po, "lto"); lto_str && !lto_str->empty()) {
|
||||||
|
pd.lto = parse_lto_mode(*lto_str);
|
||||||
|
}
|
||||||
|
pd.sysroot = get_str(*po, "sysroot").value_or("");
|
||||||
|
pd.compiler_path = get_str(*po, "compiler_path").value_or("");
|
||||||
|
if (auto ep = get_i64(*po, "reproducibility_epoch")) {
|
||||||
|
pd.reproducibility_epoch = *ep;
|
||||||
|
}
|
||||||
|
if (const auto *nd = find_key(*po, "nondeterministic")) {
|
||||||
|
if (const auto *b = std::get_if<bool>(&nd->value)) {
|
||||||
|
pd.nondeterministic = *b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pd.compile_options = get_str_array(*po, "compile_options");
|
||||||
|
pd.link_options = get_str_array(*po, "link_options");
|
||||||
|
pd.defines = get_str_array(*po, "defines");
|
||||||
|
for (const auto &s : get_str_array(*po, "sanitizers")) {
|
||||||
|
pd.sanitizers.push_back(parse_sanitizer(s));
|
||||||
|
}
|
||||||
|
result.define(std::move(pd));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
} catch (const std::exception &ex) {
|
||||||
|
return std::unexpected{make_error(ex.what())};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Graph::ProjectDescription, Void::Result::Error>
|
||||||
|
evaluate_project(const CompiledDescriptor &descriptor, const ProfileContext &context,
|
||||||
|
const FrontendOptions &options) {
|
||||||
|
std::error_code ec;
|
||||||
|
const auto run_dir =
|
||||||
|
std::filesystem::weakly_canonical(options.build_root, ec) / ".vbs" / "config" / "eval";
|
||||||
|
std::filesystem::create_directories(run_dir, ec);
|
||||||
|
|
||||||
|
const std::string req_id = std::format("desc_{}_{}", static_cast<long long>(::getpid()),
|
||||||
|
g_req_seq.fetch_add(1, std::memory_order_relaxed));
|
||||||
|
const auto ctx_file = run_dir / (req_id + ".ctx");
|
||||||
|
const auto out_file = run_dir / (req_id + ".json");
|
||||||
|
|
||||||
|
const std::string kv_text = serialize_kv_context(context);
|
||||||
|
const std::string ctx_hash = Util::sha256_hex(kv_text);
|
||||||
|
if (auto wrote = Platform::atomic_write_file(ctx_file, kv_text, false); !wrote) {
|
||||||
|
return std::unexpected{wrote.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto cleanup = [&] {
|
||||||
|
std::filesystem::remove(ctx_file, ec);
|
||||||
|
std::filesystem::remove(out_file, ec);
|
||||||
|
};
|
||||||
|
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = descriptor.executable_path;
|
||||||
|
req.arguments = {"--mode", "describe", "--output", out_file.string(),
|
||||||
|
"--request-id", req_id, "--context-file", ctx_file.string(),
|
||||||
|
"--context-hash", ctx_hash};
|
||||||
|
req.working_directory = options.project_root;
|
||||||
|
req.timeout = options.eval_timeout;
|
||||||
|
|
||||||
|
auto proc = Platform::run_supervised(req);
|
||||||
|
if (!proc) {
|
||||||
|
cleanup();
|
||||||
|
return std::unexpected{proc.error()};
|
||||||
|
}
|
||||||
|
if (!proc->succeeded()) {
|
||||||
|
cleanup();
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("project evaluation failed for profile '{}' (exit={}, signal={}): {}",
|
||||||
|
context.name, proc->exit_code, proc->term_signal, proc->stderr_data))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto text = Void::FileSystem::read_file_bounded(out_file, {64ULL * 1024ULL * 1024ULL});
|
||||||
|
cleanup();
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{make_error("project evaluation did not produce a result file")};
|
||||||
|
}
|
||||||
|
if (!Util::is_valid_utf8(*text)) {
|
||||||
|
return std::unexpected{make_error("project evaluation result contains invalid UTF-8")};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate envelope header fields cleanly, then slice out payload JSON directly.
|
||||||
|
auto parsed = Void::Json::Strict::parse(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{make_error("project evaluation emitted malformed JSON")};
|
||||||
|
}
|
||||||
|
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!root) {
|
||||||
|
return std::unexpected{make_error("project evaluation envelope must be a JSON object")};
|
||||||
|
}
|
||||||
|
if (get_i64(*root, "protocol_version").value_or(0) != kFrontendProtocolVersion) {
|
||||||
|
return std::unexpected{make_error("project evaluation protocol version mismatch")};
|
||||||
|
}
|
||||||
|
if (get_str(*root, "request_id").value_or("") != req_id) {
|
||||||
|
return std::unexpected{make_error("project evaluation request_id mismatch")};
|
||||||
|
}
|
||||||
|
if (get_str(*root, "context_hash").value_or("") != ctx_hash) {
|
||||||
|
return std::unexpected{make_error("project evaluation context_hash mismatch")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto payload_marker = text->find("\"payload\":");
|
||||||
|
if (payload_marker == std::string::npos) {
|
||||||
|
return std::unexpected{make_error("project evaluation envelope missing payload")};
|
||||||
|
}
|
||||||
|
std::string_view payload_slice{*text};
|
||||||
|
payload_slice.remove_prefix(payload_marker + 10);
|
||||||
|
while (!payload_slice.empty() &&
|
||||||
|
(payload_slice.back() == '\n' || payload_slice.back() == '\r' ||
|
||||||
|
payload_slice.back() == ' ')) {
|
||||||
|
payload_slice.remove_suffix(1);
|
||||||
|
}
|
||||||
|
if (payload_slice.empty() || payload_slice.back() != '}') {
|
||||||
|
return std::unexpected{make_error("project evaluation envelope truncated")};
|
||||||
|
}
|
||||||
|
payload_slice.remove_suffix(1); // Remove enclosing envelope '}'
|
||||||
|
|
||||||
|
auto desc = Graph::ProjectDescription::from_json(payload_slice);
|
||||||
|
if (!desc) {
|
||||||
|
return std::unexpected{desc.error()};
|
||||||
|
}
|
||||||
|
if (desc->profile.name != context.name || desc->profile.compiler != context.compiler) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error("project evaluation returned a mismatched profile context")};
|
||||||
|
}
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Config
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
|
#include <Void/Build.hpp>
|
||||||
|
#include <Void/Build/BootstrapConfig.hpp>
|
||||||
#include <Void/Configuration/Argparse.hpp>
|
#include <Void/Configuration/Argparse.hpp>
|
||||||
#include <vbs/bootstrap_config.hpp>
|
|
||||||
#include <vbs/build.hpp>
|
|
||||||
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
@@ -29,11 +29,11 @@ int main(int argc, char **argv) {
|
|||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
vbs::Profiles descriptions;
|
Void::Build::Profiles descriptions;
|
||||||
profiles(descriptions);
|
profiles(descriptions);
|
||||||
vbs::Project project{descriptions.resolve(profile, vbs::parse_compiler(compiler),
|
Void::Build::Project project{descriptions.resolve(
|
||||||
std::string{vbs::bootstrap::os},
|
profile, Void::Build::parse_compiler(compiler), std::string{Void::Build::Bootstrap::os},
|
||||||
std::string{vbs::bootstrap::architecture})};
|
std::string{Void::Build::Bootstrap::architecture})};
|
||||||
build(project);
|
build(project);
|
||||||
std::cout << project.to_json() << '\n';
|
std::cout << project.to_json() << '\n';
|
||||||
return 0;
|
return 0;
|
||||||
@@ -0,0 +1,574 @@
|
|||||||
|
#include <Void/Build/Editor/CompDb.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
|
namespace Void::Build::Editor {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using JsonVal = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
Void::Result::Error make_error(std::string msg) {
|
||||||
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string sanitize_profile_dir(std::string_view name) {
|
||||||
|
std::string out;
|
||||||
|
out.reserve(name.size());
|
||||||
|
for (const char c : name) {
|
||||||
|
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||||
|
c == '_' || c == '-' || c == '.') {
|
||||||
|
out.push_back(c);
|
||||||
|
} else {
|
||||||
|
out.push_back('_');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view status_name(GenerationStatus s) {
|
||||||
|
switch (s) {
|
||||||
|
case GenerationStatus::Valid:
|
||||||
|
return "valid";
|
||||||
|
case GenerationStatus::Stale:
|
||||||
|
return "stale";
|
||||||
|
case GenerationStatus::Invalid:
|
||||||
|
return "invalid";
|
||||||
|
}
|
||||||
|
return "invalid";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string cxx_standard_flag(CxxStandard standard) {
|
||||||
|
switch (standard) {
|
||||||
|
case CxxStandard::Default:
|
||||||
|
return {};
|
||||||
|
case CxxStandard::Cxx17:
|
||||||
|
return "-std=c++17";
|
||||||
|
case CxxStandard::Cxx20:
|
||||||
|
return "-std=c++20";
|
||||||
|
case CxxStandard::Cxx23:
|
||||||
|
return "-std=c++23";
|
||||||
|
case CxxStandard::Cxx26:
|
||||||
|
return "-std=c++26";
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string sanitizer_flag(Sanitizer s) {
|
||||||
|
switch (s) {
|
||||||
|
case Sanitizer::Address:
|
||||||
|
return "address";
|
||||||
|
case Sanitizer::Undefined:
|
||||||
|
return "undefined";
|
||||||
|
case Sanitizer::Thread:
|
||||||
|
return "thread";
|
||||||
|
case Sanitizer::Memory:
|
||||||
|
return "memory";
|
||||||
|
case Sanitizer::Leak:
|
||||||
|
return "leak";
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto it = obj.find(k);
|
||||||
|
return it == obj.end() ? nullptr : &it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&v->value);
|
||||||
|
return s ? *s : std::string{};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int64_t get_i64(const JsonVal::Object &obj, const std::string &k, std::int64_t def = 0) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
const auto *i = std::get_if<std::int64_t>(&v->value);
|
||||||
|
return i ? *i : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
const auto *b = std::get_if<bool>(&v->value);
|
||||||
|
return b ? *b : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path selection_file_path(const std::filesystem::path &project_root) {
|
||||||
|
return project_root / ".vbs" / "editor_selection.json";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path selection_lock_path(const std::filesystem::path &project_root) {
|
||||||
|
return project_root / ".vbs" / "editor_selection.lock";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_selection(const SelectionState &st) {
|
||||||
|
using Util::json_quote;
|
||||||
|
return "{\"schema_version\":1,\"ticket\":" + std::to_string(st.ticket) +
|
||||||
|
",\"selected_profile\":" + json_quote(st.selected_profile) +
|
||||||
|
",\"selected_build_root\":" + json_quote(st.selected_build_root.string()) +
|
||||||
|
",\"selected_generation_id\":" + json_quote(st.selected_generation_id) +
|
||||||
|
",\"selected_compdb_path\":" + json_quote(st.selected_compdb_path.string()) +
|
||||||
|
",\"managed_root_alias_active\":" +
|
||||||
|
std::string{st.managed_root_alias_active ? "true" : "false"} +
|
||||||
|
",\"root_alias_warning\":" + json_quote(st.root_alias_warning) + "}\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<SelectionState> load_selection_locked(const std::filesystem::path &project_root) {
|
||||||
|
auto text = Void::FileSystem::read_file(selection_file_path(project_root));
|
||||||
|
if (!text) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *obj = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!obj) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
SelectionState st;
|
||||||
|
st.ticket = static_cast<std::uint64_t>(get_i64(*obj, "ticket", 0));
|
||||||
|
st.selected_profile = get_str(*obj, "selected_profile");
|
||||||
|
st.selected_build_root = get_str(*obj, "selected_build_root");
|
||||||
|
st.selected_generation_id = get_str(*obj, "selected_generation_id");
|
||||||
|
st.selected_compdb_path = get_str(*obj, "selected_compdb_path");
|
||||||
|
st.managed_root_alias_active = get_bool(*obj, "managed_root_alias_active", false);
|
||||||
|
st.root_alias_warning = get_str(*obj, "root_alias_warning");
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updates `<project_root>/compile_commands.json` ONLY if it does not exist or is already
|
||||||
|
// a VBS-managed symlink. Preserves any unrelated user-owned file!
|
||||||
|
Void::Result::Result<bool, Void::Result::Error>
|
||||||
|
update_managed_root_alias(const std::filesystem::path &project_root,
|
||||||
|
const std::filesystem::path &build_root,
|
||||||
|
const std::filesystem::path &target_compdb, std::string &warning_out) {
|
||||||
|
const auto root_alias = project_root / "compile_commands.json";
|
||||||
|
auto meta = Platform::stat_lstat(root_alias);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (meta->exists) {
|
||||||
|
if (!meta->is_symlink) {
|
||||||
|
warning_out = "preserved existing user-owned project-root compile_commands.json";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Check if symlink points into build_root or is recorded as managed.
|
||||||
|
std::filesystem::path target_p{meta->symlink_target};
|
||||||
|
if (!target_p.is_absolute()) {
|
||||||
|
target_p = (project_root / target_p).lexically_normal();
|
||||||
|
}
|
||||||
|
std::error_code ec;
|
||||||
|
const auto canon_build = std::filesystem::weakly_canonical(build_root, ec);
|
||||||
|
if (!Platform::path_is_within(canon_build, target_p)) {
|
||||||
|
warning_out =
|
||||||
|
"preserved existing non-VBS symlink at project-root compile_commands.json";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto swapped = Platform::atomic_swap_symlink(root_alias, target_compdb);
|
||||||
|
if (!swapped) {
|
||||||
|
return std::unexpected{swapped.error()};
|
||||||
|
}
|
||||||
|
warning_out.clear();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::vector<EditorCommandEntry> project_editor_commands(const Graph::BuildGraph &graph) {
|
||||||
|
std::vector<EditorCommandEntry> entries;
|
||||||
|
std::error_code ec;
|
||||||
|
|
||||||
|
// Identify enabled targets so disabled targets are omitted, while ALL enabled targets
|
||||||
|
// are included even if a build only executed a subset.
|
||||||
|
std::set<std::string> enabled_targets;
|
||||||
|
for (const auto &t : graph.targets) {
|
||||||
|
if (t.enabled) {
|
||||||
|
enabled_targets.insert(t.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto &act : graph.actions) {
|
||||||
|
if (act.kind != Graph::ActionKind::Compile) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!enabled_targets.contains(act.target_name)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reconstruct structured logical argv directly from typed operands —
|
||||||
|
// NEVER regex/string-replace arbitrary flags or macro definitions!
|
||||||
|
EditorCommandEntry entry;
|
||||||
|
entry.directory = graph.project_root;
|
||||||
|
entry.file = act.logical_source_file;
|
||||||
|
entry.output = act.logical_output_file;
|
||||||
|
entry.target_name = act.target_name;
|
||||||
|
|
||||||
|
entry.arguments.push_back(act.executable.string());
|
||||||
|
if (!graph.toolchain.sysroot.empty()) {
|
||||||
|
entry.arguments.push_back("--sysroot=" + graph.toolchain.sysroot);
|
||||||
|
}
|
||||||
|
if (const auto std_flag = cxx_standard_flag(act.cxx_standard); !std_flag.empty()) {
|
||||||
|
entry.arguments.push_back(std_flag);
|
||||||
|
}
|
||||||
|
if (act.position_independent) {
|
||||||
|
entry.arguments.push_back("-fPIC");
|
||||||
|
}
|
||||||
|
if (act.lto == LtoMode::Full) {
|
||||||
|
entry.arguments.push_back("-flto");
|
||||||
|
} else if (act.lto == LtoMode::Thin) {
|
||||||
|
entry.arguments.push_back("-flto=thin");
|
||||||
|
}
|
||||||
|
if (!act.sanitizers.empty()) {
|
||||||
|
std::string list;
|
||||||
|
for (std::size_t i = 0; i < act.sanitizers.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
list += ',';
|
||||||
|
}
|
||||||
|
list += sanitizer_flag(act.sanitizers[i]);
|
||||||
|
}
|
||||||
|
entry.arguments.push_back("-fsanitize=" + list);
|
||||||
|
entry.arguments.push_back("-fno-omit-frame-pointer");
|
||||||
|
}
|
||||||
|
if (act.precompiled_header) {
|
||||||
|
entry.arguments.push_back("-include");
|
||||||
|
entry.arguments.push_back(act.precompiled_header->string());
|
||||||
|
}
|
||||||
|
for (const auto &[inc_path, is_system] : act.logical_include_dirs) {
|
||||||
|
entry.arguments.push_back(is_system ? "-isystem" : "-I");
|
||||||
|
entry.arguments.push_back(inc_path.string());
|
||||||
|
}
|
||||||
|
for (const auto &def : act.defines) {
|
||||||
|
entry.arguments.push_back("-D" + def);
|
||||||
|
}
|
||||||
|
for (const auto &opt : act.compile_options) {
|
||||||
|
entry.arguments.push_back(opt);
|
||||||
|
}
|
||||||
|
entry.arguments.push_back("-c");
|
||||||
|
entry.arguments.push_back(act.logical_source_file.string());
|
||||||
|
entry.arguments.push_back("-o");
|
||||||
|
entry.arguments.push_back(act.logical_output_file.string());
|
||||||
|
|
||||||
|
// Check generated prerequisites readiness (Plan 09/10).
|
||||||
|
for (const auto &dep_id : act.dependencies) {
|
||||||
|
const auto dit = graph.action_index_by_id.find(dep_id);
|
||||||
|
if (dit == graph.action_index_by_id.end()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto &producer = graph.actions[dit->second];
|
||||||
|
if (producer.kind == Graph::ActionKind::Custom ||
|
||||||
|
producer.kind == Graph::ActionKind::PrecompiledHeader) {
|
||||||
|
for (const auto &out : producer.declared_outputs) {
|
||||||
|
if (!std::filesystem::exists(out, ec)) {
|
||||||
|
entry.missing_generated_prerequisites.push_back(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
entries.push_back(std::move(entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string format_compile_commands_json(const std::vector<EditorCommandEntry> &entries) {
|
||||||
|
using Util::json_array;
|
||||||
|
using Util::json_quote;
|
||||||
|
|
||||||
|
std::string out{"[\n"};
|
||||||
|
for (std::size_t i = 0; i < entries.size(); ++i) {
|
||||||
|
const auto &e = entries[i];
|
||||||
|
out += " {\"directory\":" + json_quote(e.directory.string()) +
|
||||||
|
",\"file\":" + json_quote(e.file.string()) +
|
||||||
|
",\"output\":" + json_quote(e.output.string()) +
|
||||||
|
",\"arguments\":" + json_array(e.arguments, json_quote) + "}";
|
||||||
|
if (i + 1 < entries.size()) {
|
||||||
|
out += ',';
|
||||||
|
}
|
||||||
|
out += '\n';
|
||||||
|
}
|
||||||
|
out += "]\n";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::uint64_t, Void::Result::Error>
|
||||||
|
reserve_selection_ticket(const std::filesystem::path &project_root,
|
||||||
|
const std::filesystem::path &build_root, std::string_view profile_name) {
|
||||||
|
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
||||||
|
Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
SelectionState st = load_selection_locked(project_root).value_or(SelectionState{});
|
||||||
|
st.ticket += 1;
|
||||||
|
// Record reservation ticket monotonically without pointing to an unvalidated generation yet.
|
||||||
|
if (st.selected_build_root.empty()) {
|
||||||
|
st.selected_build_root = build_root;
|
||||||
|
}
|
||||||
|
if (st.selected_profile.empty()) {
|
||||||
|
st.selected_profile = std::string{profile_name};
|
||||||
|
}
|
||||||
|
auto wrote = Platform::atomic_write_file(selection_file_path(project_root),
|
||||||
|
serialize_selection(st), true);
|
||||||
|
if (!wrote) {
|
||||||
|
return std::unexpected{wrote.error()};
|
||||||
|
}
|
||||||
|
return st.ticket;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<EditorGeneration, Void::Result::Error>
|
||||||
|
publish_profile_compdb(const Graph::BuildGraph &graph, const PublishOptions &options) {
|
||||||
|
const auto entries = project_editor_commands(graph);
|
||||||
|
const std::string compdb_json = format_compile_commands_json(entries);
|
||||||
|
const std::string gen_id =
|
||||||
|
Util::sha256_hex(graph.profile_identity + "\n" + compdb_json).substr(0, 16);
|
||||||
|
|
||||||
|
const auto profile_dir =
|
||||||
|
options.build_root / "profiles" / sanitize_profile_dir(graph.profile.name);
|
||||||
|
const auto gen_dir = profile_dir / "editor" / "generations" / gen_id;
|
||||||
|
const auto gen_compdb = gen_dir / "compile_commands.json";
|
||||||
|
const auto profile_compdb = profile_dir / "compile_commands.json";
|
||||||
|
const auto status_file = profile_dir / "editor" / "status.json";
|
||||||
|
|
||||||
|
EditorGeneration gen;
|
||||||
|
gen.generation_id = gen_id;
|
||||||
|
gen.profile_name = graph.profile.name;
|
||||||
|
gen.profile_identity = graph.profile_identity;
|
||||||
|
gen.status = GenerationStatus::Valid;
|
||||||
|
gen.compdb_path = gen_compdb;
|
||||||
|
gen.entry_count = entries.size();
|
||||||
|
|
||||||
|
for (const auto &e : entries) {
|
||||||
|
for (const auto &missing : e.missing_generated_prerequisites) {
|
||||||
|
gen.readiness_warnings.push_back(std::format("target '{}' missing generated input '{}'",
|
||||||
|
e.target_name, missing.string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Avoid needless rewrite when identical immutable generation bytes already exist.
|
||||||
|
bool bytes_changed = true;
|
||||||
|
if (auto existing = Void::FileSystem::read_file(gen_compdb);
|
||||||
|
existing && *existing == compdb_json) {
|
||||||
|
bytes_changed = false;
|
||||||
|
}
|
||||||
|
if (bytes_changed) {
|
||||||
|
if (auto w = Platform::atomic_write_file(gen_compdb, compdb_json, true); !w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atomically update per-profile compile_commands.json pointer.
|
||||||
|
if (auto sw = Platform::atomic_swap_symlink(profile_compdb, gen_compdb); !sw) {
|
||||||
|
return std::unexpected{sw.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write per-profile status record atomically.
|
||||||
|
const std::string status_json =
|
||||||
|
"{\"schema_version\":1,\"profile\":" + Util::json_quote(graph.profile.name) +
|
||||||
|
",\"generation_id\":" + Util::json_quote(gen_id) +
|
||||||
|
",\"status\":\"valid\",\"diagnostic\":\"\"" +
|
||||||
|
",\"compdb_path\":" + Util::json_quote(gen_compdb.string()) +
|
||||||
|
",\"entry_count\":" + std::to_string(entries.size()) +
|
||||||
|
",\"readiness_warnings\":" + Util::json_array(gen.readiness_warnings, Util::json_quote) +
|
||||||
|
"}\n";
|
||||||
|
if (auto sw = Platform::atomic_write_file(status_file, status_json, true); !sw) {
|
||||||
|
return std::unexpected{sw.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Coordinate project-level editor selection under short exclusive lock with ticket/revision
|
||||||
|
// check!
|
||||||
|
auto lock = Platform::FileLock::acquire(selection_lock_path(options.project_root),
|
||||||
|
Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
SelectionState st = load_selection_locked(options.project_root).value_or(SelectionState{});
|
||||||
|
bool should_select = false;
|
||||||
|
if (options.update_selection) {
|
||||||
|
const std::uint64_t my_ticket = options.reserved_ticket.value_or(st.ticket + 1);
|
||||||
|
// Reject stale late completions whose reserved ticket was superseded by a newer request!
|
||||||
|
if (my_ticket >= st.ticket) {
|
||||||
|
st.ticket = my_ticket;
|
||||||
|
should_select = true;
|
||||||
|
}
|
||||||
|
} else if (st.selected_profile == graph.profile.name &&
|
||||||
|
st.selected_build_root == options.build_root) {
|
||||||
|
// Watchers refresh the ALREADY-SELECTED profile without stealing selection!
|
||||||
|
should_select = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (should_select) {
|
||||||
|
st.selected_profile = graph.profile.name;
|
||||||
|
st.selected_build_root = options.build_root;
|
||||||
|
st.selected_generation_id = gen_id;
|
||||||
|
st.selected_compdb_path = gen_compdb;
|
||||||
|
|
||||||
|
const auto build_root_compdb = options.build_root / "compile_commands.json";
|
||||||
|
if (auto sw = Platform::atomic_swap_symlink(build_root_compdb, gen_compdb); !sw) {
|
||||||
|
return std::unexpected{sw.error()};
|
||||||
|
}
|
||||||
|
if (options.manage_project_root_alias) {
|
||||||
|
std::string warn;
|
||||||
|
auto alias_res = update_managed_root_alias(options.project_root, options.build_root,
|
||||||
|
gen_compdb, warn);
|
||||||
|
if (!alias_res) {
|
||||||
|
return std::unexpected{alias_res.error()};
|
||||||
|
}
|
||||||
|
st.managed_root_alias_active = *alias_res;
|
||||||
|
st.root_alias_warning = std::move(warn);
|
||||||
|
}
|
||||||
|
if (auto w = Platform::atomic_write_file(selection_file_path(options.project_root),
|
||||||
|
serialize_selection(st), true);
|
||||||
|
!w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return gen;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
mark_profile_stale(const std::filesystem::path &build_root, std::string_view profile_name,
|
||||||
|
GenerationStatus status, std::string_view diagnostic) {
|
||||||
|
const auto profile_dir = build_root / "profiles" / sanitize_profile_dir(profile_name);
|
||||||
|
const auto status_file = profile_dir / "editor" / "status.json";
|
||||||
|
|
||||||
|
// Preserve previous valid generation ID/path if present so editors see clearly stale DB.
|
||||||
|
std::string prev_gen;
|
||||||
|
std::string prev_path;
|
||||||
|
if (auto existing = Void::FileSystem::read_file(status_file); existing) {
|
||||||
|
if (auto parsed = Void::Json::Strict::parse(*existing); parsed) {
|
||||||
|
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
|
||||||
|
prev_gen = get_str(*obj, "generation_id");
|
||||||
|
prev_path = get_str(*obj, "compdb_path");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string json = "{\"schema_version\":1,\"profile\":" + Util::json_quote(profile_name) +
|
||||||
|
",\"generation_id\":" + Util::json_quote(prev_gen) +
|
||||||
|
",\"status\":" + Util::json_quote(status_name(status)) +
|
||||||
|
",\"diagnostic\":" + Util::json_quote(diagnostic) +
|
||||||
|
",\"compdb_path\":" + Util::json_quote(prev_path) + "}\n";
|
||||||
|
return Platform::atomic_write_file(status_file, json, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<SelectionState, Void::Result::Error>
|
||||||
|
select_editor_profile(const std::filesystem::path &project_root,
|
||||||
|
const std::filesystem::path &build_root, std::string_view profile_name,
|
||||||
|
bool manage_project_root_alias) {
|
||||||
|
const auto profile_dir = build_root / "profiles" / sanitize_profile_dir(profile_name);
|
||||||
|
const auto status_file = profile_dir / "editor" / "status.json";
|
||||||
|
auto text = Void::FileSystem::read_file(status_file);
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("no published compilation database for profile '{}'", profile_name))};
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{make_error("corrupt editor status metadata")};
|
||||||
|
}
|
||||||
|
const auto *obj = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!obj) {
|
||||||
|
return std::unexpected{make_error("invalid editor status metadata")};
|
||||||
|
}
|
||||||
|
const auto gen_id = get_str(*obj, "generation_id");
|
||||||
|
const auto compdb_str = get_str(*obj, "compdb_path");
|
||||||
|
if (compdb_str.empty() || !std::filesystem::exists(compdb_str)) {
|
||||||
|
return std::unexpected{make_error(std::format(
|
||||||
|
"profile '{}' has no valid compilation database generation", profile_name))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
||||||
|
Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
SelectionState st = load_selection_locked(project_root).value_or(SelectionState{});
|
||||||
|
st.ticket += 1;
|
||||||
|
st.selected_profile = std::string{profile_name};
|
||||||
|
st.selected_build_root = build_root;
|
||||||
|
st.selected_generation_id = gen_id;
|
||||||
|
st.selected_compdb_path = compdb_str;
|
||||||
|
|
||||||
|
if (auto sw = Platform::atomic_swap_symlink(build_root / "compile_commands.json",
|
||||||
|
st.selected_compdb_path);
|
||||||
|
!sw) {
|
||||||
|
return std::unexpected{sw.error()};
|
||||||
|
}
|
||||||
|
if (manage_project_root_alias) {
|
||||||
|
std::string warn;
|
||||||
|
auto alias_res =
|
||||||
|
update_managed_root_alias(project_root, build_root, st.selected_compdb_path, warn);
|
||||||
|
if (!alias_res) {
|
||||||
|
return std::unexpected{alias_res.error()};
|
||||||
|
}
|
||||||
|
st.managed_root_alias_active = *alias_res;
|
||||||
|
st.root_alias_warning = std::move(warn);
|
||||||
|
}
|
||||||
|
if (auto w = Platform::atomic_write_file(selection_file_path(project_root),
|
||||||
|
serialize_selection(st), true);
|
||||||
|
!w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<SelectionState>, Void::Result::Error>
|
||||||
|
read_selection_state(const std::filesystem::path &project_root) {
|
||||||
|
auto lock =
|
||||||
|
Platform::FileLock::acquire(selection_lock_path(project_root), Platform::LockMode::Shared);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
return load_selection_locked(project_root);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
recover_editor_pointers(const std::filesystem::path &project_root) {
|
||||||
|
auto lock = Platform::FileLock::acquire(selection_lock_path(project_root),
|
||||||
|
Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
auto st = load_selection_locked(project_root);
|
||||||
|
if (!st || st->selected_compdb_path.empty() ||
|
||||||
|
!std::filesystem::exists(st->selected_compdb_path)) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (!st->selected_build_root.empty()) {
|
||||||
|
(void)Platform::atomic_swap_symlink(st->selected_build_root / "compile_commands.json",
|
||||||
|
st->selected_compdb_path);
|
||||||
|
}
|
||||||
|
if (st->managed_root_alias_active) {
|
||||||
|
std::string warn;
|
||||||
|
(void)update_managed_root_alias(project_root, st->selected_build_root,
|
||||||
|
st->selected_compdb_path, warn);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Editor
|
||||||
@@ -0,0 +1,542 @@
|
|||||||
|
#include <Void/Build/Execution/Scheduler.hpp>
|
||||||
|
|
||||||
|
#include <Void/Async/ThreadPool.hpp>
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
#include <Void/Time/Stopwatch.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <format>
|
||||||
|
#include <map>
|
||||||
|
#include <mutex>
|
||||||
|
#include <queue>
|
||||||
|
#include <set>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
|
namespace Void::Build::Execution {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Void::Result::Error make_error(std::string msg) {
|
||||||
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string compute_effective_action_key(const Graph::ActionNode &action) {
|
||||||
|
// Re-hash declared input file bytes at execution time (including generated upstream outputs!)
|
||||||
|
// so downstream compile/archive/link actions invalidate immediately when an upstream artifact
|
||||||
|
// changes.
|
||||||
|
Util::Sha256Hasher hasher;
|
||||||
|
hasher.update_length_prefixed(action.action_key);
|
||||||
|
for (const auto &in_path : action.declared_inputs) {
|
||||||
|
hasher.update_length_prefixed(in_path.string());
|
||||||
|
if (auto digest = Util::sha256_file_hex(in_path); digest) {
|
||||||
|
hasher.update_length_prefixed(*digest);
|
||||||
|
} else {
|
||||||
|
hasher.update_length_prefixed("<missing>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hasher.finalize_hex();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool verify_discovered_inputs_unchanged(
|
||||||
|
const std::map<std::string, std::string, std::less<>> &discovered_inputs) {
|
||||||
|
for (const auto &[path_str, expected_sha] : discovered_inputs) {
|
||||||
|
auto actual = Util::sha256_file_hex(std::filesystem::path{path_str});
|
||||||
|
if (!actual || *actual != expected_sha) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool verify_outputs_match_record(const Graph::ActionNode &action,
|
||||||
|
const State::ActionSuccessRecord &record) {
|
||||||
|
for (const auto &out_path : action.declared_outputs) {
|
||||||
|
const auto it = record.outputs.find(out_path.string());
|
||||||
|
if (it == record.outputs.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
auto actual = Util::sha256_file_hex(out_path);
|
||||||
|
if (!actual || *actual != it->second.sha256) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool restore_outputs_from_cache(const Graph::ActionNode &action,
|
||||||
|
const State::ActionSuccessRecord &record,
|
||||||
|
const State::StateStore &state) {
|
||||||
|
for (const auto &out_path : action.declared_outputs) {
|
||||||
|
const auto it = record.outputs.find(out_path.string());
|
||||||
|
if (it == record.outputs.end()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
auto mat = state.materialize_blob(it->second, out_path);
|
||||||
|
if (!mat) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::set<std::string> collect_ancestors(const Graph::BuildGraph &graph, const std::string &id) {
|
||||||
|
std::set<std::string> ancestors;
|
||||||
|
std::queue<std::string> q;
|
||||||
|
const auto idx_it = graph.action_index_by_id.find(id);
|
||||||
|
if (idx_it == graph.action_index_by_id.end()) {
|
||||||
|
return ancestors;
|
||||||
|
}
|
||||||
|
for (const auto &dep : graph.actions[idx_it->second].dependencies) {
|
||||||
|
if (ancestors.insert(dep).second) {
|
||||||
|
q.push(dep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (!q.empty()) {
|
||||||
|
const auto cur = q.front();
|
||||||
|
q.pop();
|
||||||
|
const auto cit = graph.action_index_by_id.find(cur);
|
||||||
|
if (cit == graph.action_index_by_id.end()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const auto &dep : graph.actions[cit->second].dependencies) {
|
||||||
|
if (ancestors.insert(dep).second) {
|
||||||
|
q.push(dep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ancestors;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||||
|
parse_depfile(const std::filesystem::path &depfile_path) {
|
||||||
|
auto text = Void::FileSystem::read_file(depfile_path);
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{text.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove backslash-newline continuations.
|
||||||
|
std::string unfolded;
|
||||||
|
unfolded.reserve(text->size());
|
||||||
|
for (std::size_t i = 0; i < text->size(); ++i) {
|
||||||
|
if ((*text)[i] == '\\' && i + 1 < text->size() && (*text)[i + 1] == '\n') {
|
||||||
|
++i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ((*text)[i] == '\\' && i + 2 < text->size() && (*text)[i + 1] == '\r' &&
|
||||||
|
(*text)[i + 2] == '\n') {
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
unfolded.push_back((*text)[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the first unescaped colon separating target(s) from prerequisites.
|
||||||
|
std::size_t colon = std::string::npos;
|
||||||
|
for (std::size_t i = 0; i < unfolded.size(); ++i) {
|
||||||
|
if (unfolded[i] == '\\' && i + 1 < unfolded.size()) {
|
||||||
|
++i;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (unfolded[i] == ':') {
|
||||||
|
colon = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (colon == std::string::npos) {
|
||||||
|
return std::unexpected{make_error(std::format(
|
||||||
|
"parse_depfile: malformed depfile '{}' (missing ':')", depfile_path.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::filesystem::path> deps;
|
||||||
|
std::set<std::string> seen;
|
||||||
|
std::size_t pos = colon + 1;
|
||||||
|
while (pos < unfolded.size()) {
|
||||||
|
while (pos < unfolded.size() && (unfolded[pos] == ' ' || unfolded[pos] == '\t' ||
|
||||||
|
unfolded[pos] == '\n' || unfolded[pos] == '\r')) {
|
||||||
|
++pos;
|
||||||
|
}
|
||||||
|
if (pos >= unfolded.size()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::string token;
|
||||||
|
while (pos < unfolded.size() && unfolded[pos] != ' ' && unfolded[pos] != '\t' &&
|
||||||
|
unfolded[pos] != '\n' && unfolded[pos] != '\r') {
|
||||||
|
if (unfolded[pos] == '\\' && pos + 1 < unfolded.size()) {
|
||||||
|
const char next = unfolded[pos + 1];
|
||||||
|
if (next == ' ' || next == '#' || next == '\\' || next == ':') {
|
||||||
|
token.push_back(next);
|
||||||
|
pos += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (unfolded[pos] == '$' && pos + 1 < unfolded.size() && unfolded[pos + 1] == '$') {
|
||||||
|
token.push_back('$');
|
||||||
|
pos += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
token.push_back(unfolded[pos++]);
|
||||||
|
}
|
||||||
|
if (!token.empty() && seen.insert(token).second) {
|
||||||
|
deps.emplace_back(std::move(token));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return deps;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ExecutionReport, Void::Result::Error>
|
||||||
|
execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||||
|
const ExecutionOptions &options, std::stop_token external_stop) {
|
||||||
|
auto selected_indices_res = graph.select_action_closure(options.selected_targets);
|
||||||
|
if (!selected_indices_res) {
|
||||||
|
return std::unexpected{selected_indices_res.error()};
|
||||||
|
}
|
||||||
|
const auto &selected_indices = *selected_indices_res;
|
||||||
|
|
||||||
|
ExecutionReport report;
|
||||||
|
report.total_selected = selected_indices.size();
|
||||||
|
if (selected_indices.empty()) {
|
||||||
|
report.succeeded = true;
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize writers to the same profile directory; independent profiles run concurrently.
|
||||||
|
const auto profile_lock_path = graph.profile_build_dir / ".profile.lock";
|
||||||
|
auto profile_lock =
|
||||||
|
Platform::FileLock::acquire(profile_lock_path, Platform::LockMode::Exclusive);
|
||||||
|
if (!profile_lock) {
|
||||||
|
return std::unexpected{profile_lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto lease = state.acquire_lease(graph.profile.name);
|
||||||
|
if (!lease) {
|
||||||
|
return std::unexpected{lease.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map every output path across the entire graph to its producer action ID
|
||||||
|
// so we can detect unordered generated inputs discovered via depfiles (Plan 03/06).
|
||||||
|
std::map<std::filesystem::path, std::string> all_output_producers;
|
||||||
|
for (const auto &act : graph.actions) {
|
||||||
|
for (const auto &out : act.declared_outputs) {
|
||||||
|
all_output_producers[out.lexically_normal()] = act.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build subgraph dependency tables over selected_indices.
|
||||||
|
std::set<std::size_t> selected_set(selected_indices.begin(), selected_indices.end());
|
||||||
|
std::map<std::size_t, std::size_t> in_degree;
|
||||||
|
std::map<std::size_t, std::vector<std::size_t>> dependents;
|
||||||
|
for (const std::size_t idx : selected_indices) {
|
||||||
|
in_degree[idx] = 0;
|
||||||
|
}
|
||||||
|
for (const std::size_t idx : selected_indices) {
|
||||||
|
for (const auto &dep_id : graph.actions[idx].dependencies) {
|
||||||
|
const auto dit = graph.action_index_by_id.find(dep_id);
|
||||||
|
if (dit != graph.action_index_by_id.end() && selected_set.contains(dit->second)) {
|
||||||
|
++in_degree[idx];
|
||||||
|
dependents[dit->second].push_back(idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::size_t worker_count =
|
||||||
|
std::min(selected_indices.size(),
|
||||||
|
options.jobs > 0 ? options.jobs
|
||||||
|
: std::max<std::size_t>(1, std::thread::hardware_concurrency()));
|
||||||
|
|
||||||
|
std::mutex mu;
|
||||||
|
std::condition_variable cv;
|
||||||
|
std::queue<std::size_t> ready;
|
||||||
|
for (const std::size_t idx : selected_indices) {
|
||||||
|
if (in_degree[idx] == 0) {
|
||||||
|
ready.push(idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::stop_source internal_stop;
|
||||||
|
std::stop_callback forward_stop(external_stop, [&] { internal_stop.request_stop(); });
|
||||||
|
|
||||||
|
std::size_t active_workers = 0;
|
||||||
|
std::size_t completed_count = 0;
|
||||||
|
bool abort_scheduling = false;
|
||||||
|
|
||||||
|
auto emit_event = [&](ExecutionEvent::Kind kind, const Graph::ActionNode &act,
|
||||||
|
std::size_t completed, std::string msg = {}) {
|
||||||
|
if (options.on_event) {
|
||||||
|
options.on_event(ExecutionEvent{kind, act.id, act.target_name, completed,
|
||||||
|
selected_indices.size(), std::move(msg)});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
auto run_one_action = [&](const Graph::ActionNode &act) -> ActionExecutionResult {
|
||||||
|
const auto timer = Void::Time::Stopwatch::started();
|
||||||
|
ActionExecutionResult res;
|
||||||
|
res.action_id = act.id;
|
||||||
|
res.target_name = act.target_name;
|
||||||
|
|
||||||
|
if (internal_stop.stop_requested()) {
|
||||||
|
res.cancelled = true;
|
||||||
|
res.error_message = "cancelled before start";
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string effective_key = compute_effective_action_key(act);
|
||||||
|
|
||||||
|
// 1. Cache lookup (ONLY when action is deterministic & cacheable!).
|
||||||
|
if (act.cacheable && !act.nondeterministic && options.use_cache) {
|
||||||
|
auto cached = state.lookup_action(effective_key);
|
||||||
|
if (cached && cached->has_value()) {
|
||||||
|
const auto &rec = **cached;
|
||||||
|
if (verify_discovered_inputs_unchanged(rec.discovered_inputs)) {
|
||||||
|
if (verify_outputs_match_record(act, rec) ||
|
||||||
|
restore_outputs_from_cache(act, rec, state)) {
|
||||||
|
res.succeeded = true;
|
||||||
|
res.from_cache = true;
|
||||||
|
res.exit_code = 0;
|
||||||
|
res.elapsed = timer.elapsed_as<std::chrono::milliseconds>();
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Prepare output directories and response file.
|
||||||
|
std::error_code ec;
|
||||||
|
for (const auto &out : act.declared_outputs) {
|
||||||
|
if (out.has_parent_path()) {
|
||||||
|
std::filesystem::create_directories(out.parent_path(), ec);
|
||||||
|
}
|
||||||
|
// Critical invariant (Plan 03): remove pre-existing archive before `ar rcsD`
|
||||||
|
// so deleted object files never linger as stale archive members!
|
||||||
|
if (act.kind == Graph::ActionKind::Archive) {
|
||||||
|
std::filesystem::remove(out, ec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (act.depfile && act.depfile->has_parent_path()) {
|
||||||
|
std::filesystem::create_directories(act.depfile->parent_path(), ec);
|
||||||
|
std::filesystem::remove(*act.depfile, ec);
|
||||||
|
}
|
||||||
|
if (act.response_file) {
|
||||||
|
auto wrote_rsp =
|
||||||
|
Platform::atomic_write_file(*act.response_file, act.response_file_content, false);
|
||||||
|
if (!wrote_rsp) {
|
||||||
|
res.error_message = "failed writing response file: " + wrote_rsp.error().message();
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Execute subprocess under Linux process-group supervisor.
|
||||||
|
Platform::ProcessRequest preq;
|
||||||
|
preq.executable = act.executable;
|
||||||
|
preq.arguments = act.arguments;
|
||||||
|
if (!act.working_directory.empty()) {
|
||||||
|
preq.working_directory = act.working_directory;
|
||||||
|
}
|
||||||
|
preq.environment.mode = Platform::EnvPolicyMode::Inherit;
|
||||||
|
preq.environment.set_vars = act.environment;
|
||||||
|
preq.timeout = options.action_timeout;
|
||||||
|
|
||||||
|
auto proc = Platform::run_supervised(preq, internal_stop.get_token());
|
||||||
|
res.elapsed = timer.elapsed_as<std::chrono::milliseconds>();
|
||||||
|
if (!proc) {
|
||||||
|
res.error_message = proc.error().message();
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.stdout_data = std::move(proc->stdout_data);
|
||||||
|
res.stderr_data = std::move(proc->stderr_data);
|
||||||
|
res.exit_code = proc->exit_code;
|
||||||
|
res.term_signal = proc->term_signal;
|
||||||
|
res.cancelled = proc->cancelled;
|
||||||
|
res.timed_out = proc->timed_out;
|
||||||
|
|
||||||
|
if (proc->exec_failed) {
|
||||||
|
res.error_message = proc->exec_error_message;
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
if (proc->cancelled) {
|
||||||
|
res.error_message = "action cancelled";
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
if (proc->timed_out) {
|
||||||
|
res.error_message = "action timed out";
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
if (proc->overflowed) {
|
||||||
|
res.error_message = "action output exceeded capture limit";
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
if (!proc->succeeded()) {
|
||||||
|
res.error_message = proc->term_signal != 0
|
||||||
|
? std::format("terminated by signal {}", proc->term_signal)
|
||||||
|
: std::format("exited with status {}", proc->exit_code);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Validate ALL declared outputs exist after zero exit!
|
||||||
|
for (const auto &out : act.declared_outputs) {
|
||||||
|
auto meta = Platform::stat_lstat(out);
|
||||||
|
if (!meta || !meta->exists || !meta->is_regular) {
|
||||||
|
res.error_message =
|
||||||
|
std::format("action '{}' exited 0 but required output '{}' is missing", act.id,
|
||||||
|
out.string());
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Parse depfile (if declared) and verify no unordered generated producer escaped DAG!
|
||||||
|
std::map<std::string, std::string, std::less<>> discovered_inputs;
|
||||||
|
if (act.depfile && std::filesystem::exists(*act.depfile, ec)) {
|
||||||
|
auto deps_res = parse_depfile(*act.depfile);
|
||||||
|
if (!deps_res) {
|
||||||
|
res.error_message = std::format("action '{}' produced invalid depfile: {}", act.id,
|
||||||
|
deps_res.error().message());
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
const auto ancestors = collect_ancestors(graph, act.id);
|
||||||
|
for (const auto &dep_raw : *deps_res) {
|
||||||
|
const auto dep_abs = dep_raw.is_absolute()
|
||||||
|
? dep_raw.lexically_normal()
|
||||||
|
: (act.working_directory / dep_raw).lexically_normal();
|
||||||
|
if (const auto prod_it = all_output_producers.find(dep_abs);
|
||||||
|
prod_it != all_output_producers.end() && prod_it->second != act.id &&
|
||||||
|
!ancestors.contains(prod_it->second)) {
|
||||||
|
res.error_message = std::format(
|
||||||
|
"action '{}' read generated file '{}' from unordered producer '{}' "
|
||||||
|
"(declare an explicit dependency/depends_on)",
|
||||||
|
act.id, dep_abs.string(), prod_it->second);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
if (auto digest = Util::sha256_file_hex(dep_abs); digest) {
|
||||||
|
discovered_inputs[dep_abs.string()] = std::move(*digest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Publish outputs to CAS BEFORE recording success (only for cacheable actions).
|
||||||
|
if (act.cacheable && !act.nondeterministic) {
|
||||||
|
State::ActionSuccessRecord rec;
|
||||||
|
rec.action_key = effective_key;
|
||||||
|
rec.profile_identity = graph.profile_identity;
|
||||||
|
rec.target_name = act.target_name;
|
||||||
|
rec.discovered_inputs = std::move(discovered_inputs);
|
||||||
|
rec.recorded_epoch = std::chrono::duration_cast<std::chrono::seconds>(
|
||||||
|
std::chrono::system_clock::now().time_since_epoch())
|
||||||
|
.count();
|
||||||
|
|
||||||
|
for (const auto &out : act.declared_outputs) {
|
||||||
|
auto stored = state.store_blob_from_file(out);
|
||||||
|
if (!stored) {
|
||||||
|
res.error_message = std::format("failed publishing output '{}' to CAS: {}",
|
||||||
|
out.string(), stored.error().message());
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
rec.outputs[out.string()] = std::move(*stored);
|
||||||
|
}
|
||||||
|
auto committed = state.record_action_success(rec);
|
||||||
|
if (!committed) {
|
||||||
|
res.error_message = std::format("failed committing action success record: {}",
|
||||||
|
committed.error().message());
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.succeeded = true;
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
auto worker_loop = [&] {
|
||||||
|
for (;;) {
|
||||||
|
std::size_t idx = 0;
|
||||||
|
{
|
||||||
|
std::unique_lock lk{mu};
|
||||||
|
cv.wait(lk, [&] {
|
||||||
|
return !ready.empty() || abort_scheduling || internal_stop.stop_requested() ||
|
||||||
|
(active_workers == 0 && ready.empty());
|
||||||
|
});
|
||||||
|
if (abort_scheduling || internal_stop.stop_requested()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ready.empty()) {
|
||||||
|
if (active_workers == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
idx = ready.front();
|
||||||
|
ready.pop();
|
||||||
|
++active_workers;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto &act = graph.actions[idx];
|
||||||
|
emit_event(ExecutionEvent::Kind::ActionStarted, act, completed_count);
|
||||||
|
auto ares = run_one_action(act);
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard lk{mu};
|
||||||
|
--active_workers;
|
||||||
|
++completed_count;
|
||||||
|
if (ares.succeeded) {
|
||||||
|
if (ares.from_cache) {
|
||||||
|
++report.cached_count;
|
||||||
|
emit_event(ExecutionEvent::Kind::ActionCached, act, completed_count);
|
||||||
|
} else {
|
||||||
|
++report.executed_count;
|
||||||
|
emit_event(ExecutionEvent::Kind::ActionSucceeded, act, completed_count);
|
||||||
|
}
|
||||||
|
for (const std::size_t dep_idx : dependents[idx]) {
|
||||||
|
if (--in_degree[dep_idx] == 0) {
|
||||||
|
ready.push(dep_idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
++report.failed_count;
|
||||||
|
if (ares.cancelled) {
|
||||||
|
report.cancelled = true;
|
||||||
|
}
|
||||||
|
if (report.diagnostic.empty()) {
|
||||||
|
report.diagnostic = act.id + ": " + ares.error_message;
|
||||||
|
}
|
||||||
|
emit_event(ExecutionEvent::Kind::ActionFailed, act, completed_count,
|
||||||
|
ares.error_message);
|
||||||
|
if (options.fail_fast) {
|
||||||
|
abort_scheduling = true;
|
||||||
|
internal_stop.request_stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report.results.push_back(std::move(ares));
|
||||||
|
}
|
||||||
|
cv.notify_all();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Void::Concurrency::ThreadPool pool{worker_count};
|
||||||
|
std::vector<std::future<void>> worker_futures;
|
||||||
|
worker_futures.reserve(worker_count);
|
||||||
|
for (std::size_t w = 0; w < worker_count; ++w) {
|
||||||
|
worker_futures.push_back(pool.submit(worker_loop));
|
||||||
|
}
|
||||||
|
for (auto &f : worker_futures) {
|
||||||
|
f.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (external_stop.stop_requested()) {
|
||||||
|
report.cancelled = true;
|
||||||
|
}
|
||||||
|
report.succeeded = (report.failed_count == 0) && !report.cancelled &&
|
||||||
|
(report.executed_count + report.cached_count == report.total_selected);
|
||||||
|
if (!report.succeeded && report.diagnostic.empty()) {
|
||||||
|
report.diagnostic = report.cancelled ? "build cancelled" : "build incomplete";
|
||||||
|
}
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Execution
|
||||||
+1924
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,418 @@
|
|||||||
|
#include <Void/Build/Install/Installer.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Core/Scope.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <format>
|
||||||
|
#include <set>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
namespace Void::Build::Install {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||||
|
return Void::System::make_system_error(code, std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_safe_relative_dest(const std::filesystem::path &rel) {
|
||||||
|
if (rel.empty() || rel.is_absolute()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto norm = rel.lexically_normal();
|
||||||
|
for (const auto &part : norm) {
|
||||||
|
if (part == "..") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string default_dest_for_kind(TargetKind kind) {
|
||||||
|
switch (kind) {
|
||||||
|
case TargetKind::Executable:
|
||||||
|
case TargetKind::Test:
|
||||||
|
return "bin";
|
||||||
|
case TargetKind::StaticLibrary:
|
||||||
|
case TargetKind::SharedLibrary:
|
||||||
|
case TargetKind::ObjectLibrary:
|
||||||
|
return "lib";
|
||||||
|
case TargetKind::HeaderOnly:
|
||||||
|
case TargetKind::CustomAction:
|
||||||
|
return "share";
|
||||||
|
}
|
||||||
|
return "share";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string escape_cmake_str(std::string_view s) {
|
||||||
|
std::string out;
|
||||||
|
for (const char c : s) {
|
||||||
|
if (c == '\\' || c == '"' || c == '$' || c == ';') {
|
||||||
|
out.push_back('\\');
|
||||||
|
}
|
||||||
|
out.push_back(c);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<InstallReport, Void::Result::Error>
|
||||||
|
install_project(const Graph::ProjectDescription &description, const Graph::BuildGraph &graph,
|
||||||
|
const InstallOptions &options) {
|
||||||
|
if (options.prefix.empty()) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument, "install prefix is empty")};
|
||||||
|
}
|
||||||
|
if (options.package_name.empty()) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"install package_name is empty")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
const auto prefix_abs = std::filesystem::weakly_canonical(options.prefix, ec);
|
||||||
|
const auto proj_root = graph.project_root;
|
||||||
|
if (Platform::path_is_within(proj_root, prefix_abs) &&
|
||||||
|
!Platform::path_is_within(graph.profile_build_dir, prefix_abs) && prefix_abs == proj_root) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::permission_denied,
|
||||||
|
"refusing to install directly onto project source root")};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build complete list of staged copy operations and detect destination collisions upfront!
|
||||||
|
struct StagedItem {
|
||||||
|
std::filesystem::path src;
|
||||||
|
std::filesystem::path rel_dest;
|
||||||
|
std::uint32_t mode{0644};
|
||||||
|
std::string target_name;
|
||||||
|
};
|
||||||
|
std::vector<StagedItem> items;
|
||||||
|
std::set<std::filesystem::path> dest_set;
|
||||||
|
|
||||||
|
auto add_item =
|
||||||
|
[&](const std::filesystem::path &src, const std::filesystem::path &rel_dest,
|
||||||
|
std::uint32_t mode,
|
||||||
|
std::string target_name = {}) -> Void::Result::Result<void, Void::Result::Error> {
|
||||||
|
if (!is_safe_relative_dest(rel_dest)) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::permission_denied,
|
||||||
|
std::format("install destination '{}' escapes prefix", rel_dest.string()))};
|
||||||
|
}
|
||||||
|
const auto norm = rel_dest.lexically_normal();
|
||||||
|
if (!dest_set.insert(norm).second) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("install destination collision on '{}'", norm.string()))};
|
||||||
|
}
|
||||||
|
if (!std::filesystem::is_regular_file(src, ec)) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("install source artifact '{}' does not exist (build target first)",
|
||||||
|
src.string()))};
|
||||||
|
}
|
||||||
|
items.push_back({src, norm, mode, std::move(target_name)});
|
||||||
|
return {};
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. Installed targets.
|
||||||
|
struct ExportedTarget {
|
||||||
|
std::string name;
|
||||||
|
TargetKind kind;
|
||||||
|
std::filesystem::path rel_artifact;
|
||||||
|
std::vector<std::string> public_defines;
|
||||||
|
std::vector<std::string> public_compile_opts;
|
||||||
|
std::vector<std::string> local_deps;
|
||||||
|
};
|
||||||
|
std::vector<ExportedTarget> exported_targets;
|
||||||
|
|
||||||
|
for (const auto &trec : description.targets) {
|
||||||
|
if (!trec.install_rule) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (options.component && trec.install_rule->component != *options.component) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const std::string dest_dir = trec.install_rule->destination.empty()
|
||||||
|
? default_dest_for_kind(trec.kind)
|
||||||
|
: trec.install_rule->destination;
|
||||||
|
const auto sum_it =
|
||||||
|
std::ranges::find(graph.targets, trec.name, &Graph::ResolvedTargetSummary::name);
|
||||||
|
if (sum_it == graph.targets.end()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ExportedTarget et;
|
||||||
|
et.name = trec.name;
|
||||||
|
et.kind = trec.kind;
|
||||||
|
for (const auto &d : trec.defines) {
|
||||||
|
if (d.visibility != Visibility::Private) {
|
||||||
|
et.public_defines.push_back(d.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &o : trec.scoped_compile_options) {
|
||||||
|
if (o.visibility != Visibility::Private) {
|
||||||
|
et.public_compile_opts.push_back(o.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &l : trec.links) {
|
||||||
|
if (l.kind == LinkKind::Local &&
|
||||||
|
(l.visibility != Visibility::Private || trec.kind == TargetKind::StaticLibrary)) {
|
||||||
|
et.local_deps.push_back(l.target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sum_it->primary_outputs.empty()) {
|
||||||
|
const auto &art = sum_it->primary_outputs.front();
|
||||||
|
const auto rel_dest = std::filesystem::path{dest_dir} / art.filename();
|
||||||
|
const std::uint32_t mode =
|
||||||
|
(trec.kind == TargetKind::Executable || trec.kind == TargetKind::SharedLibrary)
|
||||||
|
? 0755u
|
||||||
|
: 0644u;
|
||||||
|
if (auto r = add_item(art, rel_dest, mode, trec.name); !r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
et.rel_artifact = rel_dest;
|
||||||
|
}
|
||||||
|
exported_targets.push_back(std::move(et));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Project file & directory install rules (headers/data).
|
||||||
|
for (const auto &rule : description.install_rules) {
|
||||||
|
if (options.component && rule.component != *options.component) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto src_abs = std::filesystem::path{rule.source_path}.is_absolute()
|
||||||
|
? std::filesystem::path{rule.source_path}
|
||||||
|
: (proj_root / rule.source_path);
|
||||||
|
if (rule.is_directory) {
|
||||||
|
if (!std::filesystem::is_directory(src_abs, ec)) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("install directory '{}' does not exist", src_abs.string()))};
|
||||||
|
}
|
||||||
|
for (const auto &ent : std::filesystem::recursive_directory_iterator(src_abs, ec)) {
|
||||||
|
if (ent.is_regular_file(ec)) {
|
||||||
|
const auto rel = ent.path().lexically_relative(src_abs);
|
||||||
|
if (auto r = add_item(ent.path(), std::filesystem::path{rule.destination} / rel,
|
||||||
|
0644u);
|
||||||
|
!r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const auto rel_dest = std::filesystem::path{rule.destination} / src_abs.filename();
|
||||||
|
if (auto r = add_item(src_abs, rel_dest, 0644u); !r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Stage everything privately first so failed installs never leave broken metadata.
|
||||||
|
const auto stage_root = graph.profile_build_dir /
|
||||||
|
std::format("install-stage-{}", static_cast<long long>(::getpid()));
|
||||||
|
std::filesystem::remove_all(stage_root, ec);
|
||||||
|
std::filesystem::create_directories(stage_root, ec);
|
||||||
|
auto stage_guard = Void::Scope::on_exit([&] { std::filesystem::remove_all(stage_root, ec); });
|
||||||
|
|
||||||
|
std::vector<std::filesystem::path> owned_rel_files;
|
||||||
|
for (const auto &item : items) {
|
||||||
|
const auto staged = stage_root / item.rel_dest;
|
||||||
|
auto copied = Platform::copy_isolated(item.src, staged, item.mode);
|
||||||
|
if (!copied) {
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
owned_rel_files.push_back(item.rel_dest);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Generate relocatable native package metadata (ZERO build/snapshot paths!).
|
||||||
|
std::optional<std::filesystem::path> native_rel;
|
||||||
|
if (options.export_native_metadata) {
|
||||||
|
using Util::json_array;
|
||||||
|
using Util::json_quote;
|
||||||
|
|
||||||
|
native_rel = std::filesystem::path{"share"} / "vbs" / options.package_name / "package.json";
|
||||||
|
std::string pjson =
|
||||||
|
"{\"schema_version\":1,\"name\":" + json_quote(options.package_name) +
|
||||||
|
",\"version\":" + json_quote(options.package_version) +
|
||||||
|
",\"profile\":" + json_quote(graph.profile.name) +
|
||||||
|
",\"compiler\":" + json_quote(compiler_name(graph.profile.compiler)) +
|
||||||
|
",\"os\":" + json_quote(graph.profile.os) +
|
||||||
|
",\"architecture\":" + json_quote(graph.profile.architecture) +
|
||||||
|
",\"include_dir\":\"include\",\"targets\":" +
|
||||||
|
json_array(exported_targets,
|
||||||
|
[](const ExportedTarget &et) {
|
||||||
|
return "{\"name\":" + json_quote(et.name) +
|
||||||
|
",\"kind\":" + json_quote(target_kind_name(et.kind)) +
|
||||||
|
",\"artifact\":" + json_quote(et.rel_artifact.generic_string()) +
|
||||||
|
",\"defines\":" + json_array(et.public_defines, json_quote) +
|
||||||
|
",\"compile_options\":" +
|
||||||
|
json_array(et.public_compile_opts, json_quote) +
|
||||||
|
",\"dependencies\":" + json_array(et.local_deps, json_quote) +
|
||||||
|
'}';
|
||||||
|
}) +
|
||||||
|
"}\n";
|
||||||
|
if (auto w = Platform::atomic_write_file(stage_root / *native_rel, pjson, false); !w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
owned_rel_files.push_back(*native_rel);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Generate relocatable CMake Config + Targets files using ${_vbs_prefix} relative paths!
|
||||||
|
std::optional<std::filesystem::path> cmake_rel;
|
||||||
|
if (options.export_cmake_config) {
|
||||||
|
const auto cmake_dir = std::filesystem::path{"lib"} / "cmake" / options.package_name;
|
||||||
|
cmake_rel = cmake_dir / (options.package_name + "Config.cmake");
|
||||||
|
const auto targets_rel = cmake_dir / (options.package_name + "Targets.cmake");
|
||||||
|
|
||||||
|
std::string cfg_cmake =
|
||||||
|
"# Relocatable CMake config generated by VoidBuildSystem\n"
|
||||||
|
"get_filename_component(_vbs_prefix \"${CMAKE_CURRENT_LIST_DIR}/../../..\" ABSOLUTE)\n"
|
||||||
|
"include(\"${CMAKE_CURRENT_LIST_DIR}/" +
|
||||||
|
options.package_name + "Targets.cmake\")\n";
|
||||||
|
|
||||||
|
std::string tgt_cmake =
|
||||||
|
"# Relocatable CMake imported targets generated by VoidBuildSystem\n"
|
||||||
|
"get_filename_component(_vbs_prefix \"${CMAKE_CURRENT_LIST_DIR}/../../..\" ABSOLUTE)\n";
|
||||||
|
for (const auto &et : exported_targets) {
|
||||||
|
const std::string full = options.package_name + "::" + et.name;
|
||||||
|
std::string cm_type = "STATIC";
|
||||||
|
if (et.kind == TargetKind::SharedLibrary) {
|
||||||
|
cm_type = "SHARED";
|
||||||
|
} else if (et.kind == TargetKind::HeaderOnly) {
|
||||||
|
cm_type = "INTERFACE";
|
||||||
|
} else if (et.kind == TargetKind::Executable) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
tgt_cmake += "if(NOT TARGET " + full + ")\n";
|
||||||
|
tgt_cmake += " add_library(" + full + " " + cm_type + " IMPORTED)\n";
|
||||||
|
tgt_cmake += " set_target_properties(" + full + " PROPERTIES\n";
|
||||||
|
if (!et.rel_artifact.empty()) {
|
||||||
|
tgt_cmake += " IMPORTED_LOCATION \"${_vbs_prefix}/" +
|
||||||
|
escape_cmake_str(et.rel_artifact.generic_string()) + "\"\n";
|
||||||
|
}
|
||||||
|
tgt_cmake += " INTERFACE_INCLUDE_DIRECTORIES \"${_vbs_prefix}/include\"\n";
|
||||||
|
if (!et.public_defines.empty()) {
|
||||||
|
tgt_cmake += " INTERFACE_COMPILE_DEFINITIONS \"";
|
||||||
|
for (std::size_t i = 0; i < et.public_defines.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
tgt_cmake += ";";
|
||||||
|
}
|
||||||
|
tgt_cmake += escape_cmake_str(et.public_defines[i]);
|
||||||
|
}
|
||||||
|
tgt_cmake += "\"\n";
|
||||||
|
}
|
||||||
|
if (!et.local_deps.empty()) {
|
||||||
|
tgt_cmake += " INTERFACE_LINK_LIBRARIES \"";
|
||||||
|
for (std::size_t i = 0; i < et.local_deps.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
tgt_cmake += ";";
|
||||||
|
}
|
||||||
|
tgt_cmake += options.package_name + "::" + et.local_deps[i];
|
||||||
|
}
|
||||||
|
tgt_cmake += "\"\n";
|
||||||
|
}
|
||||||
|
tgt_cmake += " )\nendif()\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (auto w = Platform::atomic_write_file(stage_root / *cmake_rel, cfg_cmake, false); !w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
if (auto w = Platform::atomic_write_file(stage_root / targets_rel, tgt_cmake, false); !w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
owned_rel_files.push_back(*cmake_rel);
|
||||||
|
owned_rel_files.push_back(targets_rel);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Publish staged files into prefix atomically and write ownership manifest.
|
||||||
|
std::filesystem::create_directories(prefix_abs, ec);
|
||||||
|
InstallReport report;
|
||||||
|
report.prefix = prefix_abs;
|
||||||
|
|
||||||
|
for (const auto &rel : owned_rel_files) {
|
||||||
|
const auto staged = stage_root / rel;
|
||||||
|
const auto final_dst = prefix_abs / rel;
|
||||||
|
auto meta = Platform::stat_lstat(staged);
|
||||||
|
auto copied = Platform::copy_isolated(staged, final_dst, meta ? meta->mode : 0644u);
|
||||||
|
if (!copied) {
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
report.installed_files.push_back(final_dst);
|
||||||
|
}
|
||||||
|
|
||||||
|
report.manifest_path = prefix_abs / ".vbs-install-manifest.json";
|
||||||
|
if (native_rel) {
|
||||||
|
report.native_package_file = prefix_abs / *native_rel;
|
||||||
|
}
|
||||||
|
if (cmake_rel) {
|
||||||
|
report.cmake_config_file = prefix_abs / *cmake_rel;
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string manifest_json =
|
||||||
|
"{\"schema_version\":1,\"package\":" + Util::json_quote(options.package_name) +
|
||||||
|
",\"files\":" +
|
||||||
|
Util::json_array(
|
||||||
|
owned_rel_files,
|
||||||
|
[](const std::filesystem::path &p) { return Util::json_quote(p.generic_string()); }) +
|
||||||
|
"}\n";
|
||||||
|
auto mw = Platform::atomic_write_file(report.manifest_path, manifest_json, true);
|
||||||
|
if (!mw) {
|
||||||
|
return std::unexpected{mw.error()};
|
||||||
|
}
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::size_t, Void::Result::Error>
|
||||||
|
uninstall_prefix(const std::filesystem::path &prefix) {
|
||||||
|
const auto manifest_path = prefix / ".vbs-install-manifest.json";
|
||||||
|
auto text = Void::FileSystem::read_file(manifest_path);
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("no VBS install manifest found at '{}'", manifest_path.string()))};
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"corrupt VBS install manifest")};
|
||||||
|
}
|
||||||
|
const auto *root = std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
|
||||||
|
if (!root) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"invalid VBS install manifest")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t removed = 0;
|
||||||
|
std::error_code ec;
|
||||||
|
const auto canon_prefix = std::filesystem::weakly_canonical(prefix, ec);
|
||||||
|
const auto fit = root->find("files");
|
||||||
|
if (fit != root->end()) {
|
||||||
|
if (const auto *arr = std::get_if<Void::Json::Strict::Value::Array>(&fit->second.value)) {
|
||||||
|
for (const auto &v : *arr) {
|
||||||
|
if (const auto *s = std::get_if<std::string>(&v.value)) {
|
||||||
|
const std::filesystem::path rel{*s};
|
||||||
|
if (!is_safe_relative_dest(rel)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto target = (canon_prefix / rel).lexically_normal();
|
||||||
|
if (Platform::path_is_within(canon_prefix, target) &&
|
||||||
|
std::filesystem::is_regular_file(target, ec)) {
|
||||||
|
std::filesystem::remove(target, ec);
|
||||||
|
if (!ec) {
|
||||||
|
++removed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::filesystem::remove(manifest_path, ec);
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Install
|
||||||
+1447
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,428 @@
|
|||||||
|
#include <Void/Build/Modules/ModuleScanner.hpp>
|
||||||
|
|
||||||
|
#include <Void/Algorithms/Graph.hpp>
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <format>
|
||||||
|
#include <set>
|
||||||
|
|
||||||
|
namespace Void::Build::Modules {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using JsonVal = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
Void::Result::Error make_error(std::string msg) {
|
||||||
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto it = obj.find(k);
|
||||||
|
return it == obj.end() ? nullptr : &it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&v->value);
|
||||||
|
return s ? *s : std::string{};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string sanitize_module_filename(std::string_view logical_name) {
|
||||||
|
std::string out;
|
||||||
|
out.reserve(logical_name.size());
|
||||||
|
for (const char c : logical_name) {
|
||||||
|
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||||
|
c == '_' || c == '-' || c == '.') {
|
||||||
|
out.push_back(c);
|
||||||
|
} else {
|
||||||
|
out += "__";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string std_flag(CxxStandard standard) {
|
||||||
|
switch (standard) {
|
||||||
|
case CxxStandard::Cxx17:
|
||||||
|
return "-std=c++17";
|
||||||
|
case CxxStandard::Cxx20:
|
||||||
|
return "-std=c++20";
|
||||||
|
case CxxStandard::Cxx23:
|
||||||
|
return "-std=c++23";
|
||||||
|
case CxxStandard::Cxx26:
|
||||||
|
return "-std=c++26";
|
||||||
|
case CxxStandard::Default:
|
||||||
|
return "-std=c++20";
|
||||||
|
}
|
||||||
|
return "-std=c++20";
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<ModuleScanUnit, Void::Result::Error>
|
||||||
|
parse_p1689_json(std::string_view json_text, const std::filesystem::path &source_file) {
|
||||||
|
auto parsed = Void::Json::Strict::parse(json_text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("failed parsing P1689 module scan JSON for '{}'", source_file.string()))};
|
||||||
|
}
|
||||||
|
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!root) {
|
||||||
|
return std::unexpected{make_error("P1689 JSON root must be an object")};
|
||||||
|
}
|
||||||
|
const auto *ver_v = find_key(*root, "version");
|
||||||
|
const auto *ver = ver_v ? std::get_if<std::int64_t>(&ver_v->value) : nullptr;
|
||||||
|
if (!ver || (*ver != 0 && *ver != 1)) {
|
||||||
|
return std::unexpected{make_error("unsupported P1689 JSON version (expected 0 or 1)")};
|
||||||
|
}
|
||||||
|
|
||||||
|
ModuleScanUnit unit;
|
||||||
|
unit.source_file = source_file;
|
||||||
|
|
||||||
|
if (const auto *rules_v = find_key(*root, "rules")) {
|
||||||
|
if (const auto *rules = std::get_if<JsonVal::Array>(&rules_v->value);
|
||||||
|
rules && !rules->empty()) {
|
||||||
|
if (const auto *r0 = std::get_if<JsonVal::Object>(&rules->front().value)) {
|
||||||
|
if (const auto *prov_v = find_key(*r0, "provides")) {
|
||||||
|
if (const auto *parr = std::get_if<JsonVal::Array>(&prov_v->value)) {
|
||||||
|
for (const auto &pv : *parr) {
|
||||||
|
if (const auto *po = std::get_if<JsonVal::Object>(&pv.value)) {
|
||||||
|
const auto name = get_str(*po, "logical-name");
|
||||||
|
if (!name.empty()) {
|
||||||
|
unit.provides.push_back(name);
|
||||||
|
}
|
||||||
|
if (const auto *is_iface = find_key(*po, "is-interface")) {
|
||||||
|
if (const auto *b = std::get_if<bool>(&is_iface->value);
|
||||||
|
b && *b) {
|
||||||
|
unit.is_interface = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (const auto *req_v = find_key(*r0, "requires")) {
|
||||||
|
if (const auto *rarr = std::get_if<JsonVal::Array>(&req_v->value)) {
|
||||||
|
for (const auto &rv : *rarr) {
|
||||||
|
if (const auto *ro = std::get_if<JsonVal::Object>(&rv.value)) {
|
||||||
|
const auto name = get_str(*ro, "logical-name");
|
||||||
|
if (!name.empty()) {
|
||||||
|
unit.required_modules.push_back(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return unit;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ModuleScanUnit, Void::Result::Error>
|
||||||
|
scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain,
|
||||||
|
const std::filesystem::path &source_file,
|
||||||
|
const std::filesystem::path &scratch_dir,
|
||||||
|
const std::vector<std::pair<std::filesystem::path, bool>> &include_dirs,
|
||||||
|
const std::vector<std::string> &defines,
|
||||||
|
const std::vector<std::string> &compile_options, CxxStandard standard) {
|
||||||
|
if (!toolchain.supports_p1689_scan) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("toolchain '{}' does not support P1689 module dependency scanning",
|
||||||
|
toolchain.cxx_compiler.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::create_directories(scratch_dir, ec);
|
||||||
|
const std::string tag = Util::sha256_hex(source_file.string()).substr(0, 12);
|
||||||
|
|
||||||
|
if (toolchain.family == CompilerFamily::Gcc) {
|
||||||
|
const auto ddi_path = scratch_dir / (tag + ".ddi");
|
||||||
|
std::filesystem::remove(ddi_path, ec);
|
||||||
|
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = toolchain.cxx_compiler;
|
||||||
|
req.arguments = {std_flag(standard),
|
||||||
|
"-fmodules",
|
||||||
|
"-E",
|
||||||
|
"-M",
|
||||||
|
"-x",
|
||||||
|
"c++",
|
||||||
|
"-fdeps-format=p1689r5",
|
||||||
|
"-fdeps-file=" + ddi_path.string(),
|
||||||
|
"-fdeps-target=" + (tag + ".o"),
|
||||||
|
"-o",
|
||||||
|
"/dev/null"};
|
||||||
|
for (const auto &[inc, is_sys] : include_dirs) {
|
||||||
|
req.arguments.push_back(is_sys ? "-isystem" : "-I");
|
||||||
|
req.arguments.push_back(inc.string());
|
||||||
|
}
|
||||||
|
for (const auto &def : defines) {
|
||||||
|
req.arguments.push_back("-D" + def);
|
||||||
|
}
|
||||||
|
for (const auto &opt : compile_options) {
|
||||||
|
req.arguments.push_back(opt);
|
||||||
|
}
|
||||||
|
req.arguments.push_back(source_file.string());
|
||||||
|
req.timeout = std::chrono::seconds{30};
|
||||||
|
|
||||||
|
auto proc = Platform::run_supervised(req);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("GCC P1689 module scan failed for '{}':\n{}", source_file.string(),
|
||||||
|
proc ? proc->stderr_data : proc.error().message()))};
|
||||||
|
}
|
||||||
|
auto ddi_text = Void::FileSystem::read_file(ddi_path);
|
||||||
|
if (!ddi_text) {
|
||||||
|
return std::unexpected{make_error("GCC P1689 scan did not produce .ddi file")};
|
||||||
|
}
|
||||||
|
return parse_p1689_json(*ddi_text, source_file);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clang: use clang-scan-deps --format=p1689 -- clang++ ...
|
||||||
|
if (!toolchain.module_scanner) {
|
||||||
|
return std::unexpected{make_error("Clang module scanning requires clang-scan-deps")};
|
||||||
|
}
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *toolchain.module_scanner;
|
||||||
|
req.arguments = {"--format=p1689",
|
||||||
|
"--",
|
||||||
|
toolchain.cxx_compiler.string(),
|
||||||
|
std_flag(standard),
|
||||||
|
"-x",
|
||||||
|
"c++",
|
||||||
|
"-c",
|
||||||
|
source_file.string(),
|
||||||
|
"-o",
|
||||||
|
(scratch_dir / (tag + ".o")).string()};
|
||||||
|
for (const auto &[inc, is_sys] : include_dirs) {
|
||||||
|
req.arguments.push_back(is_sys ? "-isystem" : "-I");
|
||||||
|
req.arguments.push_back(inc.string());
|
||||||
|
}
|
||||||
|
for (const auto &def : defines) {
|
||||||
|
req.arguments.push_back("-D" + def);
|
||||||
|
}
|
||||||
|
for (const auto &opt : compile_options) {
|
||||||
|
req.arguments.push_back(opt);
|
||||||
|
}
|
||||||
|
req.timeout = std::chrono::seconds{30};
|
||||||
|
|
||||||
|
auto proc = Platform::run_supervised(req);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("clang-scan-deps P1689 scan failed for '{}':\n{}", source_file.string(),
|
||||||
|
proc ? proc->stderr_data : proc.error().message()))};
|
||||||
|
}
|
||||||
|
return parse_p1689_json(proc->stdout_data, source_file);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<CollatedModulePlan, Void::Result::Error>
|
||||||
|
collate_modules(const std::vector<ModuleScanUnit> &units, const std::filesystem::path &bmi_root,
|
||||||
|
const std::string &context_isolation_key, std::string_view bmi_extension) {
|
||||||
|
// 1. Index module providers and reject duplicates immediately.
|
||||||
|
std::map<std::string, std::size_t, std::less<>> provider_by_name;
|
||||||
|
for (std::size_t i = 0; i < units.size(); ++i) {
|
||||||
|
for (const auto &mod : units[i].provides) {
|
||||||
|
const auto [it, inserted] = provider_by_name.emplace(mod, i);
|
||||||
|
if (!inserted) {
|
||||||
|
return std::unexpected{make_error(std::format(
|
||||||
|
"duplicate module provider for '{}': defined in both '{}' and '{}'", mod,
|
||||||
|
units[it->second].source_file.string(), units[i].source_file.string()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Validate every required module has a provider and build directed dependency graph
|
||||||
|
// (edge dep -> importer so providers precede importers in topological order).
|
||||||
|
std::vector<std::vector<std::size_t>> adj(units.size());
|
||||||
|
for (std::size_t i = 0; i < units.size(); ++i) {
|
||||||
|
for (const auto &req_mod : units[i].required_modules) {
|
||||||
|
const auto it = provider_by_name.find(req_mod);
|
||||||
|
if (it == provider_by_name.end()) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(std::format("missing module provider for '{}' imported by '{}'",
|
||||||
|
req_mod, units[i].source_file.string()))};
|
||||||
|
}
|
||||||
|
const std::size_t dep = it->second;
|
||||||
|
if (dep == i) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(std::format("module '{}' cannot import itself", req_mod))};
|
||||||
|
}
|
||||||
|
if (!std::ranges::contains(adj[dep], i)) {
|
||||||
|
adj[dep].push_back(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Topological sort via Void::Algorithms::topological_order with cycle witness diagnostics.
|
||||||
|
const Void::Algorithms::AdjacencyView view{adj};
|
||||||
|
auto topo = Void::Algorithms::topological_order(view);
|
||||||
|
if (!topo) {
|
||||||
|
std::string chain;
|
||||||
|
const auto &cycle = topo.error().cycle;
|
||||||
|
for (auto it = cycle.rbegin(); it != cycle.rend(); ++it) {
|
||||||
|
if (!chain.empty()) {
|
||||||
|
chain += " -> ";
|
||||||
|
}
|
||||||
|
const auto idx = *it;
|
||||||
|
chain += units[idx].provides.empty() ? units[idx].source_file.filename().string()
|
||||||
|
: units[idx].provides.front();
|
||||||
|
}
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
chain.empty() ? std::format("module import cycle detected: {}", topo.error().message)
|
||||||
|
: std::format("module import cycle detected: {}", chain))};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Assign isolated per-profile/compiler BMI paths and emit GCC module-mapper files.
|
||||||
|
const std::string ctx_short = Util::sha256_hex(context_isolation_key).substr(0, 12);
|
||||||
|
const auto isolated_bmi_dir = bmi_root / ctx_short;
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::create_directories(isolated_bmi_dir, ec);
|
||||||
|
|
||||||
|
CollatedModulePlan plan;
|
||||||
|
for (const std::size_t idx : topo->order) {
|
||||||
|
const auto &u = units[idx];
|
||||||
|
CollatedModuleNode node;
|
||||||
|
node.source_file = u.source_file;
|
||||||
|
node.provides = u.provides;
|
||||||
|
node.required_modules = u.required_modules;
|
||||||
|
|
||||||
|
if (!u.provides.empty()) {
|
||||||
|
const std::string fname =
|
||||||
|
sanitize_module_filename(u.provides.front()) + std::string{bmi_extension};
|
||||||
|
node.bmi_output_path = isolated_bmi_dir / fname;
|
||||||
|
for (const auto &mod : u.provides) {
|
||||||
|
plan.module_to_bmi[mod] = node.bmi_output_path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build GCC module-mapper file mapping all required + provided modules.
|
||||||
|
std::string mapper;
|
||||||
|
for (const auto &mod : u.provides) {
|
||||||
|
mapper += mod + " " + node.bmi_output_path.string() + "\n";
|
||||||
|
}
|
||||||
|
for (const auto &req_mod : u.required_modules) {
|
||||||
|
const auto &bmi = plan.module_to_bmi.at(req_mod);
|
||||||
|
node.imported_bmis.emplace_back(req_mod, bmi);
|
||||||
|
mapper += req_mod + " " + bmi.string() + "\n";
|
||||||
|
}
|
||||||
|
if (!mapper.empty()) {
|
||||||
|
const std::string mtag = Util::sha256_hex(u.source_file.string()).substr(0, 12);
|
||||||
|
node.module_mapper_path = isolated_bmi_dir / (mtag + ".modmap");
|
||||||
|
auto wrote = Platform::atomic_write_file(node.module_mapper_path, mapper, false);
|
||||||
|
if (!wrote) {
|
||||||
|
return std::unexpected{wrote.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
plan.ordered_units.push_back(std::move(node));
|
||||||
|
}
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<Toolchain::LoweredCommand, Void::Result::Error>
|
||||||
|
lower_header_unit_command(const Toolchain::ToolchainCapabilities &toolchain,
|
||||||
|
const std::filesystem::path &header_path,
|
||||||
|
const std::filesystem::path &bmi_output,
|
||||||
|
const std::vector<std::pair<std::filesystem::path, bool>> &include_dirs,
|
||||||
|
const std::vector<std::string> &defines,
|
||||||
|
const std::vector<std::string> &compile_options, CxxStandard standard) {
|
||||||
|
Toolchain::LoweredCommand cmd;
|
||||||
|
cmd.executable = toolchain.cxx_compiler;
|
||||||
|
cmd.arguments.push_back(std_flag(standard));
|
||||||
|
if (toolchain.family == CompilerFamily::Gcc) {
|
||||||
|
const auto mapper_path = std::filesystem::path{bmi_output.string() + ".modmap"};
|
||||||
|
const std::string mapper_content = header_path.string() + " " + bmi_output.string() + "\n";
|
||||||
|
if (auto w = Platform::atomic_write_file(mapper_path, mapper_content, false); !w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
cmd.arguments.push_back("-fmodules");
|
||||||
|
cmd.arguments.push_back("-fmodule-header=user");
|
||||||
|
cmd.arguments.push_back("-fmodule-mapper=" + mapper_path.string());
|
||||||
|
cmd.arguments.push_back("-x");
|
||||||
|
cmd.arguments.push_back("c++-user-header");
|
||||||
|
cmd.arguments.push_back("-c");
|
||||||
|
} else {
|
||||||
|
cmd.arguments.push_back("-x");
|
||||||
|
cmd.arguments.push_back("c++-user-header");
|
||||||
|
cmd.arguments.push_back("--precompile");
|
||||||
|
}
|
||||||
|
for (const auto &[inc, is_sys] : include_dirs) {
|
||||||
|
cmd.arguments.push_back(is_sys ? "-isystem" : "-I");
|
||||||
|
cmd.arguments.push_back(inc.string());
|
||||||
|
}
|
||||||
|
for (const auto &def : defines) {
|
||||||
|
cmd.arguments.push_back("-D" + def);
|
||||||
|
}
|
||||||
|
for (const auto &opt : compile_options) {
|
||||||
|
cmd.arguments.push_back(opt);
|
||||||
|
}
|
||||||
|
cmd.arguments.push_back(header_path.string());
|
||||||
|
if (toolchain.family == CompilerFamily::Clang) {
|
||||||
|
cmd.arguments.push_back("-o");
|
||||||
|
cmd.arguments.push_back(bmi_output.string());
|
||||||
|
}
|
||||||
|
cmd.environment["SOURCE_DATE_EPOCH"] = "0";
|
||||||
|
cmd.environment["TZ"] = "UTC";
|
||||||
|
cmd.environment["LC_ALL"] = "C";
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<UnityBatchResult, Void::Result::Error>
|
||||||
|
generate_unity_batches(const std::string &target_name,
|
||||||
|
const std::vector<std::filesystem::path> &sources,
|
||||||
|
const std::vector<std::filesystem::path> &excluded_sources,
|
||||||
|
std::size_t batch_size, const std::filesystem::path &unity_dir) {
|
||||||
|
if (batch_size == 0) {
|
||||||
|
return std::unexpected{make_error("unity batch size must be positive")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::set<std::filesystem::path> excluded;
|
||||||
|
for (const auto &ex : excluded_sources) {
|
||||||
|
excluded.insert(ex.lexically_normal());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::filesystem::path> batchable;
|
||||||
|
UnityBatchResult result;
|
||||||
|
for (const auto &src : sources) {
|
||||||
|
const auto norm = src.lexically_normal();
|
||||||
|
const auto ext = norm.extension().string();
|
||||||
|
// Exclude module interface/partition extensions and explicitly excluded files from unity!
|
||||||
|
if (excluded.contains(norm) || ext == ".cppm" || ext == ".ixx" || ext == ".ccm") {
|
||||||
|
result.standalone_files.push_back(norm);
|
||||||
|
} else {
|
||||||
|
batchable.push_back(norm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::create_directories(unity_dir, ec);
|
||||||
|
|
||||||
|
std::size_t batch_idx = 0;
|
||||||
|
for (std::size_t i = 0; i < batchable.size(); i += batch_size) {
|
||||||
|
std::string content = "// Auto-generated deterministic unity batch by VoidBuildSystem\n";
|
||||||
|
const std::size_t end = std::min(batchable.size(), i + batch_size);
|
||||||
|
for (std::size_t j = i; j < end; ++j) {
|
||||||
|
content += "#include " + Util::json_quote(batchable[j].string()) + "\n";
|
||||||
|
}
|
||||||
|
const auto batch_file =
|
||||||
|
unity_dir / std::format("{}_unity_{}.cpp", target_name, batch_idx++);
|
||||||
|
auto wrote = Platform::atomic_write_file(batch_file, content, false);
|
||||||
|
if (!wrote) {
|
||||||
|
return std::unexpected{wrote.error()};
|
||||||
|
}
|
||||||
|
result.generated_unity_files.push_back(batch_file);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Modules
|
||||||
@@ -0,0 +1,581 @@
|
|||||||
|
#include <Void/Build/Package/Archive.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <cstring>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <format>
|
||||||
|
#include <set>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg, int err = 0) {
|
||||||
|
return Void::System::make_system_error(code, std::move(msg), err);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_safe_archive_path(std::string_view raw) {
|
||||||
|
if (raw.empty() || raw.front() == '/' || raw.find('\\') != std::string_view::npos) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (const unsigned char c : raw) {
|
||||||
|
if (c < 0x20 || c == 0x7f) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::size_t pos = 0;
|
||||||
|
while (pos <= raw.size()) {
|
||||||
|
const auto slash = raw.find('/', pos);
|
||||||
|
const auto seg =
|
||||||
|
raw.substr(pos, slash == std::string_view::npos ? std::string_view::npos : slash - pos);
|
||||||
|
if (seg == "..") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (slash == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = slash + 1;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void write_octal(char *dst, std::size_t width, std::uint64_t val) {
|
||||||
|
std::memset(dst, '0', width - 1);
|
||||||
|
dst[width - 1] = '\0';
|
||||||
|
for (std::size_t i = width - 1; i > 0; --i) {
|
||||||
|
dst[i - 1] = static_cast<char>('0' + (val & 7u));
|
||||||
|
val >>= 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::uint64_t> parse_octal(const char *src, std::size_t width) {
|
||||||
|
std::size_t i = 0;
|
||||||
|
while (i < width && (src[i] == ' ' || src[i] == '\0')) {
|
||||||
|
++i;
|
||||||
|
}
|
||||||
|
std::uint64_t val = 0;
|
||||||
|
bool any = false;
|
||||||
|
for (; i < width; ++i) {
|
||||||
|
if (src[i] == '\0' || src[i] == ' ') {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (src[i] < '0' || src[i] > '7') {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
any = true;
|
||||||
|
val = (val << 3) | static_cast<std::uint64_t>(src[i] - '0');
|
||||||
|
}
|
||||||
|
return any ? std::optional<std::uint64_t>{val} : std::optional<std::uint64_t>{0};
|
||||||
|
}
|
||||||
|
|
||||||
|
void finalize_tar_header(std::array<char, 512> &hdr, std::string_view name, std::uint32_t mode,
|
||||||
|
std::uint64_t size, std::int64_t mtime, char typeflag) {
|
||||||
|
hdr.fill('\0');
|
||||||
|
if (name.size() <= 100) {
|
||||||
|
std::memcpy(hdr.data(), name.data(), name.size());
|
||||||
|
} else {
|
||||||
|
// Split into USTAR prefix (155) + name (100) at a slash boundary.
|
||||||
|
const auto split = name.rfind('/', 154);
|
||||||
|
if (split != std::string_view::npos && name.size() - split - 1 <= 100) {
|
||||||
|
std::memcpy(hdr.data() + 345, name.data(), split);
|
||||||
|
std::memcpy(hdr.data(), name.data() + split + 1, name.size() - split - 1);
|
||||||
|
} else {
|
||||||
|
std::memcpy(hdr.data(), name.data(), std::min<std::size_t>(name.size(), 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
write_octal(hdr.data() + 100, 8, mode & 0777u);
|
||||||
|
write_octal(hdr.data() + 108, 8, 0); // canonical uid=0
|
||||||
|
write_octal(hdr.data() + 116, 8, 0); // canonical gid=0
|
||||||
|
write_octal(hdr.data() + 124, 12, size);
|
||||||
|
write_octal(hdr.data() + 136, 12, mtime >= 0 ? static_cast<std::uint64_t>(mtime) : 0u);
|
||||||
|
std::memset(hdr.data() + 148, ' ', 8);
|
||||||
|
hdr[156] = typeflag;
|
||||||
|
std::memcpy(hdr.data() + 257, "ustar", 6);
|
||||||
|
hdr[263] = '0';
|
||||||
|
hdr[264] = '0';
|
||||||
|
|
||||||
|
std::uint64_t chksum = 0;
|
||||||
|
for (const char c : hdr) {
|
||||||
|
chksum += static_cast<unsigned char>(c);
|
||||||
|
}
|
||||||
|
write_octal(hdr.data() + 148, 7, chksum);
|
||||||
|
hdr[155] = ' ';
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string build_pax_path_record(std::string_view path) {
|
||||||
|
// Format: "<len> path=<path>\n"
|
||||||
|
std::string body = " path=" + std::string{path} + "\n";
|
||||||
|
std::size_t total = body.size() + 1;
|
||||||
|
for (int i = 0; i < 6; ++i) {
|
||||||
|
const auto digits = std::to_string(total).size();
|
||||||
|
if (digits + body.size() == total) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
total = digits + body.size();
|
||||||
|
}
|
||||||
|
return std::to_string(total) + body;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool write_all(int fd, const void *data, std::size_t len) {
|
||||||
|
const auto *p = static_cast<const char *>(data);
|
||||||
|
std::size_t off = 0;
|
||||||
|
while (off < len) {
|
||||||
|
const ssize_t n = ::write(fd, p + off, len - off);
|
||||||
|
if (n < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
off += static_cast<std::size_t>(n);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool read_exact(int fd, void *data, std::size_t len, std::size_t &got_out) {
|
||||||
|
auto *p = static_cast<char *>(data);
|
||||||
|
got_out = 0;
|
||||||
|
while (got_out < len) {
|
||||||
|
const ssize_t n = ::read(fd, p + got_out, len - got_out);
|
||||||
|
if (n < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (n == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
got_out += static_cast<std::size_t>(n);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_zero_block(const std::array<char, 512> &blk) {
|
||||||
|
return std::ranges::all_of(blk, [](char c) { return c == '\0'; });
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_excluded_source_pkg_part(std::string_view part) {
|
||||||
|
if (part == ".git" || part == ".vbs" || part == "build" || part == ".serena" ||
|
||||||
|
part == ".cache" || part == "keys" || part == "WG.conf") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (part == ".env" || (part.starts_with(".env.") && part != ".env.example")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (part.ends_with(".pem") || part.ends_with(".key")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<std::string, Void::Result::Error>
|
||||||
|
create_deterministic_tar(const std::filesystem::path &output_tar,
|
||||||
|
std::vector<ArchiveEntrySpec> entries,
|
||||||
|
std::int64_t reproducibility_epoch) {
|
||||||
|
std::ranges::sort(entries, [](const ArchiveEntrySpec &a, const ArchiveEntrySpec &b) {
|
||||||
|
return a.archive_path < b.archive_path;
|
||||||
|
});
|
||||||
|
|
||||||
|
std::set<std::string> seen_names;
|
||||||
|
for (const auto &e : entries) {
|
||||||
|
if (!is_safe_archive_path(e.archive_path)) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("create_deterministic_tar: unsafe archive path '{}'", e.archive_path))};
|
||||||
|
}
|
||||||
|
if (!seen_names.insert(e.archive_path).second) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("create_deterministic_tar: duplicate archive path '{}'",
|
||||||
|
e.archive_path))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
if (output_tar.has_parent_path()) {
|
||||||
|
std::filesystem::create_directories(output_tar.parent_path(), ec);
|
||||||
|
}
|
||||||
|
const auto temp_tar =
|
||||||
|
output_tar.parent_path() / (output_tar.filename().string() + ".stage_" +
|
||||||
|
std::to_string(static_cast<long long>(::getpid())));
|
||||||
|
const int fd = ::open(temp_tar.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
|
||||||
|
if (fd < 0) {
|
||||||
|
return std::unexpected{make_error(Void::System::map_errno_to_system_code(errno),
|
||||||
|
"create_deterministic_tar: cannot open temp file",
|
||||||
|
errno)};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd guard{fd};
|
||||||
|
auto fail_cleanup = [&] {
|
||||||
|
(void)guard.close();
|
||||||
|
std::filesystem::remove(temp_tar, ec);
|
||||||
|
};
|
||||||
|
|
||||||
|
Util::Sha256Hasher hasher;
|
||||||
|
auto write_hashed = [&](const void *buf, std::size_t n) -> bool {
|
||||||
|
hasher.update(std::span<const std::uint8_t>{static_cast<const std::uint8_t *>(buf), n});
|
||||||
|
return write_all(fd, buf, n);
|
||||||
|
};
|
||||||
|
|
||||||
|
std::array<char, 512> zero_pad{};
|
||||||
|
std::array<char, 512> hdr{};
|
||||||
|
std::array<char, 65536> copy_buf{};
|
||||||
|
|
||||||
|
for (const auto &entry : entries) {
|
||||||
|
auto meta = Platform::stat_lstat(entry.source_file);
|
||||||
|
if (!meta || !meta->exists || !meta->is_regular) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("create_deterministic_tar: source '{}' is not a regular file",
|
||||||
|
entry.source_file.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use PAX extended header whenever path > 100 chars to guarantee lossless long paths.
|
||||||
|
if (entry.archive_path.size() > 100) {
|
||||||
|
const std::string pax = build_pax_path_record(entry.archive_path);
|
||||||
|
finalize_tar_header(hdr, "PaxHeader/" + entry.archive_path.substr(0, 60), 0644,
|
||||||
|
pax.size(), reproducibility_epoch, 'x');
|
||||||
|
if (!write_hashed(hdr.data(), hdr.size()) || !write_hashed(pax.data(), pax.size())) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error, "tar write failed")};
|
||||||
|
}
|
||||||
|
const std::size_t rem = pax.size() % 512;
|
||||||
|
if (rem != 0 && !write_hashed(zero_pad.data(), 512 - rem)) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error, "tar pad write failed")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
finalize_tar_header(hdr, entry.archive_path, entry.mode, meta->size, reproducibility_epoch,
|
||||||
|
'0');
|
||||||
|
if (!write_hashed(hdr.data(), hdr.size())) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error, "tar header write failed")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const int sfd = ::open(entry.source_file.c_str(), O_RDONLY | O_CLOEXEC);
|
||||||
|
if (sfd < 0) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{make_error(Void::System::map_errno_to_system_code(errno),
|
||||||
|
"cannot open source file for tar", errno)};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd sguard{sfd};
|
||||||
|
std::uint64_t remaining = meta->size;
|
||||||
|
while (remaining > 0) {
|
||||||
|
const std::size_t chunk =
|
||||||
|
static_cast<std::size_t>(std::min<std::uint64_t>(remaining, copy_buf.size()));
|
||||||
|
std::size_t got = 0;
|
||||||
|
if (!read_exact(sfd, copy_buf.data(), chunk, got) || got != chunk) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"short read while archiving file")};
|
||||||
|
}
|
||||||
|
if (!write_hashed(copy_buf.data(), got)) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error, "tar body write failed")};
|
||||||
|
}
|
||||||
|
remaining -= got;
|
||||||
|
}
|
||||||
|
const std::size_t pad = static_cast<std::size_t>((512 - (meta->size % 512)) % 512);
|
||||||
|
if (pad > 0 && !write_hashed(zero_pad.data(), pad)) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error, "tar padding write failed")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two 512-byte zero blocks terminate a valid tar archive.
|
||||||
|
if (!write_hashed(zero_pad.data(), 512) || !write_hashed(zero_pad.data(), 512)) {
|
||||||
|
fail_cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error, "tar trailer write failed")};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto closed = guard.close(); !closed) {
|
||||||
|
std::filesystem::remove(temp_tar, ec);
|
||||||
|
return std::unexpected{closed.error()};
|
||||||
|
}
|
||||||
|
std::filesystem::rename(temp_tar, output_tar, ec);
|
||||||
|
if (ec) {
|
||||||
|
std::filesystem::remove(temp_tar, ec);
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error, "tar atomic publish failed")};
|
||||||
|
}
|
||||||
|
return hasher.finalize_hex();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::string, Void::Result::Error>
|
||||||
|
create_source_package(const std::filesystem::path &project_root,
|
||||||
|
const std::filesystem::path &output_tar, std::int64_t reproducibility_epoch) {
|
||||||
|
std::error_code ec;
|
||||||
|
const auto canon = std::filesystem::weakly_canonical(project_root, ec);
|
||||||
|
if (ec || !std::filesystem::is_directory(canon)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::not_found, "project root does not exist")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<ArchiveEntrySpec> entries;
|
||||||
|
std::filesystem::recursive_directory_iterator it{
|
||||||
|
canon, std::filesystem::directory_options::skip_permission_denied, ec};
|
||||||
|
for (; !ec && it != std::filesystem::recursive_directory_iterator{}; it.increment(ec)) {
|
||||||
|
const auto rel = it->path().lexically_relative(canon);
|
||||||
|
bool skip = false;
|
||||||
|
for (const auto &part : rel) {
|
||||||
|
if (is_excluded_source_pkg_part(part.string())) {
|
||||||
|
skip = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (skip) {
|
||||||
|
if (it->is_directory(ec)) {
|
||||||
|
it.disable_recursion_pending();
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (it->is_regular_file(ec)) {
|
||||||
|
auto meta = Platform::stat_lstat(it->path());
|
||||||
|
const std::uint32_t mode = (meta && (meta->mode & 0111u)) ? 0755u : 0644u;
|
||||||
|
entries.push_back({rel.lexically_normal().generic_string(), it->path(), mode});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return create_deterministic_tar(output_tar, std::move(entries), reproducibility_epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ArchiveExtractionStats, Void::Result::Error>
|
||||||
|
extract_safe_tar(const std::filesystem::path &tar_path,
|
||||||
|
const std::filesystem::path &destination_dir, const ArchiveLimits &limits) {
|
||||||
|
const int fd = ::open(tar_path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||||
|
if (fd < 0) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::map_errno_to_system_code(errno),
|
||||||
|
std::format("extract_safe_tar: cannot open '{}'", tar_path.string()), errno)};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd guard{fd};
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
const auto parent = destination_dir.parent_path().empty() ? std::filesystem::path{"."}
|
||||||
|
: destination_dir.parent_path();
|
||||||
|
std::filesystem::create_directories(parent, ec);
|
||||||
|
const auto stage_dir = parent / (destination_dir.filename().string() + ".extract_" +
|
||||||
|
std::to_string(static_cast<long long>(::getpid())));
|
||||||
|
std::filesystem::remove_all(stage_dir, ec);
|
||||||
|
std::filesystem::create_directories(stage_dir, ec);
|
||||||
|
|
||||||
|
auto abort_extract = [&] { std::filesystem::remove_all(stage_dir, ec); };
|
||||||
|
|
||||||
|
ArchiveExtractionStats stats;
|
||||||
|
std::set<std::string> seen_paths;
|
||||||
|
std::optional<std::string> next_pax_path;
|
||||||
|
std::array<char, 512> hdr{};
|
||||||
|
std::array<char, 65536> buf{};
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
std::size_t got = 0;
|
||||||
|
if (!read_exact(fd, hdr.data(), 512, got)) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error, "tar read error")};
|
||||||
|
}
|
||||||
|
if (got == 0 || (got == 512 && is_zero_block(hdr))) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (got != 512) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"truncated tar header")};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify header checksum.
|
||||||
|
const auto expected_sum = parse_octal(hdr.data() + 148, 8);
|
||||||
|
if (!expected_sum) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"malformed tar checksum")};
|
||||||
|
}
|
||||||
|
std::uint64_t actual_sum = 0;
|
||||||
|
for (std::size_t i = 0; i < 512; ++i) {
|
||||||
|
actual_sum += (i >= 148 && i < 156) ? static_cast<unsigned char>(' ')
|
||||||
|
: static_cast<unsigned char>(hdr[i]);
|
||||||
|
}
|
||||||
|
if (actual_sum != *expected_sum) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"tar header checksum mismatch")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto size_opt = parse_octal(hdr.data() + 124, 12);
|
||||||
|
const auto mode_opt = parse_octal(hdr.data() + 100, 8);
|
||||||
|
if (!size_opt || !mode_opt) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"malformed tar size or mode")};
|
||||||
|
}
|
||||||
|
const std::uint64_t entry_size = *size_opt;
|
||||||
|
const std::uint32_t entry_mode = static_cast<std::uint32_t>(*mode_opt & 0777u);
|
||||||
|
const char typeflag = hdr[156];
|
||||||
|
|
||||||
|
// Handle PAX extended header ('x') for long paths.
|
||||||
|
if (typeflag == 'x') {
|
||||||
|
if (entry_size > 65536) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
|
||||||
|
"PAX header exceeds limit")};
|
||||||
|
}
|
||||||
|
std::string pax_data(static_cast<std::size_t>(entry_size), '\0');
|
||||||
|
if (!read_exact(fd, pax_data.data(), pax_data.size(), got) || got != pax_data.size()) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"truncated PAX body")};
|
||||||
|
}
|
||||||
|
const std::size_t pad = static_cast<std::size_t>((512 - (entry_size % 512)) % 512);
|
||||||
|
if (pad > 0 && (!read_exact(fd, buf.data(), pad, got) || got != pad)) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"truncated PAX padding")};
|
||||||
|
}
|
||||||
|
const auto path_pos = pax_data.find(" path=");
|
||||||
|
if (path_pos != std::string::npos) {
|
||||||
|
const auto val_start = path_pos + 6;
|
||||||
|
const auto nl = pax_data.find('\n', val_start);
|
||||||
|
next_pax_path = pax_data.substr(
|
||||||
|
val_start, nl == std::string::npos ? std::string::npos : nl - val_start);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reject symlinks ('2'), hardlinks ('1'), devices ('3'/'4'), FIFOs ('6'), etc.!
|
||||||
|
if (typeflag != '0' && typeflag != '\0' && typeflag != '5') {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::permission_denied,
|
||||||
|
std::format("archive contains disallowed non-regular entry type '{}'", typeflag))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string entry_name;
|
||||||
|
if (next_pax_path) {
|
||||||
|
entry_name = std::move(*next_pax_path);
|
||||||
|
next_pax_path.reset();
|
||||||
|
} else {
|
||||||
|
const std::string name_part(hdr.data(), ::strnlen(hdr.data(), 100));
|
||||||
|
const std::string prefix_part(hdr.data() + 345, ::strnlen(hdr.data() + 345, 155));
|
||||||
|
entry_name = prefix_part.empty() ? name_part : (prefix_part + "/" + name_part);
|
||||||
|
}
|
||||||
|
while (entry_name.starts_with("./")) {
|
||||||
|
entry_name.erase(0, 2);
|
||||||
|
}
|
||||||
|
while (!entry_name.empty() && entry_name.back() == '/') {
|
||||||
|
entry_name.pop_back();
|
||||||
|
}
|
||||||
|
if (entry_name.empty() && typeflag == '5') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!is_safe_archive_path(entry_name)) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::permission_denied,
|
||||||
|
std::format("archive contains unsafe or traversal path '{}'", entry_name))};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (++stats.entries > limits.max_entries) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
|
||||||
|
"archive entry count exceeds limit")};
|
||||||
|
}
|
||||||
|
if (entry_size > limits.max_file_bytes ||
|
||||||
|
stats.total_bytes + entry_size > limits.max_total_bytes) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::limit_exceeded,
|
||||||
|
"archive extracted size exceeds limit")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto rel_norm = std::filesystem::path{entry_name}.lexically_normal().generic_string();
|
||||||
|
if (!seen_paths.insert(rel_norm).second) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("archive contains duplicate colliding path '{}'", rel_norm))};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto dst_path = stage_dir / rel_norm;
|
||||||
|
if (!Platform::path_is_within(stage_dir, dst_path)) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::permission_denied,
|
||||||
|
std::format("archive entry '{}' escapes destination", rel_norm))};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeflag == '5') {
|
||||||
|
std::filesystem::create_directories(dst_path, ec);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dst_path.has_parent_path()) {
|
||||||
|
std::filesystem::create_directories(dst_path.parent_path(), ec);
|
||||||
|
}
|
||||||
|
const int out_fd = ::open(dst_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,
|
||||||
|
static_cast<mode_t>(entry_mode ? entry_mode : 0644u));
|
||||||
|
if (out_fd < 0) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::map_errno_to_system_code(errno),
|
||||||
|
std::format("extract_safe_tar: failed creating '{}'", dst_path.string()), errno)};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd out_guard{out_fd};
|
||||||
|
|
||||||
|
std::uint64_t remaining = entry_size;
|
||||||
|
while (remaining > 0) {
|
||||||
|
const std::size_t chunk =
|
||||||
|
static_cast<std::size_t>(std::min<std::uint64_t>(remaining, buf.size()));
|
||||||
|
if (!read_exact(fd, buf.data(), chunk, got) || got != chunk) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"truncated tar file body")};
|
||||||
|
}
|
||||||
|
if (!write_all(out_fd, buf.data(), got)) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"failed writing extracted file")};
|
||||||
|
}
|
||||||
|
remaining -= got;
|
||||||
|
}
|
||||||
|
stats.total_bytes += entry_size;
|
||||||
|
stats.extracted_files.push_back(std::filesystem::path{rel_norm});
|
||||||
|
|
||||||
|
const std::size_t pad = static_cast<std::size_t>((512 - (entry_size % 512)) % 512);
|
||||||
|
if (pad > 0 && (!read_exact(fd, buf.data(), pad, got) || got != pad)) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"truncated tar file padding")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atomic publication into destination_dir.
|
||||||
|
if (std::filesystem::exists(destination_dir, ec)) {
|
||||||
|
std::filesystem::remove_all(destination_dir, ec);
|
||||||
|
}
|
||||||
|
std::filesystem::rename(stage_dir, destination_dir, ec);
|
||||||
|
if (ec) {
|
||||||
|
abort_extract();
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::map_errno_to_system_code(ec.value()),
|
||||||
|
std::format("extract_safe_tar: atomic rename to '{}' failed", destination_dir.string()),
|
||||||
|
ec.value())};
|
||||||
|
}
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
#include <Void/Build/Package/Fetch.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||||
|
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Core/Scope.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
#include <Void/Text/Str.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <format>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||||
|
return Void::System::make_system_error(code, redact_secrets(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string sanitize_key(std::string_view text) {
|
||||||
|
std::string out;
|
||||||
|
for (const char c : text) {
|
||||||
|
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||||
|
c == '_' || c == '-') {
|
||||||
|
out.push_back(c);
|
||||||
|
} else {
|
||||||
|
out.push_back('_');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string trim(std::string_view s) { return std::string{Void::Str::trim_right_ascii(s)}; }
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string redact_secrets(std::string_view text) {
|
||||||
|
std::string out{text};
|
||||||
|
// Redact scheme://user:pass@host -> scheme://<redacted>@host
|
||||||
|
std::size_t pos = 0;
|
||||||
|
while ((pos = out.find("://", pos)) != std::string::npos) {
|
||||||
|
const auto after = pos + 3;
|
||||||
|
const auto slash = out.find('/', after);
|
||||||
|
const auto space = out.find_first_of(" \t\r\n\"'", after);
|
||||||
|
const auto bound = std::min(slash, space);
|
||||||
|
const auto at = out.find('@', after);
|
||||||
|
if (at != std::string::npos && at < bound) {
|
||||||
|
out.replace(after, at - after, "<redacted>");
|
||||||
|
pos = after + 10;
|
||||||
|
} else {
|
||||||
|
pos = after;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Redact Bearer tokens.
|
||||||
|
pos = 0;
|
||||||
|
while ((pos = out.find("Bearer ", pos)) != std::string::npos) {
|
||||||
|
const auto start = pos + 7;
|
||||||
|
const auto end = out.find_first_of(" \t\r\n\"',;}", start);
|
||||||
|
const auto len = (end == std::string::npos) ? (out.size() - start) : (end - start);
|
||||||
|
out.replace(start, len, "<redacted>");
|
||||||
|
pos = start + 10;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string BinaryCompatibilityKey::compute_key_hash() const {
|
||||||
|
Util::Sha256Hasher h;
|
||||||
|
h.update_length_prefixed("vbs-bin-abi-v1");
|
||||||
|
h.update_length_prefixed(os);
|
||||||
|
h.update_length_prefixed(architecture);
|
||||||
|
h.update_length_prefixed(compiler_family);
|
||||||
|
h.update_length_prefixed(compiler_abi);
|
||||||
|
h.update_length_prefixed(stdlib_abi);
|
||||||
|
h.update_length_prefixed(linkage);
|
||||||
|
h.update_length_prefixed(cpu_features);
|
||||||
|
h.update_length_prefixed(sanitizers_key);
|
||||||
|
h.update_length_prefixed(lto_mode);
|
||||||
|
h.update_length_prefixed(dependency_closure_hash);
|
||||||
|
return h.finalize_hex();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BinaryCompatibilityKey::matches(const BinaryVariantMeta &candidate) const noexcept {
|
||||||
|
return candidate.os == os && candidate.architecture == architecture &&
|
||||||
|
candidate.compiler_family == compiler_family && candidate.compiler_abi == compiler_abi &&
|
||||||
|
candidate.stdlib_abi == stdlib_abi && candidate.linkage == linkage &&
|
||||||
|
candidate.cpu_features == cpu_features && candidate.sanitizers_key == sanitizers_key &&
|
||||||
|
candidate.lto_mode == lto_mode &&
|
||||||
|
candidate.dependency_closure_hash == dependency_closure_hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
BinaryCompatibilityKey
|
||||||
|
make_binary_compatibility_key(const ProfileContext &profile,
|
||||||
|
const Toolchain::ToolchainCapabilities &toolchain,
|
||||||
|
std::string_view linkage, std::string_view dependency_closure_hash) {
|
||||||
|
BinaryCompatibilityKey key;
|
||||||
|
key.os = profile.os;
|
||||||
|
key.architecture = profile.architecture;
|
||||||
|
key.compiler_family = std::string{compiler_name(profile.compiler)};
|
||||||
|
key.compiler_abi = toolchain.version_banner + "|" + toolchain.target_triple;
|
||||||
|
key.stdlib_abi = (profile.compiler == CompilerFamily::Gcc) ? "libstdc++" : "libstdc++/libc++";
|
||||||
|
for (const auto &opt : profile.compile_options) {
|
||||||
|
if (opt == "-stdlib=libc++") {
|
||||||
|
key.stdlib_abi = "libc++";
|
||||||
|
} else if (opt == "-stdlib=libstdc++") {
|
||||||
|
key.stdlib_abi = "libstdc++";
|
||||||
|
} else if (opt.starts_with("-march=") || opt.starts_with("-mcpu=")) {
|
||||||
|
if (!key.cpu_features.empty()) {
|
||||||
|
key.cpu_features += ",";
|
||||||
|
}
|
||||||
|
key.cpu_features += opt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
key.linkage = std::string{linkage};
|
||||||
|
key.lto_mode = std::string{lto_mode_name(profile.lto)};
|
||||||
|
std::vector<std::string> sans;
|
||||||
|
for (const auto s : profile.sanitizers) {
|
||||||
|
sans.emplace_back(sanitizer_name(s));
|
||||||
|
}
|
||||||
|
std::ranges::sort(sans);
|
||||||
|
for (std::size_t i = 0; i < sans.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
key.sanitizers_key += "+";
|
||||||
|
}
|
||||||
|
key.sanitizers_key += sans[i];
|
||||||
|
}
|
||||||
|
key.dependency_closure_hash = std::string{dependency_closure_hash};
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<BinaryVariantMeta>
|
||||||
|
select_compatible_binary(const BinaryCompatibilityKey &key,
|
||||||
|
const std::vector<BinaryVariantMeta> &available) {
|
||||||
|
for (const auto &v : available) {
|
||||||
|
if (key.matches(v)) {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<MaterializedSource, Void::Result::Error>
|
||||||
|
materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &options) {
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::create_directories(options.cache_dir, ec);
|
||||||
|
|
||||||
|
// 1. Local path source: compute content hash without mutating the external checkout.
|
||||||
|
if (dep.source_kind == DependencySourceKind::Path) {
|
||||||
|
const std::filesystem::path raw{dep.location};
|
||||||
|
const auto abs = raw.is_absolute() ? raw : (options.project_root / raw);
|
||||||
|
const auto canon = std::filesystem::weakly_canonical(abs, ec);
|
||||||
|
if (ec || !std::filesystem::is_directory(canon)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("local path dependency '{}' at '{}' does not exist",
|
||||||
|
dep.name, dep.location))};
|
||||||
|
}
|
||||||
|
Snapshot::SnapshotOptions sopts;
|
||||||
|
sopts.project_root = canon;
|
||||||
|
sopts.snapshot_store_dir = options.cache_dir / "path-snapshots";
|
||||||
|
sopts.materialize = false;
|
||||||
|
auto snap = Snapshot::capture_snapshot(sopts, {}, {canon});
|
||||||
|
if (!snap) {
|
||||||
|
return std::unexpected{snap.error()};
|
||||||
|
}
|
||||||
|
MaterializedSource out;
|
||||||
|
out.alias = dep.name;
|
||||||
|
out.source_dir = canon;
|
||||||
|
out.content_identity_hash = snap->snapshot_id;
|
||||||
|
out.from_cache = true;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Checksummed archive source (local file:// or verified cached tar).
|
||||||
|
if (dep.source_kind == DependencySourceKind::Archive) {
|
||||||
|
const auto extract_dir = options.cache_dir / "archives" / dep.sha256;
|
||||||
|
const auto marker = extract_dir / ".vbs_verified";
|
||||||
|
const auto lock_path = options.cache_dir / "locks" / (dep.sha256 + ".lock");
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (std::filesystem::is_regular_file(marker, ec)) {
|
||||||
|
MaterializedSource out;
|
||||||
|
out.alias = dep.name;
|
||||||
|
out.source_dir = extract_dir;
|
||||||
|
out.content_identity_hash = dep.sha256;
|
||||||
|
out.from_cache = true;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto downloaded_tar = options.cache_dir / "downloads" / (dep.sha256 + ".tar");
|
||||||
|
std::filesystem::create_directories(downloaded_tar.parent_path(), ec);
|
||||||
|
|
||||||
|
if (!std::filesystem::is_regular_file(downloaded_tar, ec)) {
|
||||||
|
if (dep.location.starts_with("file://")) {
|
||||||
|
const std::filesystem::path src_file{dep.location.substr(7)};
|
||||||
|
auto copied = Platform::copy_isolated(src_file, downloaded_tar);
|
||||||
|
if (!copied) {
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
} else if (std::filesystem::is_regular_file(dep.location, ec)) {
|
||||||
|
auto copied = Platform::copy_isolated(dep.location, downloaded_tar);
|
||||||
|
if (!copied) {
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (options.offline) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("offline mode: archive '{}' (sha256={}) is not cached",
|
||||||
|
dep.location, dep.sha256))};
|
||||||
|
}
|
||||||
|
auto curl = Platform::resolve_executable("curl");
|
||||||
|
if (!curl) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::not_found,
|
||||||
|
"cannot fetch remote archive: neither curl nor Void::Net is available")};
|
||||||
|
}
|
||||||
|
const auto tmp_dl = downloaded_tar.string() + ".part";
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *curl;
|
||||||
|
req.arguments = {"--fail", "--silent", "--show-error", "--location", "--proto",
|
||||||
|
"=https,http", "--output", tmp_dl, dep.location};
|
||||||
|
req.timeout = std::chrono::seconds{120};
|
||||||
|
auto proc = Platform::run_supervised(req);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
std::filesystem::remove(tmp_dl, ec);
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("failed fetching archive '{}': {}", dep.location,
|
||||||
|
proc ? proc->stderr_data : proc.error().message()))};
|
||||||
|
}
|
||||||
|
std::filesystem::rename(tmp_dl, downloaded_tar, ec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify SHA-256 BEFORE extracting!
|
||||||
|
auto actual_sha = Util::sha256_file_hex(downloaded_tar);
|
||||||
|
if (!actual_sha) {
|
||||||
|
return std::unexpected{actual_sha.error()};
|
||||||
|
}
|
||||||
|
if (*actual_sha != dep.sha256) {
|
||||||
|
std::filesystem::remove(downloaded_tar, ec);
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("SHA-256 mismatch for archive '{}': expected {}, got {}",
|
||||||
|
dep.location, dep.sha256, *actual_sha))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto extracted = extract_safe_tar(downloaded_tar, extract_dir, options.archive_limits);
|
||||||
|
if (!extracted) {
|
||||||
|
return std::unexpected{extracted.error()};
|
||||||
|
}
|
||||||
|
(void)Platform::atomic_write_file(marker, dep.sha256 + "\n", true);
|
||||||
|
|
||||||
|
MaterializedSource out;
|
||||||
|
out.alias = dep.name;
|
||||||
|
out.source_dir = extract_dir;
|
||||||
|
out.content_identity_hash = dep.sha256;
|
||||||
|
out.from_cache = false;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Exact pinned Git revision source.
|
||||||
|
if (dep.source_kind == DependencySourceKind::Git) {
|
||||||
|
const auto git_dir =
|
||||||
|
options.cache_dir / "git" / (sanitize_key(dep.name) + "_" + dep.revision);
|
||||||
|
const auto marker = git_dir / ".vbs_verified_rev";
|
||||||
|
const auto lock_path = options.cache_dir / "locks" / ("git_" + dep.revision + ".lock");
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (std::filesystem::is_regular_file(marker, ec)) {
|
||||||
|
MaterializedSource out;
|
||||||
|
out.alias = dep.name;
|
||||||
|
out.source_dir = git_dir;
|
||||||
|
out.content_identity_hash = dep.revision;
|
||||||
|
out.from_cache = true;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool is_local_repo = dep.location.starts_with("file://") ||
|
||||||
|
dep.location.starts_with("/") ||
|
||||||
|
std::filesystem::is_directory(dep.location, ec);
|
||||||
|
if (options.offline && !is_local_repo) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("offline mode: git dependency '{}' ({}@{}) is not cached",
|
||||||
|
dep.name, dep.location, dep.revision))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto git_bin = Platform::resolve_executable("git");
|
||||||
|
if (!git_bin) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::not_found, "'git' not found in PATH")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto stage = git_dir.parent_path() / (git_dir.filename().string() + ".stage");
|
||||||
|
std::filesystem::remove_all(stage, ec);
|
||||||
|
std::filesystem::create_directories(stage.parent_path(), ec);
|
||||||
|
auto stage_cleanup = Void::Scope::on_exit([&] { std::filesystem::remove_all(stage, ec); });
|
||||||
|
|
||||||
|
auto run_git =
|
||||||
|
[&](std::vector<std::string> args,
|
||||||
|
std::optional<std::filesystem::path> cwd =
|
||||||
|
std::nullopt) -> Void::Result::Result<std::string, Void::Result::Error> {
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *git_bin;
|
||||||
|
req.arguments = std::move(args);
|
||||||
|
req.working_directory = cwd;
|
||||||
|
req.environment.set_vars["GIT_TERMINAL_PROMPT"] = "0";
|
||||||
|
req.timeout = std::chrono::seconds{180};
|
||||||
|
auto p = Platform::run_supervised(req);
|
||||||
|
if (!p || !p->succeeded()) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("git failed for '{}': {}", dep.location,
|
||||||
|
p ? p->stderr_data : p.error().message()))};
|
||||||
|
}
|
||||||
|
return p->stdout_data;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (auto r = run_git({"clone", "--no-checkout", dep.location, stage.string()}); !r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
if (auto r = run_git({"checkout", "--detach", dep.revision}, stage); !r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
auto head = run_git({"rev-parse", "HEAD"}, stage);
|
||||||
|
if (!head || trim(*head) != dep.revision) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("git checkout HEAD mismatch for '{}': expected {}", dep.name,
|
||||||
|
dep.revision))};
|
||||||
|
}
|
||||||
|
(void)Platform::atomic_write_file(stage / ".vbs_verified_rev", dep.revision + "\n", true);
|
||||||
|
if (std::filesystem::exists(git_dir, ec)) {
|
||||||
|
std::filesystem::remove_all(git_dir, ec);
|
||||||
|
}
|
||||||
|
std::filesystem::rename(stage, git_dir, ec);
|
||||||
|
if (ec) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"failed publishing git checkout")};
|
||||||
|
}
|
||||||
|
stage_cleanup.dismiss();
|
||||||
|
|
||||||
|
MaterializedSource out;
|
||||||
|
out.alias = dep.name;
|
||||||
|
out.source_dir = git_dir;
|
||||||
|
out.content_identity_hash = dep.revision;
|
||||||
|
out.from_cache = false;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("dependency '{}' requires package/registry resolution before source fetch",
|
||||||
|
dep.name))};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
#include <Void/Build/Package/Lockfile.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <format>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using JsonVal = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||||
|
return Void::System::make_system_error(code, std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto it = obj.find(k);
|
||||||
|
return it == obj.end() ? nullptr : &it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&v->value);
|
||||||
|
return s ? *s : std::string{};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int64_t get_i64(const JsonVal::Object &obj, const std::string &k, std::int64_t def = 0) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
const auto *i = std::get_if<std::int64_t>(&v->value);
|
||||||
|
return i ? *i : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
const auto *b = std::get_if<bool>(&v->value);
|
||||||
|
return b ? *b : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
std::vector<std::string> out;
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
|
||||||
|
for (const auto &item : *arr) {
|
||||||
|
if (const auto *s = std::get_if<std::string>(&item.value)) {
|
||||||
|
out.push_back(*s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strips embedded URL credentials (user:pass@host) before persisting to vbs.lock!
|
||||||
|
std::string strip_url_credentials(std::string_view url) {
|
||||||
|
const auto scheme = url.find("://");
|
||||||
|
if (scheme == std::string_view::npos) {
|
||||||
|
return std::string{url};
|
||||||
|
}
|
||||||
|
const auto after_scheme = scheme + 3;
|
||||||
|
const auto slash = url.find('/', after_scheme);
|
||||||
|
const auto at = url.find('@', after_scheme);
|
||||||
|
if (at != std::string_view::npos && (slash == std::string_view::npos || at < slash)) {
|
||||||
|
return std::string{url.substr(0, after_scheme)} + std::string{url.substr(at + 1)};
|
||||||
|
}
|
||||||
|
return std::string{url};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string
|
||||||
|
serialize_contexts_body(const std::map<std::string, LockContextRecord, std::less<>> &ctxs) {
|
||||||
|
using Util::json_array;
|
||||||
|
using Util::json_quote;
|
||||||
|
|
||||||
|
std::string out{"{"};
|
||||||
|
bool first = true;
|
||||||
|
for (const auto &[key, ctx] : ctxs) {
|
||||||
|
if (!first) {
|
||||||
|
out += ',';
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
out += json_quote(key) + ":{\"context_key\":" + json_quote(ctx.context_key) +
|
||||||
|
",\"profile_name\":" + json_quote(ctx.profile_name) +
|
||||||
|
",\"compiler\":" + json_quote(ctx.compiler) + ",\"os\":" + json_quote(ctx.os) +
|
||||||
|
",\"architecture\":" + json_quote(ctx.architecture) +
|
||||||
|
",\"machine_role\":" + json_quote(ctx.machine_role) +
|
||||||
|
",\"declaration_fingerprint\":" + json_quote(ctx.declaration_fingerprint) +
|
||||||
|
",\"entries\":";
|
||||||
|
out += json_array(ctx.entries, [](const LockedSourceEntry &e) {
|
||||||
|
return "{\"alias\":" + json_quote(e.alias) +
|
||||||
|
",\"source_kind\":" + json_quote(e.source_kind) + ",\"registry_authority\":" +
|
||||||
|
json_quote(strip_url_credentials(e.registry_authority)) +
|
||||||
|
",\"package_name\":" + json_quote(e.package_name) +
|
||||||
|
",\"version\":" + json_quote(e.version) +
|
||||||
|
",\"location\":" + json_quote(strip_url_credentials(e.location)) +
|
||||||
|
",\"revision\":" + json_quote(e.revision) +
|
||||||
|
",\"sha256\":" + json_quote(e.sha256) + ",\"builder\":" + json_quote(e.builder) +
|
||||||
|
",\"features\":" + json_array(e.features, json_quote) +
|
||||||
|
",\"build_dependency\":" + std::string{e.build_dependency ? "true" : "false"} +
|
||||||
|
'}';
|
||||||
|
});
|
||||||
|
out += '}';
|
||||||
|
}
|
||||||
|
out += '}';
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string make_lock_context_key(const ProfileContext &profile, std::string_view machine_role) {
|
||||||
|
return std::format("{}:{}:{}:{}:{}", profile.name, compiler_name(profile.compiler), profile.os,
|
||||||
|
profile.architecture, machine_role);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string compute_declaration_fingerprint(const ProfileContext &profile,
|
||||||
|
std::string_view machine_role,
|
||||||
|
const std::vector<NormalizedDependency> &declarations) {
|
||||||
|
Util::Sha256Hasher h;
|
||||||
|
h.update_length_prefixed("vbs-lock-decl-v1");
|
||||||
|
h.update_length_prefixed(profile.name);
|
||||||
|
h.update_length_prefixed(compiler_name(profile.compiler));
|
||||||
|
h.update_length_prefixed(profile.os);
|
||||||
|
h.update_length_prefixed(profile.architecture);
|
||||||
|
h.update_length_prefixed(machine_role);
|
||||||
|
|
||||||
|
std::vector<const DependencyRecord *> sorted;
|
||||||
|
for (const auto &nd : declarations) {
|
||||||
|
const bool want_build = (machine_role == "build");
|
||||||
|
if (nd.record.build_dependency == want_build) {
|
||||||
|
sorted.push_back(&nd.record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::ranges::sort(sorted, [](const DependencyRecord *a, const DependencyRecord *b) {
|
||||||
|
return a->name < b->name;
|
||||||
|
});
|
||||||
|
|
||||||
|
h.update_u64(sorted.size());
|
||||||
|
for (const auto *d : sorted) {
|
||||||
|
h.update_length_prefixed(d->name);
|
||||||
|
h.update_u64(static_cast<std::uint64_t>(d->source_kind));
|
||||||
|
h.update_length_prefixed(strip_url_credentials(d->location));
|
||||||
|
h.update_length_prefixed(d->revision);
|
||||||
|
h.update_length_prefixed(d->package);
|
||||||
|
h.update_length_prefixed(d->version);
|
||||||
|
h.update_length_prefixed(d->builder);
|
||||||
|
h.update_length_prefixed(strip_url_credentials(d->registry_authority));
|
||||||
|
h.update_length_prefixed(d->sha256);
|
||||||
|
h.update_u64(d->features.size());
|
||||||
|
for (const auto &f : d->features) {
|
||||||
|
h.update_length_prefixed(f);
|
||||||
|
}
|
||||||
|
h.update_u64(d->options.size());
|
||||||
|
for (const auto &[k, opt] : d->options) {
|
||||||
|
h.update_length_prefixed(k);
|
||||||
|
std::visit(
|
||||||
|
[&](const auto &v) {
|
||||||
|
using T = std::remove_cvref_t<decltype(v)>;
|
||||||
|
if constexpr (std::same_as<T, std::string>) {
|
||||||
|
h.update_length_prefixed("s:" + v);
|
||||||
|
} else if constexpr (std::same_as<T, bool>) {
|
||||||
|
h.update_length_prefixed(v ? "b:1" : "b:0");
|
||||||
|
} else {
|
||||||
|
h.update_length_prefixed("i:" + std::to_string(v));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
opt.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return h.finalize_hex();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_lockfile(const LockfileDocument &doc) {
|
||||||
|
const std::string body = serialize_contexts_body(doc.contexts);
|
||||||
|
const std::string rev = Util::sha256_hex(body);
|
||||||
|
return "{\"schema_version\":" + std::to_string(doc.schema_version) +
|
||||||
|
",\"revision_hash\":" + Util::json_quote(rev) + ",\"contexts\":" + body + "}\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<LockfileDocument, Void::Result::Error>
|
||||||
|
parse_lockfile(std::string_view json_text) {
|
||||||
|
if (!Util::is_valid_utf8(json_text)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument, "lockfile invalid UTF-8")};
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(json_text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"malformed JSON in vbs.lock")};
|
||||||
|
}
|
||||||
|
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!root) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"vbs.lock root must be a JSON object")};
|
||||||
|
}
|
||||||
|
LockfileDocument doc;
|
||||||
|
doc.schema_version = static_cast<int>(get_i64(*root, "schema_version", 0));
|
||||||
|
if (doc.schema_version != kLockfileSchemaVersion) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("unsupported vbs.lock schema_version {}", doc.schema_version))};
|
||||||
|
}
|
||||||
|
doc.revision_hash = get_str(*root, "revision_hash");
|
||||||
|
|
||||||
|
if (const auto *ctxs_v = find_key(*root, "contexts")) {
|
||||||
|
const auto *cobj = std::get_if<JsonVal::Object>(&ctxs_v->value);
|
||||||
|
if (!cobj) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"vbs.lock contexts must be an object")};
|
||||||
|
}
|
||||||
|
for (const auto &[key, cv] : *cobj) {
|
||||||
|
const auto *co = std::get_if<JsonVal::Object>(&cv.value);
|
||||||
|
if (!co) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
LockContextRecord rec;
|
||||||
|
rec.context_key = get_str(*co, "context_key");
|
||||||
|
rec.profile_name = get_str(*co, "profile_name");
|
||||||
|
rec.compiler = get_str(*co, "compiler");
|
||||||
|
rec.os = get_str(*co, "os");
|
||||||
|
rec.architecture = get_str(*co, "architecture");
|
||||||
|
rec.machine_role = get_str(*co, "machine_role");
|
||||||
|
rec.declaration_fingerprint = get_str(*co, "declaration_fingerprint");
|
||||||
|
if (const auto *ev = find_key(*co, "entries")) {
|
||||||
|
if (const auto *earr = std::get_if<JsonVal::Array>(&ev->value)) {
|
||||||
|
for (const auto &item : *earr) {
|
||||||
|
if (const auto *eo = std::get_if<JsonVal::Object>(&item.value)) {
|
||||||
|
LockedSourceEntry e;
|
||||||
|
e.alias = get_str(*eo, "alias");
|
||||||
|
e.source_kind = get_str(*eo, "source_kind");
|
||||||
|
e.registry_authority = get_str(*eo, "registry_authority");
|
||||||
|
e.package_name = get_str(*eo, "package_name");
|
||||||
|
e.version = get_str(*eo, "version");
|
||||||
|
e.location = get_str(*eo, "location");
|
||||||
|
e.revision = get_str(*eo, "revision");
|
||||||
|
e.sha256 = get_str(*eo, "sha256");
|
||||||
|
e.builder = get_str(*eo, "builder");
|
||||||
|
e.features = get_str_array(*eo, "features");
|
||||||
|
e.build_dependency = get_bool(*eo, "build_dependency", false);
|
||||||
|
rec.entries.push_back(std::move(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
doc.contexts[key] = std::move(rec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify revision hash integrity against canonical body!
|
||||||
|
const std::string expected_rev = Util::sha256_hex(serialize_contexts_body(doc.contexts));
|
||||||
|
if (!doc.revision_hash.empty() && doc.revision_hash != expected_rev) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"vbs.lock revision_hash does not match contents (corrupted or hand-edited lockfile)")};
|
||||||
|
}
|
||||||
|
doc.revision_hash = expected_rev;
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<PinnedLock>, Void::Result::Error>
|
||||||
|
load_pinned_lock(const std::filesystem::path &lock_path) {
|
||||||
|
auto meta = Platform::stat_lstat(lock_path);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
auto text = Void::FileSystem::read_file_bounded(lock_path, {64ULL * 1024ULL * 1024ULL});
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{text.error()};
|
||||||
|
}
|
||||||
|
auto parsed = parse_lockfile(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{parsed.error()};
|
||||||
|
}
|
||||||
|
PinnedLock pinned;
|
||||||
|
pinned.revision_hash = parsed->revision_hash;
|
||||||
|
pinned.raw_json = std::move(*text);
|
||||||
|
pinned.document = std::move(*parsed);
|
||||||
|
return pinned;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<const LockContextRecord *, Void::Result::Error>
|
||||||
|
validate_locked_context(const LockfileDocument &doc, std::string_view context_key,
|
||||||
|
std::string_view expected_declaration_fingerprint) {
|
||||||
|
const auto it = doc.contexts.find(context_key);
|
||||||
|
if (it == doc.contexts.end()) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("vbs.lock has no resolution for context '{}' (run 'vbs deps resolve')",
|
||||||
|
context_key))};
|
||||||
|
}
|
||||||
|
if (it->second.declaration_fingerprint != expected_declaration_fingerprint) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format(
|
||||||
|
"vbs.lock context '{}' is incompatible with current dependency declarations "
|
||||||
|
"(run 'vbs deps resolve' or 'vbs deps update')",
|
||||||
|
context_key))};
|
||||||
|
}
|
||||||
|
return &it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<PinnedLock, Void::Result::Error>
|
||||||
|
publish_lock_context_cas(const std::filesystem::path &lock_path,
|
||||||
|
std::string_view expected_base_revision,
|
||||||
|
const LockContextRecord &updated_context, bool locked_mode) {
|
||||||
|
if (locked_mode) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::permission_denied,
|
||||||
|
"--locked forbids creating or modifying vbs.lock")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto mutex_path = lock_path.parent_path() / ".vbs" / "lockfile.mutex";
|
||||||
|
auto mutex = Platform::FileLock::acquire(mutex_path, Platform::LockMode::Exclusive);
|
||||||
|
if (!mutex) {
|
||||||
|
return std::unexpected{mutex.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
LockfileDocument current;
|
||||||
|
std::string current_rev;
|
||||||
|
auto meta = Platform::stat_lstat(lock_path);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (meta->exists) {
|
||||||
|
auto text = Void::FileSystem::read_file_bounded(lock_path, {64ULL * 1024ULL * 1024ULL});
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{text.error()};
|
||||||
|
}
|
||||||
|
auto parsed = parse_lockfile(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{parsed.error()};
|
||||||
|
}
|
||||||
|
current = std::move(*parsed);
|
||||||
|
current_rev = current.revision_hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare-and-swap revision check (D-025): if another profile updated the lock concurrently,
|
||||||
|
// allow merging ONLY if the other update did NOT touch our context_key; if it modified our
|
||||||
|
// context_key or base mismatch occurred, report busy conflict for caller re-resolution!
|
||||||
|
if (current_rev != expected_base_revision) {
|
||||||
|
const auto existing_ctx = current.contexts.find(updated_context.context_key);
|
||||||
|
if (existing_ctx != current.contexts.end() &&
|
||||||
|
existing_ctx->second.declaration_fingerprint !=
|
||||||
|
updated_context.declaration_fingerprint) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::busy,
|
||||||
|
std::format("concurrent vbs.lock revision conflict (expected '{}', found '{}'); "
|
||||||
|
"re-resolve and retry",
|
||||||
|
expected_base_revision, current_rev))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
current.contexts[updated_context.context_key] = updated_context;
|
||||||
|
const std::string serialized = serialize_lockfile(current);
|
||||||
|
auto reparsed = parse_lockfile(serialized);
|
||||||
|
if (!reparsed) {
|
||||||
|
return std::unexpected{reparsed.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto wrote = Platform::atomic_write_file(lock_path, serialized, true);
|
||||||
|
if (!wrote) {
|
||||||
|
return std::unexpected{wrote.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
PinnedLock pinned;
|
||||||
|
pinned.revision_hash = reparsed->revision_hash;
|
||||||
|
pinned.raw_json = serialized;
|
||||||
|
pinned.document = std::move(*reparsed);
|
||||||
|
return pinned;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
#include <Void/Build/Package/RegistryClient.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Package/Fetch.hpp>
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Core/Scope.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
#include <Void/Text/Semver.hpp>
|
||||||
|
#include <Void/Text/Str.hpp>
|
||||||
|
#include <Void/Text/Url.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <array>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <cstring>
|
||||||
|
#include <format>
|
||||||
|
#include <map>
|
||||||
|
#include <netdb.h>
|
||||||
|
#include <netinet/in.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using JsonVal = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||||
|
return Void::System::make_system_error(code, redact_secrets(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ParsedHttpUrl {
|
||||||
|
std::string scheme;
|
||||||
|
std::string host;
|
||||||
|
std::uint16_t port{80};
|
||||||
|
std::string base_path;
|
||||||
|
};
|
||||||
|
|
||||||
|
Void::Result::Result<ParsedHttpUrl, Void::Result::Error> parse_registry_url(std::string_view url) {
|
||||||
|
url = Void::Str::trim_ascii(url);
|
||||||
|
const auto sep = url.find("://");
|
||||||
|
if (sep == std::string_view::npos) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"registry URL must include http:// or https:// scheme")};
|
||||||
|
}
|
||||||
|
ParsedHttpUrl out;
|
||||||
|
out.scheme = Void::Str::to_lower_ascii(url.substr(0, sep));
|
||||||
|
if (out.scheme != "http" && out.scheme != "https") {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"unsupported registry URL scheme (expected http/https)")};
|
||||||
|
}
|
||||||
|
const auto rest = url.substr(sep + 3);
|
||||||
|
const auto slash = rest.find('/');
|
||||||
|
const auto authority = slash == std::string_view::npos ? rest : rest.substr(0, slash);
|
||||||
|
out.base_path =
|
||||||
|
slash == std::string_view::npos ? std::string{} : std::string{rest.substr(slash)};
|
||||||
|
while (!out.base_path.empty() && out.base_path.back() == '/') {
|
||||||
|
out.base_path.pop_back();
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto colon = authority.rfind(':');
|
||||||
|
if (colon != std::string_view::npos) {
|
||||||
|
out.host = std::string{authority.substr(0, colon)};
|
||||||
|
int p = 0;
|
||||||
|
if (!Void::Str::to_int(authority.substr(colon + 1), p) || p <= 0 || p > 65535) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"invalid port in registry URL")};
|
||||||
|
}
|
||||||
|
out.port = static_cast<std::uint16_t>(p);
|
||||||
|
} else {
|
||||||
|
out.host = std::string{authority};
|
||||||
|
out.port = (out.scheme == "https") ? 443 : 80;
|
||||||
|
}
|
||||||
|
if (out.host.empty()) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"empty host in registry URL")};
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RawHttpReply {
|
||||||
|
std::uint16_t status{0};
|
||||||
|
std::map<std::string, std::string, std::less<>> headers;
|
||||||
|
std::string body;
|
||||||
|
};
|
||||||
|
|
||||||
|
bool send_all(int fd, std::string_view data) {
|
||||||
|
std::size_t off = 0;
|
||||||
|
while (off < data.size()) {
|
||||||
|
const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL);
|
||||||
|
if (n < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
off += static_cast<std::size_t>(n);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<RawHttpReply, Void::Result::Error>
|
||||||
|
send_http_request(const ParsedHttpUrl &parsed, std::string_view method, std::string_view path,
|
||||||
|
const std::map<std::string, std::string, std::less<>> &headers,
|
||||||
|
std::string_view body) {
|
||||||
|
const std::string full_path = parsed.base_path + std::string{path};
|
||||||
|
|
||||||
|
// Plain TCP HTTP/1.1 client for http:// (loopback/local registry without external deps).
|
||||||
|
if (parsed.scheme == "http") {
|
||||||
|
struct addrinfo hints{};
|
||||||
|
hints.ai_family = AF_INET;
|
||||||
|
hints.ai_socktype = SOCK_STREAM;
|
||||||
|
struct addrinfo *res = nullptr;
|
||||||
|
const std::string port_s = std::to_string(parsed.port);
|
||||||
|
if (::getaddrinfo(parsed.host.c_str(), port_s.c_str(), &hints, &res) != 0 || !res) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("registry client: failed resolving host '{}'", parsed.host))};
|
||||||
|
}
|
||||||
|
auto free_ai = Void::Scope::on_exit([&] { ::freeaddrinfo(res); });
|
||||||
|
|
||||||
|
const int fd = ::socket(res->ai_family, res->ai_socktype | SOCK_CLOEXEC, res->ai_protocol);
|
||||||
|
if (fd < 0) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"registry client: socket() failed")};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd guard{fd};
|
||||||
|
|
||||||
|
struct timeval tv{30, 0};
|
||||||
|
(void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||||
|
(void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||||||
|
|
||||||
|
if (::connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("registry client: connect to {}:{} failed", parsed.host, parsed.port))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string req = std::format("{} {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n"
|
||||||
|
"Content-Length: {}\r\n",
|
||||||
|
method, full_path, parsed.host, parsed.port, body.size());
|
||||||
|
for (const auto &[k, v] : headers) {
|
||||||
|
req += k + ": " + v + "\r\n";
|
||||||
|
}
|
||||||
|
req += "\r\n";
|
||||||
|
req += body;
|
||||||
|
if (!send_all(fd, req)) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"registry client: send() failed")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string raw;
|
||||||
|
std::array<char, 16384> buf{};
|
||||||
|
for (;;) {
|
||||||
|
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
|
||||||
|
if (n > 0) {
|
||||||
|
raw.append(buf.data(), static_cast<std::size_t>(n));
|
||||||
|
} else if (n == 0) {
|
||||||
|
break;
|
||||||
|
} else if (errno != EINTR) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"registry client: recv() failed")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto hdr_end = raw.find("\r\n\r\n");
|
||||||
|
if (hdr_end == std::string::npos) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"registry client: malformed HTTP response")};
|
||||||
|
}
|
||||||
|
|
||||||
|
RawHttpReply reply;
|
||||||
|
const std::string_view hdr_block{raw.data(), hdr_end};
|
||||||
|
const auto first_crlf = hdr_block.find("\r\n");
|
||||||
|
const auto status_line = hdr_block.substr(0, first_crlf);
|
||||||
|
const auto sp1 = status_line.find(' ');
|
||||||
|
if (sp1 != std::string_view::npos) {
|
||||||
|
int code = 0;
|
||||||
|
if (Void::Str::to_int(status_line.substr(sp1 + 1, 3), code)) {
|
||||||
|
reply.status = static_cast<std::uint16_t>(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (first_crlf != std::string_view::npos) {
|
||||||
|
std::size_t pos = first_crlf + 2;
|
||||||
|
while (pos < hdr_block.size()) {
|
||||||
|
const auto next = hdr_block.find("\r\n", pos);
|
||||||
|
const auto line = hdr_block.substr(
|
||||||
|
pos, next == std::string_view::npos ? std::string_view::npos : next - pos);
|
||||||
|
const auto colon = line.find(':');
|
||||||
|
if (colon != std::string_view::npos) {
|
||||||
|
reply.headers[Void::Str::to_lower_ascii(
|
||||||
|
Void::Str::trim_ascii(line.substr(0, colon)))] =
|
||||||
|
std::string{Void::Str::trim_ascii(line.substr(colon + 1))};
|
||||||
|
}
|
||||||
|
if (next == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = next + 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reply.body = raw.substr(hdr_end + 4);
|
||||||
|
return reply;
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTTPS fallback via curl (preserves TLS certificate verification; never disables TLS!).
|
||||||
|
auto curl = Platform::resolve_executable("curl");
|
||||||
|
if (!curl) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::not_found,
|
||||||
|
"HTTPS registry operations require curl (OpenSSL/Void::Net not linked)")};
|
||||||
|
}
|
||||||
|
const std::string full_url =
|
||||||
|
std::format("https://{}:{}{}", parsed.host, parsed.port, full_path);
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *curl;
|
||||||
|
req.arguments = {"--silent", "--show-error", "--proto", "=https",
|
||||||
|
"-X", std::string{method}, "-w", "\n%{http_code}"};
|
||||||
|
for (const auto &[k, v] : headers) {
|
||||||
|
req.arguments.push_back("-H");
|
||||||
|
req.arguments.push_back(k + ": " + v);
|
||||||
|
}
|
||||||
|
if (!body.empty()) {
|
||||||
|
req.arguments.push_back("--data-binary");
|
||||||
|
req.arguments.push_back("@-");
|
||||||
|
req.stdin_data = std::string{body};
|
||||||
|
}
|
||||||
|
req.arguments.push_back(full_url);
|
||||||
|
req.timeout = std::chrono::seconds{120};
|
||||||
|
auto proc = Platform::run_supervised(req);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("HTTPS request failed: {}",
|
||||||
|
proc ? proc->stderr_data : proc.error().message()))};
|
||||||
|
}
|
||||||
|
const auto nl = proc->stdout_data.rfind('\n');
|
||||||
|
RawHttpReply reply;
|
||||||
|
if (nl != std::string::npos) {
|
||||||
|
int code = 0;
|
||||||
|
if (Void::Str::to_int(Void::Str::trim_ascii(proc->stdout_data.substr(nl + 1)), code)) {
|
||||||
|
reply.status = static_cast<std::uint16_t>(code);
|
||||||
|
}
|
||||||
|
reply.body = proc->stdout_data.substr(0, nl);
|
||||||
|
}
|
||||||
|
return reply;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto it = obj.find(k);
|
||||||
|
if (it == obj.end()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&it->second.value);
|
||||||
|
return s ? *s : std::string{};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||||
|
const auto it = obj.find(k);
|
||||||
|
if (it == obj.end()) {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
const auto *b = std::get_if<bool>(&it->second.value);
|
||||||
|
return b ? *b : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<ReleaseRecord>, Void::Result::Error>
|
||||||
|
fetch_package_releases(std::string_view registry_url, std::string_view package_name,
|
||||||
|
const RegistryAuth &auth) {
|
||||||
|
auto parsed_url = parse_registry_url(registry_url);
|
||||||
|
if (!parsed_url) {
|
||||||
|
return std::unexpected{parsed_url.error()};
|
||||||
|
}
|
||||||
|
std::map<std::string, std::string, std::less<>> headers;
|
||||||
|
if (!auth.bearer_token.empty()) {
|
||||||
|
headers["Authorization"] = "Bearer " + auth.bearer_token;
|
||||||
|
}
|
||||||
|
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name);
|
||||||
|
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
|
||||||
|
if (!reply) {
|
||||||
|
return std::unexpected{reply.error()};
|
||||||
|
}
|
||||||
|
if (reply->status != 200) {
|
||||||
|
return std::unexpected{make_error(reply->status == 404
|
||||||
|
? Void::System::SystemErrorCode::not_found
|
||||||
|
: Void::System::SystemErrorCode::permission_denied,
|
||||||
|
std::format("registry GET {} failed with HTTP {}: {}",
|
||||||
|
path, reply->status, reply->body))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto json = Void::Json::Strict::parse(reply->body);
|
||||||
|
if (!json) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"invalid JSON returned by registry package endpoint")};
|
||||||
|
}
|
||||||
|
const auto *root = std::get_if<JsonVal::Object>(&json->value);
|
||||||
|
if (!root) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"registry response root must be a JSON object")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<ReleaseRecord> releases;
|
||||||
|
const auto rit = root->find("releases");
|
||||||
|
if (rit != root->end()) {
|
||||||
|
if (const auto *rarr = std::get_if<JsonVal::Array>(&rit->second.value)) {
|
||||||
|
for (const auto &rv : *rarr) {
|
||||||
|
const auto *ro = std::get_if<JsonVal::Object>(&rv.value);
|
||||||
|
if (!ro) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto ver_str = get_str(*ro, "version");
|
||||||
|
auto ver = Void::Semver::parse_strict(ver_str);
|
||||||
|
if (!ver) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ReleaseRecord rec;
|
||||||
|
rec.id = PackageId{std::string{registry_url}, std::string{package_name}};
|
||||||
|
rec.version = *ver;
|
||||||
|
rec.yanked = get_bool(*ro, "yanked", false);
|
||||||
|
rec.source_sha256 = get_str(*ro, "sha256");
|
||||||
|
rec.source_url = std::string{registry_url} + "/api/v1/packages/" +
|
||||||
|
Void::Encoding::Url::encode(package_name) + "/" +
|
||||||
|
Void::Encoding::Url::encode(ver_str) + "/download";
|
||||||
|
releases.push_back(std::move(rec));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return releases;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||||
|
download_release_archive(std::string_view registry_url, std::string_view package_name,
|
||||||
|
std::string_view version, std::string_view expected_sha256,
|
||||||
|
const std::filesystem::path &dest_file, const RegistryAuth &auth) {
|
||||||
|
auto parsed_url = parse_registry_url(registry_url);
|
||||||
|
if (!parsed_url) {
|
||||||
|
return std::unexpected{parsed_url.error()};
|
||||||
|
}
|
||||||
|
std::map<std::string, std::string, std::less<>> headers;
|
||||||
|
if (!auth.bearer_token.empty()) {
|
||||||
|
headers["Authorization"] = "Bearer " + auth.bearer_token;
|
||||||
|
}
|
||||||
|
const std::string path = "/api/v1/packages/" + Void::Encoding::Url::encode(package_name) + "/" +
|
||||||
|
Void::Encoding::Url::encode(version) + "/download";
|
||||||
|
auto reply = send_http_request(*parsed_url, "GET", path, headers, {});
|
||||||
|
if (!reply) {
|
||||||
|
return std::unexpected{reply.error()};
|
||||||
|
}
|
||||||
|
if (reply->status != 200) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("registry download {}@{} failed with HTTP {}",
|
||||||
|
package_name, version, reply->status))};
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string actual_sha = Util::sha256_hex(reply->body);
|
||||||
|
if (!expected_sha256.empty() && actual_sha != expected_sha256) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("registry archive SHA-256 mismatch for {}@{}: expected {}, got {}",
|
||||||
|
package_name, version, expected_sha256, actual_sha))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto wrote = Platform::atomic_write_file(dest_file, reply->body, true);
|
||||||
|
if (!wrote) {
|
||||||
|
return std::unexpected{wrote.error()};
|
||||||
|
}
|
||||||
|
return dest_file;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<PublishReceipt, Void::Result::Error>
|
||||||
|
publish_package_archive(const PublishOptions &options) {
|
||||||
|
if (!Void::Semver::parse_strict(options.version)) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"publish version must be strict SemVer (X.Y.Z)")};
|
||||||
|
}
|
||||||
|
auto parsed_url = parse_registry_url(options.registry_url);
|
||||||
|
if (!parsed_url) {
|
||||||
|
return std::unexpected{parsed_url.error()};
|
||||||
|
}
|
||||||
|
auto bytes = Void::FileSystem::read_file(options.archive_path);
|
||||||
|
if (!bytes) {
|
||||||
|
return std::unexpected{bytes.error()};
|
||||||
|
}
|
||||||
|
const std::string sha = Util::sha256_hex(*bytes);
|
||||||
|
|
||||||
|
std::map<std::string, std::string, std::less<>> headers;
|
||||||
|
headers["X-Content-SHA256"] = sha;
|
||||||
|
if (!options.auth.bearer_token.empty()) {
|
||||||
|
headers["Authorization"] = "Bearer " + options.auth.bearer_token;
|
||||||
|
}
|
||||||
|
if (options.is_private) {
|
||||||
|
headers["X-Package-Private"] = "true";
|
||||||
|
}
|
||||||
|
if (!options.description.empty()) {
|
||||||
|
headers["X-Package-Description"] = options.description;
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string path = "/api/v1/packages/" +
|
||||||
|
Void::Encoding::Url::encode(options.package_name) + "/" +
|
||||||
|
Void::Encoding::Url::encode(options.version);
|
||||||
|
auto reply = send_http_request(*parsed_url, "PUT", path, headers, *bytes);
|
||||||
|
if (!reply) {
|
||||||
|
return std::unexpected{reply.error()};
|
||||||
|
}
|
||||||
|
if (reply->status != 200 && reply->status != 201) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
reply->status == 409 ? Void::System::SystemErrorCode::already_exists
|
||||||
|
: Void::System::SystemErrorCode::permission_denied,
|
||||||
|
std::format("registry publish {}@{} failed with HTTP {}: {}", options.package_name,
|
||||||
|
options.version, reply->status, reply->body))};
|
||||||
|
}
|
||||||
|
return PublishReceipt{sha, reply->status == 200};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
#include <Void/Build/Package/Solver.hpp>
|
||||||
|
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
#include <Void/Text/Str.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <format>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Void::Result::Error solve_err(std::string msg) {
|
||||||
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool all_digits(std::string_view s) { return Void::Str::is_digit_ascii(s); }
|
||||||
|
|
||||||
|
std::string normalize_semver_token(std::string_view tok) {
|
||||||
|
if (tok.empty() || tok == "*") {
|
||||||
|
return std::string{tok};
|
||||||
|
}
|
||||||
|
std::string_view op;
|
||||||
|
if (tok.starts_with(">=") || tok.starts_with("<=")) {
|
||||||
|
op = tok.substr(0, 2);
|
||||||
|
tok.remove_prefix(2);
|
||||||
|
} else if (tok.starts_with('^') || tok.starts_with('~') || tok.starts_with('>') ||
|
||||||
|
tok.starts_with('<') || tok.starts_with('=')) {
|
||||||
|
op = tok.substr(0, 1);
|
||||||
|
tok.remove_prefix(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto meta_pos = tok.find_first_of("-+");
|
||||||
|
const auto core = meta_pos == std::string_view::npos ? tok : tok.substr(0, meta_pos);
|
||||||
|
const auto meta =
|
||||||
|
meta_pos == std::string_view::npos ? std::string_view{} : tok.substr(meta_pos);
|
||||||
|
|
||||||
|
if (core.find_first_of("xX*") != std::string_view::npos) {
|
||||||
|
return std::string{op} + std::string{tok};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto dot1 = core.find('.');
|
||||||
|
if (dot1 == std::string_view::npos) {
|
||||||
|
if (!all_digits(core)) {
|
||||||
|
return std::string{op} + std::string{tok};
|
||||||
|
}
|
||||||
|
if ((op == "~" || op == "^") && meta.empty()) {
|
||||||
|
const unsigned long maj = std::stoul(std::string{core});
|
||||||
|
if (op == "~" || maj == 0) {
|
||||||
|
return std::format(">={}.0.0 <{}.0.0", maj, maj + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::string{op} + std::string{core} + ".0.0" + std::string{meta};
|
||||||
|
}
|
||||||
|
const auto dot2 = core.find('.', dot1 + 1);
|
||||||
|
if (dot2 == std::string_view::npos) {
|
||||||
|
const auto p1 = core.substr(0, dot1);
|
||||||
|
const auto p2 = core.substr(dot1 + 1);
|
||||||
|
if (!all_digits(p1) || !all_digits(p2)) {
|
||||||
|
return std::string{op} + std::string{tok};
|
||||||
|
}
|
||||||
|
return std::string{op} + std::string{p1} + "." + std::string{p2} + ".0" + std::string{meta};
|
||||||
|
}
|
||||||
|
return std::string{op} + std::string{tok};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adapter for shorthand SemVer comparator tokens (^1, ^1.0, ~1.2, <2) since
|
||||||
|
// pinned Void::Semver::parse_range requires full major.minor.patch triplets.
|
||||||
|
std::optional<Void::Semver::VersionRange> parse_semver_range_compat(std::string_view expr) {
|
||||||
|
if (auto direct = Void::Semver::parse_range(expr); direct) {
|
||||||
|
return direct;
|
||||||
|
}
|
||||||
|
std::string normalized;
|
||||||
|
std::size_t pos = 0;
|
||||||
|
bool first_clause = true;
|
||||||
|
while (pos <= expr.size()) {
|
||||||
|
const auto sep = expr.find("||", pos);
|
||||||
|
const auto clause = expr.substr(pos, sep == std::string_view::npos ? sep : sep - pos);
|
||||||
|
if (!first_clause) {
|
||||||
|
normalized += " || ";
|
||||||
|
}
|
||||||
|
first_clause = false;
|
||||||
|
|
||||||
|
bool first_tok = true;
|
||||||
|
std::size_t i = 0;
|
||||||
|
while (i < clause.size()) {
|
||||||
|
while (i < clause.size() && (clause[i] == ' ' || clause[i] == '\t')) {
|
||||||
|
++i;
|
||||||
|
}
|
||||||
|
if (i == clause.size()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
auto end = clause.find_first_of(" \t", i);
|
||||||
|
if (end == std::string_view::npos) {
|
||||||
|
end = clause.size();
|
||||||
|
}
|
||||||
|
if (!first_tok) {
|
||||||
|
normalized.push_back(' ');
|
||||||
|
}
|
||||||
|
first_tok = false;
|
||||||
|
normalized += normalize_semver_token(clause.substr(i, end - i));
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
if (sep == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = sep + 2;
|
||||||
|
}
|
||||||
|
return Void::Semver::parse_range(normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ActiveConstraint {
|
||||||
|
Void::Semver::VersionRange range;
|
||||||
|
std::string range_expr;
|
||||||
|
std::string requirer;
|
||||||
|
std::vector<std::string> features;
|
||||||
|
};
|
||||||
|
|
||||||
|
// PubGrub-style conflict-driven backtracking solver with incompatibility explanation trace.
|
||||||
|
class PubGrubSolver {
|
||||||
|
public:
|
||||||
|
PubGrubSolver(const PackageIndex &index, const SolveOptions &options)
|
||||||
|
: index_{index}, options_{options} {}
|
||||||
|
|
||||||
|
Void::Result::Result<SolveResult, Void::Result::Error>
|
||||||
|
solve(const std::vector<DependencyConstraint> &roots) {
|
||||||
|
std::map<PackageId, std::vector<ActiveConstraint>> constraints;
|
||||||
|
for (const auto &rc : roots) {
|
||||||
|
auto parsed = parse_semver_range_compat(rc.range_expr);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{
|
||||||
|
solve_err(std::format("invalid version range '{}' for '{}' (from {})",
|
||||||
|
rc.range_expr, rc.target.format(), rc.origin_label))};
|
||||||
|
}
|
||||||
|
constraints[rc.target].push_back(ActiveConstraint{
|
||||||
|
*parsed, rc.range_expr, rc.origin_label.empty() ? "root" : rc.origin_label,
|
||||||
|
rc.required_features});
|
||||||
|
}
|
||||||
|
|
||||||
|
std::map<PackageId, ReleaseRecord> chosen;
|
||||||
|
if (backtrack(constraints, chosen)) {
|
||||||
|
SolveResult out;
|
||||||
|
for (const auto &[id, rel] : chosen) {
|
||||||
|
SolvedPackage sp;
|
||||||
|
sp.id = id;
|
||||||
|
sp.version = rel.version;
|
||||||
|
sp.source_sha256 = rel.source_sha256;
|
||||||
|
sp.source_url = rel.source_url;
|
||||||
|
sp.binaries = rel.binaries;
|
||||||
|
if (const auto cit = constraints.find(id); cit != constraints.end()) {
|
||||||
|
for (const auto &ac : cit->second) {
|
||||||
|
for (const auto &f : ac.features) {
|
||||||
|
sp.enabled_features.insert(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &dep : rel.dependencies) {
|
||||||
|
sp.dependencies.push_back(dep.target);
|
||||||
|
}
|
||||||
|
std::ranges::sort(sp.dependencies);
|
||||||
|
sp.dependencies.erase(std::unique(sp.dependencies.begin(), sp.dependencies.end()),
|
||||||
|
sp.dependencies.end());
|
||||||
|
out.packages.emplace(id, std::move(sp));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string report = "dependency version resolution failed:\n";
|
||||||
|
if (conflicts_.empty()) {
|
||||||
|
report += " no satisfiable version assignment found within solver step budget";
|
||||||
|
} else {
|
||||||
|
const std::size_t shown = std::min<std::size_t>(conflicts_.size(), 8);
|
||||||
|
for (std::size_t i = 0; i < shown; ++i) {
|
||||||
|
report += " - " + conflicts_[i] + "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::unexpected{solve_err(std::move(report))};
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
bool matches_all(const Void::Semver::Version &v,
|
||||||
|
const std::vector<ActiveConstraint> &list) const {
|
||||||
|
for (const auto &c : list) {
|
||||||
|
if (!c.range.contains(v)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<ReleaseRecord> ordered_candidates(const PackageId &id,
|
||||||
|
const std::vector<ActiveConstraint> &list) const {
|
||||||
|
auto all = index_.releases_for(id);
|
||||||
|
std::vector<ReleaseRecord> matching;
|
||||||
|
const auto pin_it = options_.pinned_versions.find(id);
|
||||||
|
|
||||||
|
for (auto &rel : all) {
|
||||||
|
const bool is_pinned =
|
||||||
|
(pin_it != options_.pinned_versions.end() && rel.version == pin_it->second);
|
||||||
|
if (rel.yanked && !(is_pinned && options_.allow_yanked_if_pinned)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (matches_all(rel.version, list)) {
|
||||||
|
matching.push_back(std::move(rel));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deterministic priority: pinned compatible version first, then highest SemVer descending.
|
||||||
|
std::ranges::sort(matching, [&](const ReleaseRecord &a, const ReleaseRecord &b) {
|
||||||
|
const bool a_pin =
|
||||||
|
(pin_it != options_.pinned_versions.end() && a.version == pin_it->second);
|
||||||
|
const bool b_pin =
|
||||||
|
(pin_it != options_.pinned_versions.end() && b.version == pin_it->second);
|
||||||
|
if (a_pin != b_pin) {
|
||||||
|
return a_pin;
|
||||||
|
}
|
||||||
|
return a.version > b.version;
|
||||||
|
});
|
||||||
|
return matching;
|
||||||
|
}
|
||||||
|
|
||||||
|
void record_incompatibility(const PackageId &id, const std::vector<ActiveConstraint> &list) {
|
||||||
|
std::string msg = "no version of " + id.format() + " satisfies: ";
|
||||||
|
for (std::size_t i = 0; i < list.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
msg += " AND ";
|
||||||
|
}
|
||||||
|
msg += list[i].range_expr + " (from " + list[i].requirer + ")";
|
||||||
|
}
|
||||||
|
if (conflicts_.size() < 32 && !std::ranges::contains(conflicts_, msg)) {
|
||||||
|
conflicts_.push_back(std::move(msg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool backtrack(std::map<PackageId, std::vector<ActiveConstraint>> &constraints,
|
||||||
|
std::map<PackageId, ReleaseRecord> &chosen) {
|
||||||
|
if (++steps_ > options_.max_steps) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unit propagation / fail-fast check: choose undecided package with fewest candidates!
|
||||||
|
std::optional<PackageId> next_pkg;
|
||||||
|
std::vector<ReleaseRecord> best_candidates;
|
||||||
|
std::size_t min_count = std::numeric_limits<std::size_t>::max();
|
||||||
|
|
||||||
|
for (const auto &[id, clist] : constraints) {
|
||||||
|
if (const auto cit = chosen.find(id); cit != chosen.end()) {
|
||||||
|
if (!matches_all(cit->second.version, clist)) {
|
||||||
|
record_incompatibility(id, clist);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto cands = ordered_candidates(id, clist);
|
||||||
|
if (cands.empty()) {
|
||||||
|
record_incompatibility(id, clist);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (cands.size() < min_count) {
|
||||||
|
min_count = cands.size();
|
||||||
|
next_pkg = id;
|
||||||
|
best_candidates = std::move(cands);
|
||||||
|
if (min_count == 1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!next_pkg) {
|
||||||
|
return true; // All constrained packages decided and mutually consistent!
|
||||||
|
}
|
||||||
|
|
||||||
|
const PackageId pkg = *next_pkg;
|
||||||
|
for (const auto &candidate : best_candidates) {
|
||||||
|
// Save constraints snapshot before descending.
|
||||||
|
auto next_constraints = constraints;
|
||||||
|
bool valid_ranges = true;
|
||||||
|
const std::string origin = pkg.format() + "@" + candidate.version.to_string();
|
||||||
|
|
||||||
|
for (const auto &dep : candidate.dependencies) {
|
||||||
|
auto parsed = parse_semver_range_compat(dep.range_expr);
|
||||||
|
if (!parsed) {
|
||||||
|
valid_ranges = false;
|
||||||
|
conflicts_.push_back(
|
||||||
|
std::format("package {} declares invalid range '{}' for {}", origin,
|
||||||
|
dep.range_expr, dep.target.format()));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
next_constraints[dep.target].push_back(
|
||||||
|
ActiveConstraint{*parsed, dep.range_expr, origin, dep.required_features});
|
||||||
|
}
|
||||||
|
if (!valid_ranges) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
chosen.insert_or_assign(pkg, candidate);
|
||||||
|
if (backtrack(next_constraints, chosen)) {
|
||||||
|
constraints = std::move(next_constraints);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
chosen.erase(pkg);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PackageIndex &index_;
|
||||||
|
const SolveOptions &options_;
|
||||||
|
std::size_t steps_{0};
|
||||||
|
std::vector<std::string> conflicts_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string PackageId::format() const {
|
||||||
|
if (registry_authority.empty()) {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
return registry_authority + "/" + name;
|
||||||
|
}
|
||||||
|
|
||||||
|
void PackageIndex::add_release(ReleaseRecord release) {
|
||||||
|
releases_[release.id].push_back(std::move(release));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<ReleaseRecord> PackageIndex::releases_for(const PackageId &id) const {
|
||||||
|
const auto it = releases_.find(id);
|
||||||
|
if (it == releases_.end()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<SolveResult, Void::Result::Error>
|
||||||
|
solve_dependencies(const std::vector<DependencyConstraint> &root_constraints,
|
||||||
|
const PackageIndex &index, const SolveOptions &options) {
|
||||||
|
PubGrubSolver solver{index, options};
|
||||||
|
return solver.solve(root_constraints);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,949 @@
|
|||||||
|
#include <Void/Build/Package/Toml.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cctype>
|
||||||
|
#include <charconv>
|
||||||
|
#include <cmath>
|
||||||
|
#include <format>
|
||||||
|
#include <set>
|
||||||
|
|
||||||
|
namespace Void::Build::Package {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Void::Result::Error parse_err(const SourceOrigin &orig, std::string msg) {
|
||||||
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("{}: {}", orig.format(), std::move(msg)));
|
||||||
|
}
|
||||||
|
|
||||||
|
class TomlParser {
|
||||||
|
public:
|
||||||
|
TomlParser(std::string_view text, std::string source_name)
|
||||||
|
: text_{text}, source_name_{std::move(source_name)} {}
|
||||||
|
|
||||||
|
Void::Result::Result<TomlTable, Void::Result::Error> parse() {
|
||||||
|
if (!Util::is_valid_utf8(text_)) {
|
||||||
|
return std::unexpected{parse_err({source_name_, 1, 1}, "invalid UTF-8 in TOML")};
|
||||||
|
}
|
||||||
|
TomlValue root = TomlValue::make_table({source_name_, 1, 1});
|
||||||
|
TomlTable *current_table = &root.as_table_mut();
|
||||||
|
|
||||||
|
while (!eof()) {
|
||||||
|
skip_ws_and_comments(true);
|
||||||
|
if (eof()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (peek() == '[') {
|
||||||
|
const auto hdr_origin = origin();
|
||||||
|
advance();
|
||||||
|
const bool is_array_table = (!eof() && peek() == '[');
|
||||||
|
if (is_array_table) {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
skip_inline_ws();
|
||||||
|
auto keys = parse_key_path();
|
||||||
|
if (!keys) {
|
||||||
|
return std::unexpected{keys.error()};
|
||||||
|
}
|
||||||
|
skip_inline_ws();
|
||||||
|
if (eof() || peek() != ']') {
|
||||||
|
return std::unexpected{parse_err(origin(), "expected ']' in table header")};
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
if (is_array_table) {
|
||||||
|
if (eof() || peek() != ']') {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(origin(), "expected ']]' in array-of-tables header")};
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
if (auto r = expect_line_end(); !r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
auto tbl =
|
||||||
|
navigate_table_header(root.as_table_mut(), *keys, is_array_table, hdr_origin);
|
||||||
|
if (!tbl) {
|
||||||
|
return std::unexpected{tbl.error()};
|
||||||
|
}
|
||||||
|
current_table = *tbl;
|
||||||
|
} else {
|
||||||
|
const auto kv_origin = origin();
|
||||||
|
auto keys = parse_key_path();
|
||||||
|
if (!keys) {
|
||||||
|
return std::unexpected{keys.error()};
|
||||||
|
}
|
||||||
|
skip_inline_ws();
|
||||||
|
if (eof() || peek() != '=') {
|
||||||
|
return std::unexpected{parse_err(origin(), "expected '=' after key")};
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
skip_inline_ws();
|
||||||
|
auto val = parse_value();
|
||||||
|
if (!val) {
|
||||||
|
return std::unexpected{val.error()};
|
||||||
|
}
|
||||||
|
if (auto r = expect_line_end(); !r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
if (auto r = insert_key_value(*current_table, *keys, std::move(*val), kv_origin);
|
||||||
|
!r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::move(root.as_table_mut());
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
bool eof() const noexcept { return pos_ >= text_.size(); }
|
||||||
|
char peek(std::size_t off = 0) const noexcept {
|
||||||
|
return (pos_ + off < text_.size()) ? text_[pos_ + off] : '\0';
|
||||||
|
}
|
||||||
|
char advance() noexcept {
|
||||||
|
const char c = text_[pos_++];
|
||||||
|
if (c == '\n') {
|
||||||
|
++line_;
|
||||||
|
col_ = 1;
|
||||||
|
} else {
|
||||||
|
++col_;
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
SourceOrigin origin() const { return {source_name_, line_, col_}; }
|
||||||
|
|
||||||
|
void skip_inline_ws() noexcept {
|
||||||
|
while (!eof() && (peek() == ' ' || peek() == '\t')) {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void skip_ws_and_comments(bool allow_newlines) noexcept {
|
||||||
|
while (!eof()) {
|
||||||
|
const char c = peek();
|
||||||
|
if (c == ' ' || c == '\t' || (allow_newlines && (c == '\n' || c == '\r'))) {
|
||||||
|
advance();
|
||||||
|
} else if (c == '#') {
|
||||||
|
while (!eof() && peek() != '\n') {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error> expect_line_end() {
|
||||||
|
skip_inline_ws();
|
||||||
|
if (!eof() && peek() == '#') {
|
||||||
|
while (!eof() && peek() != '\n') {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (eof()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (peek() == '\r') {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
if (eof() || peek() == '\n') {
|
||||||
|
if (!eof()) {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return std::unexpected{parse_err(origin(), "unexpected trailing characters on line")};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::string, Void::Result::Error> parse_basic_string(bool multiline) {
|
||||||
|
const auto start = origin();
|
||||||
|
if (multiline && !eof() && (peek() == '\n' || (peek() == '\r' && peek(1) == '\n'))) {
|
||||||
|
if (peek() == '\r') {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
std::string out;
|
||||||
|
while (!eof()) {
|
||||||
|
if (multiline && peek() == '"' && peek(1) == '"' && peek(2) == '"') {
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (!multiline && peek() == '"') {
|
||||||
|
advance();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const char c = advance();
|
||||||
|
if (!multiline && (c == '\n' || c == '\r')) {
|
||||||
|
return std::unexpected{parse_err(start, "unterminated basic string")};
|
||||||
|
}
|
||||||
|
if (c == '\\') {
|
||||||
|
if (eof()) {
|
||||||
|
return std::unexpected{parse_err(origin(), "unterminated escape sequence")};
|
||||||
|
}
|
||||||
|
const char esc = advance();
|
||||||
|
switch (esc) {
|
||||||
|
case 'b':
|
||||||
|
out.push_back('\b');
|
||||||
|
break;
|
||||||
|
case 't':
|
||||||
|
out.push_back('\t');
|
||||||
|
break;
|
||||||
|
case 'n':
|
||||||
|
out.push_back('\n');
|
||||||
|
break;
|
||||||
|
case 'f':
|
||||||
|
out.push_back('\f');
|
||||||
|
break;
|
||||||
|
case 'r':
|
||||||
|
out.push_back('\r');
|
||||||
|
break;
|
||||||
|
case '"':
|
||||||
|
out.push_back('"');
|
||||||
|
break;
|
||||||
|
case '\\':
|
||||||
|
out.push_back('\\');
|
||||||
|
break;
|
||||||
|
case '\n':
|
||||||
|
case '\r':
|
||||||
|
case ' ':
|
||||||
|
case '\t':
|
||||||
|
if (!multiline) {
|
||||||
|
return std::unexpected{parse_err(origin(), "invalid escape in string")};
|
||||||
|
}
|
||||||
|
while (!eof() &&
|
||||||
|
(peek() == ' ' || peek() == '\t' || peek() == '\n' || peek() == '\r')) {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(origin(), std::format("unsupported escape '\\{}'", esc))};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
out.push_back(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::unexpected{parse_err(start, "unterminated string literal")};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::string, Void::Result::Error> parse_literal_string(bool multiline) {
|
||||||
|
const auto start = origin();
|
||||||
|
if (multiline && !eof() && (peek() == '\n' || (peek() == '\r' && peek(1) == '\n'))) {
|
||||||
|
if (peek() == '\r') {
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
}
|
||||||
|
std::string out;
|
||||||
|
while (!eof()) {
|
||||||
|
if (multiline && peek() == '\'' && peek(1) == '\'' && peek(2) == '\'') {
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (!multiline && peek() == '\'') {
|
||||||
|
advance();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const char c = advance();
|
||||||
|
if (!multiline && (c == '\n' || c == '\r')) {
|
||||||
|
return std::unexpected{parse_err(start, "unterminated literal string")};
|
||||||
|
}
|
||||||
|
out.push_back(c);
|
||||||
|
}
|
||||||
|
return std::unexpected{parse_err(start, "unterminated literal string")};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::string, Void::Result::Error> parse_single_key() {
|
||||||
|
skip_inline_ws();
|
||||||
|
if (eof()) {
|
||||||
|
return std::unexpected{parse_err(origin(), "expected key")};
|
||||||
|
}
|
||||||
|
if (peek() == '"') {
|
||||||
|
advance();
|
||||||
|
return parse_basic_string(false);
|
||||||
|
}
|
||||||
|
if (peek() == '\'') {
|
||||||
|
advance();
|
||||||
|
return parse_literal_string(false);
|
||||||
|
}
|
||||||
|
std::string key;
|
||||||
|
while (!eof()) {
|
||||||
|
const char c = peek();
|
||||||
|
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||||
|
c == '_' || c == '-') {
|
||||||
|
key.push_back(advance());
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (key.empty()) {
|
||||||
|
return std::unexpected{parse_err(origin(), "empty or invalid bare key")};
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<std::string>, Void::Result::Error> parse_key_path() {
|
||||||
|
std::vector<std::string> parts;
|
||||||
|
auto first = parse_single_key();
|
||||||
|
if (!first) {
|
||||||
|
return std::unexpected{first.error()};
|
||||||
|
}
|
||||||
|
parts.push_back(std::move(*first));
|
||||||
|
for (;;) {
|
||||||
|
skip_inline_ws();
|
||||||
|
if (!eof() && peek() == '.') {
|
||||||
|
advance();
|
||||||
|
auto next = parse_single_key();
|
||||||
|
if (!next) {
|
||||||
|
return std::unexpected{next.error()};
|
||||||
|
}
|
||||||
|
parts.push_back(std::move(*next));
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<TomlValue, Void::Result::Error> parse_value() {
|
||||||
|
skip_inline_ws();
|
||||||
|
const auto start = origin();
|
||||||
|
if (eof()) {
|
||||||
|
return std::unexpected{parse_err(start, "expected value")};
|
||||||
|
}
|
||||||
|
const char c = peek();
|
||||||
|
if (c == '"') {
|
||||||
|
if (peek(1) == '"' && peek(2) == '"') {
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
auto s = parse_basic_string(true);
|
||||||
|
if (!s) {
|
||||||
|
return std::unexpected{s.error()};
|
||||||
|
}
|
||||||
|
return TomlValue{std::move(*s), start};
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
auto s = parse_basic_string(false);
|
||||||
|
if (!s) {
|
||||||
|
return std::unexpected{s.error()};
|
||||||
|
}
|
||||||
|
return TomlValue{std::move(*s), start};
|
||||||
|
}
|
||||||
|
if (c == '\'') {
|
||||||
|
if (peek(1) == '\'' && peek(2) == '\'') {
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
advance();
|
||||||
|
auto s = parse_literal_string(true);
|
||||||
|
if (!s) {
|
||||||
|
return std::unexpected{s.error()};
|
||||||
|
}
|
||||||
|
return TomlValue{std::move(*s), start};
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
auto s = parse_literal_string(false);
|
||||||
|
if (!s) {
|
||||||
|
return std::unexpected{s.error()};
|
||||||
|
}
|
||||||
|
return TomlValue{std::move(*s), start};
|
||||||
|
}
|
||||||
|
if (c == '[') {
|
||||||
|
return parse_array();
|
||||||
|
}
|
||||||
|
if (c == '{') {
|
||||||
|
return parse_inline_table();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read scalar token (bool, int, float).
|
||||||
|
std::string token;
|
||||||
|
while (!eof()) {
|
||||||
|
const char ch = peek();
|
||||||
|
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '#' || ch == ',' ||
|
||||||
|
ch == ']' || ch == '}') {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
token.push_back(advance());
|
||||||
|
}
|
||||||
|
if (token == "true") {
|
||||||
|
return TomlValue{true, start};
|
||||||
|
}
|
||||||
|
if (token == "false") {
|
||||||
|
return TomlValue{false, start};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string clean;
|
||||||
|
for (const char ch : token) {
|
||||||
|
if (ch != '_') {
|
||||||
|
clean.push_back(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (clean.empty()) {
|
||||||
|
return std::unexpected{parse_err(start, "empty scalar value")};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Integer (hex/oct/bin/dec).
|
||||||
|
const bool looks_float = clean.find('.') != std::string::npos ||
|
||||||
|
clean.find('e') != std::string::npos ||
|
||||||
|
clean.find('E') != std::string::npos;
|
||||||
|
if (!looks_float) {
|
||||||
|
int base = 10;
|
||||||
|
std::string_view digits{clean};
|
||||||
|
if (digits.starts_with("0x")) {
|
||||||
|
base = 16;
|
||||||
|
digits.remove_prefix(2);
|
||||||
|
} else if (digits.starts_with("0o")) {
|
||||||
|
base = 8;
|
||||||
|
digits.remove_prefix(2);
|
||||||
|
} else if (digits.starts_with("0b")) {
|
||||||
|
base = 2;
|
||||||
|
digits.remove_prefix(2);
|
||||||
|
} else if (digits.starts_with("+")) {
|
||||||
|
digits.remove_prefix(1);
|
||||||
|
}
|
||||||
|
std::int64_t iv = 0;
|
||||||
|
const auto [ptr, ec] =
|
||||||
|
std::from_chars(digits.data(), digits.data() + digits.size(), iv, base);
|
||||||
|
if (ec == std::errc{} && ptr == digits.data() + digits.size()) {
|
||||||
|
return TomlValue{iv, start};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
double dv = 0.0;
|
||||||
|
const auto [ptr, ec] = std::from_chars(clean.data(), clean.data() + clean.size(), dv);
|
||||||
|
if (ec == std::errc{} && ptr == clean.data() + clean.size()) {
|
||||||
|
return TomlValue{dv, start};
|
||||||
|
}
|
||||||
|
return std::unexpected{parse_err(start, std::format("invalid TOML value '{}'", token))};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<TomlValue, Void::Result::Error> parse_array() {
|
||||||
|
const auto start = origin();
|
||||||
|
advance(); // '['
|
||||||
|
TomlValue arr = TomlValue::make_array(start);
|
||||||
|
for (;;) {
|
||||||
|
skip_ws_and_comments(true);
|
||||||
|
if (eof()) {
|
||||||
|
return std::unexpected{parse_err(start, "unterminated array")};
|
||||||
|
}
|
||||||
|
if (peek() == ']') {
|
||||||
|
advance();
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
auto elem = parse_value();
|
||||||
|
if (!elem) {
|
||||||
|
return std::unexpected{elem.error()};
|
||||||
|
}
|
||||||
|
arr.as_array_mut().push_back(std::move(*elem));
|
||||||
|
skip_ws_and_comments(true);
|
||||||
|
if (!eof() && peek() == ',') {
|
||||||
|
advance();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!eof() && peek() == ']') {
|
||||||
|
advance();
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
return std::unexpected{parse_err(origin(), "expected ',' or ']' in array")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<TomlValue, Void::Result::Error> parse_inline_table() {
|
||||||
|
const auto start = origin();
|
||||||
|
advance(); // '{'
|
||||||
|
TomlValue tbl = TomlValue::make_table(start);
|
||||||
|
skip_inline_ws();
|
||||||
|
if (!eof() && peek() == '}') {
|
||||||
|
advance();
|
||||||
|
return tbl;
|
||||||
|
}
|
||||||
|
for (;;) {
|
||||||
|
skip_inline_ws();
|
||||||
|
const auto kv_origin = origin();
|
||||||
|
auto keys = parse_key_path();
|
||||||
|
if (!keys) {
|
||||||
|
return std::unexpected{keys.error()};
|
||||||
|
}
|
||||||
|
skip_inline_ws();
|
||||||
|
if (eof() || peek() != '=') {
|
||||||
|
return std::unexpected{parse_err(origin(), "expected '=' in inline table")};
|
||||||
|
}
|
||||||
|
advance();
|
||||||
|
auto val = parse_value();
|
||||||
|
if (!val) {
|
||||||
|
return std::unexpected{val.error()};
|
||||||
|
}
|
||||||
|
if (auto r = insert_key_value(tbl.as_table_mut(), *keys, std::move(*val), kv_origin);
|
||||||
|
!r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
skip_inline_ws();
|
||||||
|
if (!eof() && peek() == ',') {
|
||||||
|
advance();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!eof() && peek() == '}') {
|
||||||
|
advance();
|
||||||
|
return tbl;
|
||||||
|
}
|
||||||
|
return std::unexpected{parse_err(origin(), "expected ',' or '}' in inline table")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<TomlTable *, Void::Result::Error>
|
||||||
|
navigate_table_header(TomlTable &root, const std::vector<std::string> &keys,
|
||||||
|
bool is_array_table, const SourceOrigin &hdr_origin) {
|
||||||
|
TomlTable *cur = &root;
|
||||||
|
for (std::size_t i = 0; i + 1 < keys.size(); ++i) {
|
||||||
|
const auto &k = keys[i];
|
||||||
|
auto it = cur->find(k);
|
||||||
|
if (it == cur->end()) {
|
||||||
|
it = cur->emplace(k, TomlValue::make_table(hdr_origin)).first;
|
||||||
|
}
|
||||||
|
if (it->second.is_table()) {
|
||||||
|
cur = &it->second.as_table_mut();
|
||||||
|
} else if (it->second.is_array() && !it->second.as_array().empty() &&
|
||||||
|
it->second.as_array().back().is_table()) {
|
||||||
|
cur = &it->second.as_array_mut().back().as_table_mut();
|
||||||
|
} else {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(hdr_origin, std::format("key '{}' is not a table", k))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const auto &last = keys.back();
|
||||||
|
if (is_array_table) {
|
||||||
|
auto it = cur->find(last);
|
||||||
|
if (it == cur->end()) {
|
||||||
|
it = cur->emplace(last, TomlValue::make_array(hdr_origin)).first;
|
||||||
|
}
|
||||||
|
if (!it->second.is_array()) {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
hdr_origin, std::format("key '{}' cannot be redefined as array table", last))};
|
||||||
|
}
|
||||||
|
it->second.as_array_mut().push_back(TomlValue::make_table(hdr_origin));
|
||||||
|
return &it->second.as_array_mut().back().as_table_mut();
|
||||||
|
}
|
||||||
|
auto it = cur->find(last);
|
||||||
|
if (it == cur->end()) {
|
||||||
|
it = cur->emplace(last, TomlValue::make_table(hdr_origin)).first;
|
||||||
|
}
|
||||||
|
if (!it->second.is_table()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(hdr_origin, std::format("key '{}' already defined as non-table", last))};
|
||||||
|
}
|
||||||
|
std::string full_header;
|
||||||
|
for (std::size_t i = 0; i < keys.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
full_header += '.';
|
||||||
|
}
|
||||||
|
full_header += keys[i];
|
||||||
|
}
|
||||||
|
if (!explicit_tables_.insert(full_header).second) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(hdr_origin, std::format("duplicate table header [{}]", full_header))};
|
||||||
|
}
|
||||||
|
return &it->second.as_table_mut();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
insert_key_value(TomlTable &table, const std::vector<std::string> &keys, TomlValue val,
|
||||||
|
const SourceOrigin &kv_origin) {
|
||||||
|
TomlTable *cur = &table;
|
||||||
|
for (std::size_t i = 0; i + 1 < keys.size(); ++i) {
|
||||||
|
const auto &k = keys[i];
|
||||||
|
auto it = cur->find(k);
|
||||||
|
if (it == cur->end()) {
|
||||||
|
it = cur->emplace(k, TomlValue::make_table(kv_origin)).first;
|
||||||
|
}
|
||||||
|
if (!it->second.is_table()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(kv_origin, std::format("cannot index into non-table key '{}'", k))};
|
||||||
|
}
|
||||||
|
cur = &it->second.as_table_mut();
|
||||||
|
}
|
||||||
|
const auto &leaf = keys.back();
|
||||||
|
if (cur->contains(leaf)) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(kv_origin, std::format("duplicate TOML key '{}'", leaf))};
|
||||||
|
}
|
||||||
|
cur->emplace(leaf, std::move(val));
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string_view text_;
|
||||||
|
std::string source_name_;
|
||||||
|
std::size_t pos_{0};
|
||||||
|
std::size_t line_{1};
|
||||||
|
std::size_t col_{1};
|
||||||
|
std::set<std::string> explicit_tables_;
|
||||||
|
};
|
||||||
|
|
||||||
|
std::string toml_quote_key(std::string_view key) {
|
||||||
|
bool bare_ok = !key.empty();
|
||||||
|
for (const char c : key) {
|
||||||
|
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
|
||||||
|
c == '_' || c == '-')) {
|
||||||
|
bare_ok = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bare_ok ? std::string{key} : Util::json_quote(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_scalar_or_inline(const TomlValue &v) {
|
||||||
|
if (v.is_string()) {
|
||||||
|
return Util::json_quote(v.as_string());
|
||||||
|
}
|
||||||
|
if (v.is_bool()) {
|
||||||
|
return v.as_bool() ? "true" : "false";
|
||||||
|
}
|
||||||
|
if (v.is_int()) {
|
||||||
|
return std::to_string(v.as_int());
|
||||||
|
}
|
||||||
|
if (v.is_double()) {
|
||||||
|
return std::format("{}", v.as_double());
|
||||||
|
}
|
||||||
|
if (v.is_array()) {
|
||||||
|
std::string out{"["};
|
||||||
|
const auto &arr = v.as_array();
|
||||||
|
for (std::size_t i = 0; i < arr.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
out += ", ";
|
||||||
|
}
|
||||||
|
out += serialize_scalar_or_inline(arr[i]);
|
||||||
|
}
|
||||||
|
out += "]";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
std::string out{"{"};
|
||||||
|
bool first = true;
|
||||||
|
for (const auto &[k, val] : v.as_table()) {
|
||||||
|
if (!first) {
|
||||||
|
out += ", ";
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
out += toml_quote_key(k) + " = " + serialize_scalar_or_inline(val);
|
||||||
|
}
|
||||||
|
out += "}";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
void serialize_table_section(const TomlTable &tbl, const std::string &prefix, std::string &out) {
|
||||||
|
// Scalars & arrays first.
|
||||||
|
for (const auto &[k, v] : tbl) {
|
||||||
|
if (!v.is_table()) {
|
||||||
|
out += toml_quote_key(k) + " = " + serialize_scalar_or_inline(v) + "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Nested subtables next.
|
||||||
|
for (const auto &[k, v] : tbl) {
|
||||||
|
if (v.is_table()) {
|
||||||
|
const std::string header =
|
||||||
|
prefix.empty() ? toml_quote_key(k) : (prefix + "." + toml_quote_key(k));
|
||||||
|
out += "\n[" + header + "]\n";
|
||||||
|
serialize_table_section(v.as_table(), header, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool option_value_equal(const OptionValue &a, const OptionValue &b) { return a.value == b.value; }
|
||||||
|
|
||||||
|
bool dependency_records_equal(const DependencyRecord &a, const DependencyRecord &b) {
|
||||||
|
if (a.source_kind != b.source_kind || a.location != b.location || a.revision != b.revision ||
|
||||||
|
a.package != b.package || a.version != b.version || a.builder != b.builder ||
|
||||||
|
a.registry_authority != b.registry_authority || a.sha256 != b.sha256 ||
|
||||||
|
a.features != b.features || a.build_dependency != b.build_dependency ||
|
||||||
|
a.options.size() != b.options.size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (const auto &[k, av] : a.options) {
|
||||||
|
const auto bit = b.options.find(k);
|
||||||
|
if (bit == b.options.end() || !option_value_equal(av, bit->second)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string SourceOrigin::format() const {
|
||||||
|
if (line == 0) {
|
||||||
|
return file.empty() ? "<unknown>" : file;
|
||||||
|
}
|
||||||
|
return std::format("{}:{}:{}", file, line, column);
|
||||||
|
}
|
||||||
|
|
||||||
|
TomlValue TomlValue::make_table(SourceOrigin origin) {
|
||||||
|
return TomlValue{std::make_shared<TomlTable>(), std::move(origin)};
|
||||||
|
}
|
||||||
|
|
||||||
|
TomlValue TomlValue::make_array(SourceOrigin origin) {
|
||||||
|
return TomlValue{std::make_shared<TomlArray>(), std::move(origin)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<TomlTable, Void::Result::Error> parse_toml(std::string_view text,
|
||||||
|
std::string_view source_name) {
|
||||||
|
TomlParser parser{text, std::string{source_name}};
|
||||||
|
return parser.parse();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<TomlTable, Void::Result::Error>
|
||||||
|
parse_toml_file(const std::filesystem::path &path) {
|
||||||
|
auto content = Void::FileSystem::read_file(path);
|
||||||
|
if (!content) {
|
||||||
|
return std::unexpected{content.error()};
|
||||||
|
}
|
||||||
|
return parse_toml(*content, path.string());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_toml(const TomlTable &table) {
|
||||||
|
std::string out;
|
||||||
|
serialize_table_section(table, "", out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
|
||||||
|
load_dependencies_toml(const std::filesystem::path &toml_path) {
|
||||||
|
auto root_res = parse_toml_file(toml_path);
|
||||||
|
if (!root_res) {
|
||||||
|
return std::unexpected{root_res.error()};
|
||||||
|
}
|
||||||
|
const auto &root = *root_res;
|
||||||
|
|
||||||
|
// Validate top-level keys (reject unknown fields explicitly!).
|
||||||
|
for (const auto &[k, v] : root) {
|
||||||
|
if (k != "dependencies" && k != "build_dependencies" && k != "registries") {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
v.origin, std::format("unknown top-level key '{}' in dependency manifest", k))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<NormalizedDependency> out;
|
||||||
|
auto parse_dep_section =
|
||||||
|
[&](const std::string §ion_key,
|
||||||
|
bool is_build_dep) -> Void::Result::Result<void, Void::Result::Error> {
|
||||||
|
const auto sec_it = root.find(section_key);
|
||||||
|
if (sec_it == root.end()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (!sec_it->second.is_table()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(sec_it->second.origin, std::format("'{}' must be a table", section_key))};
|
||||||
|
}
|
||||||
|
for (const auto &[alias, dep_val] : sec_it->second.as_table()) {
|
||||||
|
if (!dep_val.is_table()) {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
dep_val.origin, std::format("dependency '{}' must be a table", alias))};
|
||||||
|
}
|
||||||
|
const auto &dtbl = dep_val.as_table();
|
||||||
|
DependencyRecord rec;
|
||||||
|
rec.name = alias;
|
||||||
|
rec.build_dependency = is_build_dep;
|
||||||
|
|
||||||
|
static const std::set<std::string_view> kAllowedFields{
|
||||||
|
"git", "rev", "path", "archive", "sha256", "package", "version",
|
||||||
|
"conan", "builder", "options", "registry", "features", "build_dependency"};
|
||||||
|
for (const auto &[fk, fv] : dtbl) {
|
||||||
|
if (!kAllowedFields.contains(fk)) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(fv.origin,
|
||||||
|
std::format("unknown field '{}' in dependency '{}'", fk, alias))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int source_count = 0;
|
||||||
|
if (const auto it = dtbl.find("git"); it != dtbl.end()) {
|
||||||
|
++source_count;
|
||||||
|
if (!it->second.is_string()) {
|
||||||
|
return std::unexpected{parse_err(it->second.origin, "'git' must be a string")};
|
||||||
|
}
|
||||||
|
const auto rev_it = dtbl.find("rev");
|
||||||
|
if (rev_it == dtbl.end() || !rev_it->second.is_string()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(dep_val.origin,
|
||||||
|
std::format("git dependency '{}' requires 40-hex 'rev'", alias))};
|
||||||
|
}
|
||||||
|
const auto &rev = rev_it->second.as_string();
|
||||||
|
if (rev.size() != 40 || !std::ranges::all_of(rev, [](char c) {
|
||||||
|
return std::isxdigit(static_cast<unsigned char>(c)) != 0;
|
||||||
|
})) {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
rev_it->second.origin, "git 'rev' must be an exact 40-hex commit SHA")};
|
||||||
|
}
|
||||||
|
rec.source_kind = DependencySourceKind::Git;
|
||||||
|
rec.location = it->second.as_string();
|
||||||
|
rec.revision = rev;
|
||||||
|
}
|
||||||
|
if (const auto it = dtbl.find("package"); it != dtbl.end()) {
|
||||||
|
++source_count;
|
||||||
|
if (!it->second.is_string()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, "'package' must be a string")};
|
||||||
|
}
|
||||||
|
const auto ver_it = dtbl.find("version");
|
||||||
|
if (ver_it == dtbl.end() || !ver_it->second.is_string()) {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
dep_val.origin,
|
||||||
|
std::format("package dependency '{}' requires 'version'", alias))};
|
||||||
|
}
|
||||||
|
rec.source_kind = DependencySourceKind::Package;
|
||||||
|
rec.package = it->second.as_string();
|
||||||
|
rec.version = ver_it->second.as_string();
|
||||||
|
}
|
||||||
|
if (const auto it = dtbl.find("path"); it != dtbl.end()) {
|
||||||
|
++source_count;
|
||||||
|
if (!it->second.is_string()) {
|
||||||
|
return std::unexpected{parse_err(it->second.origin, "'path' must be a string")};
|
||||||
|
}
|
||||||
|
rec.source_kind = DependencySourceKind::Path;
|
||||||
|
rec.location = it->second.as_string();
|
||||||
|
}
|
||||||
|
if (const auto it = dtbl.find("archive"); it != dtbl.end()) {
|
||||||
|
++source_count;
|
||||||
|
if (!it->second.is_string()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, "'archive' must be a string")};
|
||||||
|
}
|
||||||
|
const auto sha_it = dtbl.find("sha256");
|
||||||
|
if (sha_it == dtbl.end() || !sha_it->second.is_string() ||
|
||||||
|
sha_it->second.as_string().size() != 64) {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
dep_val.origin,
|
||||||
|
std::format("archive dependency '{}' requires 64-hex 'sha256'", alias))};
|
||||||
|
}
|
||||||
|
rec.source_kind = DependencySourceKind::Archive;
|
||||||
|
rec.location = it->second.as_string();
|
||||||
|
rec.sha256 = sha_it->second.as_string();
|
||||||
|
}
|
||||||
|
if (const auto it = dtbl.find("conan"); it != dtbl.end()) {
|
||||||
|
++source_count;
|
||||||
|
if (!it->second.is_string()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, "'conan' must be a string")};
|
||||||
|
}
|
||||||
|
rec.source_kind = DependencySourceKind::Conan;
|
||||||
|
rec.package = it->second.as_string();
|
||||||
|
rec.builder = "conan";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (source_count != 1) {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
dep_val.origin, std::format("dependency '{}' must specify exactly one source "
|
||||||
|
"(git/package/path/archive/conan)",
|
||||||
|
alias))};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto it = dtbl.find("builder"); it != dtbl.end()) {
|
||||||
|
if (!it->second.is_string()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, "'builder' must be a string")};
|
||||||
|
}
|
||||||
|
const auto &b = it->second.as_string();
|
||||||
|
if (b != "cmake" && b != "meson" && b != "conan" && b != "native") {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, std::format("unsupported builder '{}'", b))};
|
||||||
|
}
|
||||||
|
if (rec.source_kind == DependencySourceKind::Package && b != "native") {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
it->second.origin, "contradictory builder on native package dependency")};
|
||||||
|
}
|
||||||
|
rec.builder = b;
|
||||||
|
}
|
||||||
|
if (const auto it = dtbl.find("registry"); it != dtbl.end()) {
|
||||||
|
if (!it->second.is_string()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, "'registry' must be a string")};
|
||||||
|
}
|
||||||
|
rec.registry_authority = it->second.as_string();
|
||||||
|
}
|
||||||
|
if (const auto it = dtbl.find("build_dependency"); it != dtbl.end()) {
|
||||||
|
if (!it->second.is_bool()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, "'build_dependency' must be a bool")};
|
||||||
|
}
|
||||||
|
rec.build_dependency = it->second.as_bool();
|
||||||
|
}
|
||||||
|
if (const auto it = dtbl.find("features"); it != dtbl.end()) {
|
||||||
|
if (!it->second.is_array()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, "'features' must be an array of strings")};
|
||||||
|
}
|
||||||
|
for (const auto &fv : it->second.as_array()) {
|
||||||
|
if (!fv.is_string()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(fv.origin, "feature entry must be a string")};
|
||||||
|
}
|
||||||
|
rec.features.push_back(fv.as_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (const auto it = dtbl.find("options"); it != dtbl.end()) {
|
||||||
|
if (!it->second.is_table()) {
|
||||||
|
return std::unexpected{
|
||||||
|
parse_err(it->second.origin, "'options' must be a table")};
|
||||||
|
}
|
||||||
|
for (const auto &[ok, ov] : it->second.as_table()) {
|
||||||
|
if (ov.is_string()) {
|
||||||
|
rec.options.emplace(ok, OptionValue{ov.as_string()});
|
||||||
|
} else if (ov.is_bool()) {
|
||||||
|
rec.options.emplace(ok, OptionValue{ov.as_bool()});
|
||||||
|
} else if (ov.is_int()) {
|
||||||
|
rec.options.emplace(ok, OptionValue{ov.as_int()});
|
||||||
|
} else {
|
||||||
|
return std::unexpected{parse_err(
|
||||||
|
ov.origin,
|
||||||
|
std::format("option '{}' must be string, bool, or integer", ok))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push_back(NormalizedDependency{std::move(rec), dep_val.origin});
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
};
|
||||||
|
|
||||||
|
if (auto r = parse_dep_section("dependencies", false); !r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
if (auto r = parse_dep_section("build_dependencies", true); !r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<NormalizedDependency>, Void::Result::Error>
|
||||||
|
merge_dependencies(const std::vector<DependencyRecord> &cpp_deps,
|
||||||
|
const std::vector<NormalizedDependency> &toml_deps) {
|
||||||
|
std::map<std::string, NormalizedDependency, std::less<>> merged;
|
||||||
|
for (const auto &d : cpp_deps) {
|
||||||
|
merged.emplace(d.name, NormalizedDependency{d, SourceOrigin{"build.cpp", 0, 0}});
|
||||||
|
}
|
||||||
|
for (const auto &td : toml_deps) {
|
||||||
|
const auto it = merged.find(td.record.name);
|
||||||
|
if (it == merged.end()) {
|
||||||
|
merged.emplace(td.record.name, td);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!dependency_records_equal(it->second.record, td.record)) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("conflicting declaration for dependency '{}': first declared at {}, "
|
||||||
|
"conflicting declaration at {}",
|
||||||
|
td.record.name, it->second.origin.format(), td.origin.format()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::vector<NormalizedDependency> out;
|
||||||
|
out.reserve(merged.size());
|
||||||
|
for (auto &[k, v] : merged) {
|
||||||
|
out.push_back(std::move(v));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Package
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <atomic>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <format>
|
||||||
|
#include <linux/fs.h>
|
||||||
|
#include <set>
|
||||||
|
#include <sys/file.h>
|
||||||
|
#include <sys/ioctl.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Build::Platform {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
std::atomic<std::uint64_t> g_temp_seq{0};
|
||||||
|
|
||||||
|
std::string unique_suffix() {
|
||||||
|
const auto seq = g_temp_seq.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
return std::format(".vbs_tmp_{}_{}", static_cast<long long>(::getpid()), seq);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Error sys_err(int err, std::string message) {
|
||||||
|
return Void::System::make_system_error(Void::System::map_errno_to_system_code(err),
|
||||||
|
std::move(message), err);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
FileLock::~FileLock() noexcept { release(); }
|
||||||
|
|
||||||
|
FileLock::FileLock(FileLock &&other) noexcept : fd_{std::exchange(other.fd_, -1)} {}
|
||||||
|
|
||||||
|
FileLock &FileLock::operator=(FileLock &&other) noexcept {
|
||||||
|
if (this != &other) {
|
||||||
|
release();
|
||||||
|
fd_ = std::exchange(other.fd_, -1);
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FileLock::release() noexcept {
|
||||||
|
if (fd_ >= 0) {
|
||||||
|
(void)::flock(fd_, LOCK_UN);
|
||||||
|
(void)::close(fd_);
|
||||||
|
fd_ = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<FileLock, Void::Result::Error>
|
||||||
|
FileLock::acquire(const std::filesystem::path &lock_path, LockMode mode, bool non_blocking) {
|
||||||
|
std::error_code ec;
|
||||||
|
if (lock_path.has_parent_path()) {
|
||||||
|
std::filesystem::create_directories(lock_path.parent_path(), ec);
|
||||||
|
if (ec) {
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(ec.value(), std::format("FileLock: failed creating parent for '{}': {}",
|
||||||
|
lock_path.string(), ec.message()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const int fd = ::open(lock_path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0644);
|
||||||
|
if (fd < 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("FileLock: cannot open '{}'", lock_path.string()))};
|
||||||
|
}
|
||||||
|
int op = (mode == LockMode::Exclusive) ? LOCK_EX : LOCK_SH;
|
||||||
|
if (non_blocking) {
|
||||||
|
op |= LOCK_NB;
|
||||||
|
}
|
||||||
|
for (;;) {
|
||||||
|
if (::flock(fd, op) == 0) {
|
||||||
|
return FileLock{fd};
|
||||||
|
}
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const int err = errno;
|
||||||
|
(void)::close(fd);
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("FileLock: flock failed for '{}'", lock_path.string()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<FileMetadata, Void::Result::Error>
|
||||||
|
stat_lstat(const std::filesystem::path &path) {
|
||||||
|
struct stat st{};
|
||||||
|
if (::lstat(path.c_str(), &st) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
if (err == ENOENT || err == ENOTDIR) {
|
||||||
|
FileMetadata missing;
|
||||||
|
missing.exists = false;
|
||||||
|
return missing;
|
||||||
|
}
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("stat_lstat: lstat failed for '{}'", path.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
FileMetadata meta;
|
||||||
|
meta.exists = true;
|
||||||
|
meta.is_regular = S_ISREG(st.st_mode);
|
||||||
|
meta.is_directory = S_ISDIR(st.st_mode);
|
||||||
|
meta.is_symlink = S_ISLNK(st.st_mode);
|
||||||
|
meta.dev = static_cast<std::uint64_t>(st.st_dev);
|
||||||
|
meta.ino = static_cast<std::uint64_t>(st.st_ino);
|
||||||
|
meta.size = static_cast<std::uint64_t>(st.st_size);
|
||||||
|
meta.nlink = static_cast<std::uint64_t>(st.st_nlink);
|
||||||
|
meta.mode = static_cast<std::uint32_t>(st.st_mode & 07777u);
|
||||||
|
meta.mtime_sec = static_cast<std::int64_t>(st.st_mtim.tv_sec);
|
||||||
|
meta.mtime_nsec = static_cast<std::int64_t>(st.st_mtim.tv_nsec);
|
||||||
|
|
||||||
|
if (meta.is_symlink) {
|
||||||
|
std::size_t buf_size =
|
||||||
|
st.st_size > 0 ? static_cast<std::size_t>(st.st_size) + 1 : std::size_t{256};
|
||||||
|
for (int attempt = 0; attempt < 8; ++attempt) {
|
||||||
|
std::string target(buf_size, '\0');
|
||||||
|
const ssize_t n = ::readlink(path.c_str(), target.data(), target.size());
|
||||||
|
if (n < 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{sys_err(
|
||||||
|
err, std::format("stat_lstat: readlink failed for '{}'", path.string()))};
|
||||||
|
}
|
||||||
|
if (static_cast<std::size_t>(n) < target.size()) {
|
||||||
|
target.resize(static_cast<std::size_t>(n));
|
||||||
|
meta.symlink_target = std::move(target);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
buf_size *= 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return meta;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<bool, Void::Result::Error>
|
||||||
|
copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst,
|
||||||
|
std::optional<std::uint32_t> mode_override) {
|
||||||
|
const int src_fd = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
|
||||||
|
if (src_fd < 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("copy_isolated: cannot open source '{}'", src.string()))};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd src_guard{src_fd};
|
||||||
|
|
||||||
|
struct stat src_st{};
|
||||||
|
if (::fstat(src_fd, &src_st) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("copy_isolated: fstat failed for '{}'", src.string()))};
|
||||||
|
}
|
||||||
|
if (!S_ISREG(src_st.st_mode)) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("copy_isolated: source '{}' is not a regular file", src.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
if (dst.has_parent_path()) {
|
||||||
|
std::filesystem::create_directories(dst.parent_path(), ec);
|
||||||
|
if (ec) {
|
||||||
|
return std::unexpected{sys_err(
|
||||||
|
ec.value(), std::format("copy_isolated: cannot create parent dir for '{}': {}",
|
||||||
|
dst.string(), ec.message()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto mode = mode_override.value_or(static_cast<std::uint32_t>(src_st.st_mode & 0777u));
|
||||||
|
const auto temp_path = dst.parent_path() / (dst.filename().string() + unique_suffix());
|
||||||
|
const int dst_fd = ::open(temp_path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC,
|
||||||
|
static_cast<mode_t>(mode));
|
||||||
|
if (dst_fd < 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{sys_err(
|
||||||
|
err, std::format("copy_isolated: cannot create temp '{}'", temp_path.string()))};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd dst_guard{dst_fd};
|
||||||
|
auto cleanup = [&] { (void)::unlink(temp_path.c_str()); };
|
||||||
|
|
||||||
|
bool used_reflink = false;
|
||||||
|
#ifdef FICLONE
|
||||||
|
if (::ioctl(dst_fd, FICLONE, src_fd) == 0) {
|
||||||
|
used_reflink = true;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if (!used_reflink) {
|
||||||
|
std::array<char, 65536> buf{};
|
||||||
|
for (;;) {
|
||||||
|
const ssize_t n = ::read(src_fd, buf.data(), buf.size());
|
||||||
|
if (n > 0) {
|
||||||
|
std::size_t off = 0;
|
||||||
|
while (off < static_cast<std::size_t>(n)) {
|
||||||
|
const ssize_t w =
|
||||||
|
::write(dst_fd, buf.data() + off, static_cast<std::size_t>(n) - off);
|
||||||
|
if (w < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const int err = errno;
|
||||||
|
cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("copy_isolated: write failed for '{}'",
|
||||||
|
dst.string()))};
|
||||||
|
}
|
||||||
|
off += static_cast<std::size_t>(w);
|
||||||
|
}
|
||||||
|
} else if (n == 0) {
|
||||||
|
break;
|
||||||
|
} else if (errno != EINTR) {
|
||||||
|
const int err = errno;
|
||||||
|
cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("copy_isolated: read failed for '{}'", src.string()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(void)::fchmod(dst_fd, static_cast<mode_t>(mode));
|
||||||
|
if (const auto closed = dst_guard.close(); !closed) {
|
||||||
|
cleanup();
|
||||||
|
return std::unexpected{closed.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (::rename(temp_path.c_str(), dst.c_str()) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
cleanup();
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("copy_isolated: rename failed for '{}'", dst.string()))};
|
||||||
|
}
|
||||||
|
return used_reflink;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds) {
|
||||||
|
struct timespec times[2];
|
||||||
|
times[0].tv_sec = static_cast<time_t>(epoch_seconds);
|
||||||
|
times[0].tv_nsec = 0;
|
||||||
|
times[1].tv_sec = static_cast<time_t>(epoch_seconds);
|
||||||
|
times[1].tv_nsec = 0;
|
||||||
|
if (::utimensat(AT_FDCWD, path.c_str(), times, AT_SYMLINK_NOFOLLOW) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{sys_err(
|
||||||
|
err, std::format("set_canonical_mtime: utimensat failed for '{}'", path.string()))};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
atomic_write_bytes(const std::filesystem::path &path, std::span<const std::byte> bytes,
|
||||||
|
bool durable_sync, unsigned mode) {
|
||||||
|
std::error_code ec;
|
||||||
|
if (path.has_parent_path()) {
|
||||||
|
std::filesystem::create_directories(path.parent_path(), ec);
|
||||||
|
if (ec) {
|
||||||
|
return std::unexpected{sys_err(
|
||||||
|
ec.value(), std::format("atomic_write_bytes: create_directories failed for '{}'",
|
||||||
|
path.string()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Void::FileSystem::ReplaceOptions opts;
|
||||||
|
opts.durability = durable_sync ? Void::FileSystem::ReplaceDurability::durable_sync
|
||||||
|
: Void::FileSystem::ReplaceDurability::atomic_visibility;
|
||||||
|
opts.mode = mode;
|
||||||
|
auto res = Void::FileSystem::replace_file(path, bytes, opts);
|
||||||
|
if (!res) {
|
||||||
|
return std::unexpected{std::move(res.error().error)};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error> atomic_write_file(const std::filesystem::path &path,
|
||||||
|
std::string_view content,
|
||||||
|
bool durable_sync,
|
||||||
|
unsigned mode) {
|
||||||
|
return atomic_write_bytes(path,
|
||||||
|
std::as_bytes(std::span<const char>{content.data(), content.size()}),
|
||||||
|
durable_sync, mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
fsync_directory(const std::filesystem::path &dir_path) {
|
||||||
|
const int fd = ::open(dir_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||||
|
if (fd < 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("fsync_directory: open failed for '{}'", dir_path.string()))};
|
||||||
|
}
|
||||||
|
Void::System::OwnedFd guard{fd};
|
||||||
|
for (;;) {
|
||||||
|
if (::fsync(fd) == 0) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const int err = errno;
|
||||||
|
if (err == EINVAL || err == EROFS) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(err, std::format("fsync_directory: fsync failed for '{}'", dir_path.string()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesystem::path &target) {
|
||||||
|
std::error_code ec;
|
||||||
|
const auto parent =
|
||||||
|
link_path.has_parent_path() ? link_path.parent_path() : std::filesystem::path{"."};
|
||||||
|
std::filesystem::create_directories(parent, ec);
|
||||||
|
if (ec) {
|
||||||
|
return std::unexpected{sys_err(
|
||||||
|
ec.value(), std::format("atomic_swap_symlink: create_directories failed for '{}'",
|
||||||
|
parent.string()))};
|
||||||
|
}
|
||||||
|
const auto temp_link = parent / (link_path.filename().string() + unique_suffix());
|
||||||
|
if (::symlink(target.c_str(), temp_link.c_str()) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{sys_err(
|
||||||
|
err, std::format("atomic_swap_symlink: symlink failed for '{}'", temp_link.string()))};
|
||||||
|
}
|
||||||
|
if (::rename(temp_link.c_str(), link_path.c_str()) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
(void)::unlink(temp_link.c_str());
|
||||||
|
return std::unexpected{sys_err(
|
||||||
|
err, std::format("atomic_swap_symlink: rename failed for '{}'", link_path.string()))};
|
||||||
|
}
|
||||||
|
return fsync_directory(parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool path_is_within(const std::filesystem::path &root, const std::filesystem::path &path) {
|
||||||
|
const auto norm_root = root.lexically_normal();
|
||||||
|
const auto norm_path = path.lexically_normal();
|
||||||
|
auto r_it = norm_root.begin();
|
||||||
|
auto p_it = norm_path.begin();
|
||||||
|
for (; r_it != norm_root.end(); ++r_it, ++p_it) {
|
||||||
|
if (r_it->empty() || *r_it == ".") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (p_it == norm_path.end() || *r_it != *p_it) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||||
|
resolve_confined_path(const std::filesystem::path &root, const std::filesystem::path &candidate,
|
||||||
|
const std::vector<std::filesystem::path> &allowed_external_roots) {
|
||||||
|
std::error_code ec;
|
||||||
|
const auto canonical_root = std::filesystem::weakly_canonical(root, ec);
|
||||||
|
if (ec) {
|
||||||
|
return std::unexpected{
|
||||||
|
sys_err(ec.value(), std::format("resolve_confined_path: cannot canonicalize root '{}'",
|
||||||
|
root.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::filesystem::path> allowed{canonical_root};
|
||||||
|
for (const auto &ext : allowed_external_roots) {
|
||||||
|
const auto ce = std::filesystem::weakly_canonical(ext, ec);
|
||||||
|
if (!ec) {
|
||||||
|
allowed.push_back(ce);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path current =
|
||||||
|
candidate.is_absolute() ? candidate : (canonical_root / candidate);
|
||||||
|
current = current.lexically_normal();
|
||||||
|
|
||||||
|
// Manually walk symlinks with a strict hop budget to detect loops explicitly.
|
||||||
|
constexpr int kMaxSymlinkHops = 40;
|
||||||
|
int hops = 0;
|
||||||
|
std::set<std::filesystem::path> seen;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
std::filesystem::path acc;
|
||||||
|
bool followed_symlink = false;
|
||||||
|
auto it = current.begin();
|
||||||
|
for (; it != current.end(); ++it) {
|
||||||
|
if (*it == ".") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (*it == "..") {
|
||||||
|
acc = acc.parent_path();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
acc /= *it;
|
||||||
|
auto meta = stat_lstat(acc);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists) {
|
||||||
|
// Append remaining lexical components for non-existent path checks.
|
||||||
|
++it;
|
||||||
|
for (; it != current.end(); ++it) {
|
||||||
|
acc /= *it;
|
||||||
|
}
|
||||||
|
current = acc.lexically_normal();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (meta->is_symlink) {
|
||||||
|
if (++hops > kMaxSymlinkHops || !seen.insert(acc).second) {
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("resolve_confined_path: symlink loop detected at '{}'",
|
||||||
|
acc.string()),
|
||||||
|
ELOOP)};
|
||||||
|
}
|
||||||
|
std::filesystem::path target_path{meta->symlink_target};
|
||||||
|
std::filesystem::path rebuilt =
|
||||||
|
target_path.is_absolute() ? target_path : (acc.parent_path() / target_path);
|
||||||
|
++it;
|
||||||
|
for (; it != current.end(); ++it) {
|
||||||
|
rebuilt /= *it;
|
||||||
|
}
|
||||||
|
current = rebuilt.lexically_normal();
|
||||||
|
followed_symlink = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!followed_symlink) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto &allowed_root : allowed) {
|
||||||
|
if (path_is_within(allowed_root, current)) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::SystemErrorCode::permission_denied,
|
||||||
|
std::format("resolve_confined_path: '{}' escapes declared roots (root='{}')",
|
||||||
|
candidate.string(), canonical_root.string()),
|
||||||
|
EACCES)};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Platform
|
||||||
@@ -0,0 +1,530 @@
|
|||||||
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||||
|
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <csignal>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <format>
|
||||||
|
#include <poll.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <sys/wait.h>
|
||||||
|
#include <thread>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
extern char **environ;
|
||||||
|
|
||||||
|
namespace Void::Build::Platform {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
struct ExecErrorPacket {
|
||||||
|
int err_no{0};
|
||||||
|
int stage{0}; // 1 = chdir, 2 = execve
|
||||||
|
};
|
||||||
|
|
||||||
|
bool is_executable_file(const std::filesystem::path &p) {
|
||||||
|
struct stat st{};
|
||||||
|
if (::stat(p.c_str(), &st) != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return S_ISREG(st.st_mode) && ::access(p.c_str(), X_OK) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void set_nonblocking(int fd) noexcept {
|
||||||
|
const int flags = ::fcntl(fd, F_GETFL, 0);
|
||||||
|
if (flags >= 0) {
|
||||||
|
(void)::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> build_env_strings(const ProcessEnvironment &policy) {
|
||||||
|
std::map<std::string, std::string, std::less<>> env_map;
|
||||||
|
if (policy.mode != EnvPolicyMode::ExplicitOnly && environ != nullptr) {
|
||||||
|
for (char **ep = environ; *ep != nullptr; ++ep) {
|
||||||
|
const std::string_view entry{*ep};
|
||||||
|
const auto eq = entry.find('=');
|
||||||
|
if (eq == std::string_view::npos) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto key = std::string{entry.substr(0, eq)};
|
||||||
|
if (policy.mode == EnvPolicyMode::Allowlist &&
|
||||||
|
!std::ranges::contains(policy.allowlist, key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
env_map[key] = std::string{entry.substr(eq + 1)};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &k : policy.unset_keys) {
|
||||||
|
env_map.erase(k);
|
||||||
|
}
|
||||||
|
for (const auto &[k, v] : policy.set_vars) {
|
||||||
|
env_map[k] = v;
|
||||||
|
}
|
||||||
|
std::vector<std::string> result;
|
||||||
|
result.reserve(env_map.size());
|
||||||
|
for (const auto &[k, v] : env_map) {
|
||||||
|
result.push_back(k + "=" + v);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool process_group_alive(pid_t pgid) noexcept {
|
||||||
|
if (pgid <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (::kill(-pgid, 0) == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return errno != ESRCH;
|
||||||
|
}
|
||||||
|
|
||||||
|
void reap_leader(pid_t pid, bool &reaped, int &raw_status, bool blocking) noexcept {
|
||||||
|
if (reaped || pid <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (;;) {
|
||||||
|
const pid_t r = ::waitpid(pid, &raw_status, blocking ? 0 : WNOHANG);
|
||||||
|
if (r == pid) {
|
||||||
|
reaped = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (r == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (errno == ECHILD) {
|
||||||
|
reaped = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Terminates the entire process group (-pgid) and waits until every descendant
|
||||||
|
// (even grandchildren whose group leader already exited) is gone.
|
||||||
|
void terminate_process_group(pid_t leader_pid, pid_t pgid, bool &leader_reaped, int &raw_status,
|
||||||
|
std::chrono::milliseconds grace) noexcept {
|
||||||
|
if (pgid <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const auto effective_grace = grace.count() >= 0 ? grace : std::chrono::milliseconds{200};
|
||||||
|
(void)::kill(-pgid, SIGTERM);
|
||||||
|
|
||||||
|
const auto deadline = std::chrono::steady_clock::now() + effective_grace;
|
||||||
|
while (std::chrono::steady_clock::now() < deadline) {
|
||||||
|
reap_leader(leader_pid, leader_reaped, raw_status, false);
|
||||||
|
if (leader_reaped && !process_group_alive(pgid)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Escalate to SIGKILL on the entire process group and verify full disappearance.
|
||||||
|
(void)::kill(-pgid, SIGKILL);
|
||||||
|
reap_leader(leader_pid, leader_reaped, raw_status, true);
|
||||||
|
|
||||||
|
const auto kill_deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5};
|
||||||
|
while (process_group_alive(pgid) && std::chrono::steady_clock::now() < kill_deadline) {
|
||||||
|
(void)::kill(-pgid, SIGKILL);
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::optional<std::filesystem::path>
|
||||||
|
resolve_executable(const std::filesystem::path &executable,
|
||||||
|
std::optional<std::string_view> path_override) {
|
||||||
|
if (executable.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (executable.is_absolute() || executable.string().find('/') != std::string::npos) {
|
||||||
|
std::error_code ec;
|
||||||
|
const auto abs = std::filesystem::absolute(executable, ec);
|
||||||
|
if (!ec && is_executable_file(abs)) {
|
||||||
|
return abs.lexically_normal();
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
std::string_view path_env;
|
||||||
|
if (path_override) {
|
||||||
|
path_env = *path_override;
|
||||||
|
} else if (const char *env_val = std::getenv("PATH")) {
|
||||||
|
path_env = env_val;
|
||||||
|
}
|
||||||
|
std::size_t start = 0;
|
||||||
|
while (start <= path_env.size()) {
|
||||||
|
const auto colon = path_env.find(':', start);
|
||||||
|
const auto segment = path_env.substr(
|
||||||
|
start, colon == std::string_view::npos ? std::string_view::npos : colon - start);
|
||||||
|
const std::filesystem::path dir =
|
||||||
|
segment.empty() ? std::filesystem::path{"."} : std::filesystem::path{segment};
|
||||||
|
const auto candidate = dir / executable;
|
||||||
|
if (is_executable_file(candidate)) {
|
||||||
|
std::error_code ec;
|
||||||
|
auto abs = std::filesystem::absolute(candidate, ec);
|
||||||
|
return ec ? candidate : abs.lexically_normal();
|
||||||
|
}
|
||||||
|
if (colon == std::string_view::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
start = colon + 1;
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ProcessResult, Void::Result::Error>
|
||||||
|
run_supervised(const ProcessRequest &request, std::stop_token stop) {
|
||||||
|
if (request.executable.empty()) {
|
||||||
|
return std::unexpected{
|
||||||
|
Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
"run_supervised: executable path must not be empty")};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto env_strings = build_env_strings(request.environment);
|
||||||
|
std::optional<std::string_view> child_path;
|
||||||
|
for (const auto &entry : env_strings) {
|
||||||
|
if (entry.starts_with("PATH=")) {
|
||||||
|
child_path = std::string_view{entry}.substr(5);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path resolved_exec = request.executable;
|
||||||
|
if (request.search_path) {
|
||||||
|
if (auto found = resolve_executable(request.executable, child_path)) {
|
||||||
|
resolved_exec = std::move(*found);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int stdin_pipe[2]{-1, -1};
|
||||||
|
int stdout_pipe[2]{-1, -1};
|
||||||
|
int stderr_pipe[2]{-1, -1};
|
||||||
|
int err_pipe[2]{-1, -1};
|
||||||
|
|
||||||
|
auto close_pair = [](int p[2]) {
|
||||||
|
if (p[0] >= 0) {
|
||||||
|
(void)::close(p[0]);
|
||||||
|
p[0] = -1;
|
||||||
|
}
|
||||||
|
if (p[1] >= 0) {
|
||||||
|
(void)::close(p[1]);
|
||||||
|
p[1] = -1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (::pipe2(stdin_pipe, O_CLOEXEC) != 0 || ::pipe2(stdout_pipe, O_CLOEXEC) != 0 ||
|
||||||
|
::pipe2(stderr_pipe, O_CLOEXEC) != 0 || ::pipe2(err_pipe, O_CLOEXEC) != 0) {
|
||||||
|
const int err = errno;
|
||||||
|
close_pair(stdin_pipe);
|
||||||
|
close_pair(stdout_pipe);
|
||||||
|
close_pair(stderr_pipe);
|
||||||
|
close_pair(err_pipe);
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::map_errno_to_system_code(err), "run_supervised: pipe2 failed", err)};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> argv_storage;
|
||||||
|
argv_storage.reserve(request.arguments.size() + 1);
|
||||||
|
argv_storage.push_back(resolved_exec.string());
|
||||||
|
for (const auto &arg : request.arguments) {
|
||||||
|
argv_storage.push_back(arg);
|
||||||
|
}
|
||||||
|
std::vector<char *> argv_ptrs;
|
||||||
|
argv_ptrs.reserve(argv_storage.size() + 1);
|
||||||
|
for (auto &s : argv_storage) {
|
||||||
|
argv_ptrs.push_back(s.data());
|
||||||
|
}
|
||||||
|
argv_ptrs.push_back(nullptr);
|
||||||
|
|
||||||
|
std::vector<char *> envp_ptrs;
|
||||||
|
envp_ptrs.reserve(env_strings.size() + 1);
|
||||||
|
for (auto &s : env_strings) {
|
||||||
|
envp_ptrs.push_back(s.data());
|
||||||
|
}
|
||||||
|
envp_ptrs.push_back(nullptr);
|
||||||
|
|
||||||
|
const std::string exec_str = resolved_exec.string();
|
||||||
|
const std::string cwd_str =
|
||||||
|
request.working_directory ? request.working_directory->string() : std::string{};
|
||||||
|
|
||||||
|
const pid_t pid = ::fork();
|
||||||
|
if (pid < 0) {
|
||||||
|
const int err = errno;
|
||||||
|
close_pair(stdin_pipe);
|
||||||
|
close_pair(stdout_pipe);
|
||||||
|
close_pair(stderr_pipe);
|
||||||
|
close_pair(err_pipe);
|
||||||
|
return std::unexpected{Void::System::make_system_error(
|
||||||
|
Void::System::map_errno_to_system_code(err), "run_supervised: fork failed", err)};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pid == 0) {
|
||||||
|
// Child: place into its own process group.
|
||||||
|
(void)::setpgid(0, 0);
|
||||||
|
// Reset signals to defaults.
|
||||||
|
::signal(SIGINT, SIG_DFL);
|
||||||
|
::signal(SIGTERM, SIG_DFL);
|
||||||
|
::signal(SIGPIPE, SIG_DFL);
|
||||||
|
|
||||||
|
(void)::dup2(stdin_pipe[0], STDIN_FILENO);
|
||||||
|
(void)::dup2(stdout_pipe[1], STDOUT_FILENO);
|
||||||
|
(void)::dup2(stderr_pipe[1], STDERR_FILENO);
|
||||||
|
|
||||||
|
close_pair(stdin_pipe);
|
||||||
|
close_pair(stdout_pipe);
|
||||||
|
close_pair(stderr_pipe);
|
||||||
|
(void)::close(err_pipe[0]);
|
||||||
|
|
||||||
|
if (!cwd_str.empty() && ::chdir(cwd_str.c_str()) != 0) {
|
||||||
|
ExecErrorPacket pkt{errno, 1};
|
||||||
|
(void)::write(err_pipe[1], &pkt, sizeof(pkt));
|
||||||
|
::_exit(127);
|
||||||
|
}
|
||||||
|
|
||||||
|
::execve(exec_str.c_str(), argv_ptrs.data(), envp_ptrs.data());
|
||||||
|
ExecErrorPacket pkt{errno, 2};
|
||||||
|
(void)::write(err_pipe[1], &pkt, sizeof(pkt));
|
||||||
|
::_exit(127);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parent: ensure pgid is established to avoid race with child setpgid.
|
||||||
|
(void)::setpgid(pid, pid);
|
||||||
|
const pid_t pgid = pid;
|
||||||
|
|
||||||
|
(void)::close(stdin_pipe[0]);
|
||||||
|
(void)::close(stdout_pipe[1]);
|
||||||
|
(void)::close(stderr_pipe[1]);
|
||||||
|
(void)::close(err_pipe[1]);
|
||||||
|
|
||||||
|
int in_fd = stdin_pipe[1];
|
||||||
|
int out_fd = stdout_pipe[0];
|
||||||
|
int err_fd = stderr_pipe[0];
|
||||||
|
int exec_err_fd = err_pipe[0];
|
||||||
|
|
||||||
|
set_nonblocking(in_fd);
|
||||||
|
set_nonblocking(out_fd);
|
||||||
|
set_nonblocking(err_fd);
|
||||||
|
|
||||||
|
if (request.stdin_data.empty()) {
|
||||||
|
(void)::close(in_fd);
|
||||||
|
in_fd = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read exec error pipe first (blocking is fine because child closes on exec or writes & exits).
|
||||||
|
ExecErrorPacket exec_pkt{};
|
||||||
|
ssize_t exec_read = 0;
|
||||||
|
while (exec_read < static_cast<ssize_t>(sizeof(exec_pkt))) {
|
||||||
|
const ssize_t n = ::read(exec_err_fd, reinterpret_cast<char *>(&exec_pkt) + exec_read,
|
||||||
|
sizeof(exec_pkt) - static_cast<std::size_t>(exec_read));
|
||||||
|
if (n > 0) {
|
||||||
|
exec_read += n;
|
||||||
|
} else if (n == 0) {
|
||||||
|
break;
|
||||||
|
} else if (errno != EINTR) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(void)::close(exec_err_fd);
|
||||||
|
|
||||||
|
ProcessResult result;
|
||||||
|
bool leader_reaped = false;
|
||||||
|
int raw_status = 0;
|
||||||
|
|
||||||
|
if (exec_read == static_cast<ssize_t>(sizeof(exec_pkt)) && exec_pkt.err_no != 0) {
|
||||||
|
if (in_fd >= 0) {
|
||||||
|
(void)::close(in_fd);
|
||||||
|
}
|
||||||
|
(void)::close(out_fd);
|
||||||
|
(void)::close(err_fd);
|
||||||
|
reap_leader(pid, leader_reaped, raw_status, true);
|
||||||
|
result.exec_failed = true;
|
||||||
|
result.exec_errno = exec_pkt.err_no;
|
||||||
|
result.exec_error_message =
|
||||||
|
exec_pkt.stage == 1
|
||||||
|
? std::format("chdir('{}') failed: {}", cwd_str, std::strerror(exec_pkt.err_no))
|
||||||
|
: std::format("execve('{}') failed: {}", exec_str, std::strerror(exec_pkt.err_no));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t stdin_offset = 0;
|
||||||
|
const auto start_time = std::chrono::steady_clock::now();
|
||||||
|
const bool has_timeout = request.timeout.count() > 0;
|
||||||
|
const auto deadline = start_time + request.timeout;
|
||||||
|
|
||||||
|
std::array<char, 16384> buf{};
|
||||||
|
|
||||||
|
while (in_fd >= 0 || out_fd >= 0 || err_fd >= 0) {
|
||||||
|
if (stop.stop_requested()) {
|
||||||
|
result.cancelled = true;
|
||||||
|
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (has_timeout && std::chrono::steady_clock::now() >= deadline) {
|
||||||
|
result.timed_out = true;
|
||||||
|
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct pollfd fds[3];
|
||||||
|
int nfds = 0;
|
||||||
|
int in_idx = -1;
|
||||||
|
int out_idx = -1;
|
||||||
|
int err_idx = -1;
|
||||||
|
if (in_fd >= 0) {
|
||||||
|
in_idx = nfds;
|
||||||
|
fds[nfds++] = {in_fd, POLLOUT, 0};
|
||||||
|
}
|
||||||
|
if (out_fd >= 0) {
|
||||||
|
out_idx = nfds;
|
||||||
|
fds[nfds++] = {out_fd, POLLIN, 0};
|
||||||
|
}
|
||||||
|
if (err_fd >= 0) {
|
||||||
|
err_idx = nfds;
|
||||||
|
fds[nfds++] = {err_fd, POLLIN, 0};
|
||||||
|
}
|
||||||
|
|
||||||
|
int poll_ms = 25;
|
||||||
|
if (has_timeout) {
|
||||||
|
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
|
deadline - std::chrono::steady_clock::now());
|
||||||
|
poll_ms = static_cast<int>(std::clamp<long long>(rem.count(), 1, 25));
|
||||||
|
}
|
||||||
|
|
||||||
|
const int ready = ::poll(fds, static_cast<nfds_t>(nfds), poll_ms);
|
||||||
|
if (ready < 0) {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (ready == 0) {
|
||||||
|
reap_leader(pid, leader_reaped, raw_status, false);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_idx >= 0 && (fds[in_idx].revents & (POLLOUT | POLLERR | POLLHUP))) {
|
||||||
|
const ssize_t w = ::write(in_fd, request.stdin_data.data() + stdin_offset,
|
||||||
|
request.stdin_data.size() - stdin_offset);
|
||||||
|
if (w > 0) {
|
||||||
|
stdin_offset += static_cast<std::size_t>(w);
|
||||||
|
if (stdin_offset >= request.stdin_data.size()) {
|
||||||
|
(void)::close(in_fd);
|
||||||
|
in_fd = -1;
|
||||||
|
}
|
||||||
|
} else if (w < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
|
||||||
|
(void)::close(in_fd);
|
||||||
|
in_fd = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto drain_stream = [&](int &fd, std::string &target, std::size_t limit, bool &truncated,
|
||||||
|
const std::function<void(std::string_view)> &cb) {
|
||||||
|
for (;;) {
|
||||||
|
const ssize_t n = ::read(fd, buf.data(), buf.size());
|
||||||
|
if (n > 0) {
|
||||||
|
const std::string_view chunk{buf.data(), static_cast<std::size_t>(n)};
|
||||||
|
if (cb) {
|
||||||
|
cb(chunk);
|
||||||
|
}
|
||||||
|
if (target.size() < limit) {
|
||||||
|
const std::size_t take = std::min(chunk.size(), limit - target.size());
|
||||||
|
target.append(chunk.data(), take);
|
||||||
|
if (take < chunk.size()) {
|
||||||
|
truncated = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
truncated = true;
|
||||||
|
}
|
||||||
|
if (truncated && request.fail_on_overflow) {
|
||||||
|
result.overflowed = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (n == 0) {
|
||||||
|
(void)::close(fd);
|
||||||
|
fd = -1;
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
if (errno == EINTR) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
(void)::close(fd);
|
||||||
|
fd = -1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (out_idx >= 0 && (fds[out_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
|
||||||
|
drain_stream(out_fd, result.stdout_data, request.max_stdout_bytes,
|
||||||
|
result.stdout_truncated, request.on_stdout_chunk);
|
||||||
|
}
|
||||||
|
if (err_idx >= 0 && (fds[err_idx].revents & (POLLIN | POLLHUP | POLLERR))) {
|
||||||
|
drain_stream(err_fd, result.stderr_data, request.max_stderr_bytes,
|
||||||
|
result.stderr_truncated, request.on_stderr_chunk);
|
||||||
|
}
|
||||||
|
if (result.overflowed) {
|
||||||
|
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_fd >= 0) {
|
||||||
|
(void)::close(in_fd);
|
||||||
|
}
|
||||||
|
if (out_fd >= 0) {
|
||||||
|
(void)::close(out_fd);
|
||||||
|
}
|
||||||
|
if (err_fd >= 0) {
|
||||||
|
(void)::close(err_fd);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for leader AND any remaining process-group descendants, polling for stop/timeout.
|
||||||
|
while (!leader_reaped || process_group_alive(pgid)) {
|
||||||
|
reap_leader(pid, leader_reaped, raw_status, false);
|
||||||
|
if (leader_reaped && !process_group_alive(pgid)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (stop.stop_requested()) {
|
||||||
|
result.cancelled = true;
|
||||||
|
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (has_timeout && std::chrono::steady_clock::now() >= deadline) {
|
||||||
|
result.timed_out = true;
|
||||||
|
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Even if the leader exited cleanly or early, ensure no stray process-group
|
||||||
|
// descendants remain alive if we were cancelled/timed out/overflowed, or wait/clean them up.
|
||||||
|
if (result.cancelled || result.timed_out || result.overflowed) {
|
||||||
|
if (process_group_alive(pgid)) {
|
||||||
|
terminate_process_group(pid, pgid, leader_reaped, raw_status, request.kill_grace);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (leader_reaped) {
|
||||||
|
if (WIFEXITED(raw_status)) {
|
||||||
|
result.exited = true;
|
||||||
|
result.exit_code = WEXITSTATUS(raw_status);
|
||||||
|
} else if (WIFSIGNALED(raw_status)) {
|
||||||
|
result.exited = false;
|
||||||
|
result.term_signal = WTERMSIG(raw_status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Platform
|
||||||
@@ -0,0 +1,773 @@
|
|||||||
|
#include <Void/Build/Provider/Provider.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <format>
|
||||||
|
#include <set>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
namespace Void::Build::Provider {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using JsonVal = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
|
||||||
|
return Void::System::make_system_error(code, std::move(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto it = obj.find(k);
|
||||||
|
return it == obj.end() ? nullptr : &it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&v->value);
|
||||||
|
return s ? *s : std::string{};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
const auto *b = std::get_if<bool>(&v->value);
|
||||||
|
return b ? *b : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::string &k) {
|
||||||
|
std::vector<std::string> out;
|
||||||
|
const auto *v = find_key(obj, k);
|
||||||
|
if (!v) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (const auto *arr = std::get_if<JsonVal::Array>(&v->value)) {
|
||||||
|
for (const auto &item : *arr) {
|
||||||
|
if (const auto *s = std::get_if<std::string>(&item.value)) {
|
||||||
|
out.push_back(*s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<JsonVal> parse_json_file(const std::filesystem::path &path) {
|
||||||
|
auto text = Void::FileSystem::read_file(path);
|
||||||
|
if (!text) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return std::move(*parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_export(const ProviderExport &exp) {
|
||||||
|
using Util::json_array;
|
||||||
|
using Util::json_quote;
|
||||||
|
|
||||||
|
std::string out =
|
||||||
|
"{\"schema_version\":1,\"dependency_name\":" + json_quote(exp.dependency_name) +
|
||||||
|
",\"builder\":" + json_quote(exp.builder) +
|
||||||
|
",\"input_identity_hash\":" + json_quote(exp.input_identity_hash) + ",\"targets\":{";
|
||||||
|
bool first = true;
|
||||||
|
for (const auto &[tname, iface] : exp.targets) {
|
||||||
|
if (!first) {
|
||||||
|
out += ',';
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
out += json_quote(tname) + ":{\"dependency_name\":" + json_quote(iface.dependency_name) +
|
||||||
|
",\"target_name\":" + json_quote(iface.target_name) + ",\"include_dirs\":" +
|
||||||
|
json_array(iface.include_dirs,
|
||||||
|
[](const std::pair<std::filesystem::path, bool> &inc) {
|
||||||
|
return "{\"path\":" + json_quote(inc.first.string()) +
|
||||||
|
",\"is_system\":" +
|
||||||
|
std::string{inc.second ? "true" : "false"} + '}';
|
||||||
|
}) +
|
||||||
|
",\"defines\":" + json_array(iface.defines, json_quote) +
|
||||||
|
",\"compile_options\":" + json_array(iface.compile_options, json_quote) +
|
||||||
|
",\"link_options\":" + json_array(iface.link_options, json_quote) +
|
||||||
|
",\"static_libraries\":" +
|
||||||
|
json_array(iface.static_libraries,
|
||||||
|
[](const std::filesystem::path &p) { return json_quote(p.string()); }) +
|
||||||
|
",\"shared_libraries\":" +
|
||||||
|
json_array(iface.shared_libraries,
|
||||||
|
[](const std::filesystem::path &p) { return json_quote(p.string()); }) +
|
||||||
|
",\"runtime_files\":" +
|
||||||
|
json_array(iface.runtime_files,
|
||||||
|
[](const std::filesystem::path &p) { return json_quote(p.string()); }) +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
out += "}}\n";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ProviderExport> load_cached_export(const std::filesystem::path &export_file,
|
||||||
|
std::string_view expected_hash) {
|
||||||
|
auto text = Void::FileSystem::read_file(export_file);
|
||||||
|
if (!text) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!root) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (get_str(*root, "input_identity_hash") != expected_hash) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
ProviderExport exp;
|
||||||
|
exp.dependency_name = get_str(*root, "dependency_name");
|
||||||
|
exp.builder = get_str(*root, "builder");
|
||||||
|
exp.input_identity_hash = std::string{expected_hash};
|
||||||
|
exp.from_cache = true;
|
||||||
|
|
||||||
|
if (const auto *tv = find_key(*root, "targets")) {
|
||||||
|
if (const auto *tobj = std::get_if<JsonVal::Object>(&tv->value)) {
|
||||||
|
for (const auto &[k, val] : *tobj) {
|
||||||
|
const auto *io = std::get_if<JsonVal::Object>(&val.value);
|
||||||
|
if (!io) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Graph::ImportedTargetInterface iface;
|
||||||
|
iface.dependency_name = get_str(*io, "dependency_name");
|
||||||
|
iface.target_name = get_str(*io, "target_name");
|
||||||
|
if (const auto *iv = find_key(*io, "include_dirs")) {
|
||||||
|
if (const auto *iarr = std::get_if<JsonVal::Array>(&iv->value)) {
|
||||||
|
for (const auto &item : *iarr) {
|
||||||
|
if (const auto *inc = std::get_if<JsonVal::Object>(&item.value)) {
|
||||||
|
iface.include_dirs.emplace_back(get_str(*inc, "path"),
|
||||||
|
get_bool(*inc, "is_system", false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
iface.defines = get_str_array(*io, "defines");
|
||||||
|
iface.compile_options = get_str_array(*io, "compile_options");
|
||||||
|
iface.link_options = get_str_array(*io, "link_options");
|
||||||
|
for (const auto &s : get_str_array(*io, "static_libraries")) {
|
||||||
|
iface.static_libraries.emplace_back(s);
|
||||||
|
}
|
||||||
|
for (const auto &s : get_str_array(*io, "shared_libraries")) {
|
||||||
|
iface.shared_libraries.emplace_back(s);
|
||||||
|
}
|
||||||
|
for (const auto &s : get_str_array(*io, "runtime_files")) {
|
||||||
|
iface.runtime_files.emplace_back(s);
|
||||||
|
}
|
||||||
|
// Verify materialized library artifacts still exist on disk!
|
||||||
|
std::error_code ec;
|
||||||
|
for (const auto &lib : iface.static_libraries) {
|
||||||
|
if (!std::filesystem::is_regular_file(lib, ec)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &lib : iface.shared_libraries) {
|
||||||
|
if (!std::filesystem::is_regular_file(lib, ec)) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exp.targets[k] = std::move(iface);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return exp;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string cmake_option_value(const OptionValue &v) {
|
||||||
|
return std::visit(
|
||||||
|
[](const auto &inner) -> std::string {
|
||||||
|
using T = std::remove_cvref_t<decltype(inner)>;
|
||||||
|
if constexpr (std::same_as<T, std::string>) {
|
||||||
|
return inner;
|
||||||
|
} else if constexpr (std::same_as<T, bool>) {
|
||||||
|
return inner ? "ON" : "OFF";
|
||||||
|
} else {
|
||||||
|
return std::to_string(inner);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
v.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string meson_option_value(const OptionValue &v) {
|
||||||
|
return std::visit(
|
||||||
|
[](const auto &inner) -> std::string {
|
||||||
|
using T = std::remove_cvref_t<decltype(inner)>;
|
||||||
|
if constexpr (std::same_as<T, std::string>) {
|
||||||
|
return inner;
|
||||||
|
} else if constexpr (std::same_as<T, bool>) {
|
||||||
|
return inner ? "true" : "false";
|
||||||
|
} else {
|
||||||
|
return std::to_string(inner);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
v.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Imports CMake File API reply (index-*.json -> codemodel-v2 -> target-*.json).
|
||||||
|
Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||||
|
run_cmake_provider(const ProviderRequest &request, const std::filesystem::path &build_dir,
|
||||||
|
const std::string &input_hash, std::stop_token stop) {
|
||||||
|
auto cmake_bin = Platform::resolve_executable("cmake");
|
||||||
|
if (!cmake_bin) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
|
||||||
|
"CMake provider requires 'cmake' in PATH")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
// Fresh build dir whenever input hash changed so foreign timestamp shortcuts cannot retain
|
||||||
|
// stale objects (Plan 13 acceptance #3).
|
||||||
|
std::filesystem::remove_all(build_dir, ec);
|
||||||
|
std::filesystem::create_directories(build_dir / ".cmake" / "api" / "v1" / "query", ec);
|
||||||
|
(void)Platform::atomic_write_file(
|
||||||
|
build_dir / ".cmake" / "api" / "v1" / "query" / "codemodel-v2", "", false);
|
||||||
|
|
||||||
|
// 1. Configure with isolated profile/toolchain context.
|
||||||
|
{
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *cmake_bin;
|
||||||
|
req.arguments = {"-S", request.source.source_dir.string(), "-B", build_dir.string()};
|
||||||
|
if (Platform::resolve_executable("ninja").has_value()) {
|
||||||
|
req.arguments.push_back("-G");
|
||||||
|
req.arguments.push_back("Ninja");
|
||||||
|
}
|
||||||
|
req.arguments.push_back("-DCMAKE_CXX_COMPILER=" + request.toolchain.cxx_compiler.string());
|
||||||
|
const std::string cfg =
|
||||||
|
(request.profile.name == "release" || request.profile.name == "Release") ? "Release"
|
||||||
|
: "Debug";
|
||||||
|
req.arguments.push_back("-DCMAKE_BUILD_TYPE=" + cfg);
|
||||||
|
for (const auto &[k, v] : request.dependency.options) {
|
||||||
|
req.arguments.push_back("-D" + k + "=" + cmake_option_value(v));
|
||||||
|
}
|
||||||
|
req.timeout = std::chrono::seconds{180};
|
||||||
|
auto proc = Platform::run_supervised(req, stop);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("CMake configure failed for '{}':\n{}", request.dependency.name,
|
||||||
|
proc ? (proc->stderr_data + proc->stdout_data)
|
||||||
|
: proc.error().message()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Build all targets in isolated build directory.
|
||||||
|
{
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *cmake_bin;
|
||||||
|
req.arguments = {"--build", build_dir.string()};
|
||||||
|
req.timeout = std::chrono::seconds{300};
|
||||||
|
auto proc = Platform::run_supervised(req, stop);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("CMake build failed for '{}':\n{}", request.dependency.name,
|
||||||
|
proc ? (proc->stderr_data + proc->stdout_data)
|
||||||
|
: proc.error().message()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Parse CMake File API reply -> codemodel-v2 -> per-target metadata.
|
||||||
|
const auto reply_dir = build_dir / ".cmake" / "api" / "v1" / "reply";
|
||||||
|
std::filesystem::path index_file;
|
||||||
|
for (const auto &ent : std::filesystem::directory_iterator(reply_dir, ec)) {
|
||||||
|
if (ent.is_regular_file() && ent.path().filename().string().starts_with("index-")) {
|
||||||
|
index_file = ent.path();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (index_file.empty()) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("CMake File API reply missing for '{}'", request.dependency.name))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto index_json = parse_json_file(index_file);
|
||||||
|
if (!index_json) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"failed parsing CMake File API index JSON")};
|
||||||
|
}
|
||||||
|
const auto *idx_obj = std::get_if<JsonVal::Object>(&index_json->value);
|
||||||
|
std::string codemodel_file;
|
||||||
|
if (idx_obj) {
|
||||||
|
if (const auto *objs = find_key(*idx_obj, "objects")) {
|
||||||
|
if (const auto *arr = std::get_if<JsonVal::Array>(&objs->value)) {
|
||||||
|
for (const auto &item : *arr) {
|
||||||
|
if (const auto *o = std::get_if<JsonVal::Object>(&item.value)) {
|
||||||
|
if (get_str(*o, "kind") == "codemodel") {
|
||||||
|
codemodel_file = get_str(*o, "jsonFile");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (codemodel_file.empty()) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"CMake File API index missing codemodel object")};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto cm_json = parse_json_file(reply_dir / codemodel_file);
|
||||||
|
if (!cm_json) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"failed parsing CMake codemodel JSON")};
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RawTarget {
|
||||||
|
std::string id;
|
||||||
|
std::string name;
|
||||||
|
std::string type;
|
||||||
|
std::vector<std::string> dep_ids;
|
||||||
|
Graph::ImportedTargetInterface iface;
|
||||||
|
};
|
||||||
|
std::map<std::string, RawTarget, std::less<>> raw_by_id;
|
||||||
|
|
||||||
|
if (const auto *cm_obj = std::get_if<JsonVal::Object>(&cm_json->value)) {
|
||||||
|
if (const auto *cfgs = find_key(*cm_obj, "configurations")) {
|
||||||
|
if (const auto *carr = std::get_if<JsonVal::Array>(&cfgs->value);
|
||||||
|
carr && !carr->empty()) {
|
||||||
|
if (const auto *cfg0 = std::get_if<JsonVal::Object>(&carr->front().value)) {
|
||||||
|
if (const auto *tgts = find_key(*cfg0, "targets")) {
|
||||||
|
if (const auto *tarr = std::get_if<JsonVal::Array>(&tgts->value)) {
|
||||||
|
for (const auto &tv : *tarr) {
|
||||||
|
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
|
||||||
|
if (!to) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto tfile = get_str(*to, "jsonFile");
|
||||||
|
auto tjson = parse_json_file(reply_dir / tfile);
|
||||||
|
if (!tjson) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto *td = std::get_if<JsonVal::Object>(&tjson->value);
|
||||||
|
if (!td) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
RawTarget rt;
|
||||||
|
rt.id = get_str(*td, "id");
|
||||||
|
rt.name = get_str(*td, "name");
|
||||||
|
rt.type = get_str(*td, "type");
|
||||||
|
rt.iface.dependency_name = request.dependency.name;
|
||||||
|
rt.iface.target_name = rt.name;
|
||||||
|
|
||||||
|
// Extract artifacts.
|
||||||
|
if (const auto *arts = find_key(*td, "artifacts")) {
|
||||||
|
if (const auto *aarr =
|
||||||
|
std::get_if<JsonVal::Array>(&arts->value)) {
|
||||||
|
for (const auto &av : *aarr) {
|
||||||
|
if (const auto *ao =
|
||||||
|
std::get_if<JsonVal::Object>(&av.value)) {
|
||||||
|
const auto p = build_dir / get_str(*ao, "path");
|
||||||
|
if (rt.type == "STATIC_LIBRARY") {
|
||||||
|
rt.iface.static_libraries.push_back(p);
|
||||||
|
} else if (rt.type == "SHARED_LIBRARY") {
|
||||||
|
rt.iface.shared_libraries.push_back(p);
|
||||||
|
rt.iface.runtime_files.push_back(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract compile groups (includes, defines).
|
||||||
|
if (const auto *cgs = find_key(*td, "compileGroups")) {
|
||||||
|
if (const auto *cgarr =
|
||||||
|
std::get_if<JsonVal::Array>(&cgs->value)) {
|
||||||
|
for (const auto &cgv : *cgarr) {
|
||||||
|
const auto *cgo =
|
||||||
|
std::get_if<JsonVal::Object>(&cgv.value);
|
||||||
|
if (!cgo) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (const auto *incs = find_key(*cgo, "includes")) {
|
||||||
|
if (const auto *iarr =
|
||||||
|
std::get_if<JsonVal::Array>(&incs->value)) {
|
||||||
|
for (const auto &iv : *iarr) {
|
||||||
|
if (const auto *io =
|
||||||
|
std::get_if<JsonVal::Object>(
|
||||||
|
&iv.value)) {
|
||||||
|
const std::filesystem::path ip{
|
||||||
|
get_str(*io, "path")};
|
||||||
|
const bool sys =
|
||||||
|
get_bool(*io, "isSystem", false);
|
||||||
|
if (!std::ranges::contains(
|
||||||
|
rt.iface.include_dirs,
|
||||||
|
std::pair{ip, sys})) {
|
||||||
|
rt.iface.include_dirs.emplace_back(
|
||||||
|
ip, sys);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (const auto *defs = find_key(*cgo, "defines")) {
|
||||||
|
if (const auto *darr =
|
||||||
|
std::get_if<JsonVal::Array>(&defs->value)) {
|
||||||
|
for (const auto &dv : *darr) {
|
||||||
|
if (const auto *do_obj =
|
||||||
|
std::get_if<JsonVal::Object>(
|
||||||
|
&dv.value)) {
|
||||||
|
const auto d =
|
||||||
|
get_str(*do_obj, "define");
|
||||||
|
if (!d.empty() &&
|
||||||
|
!std::ranges::contains(
|
||||||
|
rt.iface.defines, d)) {
|
||||||
|
rt.iface.defines.push_back(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract dependencies for transitive static archive ordering.
|
||||||
|
if (const auto *deps = find_key(*td, "dependencies")) {
|
||||||
|
if (const auto *darr =
|
||||||
|
std::get_if<JsonVal::Array>(&deps->value)) {
|
||||||
|
for (const auto &dv : *darr) {
|
||||||
|
if (const auto *do_obj =
|
||||||
|
std::get_if<JsonVal::Object>(&dv.value)) {
|
||||||
|
rt.dep_ids.push_back(get_str(*do_obj, "id"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
raw_by_id[rt.id] = std::move(rt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve transitive static library link order across CMake targets.
|
||||||
|
ProviderExport exp;
|
||||||
|
exp.dependency_name = request.dependency.name;
|
||||||
|
exp.builder = "cmake";
|
||||||
|
exp.input_identity_hash = input_hash;
|
||||||
|
|
||||||
|
for (const auto &[id, rt] : raw_by_id) {
|
||||||
|
Graph::ImportedTargetInterface resolved = rt.iface;
|
||||||
|
std::set<std::string> visited{id};
|
||||||
|
std::vector<std::string> queue = rt.dep_ids;
|
||||||
|
for (std::size_t qi = 0; qi < queue.size(); ++qi) {
|
||||||
|
const auto &dep_id = queue[qi];
|
||||||
|
if (!visited.insert(dep_id).second) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto dit = raw_by_id.find(dep_id);
|
||||||
|
if (dit == raw_by_id.end()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const auto &lib : dit->second.iface.static_libraries) {
|
||||||
|
resolved.static_libraries.push_back(lib);
|
||||||
|
}
|
||||||
|
for (const auto &lib : dit->second.iface.shared_libraries) {
|
||||||
|
resolved.shared_libraries.push_back(lib);
|
||||||
|
}
|
||||||
|
for (const auto &inc : dit->second.iface.include_dirs) {
|
||||||
|
if (!std::ranges::contains(resolved.include_dirs, inc)) {
|
||||||
|
resolved.include_dirs.push_back(inc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &sub : dit->second.dep_ids) {
|
||||||
|
queue.push_back(sub);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exp.targets[rt.name] = resolved;
|
||||||
|
exp.targets[request.dependency.name + "::" + rt.name] = resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply explicit user overrides if supplied.
|
||||||
|
for (const auto &[k, v] : request.explicit_overrides) {
|
||||||
|
exp.targets[k] = v;
|
||||||
|
}
|
||||||
|
return exp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Imports Meson introspection metadata (`meson-info/intro-targets.json`).
|
||||||
|
Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||||
|
run_meson_provider(const ProviderRequest &request, const std::filesystem::path &build_dir,
|
||||||
|
const std::string &input_hash, std::stop_token stop) {
|
||||||
|
auto meson_bin = Platform::resolve_executable("meson");
|
||||||
|
if (!meson_bin) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
|
||||||
|
"Meson provider requires 'meson' in PATH")};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::remove_all(build_dir, ec);
|
||||||
|
std::filesystem::create_directories(build_dir.parent_path(), ec);
|
||||||
|
|
||||||
|
{
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *meson_bin;
|
||||||
|
req.arguments = {"setup", build_dir.string(), request.source.source_dir.string()};
|
||||||
|
const std::string btype =
|
||||||
|
(request.profile.name == "release" || request.profile.name == "Release") ? "release"
|
||||||
|
: "debug";
|
||||||
|
req.arguments.push_back("-Dbuildtype=" + btype);
|
||||||
|
for (const auto &[k, v] : request.dependency.options) {
|
||||||
|
req.arguments.push_back("-D" + k + "=" + meson_option_value(v));
|
||||||
|
}
|
||||||
|
req.environment.set_vars["CXX"] = request.toolchain.cxx_compiler.string();
|
||||||
|
req.timeout = std::chrono::seconds{180};
|
||||||
|
auto proc = Platform::run_supervised(req, stop);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("Meson setup failed for '{}':\n{}", request.dependency.name,
|
||||||
|
proc ? (proc->stderr_data + proc->stdout_data)
|
||||||
|
: proc.error().message()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *meson_bin;
|
||||||
|
req.arguments = {"compile", "-C", build_dir.string()};
|
||||||
|
req.timeout = std::chrono::seconds{300};
|
||||||
|
auto proc = Platform::run_supervised(req, stop);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("Meson compile failed for '{}':\n{}", request.dependency.name,
|
||||||
|
proc ? (proc->stderr_data + proc->stdout_data)
|
||||||
|
: proc.error().message()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto intro_targets = build_dir / "meson-info" / "intro-targets.json";
|
||||||
|
auto parsed = parse_json_file(intro_targets);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"failed parsing Meson intro-targets.json")};
|
||||||
|
}
|
||||||
|
|
||||||
|
ProviderExport exp;
|
||||||
|
exp.dependency_name = request.dependency.name;
|
||||||
|
exp.builder = "meson";
|
||||||
|
exp.input_identity_hash = input_hash;
|
||||||
|
|
||||||
|
if (const auto *arr = std::get_if<JsonVal::Array>(&parsed->value)) {
|
||||||
|
for (const auto &tv : *arr) {
|
||||||
|
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
|
||||||
|
if (!to) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto tname = get_str(*to, "name");
|
||||||
|
const auto ttype = get_str(*to, "type");
|
||||||
|
Graph::ImportedTargetInterface iface;
|
||||||
|
iface.dependency_name = request.dependency.name;
|
||||||
|
iface.target_name = tname;
|
||||||
|
|
||||||
|
for (const auto &fname : get_str_array(*to, "filename")) {
|
||||||
|
if (ttype == "static library") {
|
||||||
|
iface.static_libraries.emplace_back(fname);
|
||||||
|
} else if (ttype == "shared library") {
|
||||||
|
iface.shared_libraries.emplace_back(fname);
|
||||||
|
iface.runtime_files.emplace_back(fname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect include directories from target_sources parameters (-I...) plus source
|
||||||
|
// include/.
|
||||||
|
if (const auto *ts = find_key(*to, "target_sources")) {
|
||||||
|
if (const auto *tsarr = std::get_if<JsonVal::Array>(&ts->value)) {
|
||||||
|
for (const auto &tsv : *tsarr) {
|
||||||
|
if (const auto *tso = std::get_if<JsonVal::Object>(&tsv.value)) {
|
||||||
|
const auto params = get_str_array(*tso, "parameters");
|
||||||
|
for (std::size_t i = 0; i < params.size(); ++i) {
|
||||||
|
if (params[i].starts_with("-I") && params[i].size() > 2) {
|
||||||
|
std::filesystem::path p{params[i].substr(2)};
|
||||||
|
if (!p.is_absolute()) {
|
||||||
|
p = (build_dir / p).lexically_normal();
|
||||||
|
}
|
||||||
|
if (!std::ranges::contains(iface.include_dirs,
|
||||||
|
std::pair{p, false})) {
|
||||||
|
iface.include_dirs.emplace_back(p, false);
|
||||||
|
}
|
||||||
|
} else if (params[i] == "-I" && i + 1 < params.size()) {
|
||||||
|
std::filesystem::path p{params[++i]};
|
||||||
|
if (!p.is_absolute()) {
|
||||||
|
p = (build_dir / p).lexically_normal();
|
||||||
|
}
|
||||||
|
if (!std::ranges::contains(iface.include_dirs,
|
||||||
|
std::pair{p, false})) {
|
||||||
|
iface.include_dirs.emplace_back(p, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (std::filesystem::is_directory(request.source.source_dir / "include", ec)) {
|
||||||
|
const auto inc = (request.source.source_dir / "include").lexically_normal();
|
||||||
|
if (!std::ranges::contains(iface.include_dirs, std::pair{inc, false})) {
|
||||||
|
iface.include_dirs.emplace_back(inc, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exp.targets[tname] = iface;
|
||||||
|
exp.targets[request.dependency.name + "::" + tname] = iface;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto &[k, v] : request.explicit_overrides) {
|
||||||
|
exp.targets[k] = v;
|
||||||
|
}
|
||||||
|
return exp;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||||
|
run_conan_provider(const ProviderRequest &request, const std::filesystem::path &build_dir,
|
||||||
|
const std::string &input_hash, std::stop_token stop) {
|
||||||
|
auto conan_bin = Platform::resolve_executable("conan");
|
||||||
|
if (!conan_bin) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("Conan2 provider requires 'conan' in PATH for dependency '{}' "
|
||||||
|
"(prerequisite missing; refusing empty import)",
|
||||||
|
request.dependency.name))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::create_directories(build_dir, ec);
|
||||||
|
const auto host_profile = build_dir / "conan_host.profile";
|
||||||
|
const auto build_profile = build_dir / "conan_build.profile";
|
||||||
|
const std::string btype =
|
||||||
|
(request.profile.name == "release" || request.profile.name == "Release") ? "Release"
|
||||||
|
: "Debug";
|
||||||
|
const std::string prof_text =
|
||||||
|
std::format("[settings]\nos={}\narch={}\ncompiler={}\nbuild_type={}\n", request.profile.os,
|
||||||
|
request.profile.architecture, compiler_name(request.profile.compiler), btype);
|
||||||
|
(void)Platform::atomic_write_file(host_profile, prof_text, false);
|
||||||
|
(void)Platform::atomic_write_file(build_profile, prof_text, false);
|
||||||
|
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = *conan_bin;
|
||||||
|
req.arguments = {"install",
|
||||||
|
"--requires",
|
||||||
|
request.dependency.package,
|
||||||
|
"--profile:host",
|
||||||
|
host_profile.string(),
|
||||||
|
"--profile:build",
|
||||||
|
build_profile.string(),
|
||||||
|
"--output-folder",
|
||||||
|
build_dir.string(),
|
||||||
|
"--format",
|
||||||
|
"json"};
|
||||||
|
req.timeout = std::chrono::seconds{300};
|
||||||
|
auto proc = Platform::run_supervised(req, stop);
|
||||||
|
if (!proc || !proc->succeeded()) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("Conan2 install failed for '{}':\n{}", request.dependency.name,
|
||||||
|
proc ? proc->stderr_data : proc.error().message()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
ProviderExport exp;
|
||||||
|
exp.dependency_name = request.dependency.name;
|
||||||
|
exp.builder = "conan";
|
||||||
|
exp.input_identity_hash = input_hash;
|
||||||
|
for (const auto &[k, v] : request.explicit_overrides) {
|
||||||
|
exp.targets[k] = v;
|
||||||
|
}
|
||||||
|
return exp;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string compute_provider_input_hash(const ProviderRequest &request) {
|
||||||
|
Util::Sha256Hasher h;
|
||||||
|
h.update_length_prefixed("vbs-provider-v1");
|
||||||
|
h.update_length_prefixed(request.dependency.name);
|
||||||
|
h.update_length_prefixed(request.dependency.builder);
|
||||||
|
h.update_length_prefixed(request.source.content_identity_hash);
|
||||||
|
h.update_length_prefixed(request.profile.name);
|
||||||
|
h.update_length_prefixed(request.toolchain.identity_hash);
|
||||||
|
for (const auto &[k, v] : request.dependency.options) {
|
||||||
|
h.update_length_prefixed(k);
|
||||||
|
h.update_length_prefixed(cmake_option_value(v));
|
||||||
|
}
|
||||||
|
return h.finalize_hex();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ProviderExport, Void::Result::Error>
|
||||||
|
resolve_foreign_provider(const ProviderRequest &request, std::stop_token stop) {
|
||||||
|
const std::string input_hash = compute_provider_input_hash(request);
|
||||||
|
const auto isolated_dir =
|
||||||
|
request.provider_build_root / request.dependency.name / input_hash.substr(0, 16);
|
||||||
|
const auto export_file = isolated_dir / "provider-export.json";
|
||||||
|
|
||||||
|
// Always try validated cache first (in BOTH FullBuild and MetadataOnly modes).
|
||||||
|
if (auto cached = load_cached_export(export_file, input_hash); cached) {
|
||||||
|
return *cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strict MetadataOnly boundary (D-026 / Plan 10 / Plan 13):
|
||||||
|
// NEVER invoke CMake configure, Meson setup, Conan install, or builds!
|
||||||
|
if (request.mode == ProviderMode::MetadataOnly) {
|
||||||
|
ProviderExport stale;
|
||||||
|
stale.dependency_name = request.dependency.name;
|
||||||
|
stale.builder = request.dependency.builder;
|
||||||
|
stale.input_identity_hash = input_hash;
|
||||||
|
stale.stale_needs_build = true;
|
||||||
|
stale.stale_diagnostic = std::format(
|
||||||
|
"cached {} provider metadata for '{}' is missing or stale (input={}); "
|
||||||
|
"run 'vbs build' to configure/build dependencies",
|
||||||
|
request.dependency.builder, request.dependency.name, input_hash.substr(0, 12));
|
||||||
|
return stale;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto lock_path = isolated_dir.parent_path() / (request.dependency.name + ".lock");
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_path, Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-check cache after acquiring lock in case a peer just finished.
|
||||||
|
if (auto cached = load_cached_export(export_file, input_hash); cached) {
|
||||||
|
return *cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto tool_build_dir = isolated_dir / "build";
|
||||||
|
Void::Result::Result<ProviderExport, Void::Result::Error> res = std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("unsupported foreign builder '{}'", request.dependency.builder))};
|
||||||
|
if (request.dependency.builder == "cmake") {
|
||||||
|
res = run_cmake_provider(request, tool_build_dir, input_hash, stop);
|
||||||
|
} else if (request.dependency.builder == "meson") {
|
||||||
|
res = run_meson_provider(request, tool_build_dir, input_hash, stop);
|
||||||
|
} else if (request.dependency.builder == "conan") {
|
||||||
|
res = run_conan_provider(request, tool_build_dir, input_hash, stop);
|
||||||
|
}
|
||||||
|
if (!res) {
|
||||||
|
return std::unexpected{res.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish validated provider export atomically!
|
||||||
|
if (auto w = Platform::atomic_write_file(export_file, serialize_export(*res), true); !w) {
|
||||||
|
return std::unexpected{w.error()};
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Provider
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
#include <Void/Build/SelfHost/TestRegistryGen.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <format>
|
||||||
|
#include <regex>
|
||||||
|
|
||||||
|
namespace Void::Build::SelfHost {
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<DiscoveredTestCase>, Void::Result::Error>
|
||||||
|
scan_void_tests(const std::filesystem::path &source_file) {
|
||||||
|
auto text = Void::FileSystem::read_file(source_file);
|
||||||
|
if (!text) {
|
||||||
|
return std::unexpected{text.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string suite = source_file.stem().string();
|
||||||
|
const std::regex pattern{
|
||||||
|
R"((?:^|[\r\n])\s*(?:Void::Testing::)?Test\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(\s*\))"};
|
||||||
|
|
||||||
|
std::vector<DiscoveredTestCase> found;
|
||||||
|
std::size_t line_no = 1;
|
||||||
|
std::size_t pos = 0;
|
||||||
|
|
||||||
|
while (pos < text->size()) {
|
||||||
|
const auto nl = text->find('\n', pos);
|
||||||
|
const auto line =
|
||||||
|
std::string{text->substr(pos, nl == std::string::npos ? std::string::npos : nl - pos)};
|
||||||
|
std::smatch m;
|
||||||
|
if (std::regex_search(line, m, pattern)) {
|
||||||
|
found.push_back(DiscoveredTestCase{suite, m[1].str(), source_file, line_no});
|
||||||
|
}
|
||||||
|
if (nl == std::string::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos = nl + 1;
|
||||||
|
++line_no;
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<GeneratedRegistration, Void::Result::Error>
|
||||||
|
generate_test_registration_unit(const std::filesystem::path &source_file,
|
||||||
|
const std::filesystem::path &output_dir) {
|
||||||
|
auto cases_res = scan_void_tests(source_file);
|
||||||
|
if (!cases_res) {
|
||||||
|
return std::unexpected{cases_res.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
const auto abs_src = std::filesystem::weakly_canonical(source_file, ec);
|
||||||
|
const std::string path_hash = Util::sha256_hex(abs_src.string()).substr(0, 12);
|
||||||
|
const auto out_cpp =
|
||||||
|
output_dir / (source_file.stem().string() + "_" + path_hash + ".void_tests.cpp");
|
||||||
|
|
||||||
|
std::string code =
|
||||||
|
"// Auto-generated by VoidBuildSystem native Void::Testing registration generator\n"
|
||||||
|
"#include <Void/Testing/Detail/Registrar.hpp>\n"
|
||||||
|
"#include <Void/Testing/Test.hpp>\n"
|
||||||
|
"#include <string>\n"
|
||||||
|
"#include <vector>\n\n";
|
||||||
|
|
||||||
|
for (const auto &c : *cases_res) {
|
||||||
|
code += "Void::Testing::Test " + c.function_name + "();\n";
|
||||||
|
}
|
||||||
|
code += "\nnamespace {\n";
|
||||||
|
for (std::size_t i = 0; i < cases_res->size(); ++i) {
|
||||||
|
const auto &c = (*cases_res)[i];
|
||||||
|
code += std::format("static Void::Testing::Detail::test_registrar<&{}> _vbs_reg_{}_{}{{\n"
|
||||||
|
" {}, {}, {}, {}, std::vector<std::string>{{}}, false, \"\"\n"
|
||||||
|
"}};\n",
|
||||||
|
c.function_name, path_hash, i, Util::json_quote(c.suite_name),
|
||||||
|
Util::json_quote(abs_src.string()), c.line_number,
|
||||||
|
Util::json_quote(c.function_name));
|
||||||
|
}
|
||||||
|
code += "} // namespace\n";
|
||||||
|
|
||||||
|
auto wrote = Platform::atomic_write_file(out_cpp, code, false);
|
||||||
|
if (!wrote) {
|
||||||
|
return std::unexpected{wrote.error()};
|
||||||
|
}
|
||||||
|
return GeneratedRegistration{out_cpp, std::move(*cases_res)};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::SelfHost
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
#include <Void/Build/Snapshot/Snapshot.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <dirent.h>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <format>
|
||||||
|
#include <functional>
|
||||||
|
#include <set>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
namespace Void::Build::Snapshot {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg, int err = 0) {
|
||||||
|
return Void::System::make_system_error(code, std::move(msg), err);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_excluded_name(std::string_view name, const std::vector<std::string> &excluded) {
|
||||||
|
if (name == ".env" || name.starts_with(".env.")) {
|
||||||
|
return name != ".env.example";
|
||||||
|
}
|
||||||
|
if (name.ends_with(".pem") || name.ends_with(".key")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return std::ranges::contains(excluded, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool path_has_excluded_component(const std::filesystem::path &rel_path,
|
||||||
|
const std::vector<std::string> &excluded) {
|
||||||
|
for (const auto &part : rel_path) {
|
||||||
|
const auto s = part.string();
|
||||||
|
if (s.empty() || s == ".") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (is_excluded_name(s, excluded)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<std::string>, Void::Result::Error>
|
||||||
|
read_sorted_dir_entries(const std::filesystem::path &dir_path,
|
||||||
|
const std::vector<std::string> &excluded) {
|
||||||
|
const int fd = ::open(dir_path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||||
|
if (fd < 0) {
|
||||||
|
const int err = errno;
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::map_errno_to_system_code(err),
|
||||||
|
std::format("snapshot: cannot open directory '{}'", dir_path.string()), err)};
|
||||||
|
}
|
||||||
|
DIR *dir = ::fdopendir(fd);
|
||||||
|
if (!dir) {
|
||||||
|
const int err = errno;
|
||||||
|
(void)::close(fd);
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::map_errno_to_system_code(err),
|
||||||
|
std::format("snapshot: fdopendir failed for '{}'", dir_path.string()), err)};
|
||||||
|
}
|
||||||
|
std::vector<std::string> names;
|
||||||
|
errno = 0;
|
||||||
|
while (const struct dirent *ent = ::readdir(dir)) {
|
||||||
|
const std::string_view name{ent->d_name};
|
||||||
|
if (name == "." || name == "..") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (is_excluded_name(name, excluded)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
names.emplace_back(name);
|
||||||
|
}
|
||||||
|
const int read_err = errno;
|
||||||
|
(void)::closedir(dir);
|
||||||
|
if (read_err != 0) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::map_errno_to_system_code(read_err),
|
||||||
|
std::format("snapshot: readdir failed for '{}'", dir_path.string()), read_err)};
|
||||||
|
}
|
||||||
|
std::ranges::sort(names);
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string normalize_logical(const std::filesystem::path &rel) {
|
||||||
|
std::string s = rel.lexically_normal().generic_string();
|
||||||
|
if (s == ".") {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (s.starts_with("./")) {
|
||||||
|
s.erase(0, 2);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string compute_snapshot_id(const InputSnapshot &snap) {
|
||||||
|
Util::Sha256Hasher hasher;
|
||||||
|
hasher.update_length_prefixed("vbs-snapshot-v1");
|
||||||
|
hasher.update_u64(static_cast<std::uint64_t>(snap.reproducibility_epoch));
|
||||||
|
hasher.update_u64(snap.entries.size());
|
||||||
|
for (const auto &[logical, entry] : snap.entries) {
|
||||||
|
hasher.update_length_prefixed(logical);
|
||||||
|
hasher.update_u64(static_cast<std::uint64_t>(entry.kind));
|
||||||
|
hasher.update_length_prefixed(entry.sha256);
|
||||||
|
hasher.update_u64(entry.size);
|
||||||
|
hasher.update_u64(entry.mode & 0777u);
|
||||||
|
hasher.update_length_prefixed(entry.symlink_target);
|
||||||
|
}
|
||||||
|
hasher.update_u64(snap.memberships.size());
|
||||||
|
for (const auto &[dir, mem] : snap.memberships) {
|
||||||
|
hasher.update_length_prefixed(dir);
|
||||||
|
hasher.update_u64(mem.entries.size());
|
||||||
|
for (const auto &name : mem.entries) {
|
||||||
|
hasher.update_length_prefixed(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hasher.update_u64(snap.lookup_guards.size());
|
||||||
|
for (const auto &guard : snap.lookup_guards) {
|
||||||
|
hasher.update_u64(guard.search_roots.size());
|
||||||
|
for (const auto &r : guard.search_roots) {
|
||||||
|
hasher.update_length_prefixed(r);
|
||||||
|
}
|
||||||
|
hasher.update_length_prefixed(guard.lookup_name);
|
||||||
|
hasher.update_u64(static_cast<std::uint64_t>(guard.matched_root_index + 1));
|
||||||
|
hasher.update_length_prefixed(guard.matched_sha256);
|
||||||
|
}
|
||||||
|
return hasher.finalize_hex();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<LookupGuard, Void::Result::Error>
|
||||||
|
evaluate_one_guard(const std::filesystem::path &project_root,
|
||||||
|
const std::vector<std::filesystem::path> &allowed_external_roots,
|
||||||
|
const std::vector<std::string> &search_roots, const std::string &lookup_name) {
|
||||||
|
LookupGuard guard;
|
||||||
|
guard.search_roots = search_roots;
|
||||||
|
guard.lookup_name = lookup_name;
|
||||||
|
guard.matched_root_index = -1;
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < search_roots.size(); ++i) {
|
||||||
|
const std::filesystem::path root_path{search_roots[i]};
|
||||||
|
const auto abs_root = root_path.is_absolute() ? root_path : (project_root / root_path);
|
||||||
|
const auto candidate = abs_root / lookup_name;
|
||||||
|
auto meta = Platform::stat_lstat(candidate);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto confined =
|
||||||
|
Platform::resolve_confined_path(project_root, candidate, allowed_external_roots);
|
||||||
|
if (!confined) {
|
||||||
|
return std::unexpected{confined.error()};
|
||||||
|
}
|
||||||
|
auto target_meta = Platform::stat_lstat(*confined);
|
||||||
|
if (!target_meta) {
|
||||||
|
return std::unexpected{target_meta.error()};
|
||||||
|
}
|
||||||
|
if (target_meta->exists && target_meta->is_regular) {
|
||||||
|
auto digest = Util::sha256_file_hex(*confined);
|
||||||
|
if (!digest) {
|
||||||
|
return std::unexpected{digest.error()};
|
||||||
|
}
|
||||||
|
guard.matched_root_index = static_cast<int>(i);
|
||||||
|
guard.matched_sha256 = std::move(*digest);
|
||||||
|
return guard;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return guard;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Result::Result<InputSnapshot, Void::Result::Error> capture_snapshot(
|
||||||
|
const SnapshotOptions &options, const std::vector<std::filesystem::path> &explicit_files,
|
||||||
|
const std::vector<std::filesystem::path> &directory_roots,
|
||||||
|
const std::vector<std::pair<std::vector<std::string>, std::string>> &lookup_queries) {
|
||||||
|
std::error_code ec;
|
||||||
|
const auto canonical_root = std::filesystem::weakly_canonical(options.project_root, ec);
|
||||||
|
if (ec || !std::filesystem::is_directory(canonical_root)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("snapshot: project root '{}' is not a directory",
|
||||||
|
options.project_root.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
const int attempts = std::max(1, options.max_revalidate_retries);
|
||||||
|
for (int attempt = 0; attempt < attempts; ++attempt) {
|
||||||
|
InputSnapshot snap;
|
||||||
|
snap.project_root = canonical_root;
|
||||||
|
snap.reproducibility_epoch = options.reproducibility_epoch;
|
||||||
|
|
||||||
|
std::map<std::string, std::filesystem::path, std::less<>> source_files_to_verify;
|
||||||
|
std::map<std::string, std::filesystem::path, std::less<>> dirs_to_verify;
|
||||||
|
|
||||||
|
auto capture_single_file = [&](const std::filesystem::path &raw_path)
|
||||||
|
-> Void::Result::Result<void, Void::Result::Error> {
|
||||||
|
const auto abs_path = raw_path.is_absolute() ? raw_path : (canonical_root / raw_path);
|
||||||
|
auto lmeta = Platform::stat_lstat(abs_path);
|
||||||
|
if (!lmeta) {
|
||||||
|
return std::unexpected{lmeta.error()};
|
||||||
|
}
|
||||||
|
if (!lmeta->exists) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("snapshot: required input '{}' does not exist", raw_path.string()),
|
||||||
|
ENOENT)};
|
||||||
|
}
|
||||||
|
auto confined = Platform::resolve_confined_path(canonical_root, abs_path,
|
||||||
|
options.allowed_external_roots);
|
||||||
|
if (!confined) {
|
||||||
|
return std::unexpected{confined.error()};
|
||||||
|
}
|
||||||
|
std::filesystem::path rel = abs_path.lexically_relative(canonical_root);
|
||||||
|
std::string logical = normalize_logical(rel);
|
||||||
|
if (logical.empty() || logical.starts_with("..")) {
|
||||||
|
logical = "external/" + Util::sha256_hex(confined->string()).substr(0, 16) + "/" +
|
||||||
|
confined->filename().string();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lmeta->is_symlink) {
|
||||||
|
SnapshotEntry sym;
|
||||||
|
sym.logical_path = logical;
|
||||||
|
sym.kind = EntryKind::Symlink;
|
||||||
|
sym.symlink_target = lmeta->symlink_target;
|
||||||
|
sym.mode = lmeta->mode;
|
||||||
|
// Hash the resolved target content if it is a regular file so retargeting or
|
||||||
|
// editing target bytes invalidates the snapshot.
|
||||||
|
auto target_meta = Platform::stat_lstat(*confined);
|
||||||
|
if (!target_meta) {
|
||||||
|
return std::unexpected{target_meta.error()};
|
||||||
|
}
|
||||||
|
if (target_meta->exists && target_meta->is_regular) {
|
||||||
|
auto digest = Util::sha256_file_hex(*confined);
|
||||||
|
if (!digest) {
|
||||||
|
return std::unexpected{digest.error()};
|
||||||
|
}
|
||||||
|
sym.sha256 = std::move(*digest);
|
||||||
|
sym.size = target_meta->size;
|
||||||
|
source_files_to_verify[logical] = *confined;
|
||||||
|
}
|
||||||
|
snap.entries[logical] = std::move(sym);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!lmeta->is_regular) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("snapshot: '{}' is not a regular file or symlink",
|
||||||
|
abs_path.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
SnapshotEntry entry;
|
||||||
|
entry.logical_path = logical;
|
||||||
|
entry.kind = EntryKind::RegularFile;
|
||||||
|
entry.size = lmeta->size;
|
||||||
|
entry.mode = lmeta->mode;
|
||||||
|
|
||||||
|
if (options.materialize) {
|
||||||
|
const auto staging_blob =
|
||||||
|
options.snapshot_store_dir / "blobs" /
|
||||||
|
(Util::sha256_hex(logical + "#" + std::to_string(attempt)) + ".stage");
|
||||||
|
auto copied = Platform::copy_isolated(*confined, staging_blob, entry.mode);
|
||||||
|
if (!copied) {
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
auto digest = Util::sha256_file_hex(staging_blob);
|
||||||
|
if (!digest) {
|
||||||
|
std::filesystem::remove(staging_blob, ec);
|
||||||
|
return std::unexpected{digest.error()};
|
||||||
|
}
|
||||||
|
entry.sha256 = std::move(*digest);
|
||||||
|
const auto final_blob =
|
||||||
|
options.snapshot_store_dir / "blobs" / entry.sha256.substr(0, 2) / entry.sha256;
|
||||||
|
std::filesystem::create_directories(final_blob.parent_path(), ec);
|
||||||
|
if (!std::filesystem::exists(final_blob, ec)) {
|
||||||
|
(void)Platform::set_canonical_mtime(staging_blob,
|
||||||
|
options.reproducibility_epoch);
|
||||||
|
std::filesystem::rename(staging_blob, final_blob, ec);
|
||||||
|
if (ec) {
|
||||||
|
std::filesystem::remove(staging_blob, ec);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
std::filesystem::remove(staging_blob, ec);
|
||||||
|
}
|
||||||
|
entry.materialized_path = final_blob;
|
||||||
|
} else {
|
||||||
|
auto digest = Util::sha256_file_hex(*confined);
|
||||||
|
if (!digest) {
|
||||||
|
return std::unexpected{digest.error()};
|
||||||
|
}
|
||||||
|
entry.sha256 = std::move(*digest);
|
||||||
|
}
|
||||||
|
|
||||||
|
source_files_to_verify[logical] = *confined;
|
||||||
|
snap.entries[logical] = std::move(entry);
|
||||||
|
return {};
|
||||||
|
};
|
||||||
|
|
||||||
|
std::function<Void::Result::Result<void, Void::Result::Error>(
|
||||||
|
const std::filesystem::path &, std::set<std::pair<std::uint64_t, std::uint64_t>> &)>
|
||||||
|
walk_dir;
|
||||||
|
walk_dir = [&](const std::filesystem::path &dir_path,
|
||||||
|
std::set<std::pair<std::uint64_t, std::uint64_t>> &visited_dirs)
|
||||||
|
-> Void::Result::Result<void, Void::Result::Error> {
|
||||||
|
auto confined = Platform::resolve_confined_path(canonical_root, dir_path,
|
||||||
|
options.allowed_external_roots);
|
||||||
|
if (!confined) {
|
||||||
|
return std::unexpected{confined.error()};
|
||||||
|
}
|
||||||
|
auto meta = Platform::stat_lstat(*confined);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists) {
|
||||||
|
// Record empty membership for absent search roots so creation invalidates.
|
||||||
|
const std::string logical_dir =
|
||||||
|
normalize_logical(dir_path.lexically_relative(canonical_root));
|
||||||
|
snap.memberships[logical_dir] = DirectoryMembership{logical_dir, {}};
|
||||||
|
dirs_to_verify[logical_dir] = dir_path;
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (!meta->is_directory) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if (!visited_dirs.insert({meta->dev, meta->ino}).second) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto entries_res = read_sorted_dir_entries(*confined, options.excluded_names);
|
||||||
|
if (!entries_res) {
|
||||||
|
return std::unexpected{entries_res.error()};
|
||||||
|
}
|
||||||
|
const std::string logical_dir =
|
||||||
|
normalize_logical(dir_path.lexically_relative(canonical_root));
|
||||||
|
snap.memberships[logical_dir] = DirectoryMembership{logical_dir, *entries_res};
|
||||||
|
dirs_to_verify[logical_dir] = *confined;
|
||||||
|
|
||||||
|
for (const auto &name : *entries_res) {
|
||||||
|
const auto child = dir_path / name;
|
||||||
|
const auto child_rel = child.lexically_relative(canonical_root);
|
||||||
|
if (path_has_excluded_component(child_rel, options.excluded_names)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto cmeta = Platform::stat_lstat(child);
|
||||||
|
if (!cmeta) {
|
||||||
|
return std::unexpected{cmeta.error()};
|
||||||
|
}
|
||||||
|
if (!cmeta->exists) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (cmeta->is_directory) {
|
||||||
|
auto sub = walk_dir(child, visited_dirs);
|
||||||
|
if (!sub) {
|
||||||
|
return sub;
|
||||||
|
}
|
||||||
|
} else if (cmeta->is_regular || cmeta->is_symlink) {
|
||||||
|
auto cap = capture_single_file(child);
|
||||||
|
if (!cap) {
|
||||||
|
return cap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const auto &file : explicit_files) {
|
||||||
|
auto r = capture_single_file(file);
|
||||||
|
if (!r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::set<std::pair<std::uint64_t, std::uint64_t>> visited_dirs;
|
||||||
|
for (const auto &root : directory_roots) {
|
||||||
|
const auto abs_dir = root.is_absolute() ? root : (canonical_root / root);
|
||||||
|
auto r = walk_dir(abs_dir, visited_dirs);
|
||||||
|
if (!r) {
|
||||||
|
return std::unexpected{r.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &[search_roots, lookup_name] : lookup_queries) {
|
||||||
|
auto guard = evaluate_one_guard(canonical_root, options.allowed_external_roots,
|
||||||
|
search_roots, lookup_name);
|
||||||
|
if (!guard) {
|
||||||
|
return std::unexpected{guard.error()};
|
||||||
|
}
|
||||||
|
snap.lookup_guards.push_back(std::move(*guard));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revalidation pass before sealing: detect concurrent mutations during capture.
|
||||||
|
bool mutated = false;
|
||||||
|
for (const auto &[logical, src_path] : source_files_to_verify) {
|
||||||
|
auto rehash = Util::sha256_file_hex(src_path);
|
||||||
|
if (!rehash || *rehash != snap.entries.at(logical).sha256) {
|
||||||
|
mutated = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!mutated) {
|
||||||
|
for (const auto &[logical_dir, dir_path] : dirs_to_verify) {
|
||||||
|
auto meta = Platform::stat_lstat(dir_path);
|
||||||
|
if (!meta) {
|
||||||
|
mutated = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!meta->exists) {
|
||||||
|
if (!snap.memberships.at(logical_dir).entries.empty()) {
|
||||||
|
mutated = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto cur = read_sorted_dir_entries(dir_path, options.excluded_names);
|
||||||
|
if (!cur || *cur != snap.memberships.at(logical_dir).entries) {
|
||||||
|
mutated = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (mutated) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
snap.snapshot_id = compute_snapshot_id(snap);
|
||||||
|
|
||||||
|
// Materialize a per-snapshot logical tree using private copies/reflinks (no hardlinks)
|
||||||
|
// with canonical mtime so compiler builds see isolated, immutable bytes.
|
||||||
|
if (options.materialize) {
|
||||||
|
snap.materialized_root = options.snapshot_store_dir / "trees" / snap.snapshot_id;
|
||||||
|
const auto seal_marker = snap.materialized_root / ".sealed";
|
||||||
|
if (!std::filesystem::exists(seal_marker, ec)) {
|
||||||
|
const auto tmp_tree = options.snapshot_store_dir / "trees" /
|
||||||
|
(snap.snapshot_id + ".staging_" +
|
||||||
|
std::to_string(static_cast<long long>(::getpid())));
|
||||||
|
std::filesystem::remove_all(tmp_tree, ec);
|
||||||
|
std::filesystem::create_directories(tmp_tree, ec);
|
||||||
|
|
||||||
|
for (auto &[logical, entry] : snap.entries) {
|
||||||
|
const auto dst = tmp_tree / logical;
|
||||||
|
std::filesystem::create_directories(dst.parent_path(), ec);
|
||||||
|
if (entry.kind == EntryKind::RegularFile && !entry.materialized_path.empty()) {
|
||||||
|
auto copied =
|
||||||
|
Platform::copy_isolated(entry.materialized_path, dst, entry.mode);
|
||||||
|
if (!copied) {
|
||||||
|
std::filesystem::remove_all(tmp_tree, ec);
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
(void)Platform::set_canonical_mtime(dst, options.reproducibility_epoch);
|
||||||
|
} else if (entry.kind == EntryKind::Symlink) {
|
||||||
|
if (!entry.sha256.empty()) {
|
||||||
|
// Materialize symlinked regular file target inside snapshot tree
|
||||||
|
// safely.
|
||||||
|
const auto src_target = source_files_to_verify.find(logical);
|
||||||
|
if (src_target != source_files_to_verify.end()) {
|
||||||
|
auto copied =
|
||||||
|
Platform::copy_isolated(src_target->second, dst, entry.mode);
|
||||||
|
if (!copied) {
|
||||||
|
std::filesystem::remove_all(tmp_tree, ec);
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
(void)Platform::set_canonical_mtime(dst,
|
||||||
|
options.reproducibility_epoch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(void)Platform::atomic_write_file(tmp_tree / ".sealed", snap.snapshot_id + "\n",
|
||||||
|
false);
|
||||||
|
std::filesystem::rename(tmp_tree, snap.materialized_root, ec);
|
||||||
|
if (ec) {
|
||||||
|
// Another concurrent worker may have sealed the identical content-addressed
|
||||||
|
// tree.
|
||||||
|
std::filesystem::remove_all(tmp_tree, ec);
|
||||||
|
if (!std::filesystem::exists(seal_marker, ec)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("snapshot: failed publishing tree '{}'",
|
||||||
|
snap.materialized_root.string()))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (auto &[logical, entry] : snap.entries) {
|
||||||
|
entry.materialized_path = snap.materialized_root / logical;
|
||||||
|
}
|
||||||
|
(void)write_snapshot_manifest(snap, options.snapshot_store_dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
return snap;
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::busy,
|
||||||
|
std::format("snapshot: source tree remained unstable across {} revalidation retries",
|
||||||
|
attempts))};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<bool, Void::Result::Error> is_snapshot_fresh(const InputSnapshot &snapshot,
|
||||||
|
const SnapshotOptions &options) {
|
||||||
|
for (const auto &[logical, entry] : snapshot.entries) {
|
||||||
|
if (logical.starts_with("external/")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto live_path = snapshot.project_root / logical;
|
||||||
|
auto meta = Platform::stat_lstat(live_path);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (entry.kind == EntryKind::Symlink) {
|
||||||
|
if (!meta->is_symlink || meta->symlink_target != entry.symlink_target) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
auto confined = Platform::resolve_confined_path(snapshot.project_root, live_path,
|
||||||
|
options.allowed_external_roots);
|
||||||
|
if (!confined) {
|
||||||
|
return std::unexpected{confined.error()};
|
||||||
|
}
|
||||||
|
if (!entry.sha256.empty()) {
|
||||||
|
auto rehash = Util::sha256_file_hex(*confined);
|
||||||
|
if (!rehash || *rehash != entry.sha256) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (entry.kind == EntryKind::RegularFile) {
|
||||||
|
if (!meta->is_regular || meta->size != entry.size) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Content verification: NEVER shortcut on mtime/size alone (catches restored-mtime
|
||||||
|
// edits!).
|
||||||
|
auto rehash = Util::sha256_file_hex(live_path);
|
||||||
|
if (!rehash) {
|
||||||
|
return std::unexpected{rehash.error()};
|
||||||
|
}
|
||||||
|
if (*rehash != entry.sha256) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto &[logical_dir, mem] : snapshot.memberships) {
|
||||||
|
const auto live_dir =
|
||||||
|
logical_dir.empty() ? snapshot.project_root : (snapshot.project_root / logical_dir);
|
||||||
|
auto meta = Platform::stat_lstat(live_dir);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists) {
|
||||||
|
if (!mem.entries.empty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!meta->is_directory) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
auto live_entries = read_sorted_dir_entries(live_dir, options.excluded_names);
|
||||||
|
if (!live_entries) {
|
||||||
|
return std::unexpected{live_entries.error()};
|
||||||
|
}
|
||||||
|
if (*live_entries != mem.entries) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto &guard : snapshot.lookup_guards) {
|
||||||
|
auto live = evaluate_one_guard(snapshot.project_root, options.allowed_external_roots,
|
||||||
|
guard.search_roots, guard.lookup_name);
|
||||||
|
if (!live) {
|
||||||
|
return std::unexpected{live.error()};
|
||||||
|
}
|
||||||
|
if (live->matched_root_index != guard.matched_root_index ||
|
||||||
|
live->matched_sha256 != guard.matched_sha256) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<SnapshotEntry, Void::Result::Error>
|
||||||
|
seal_generated_artifact(const std::filesystem::path &staged_file, std::string logical_path,
|
||||||
|
const std::filesystem::path &snapshot_store_dir,
|
||||||
|
std::int64_t reproducibility_epoch) {
|
||||||
|
auto meta = Platform::stat_lstat(staged_file);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists || !meta->is_regular) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("seal_generated_artifact: '{}' is missing or not a regular file",
|
||||||
|
staged_file.string()))};
|
||||||
|
}
|
||||||
|
auto digest = Util::sha256_file_hex(staged_file);
|
||||||
|
if (!digest) {
|
||||||
|
return std::unexpected{digest.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto dst = snapshot_store_dir / "generated" / digest->substr(0, 2) / *digest;
|
||||||
|
std::error_code ec;
|
||||||
|
if (!std::filesystem::exists(dst, ec)) {
|
||||||
|
auto copied = Platform::copy_isolated(staged_file, dst, meta->mode);
|
||||||
|
if (!copied) {
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
(void)Platform::set_canonical_mtime(dst, reproducibility_epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
SnapshotEntry entry;
|
||||||
|
entry.logical_path = std::move(logical_path);
|
||||||
|
entry.kind = EntryKind::RegularFile;
|
||||||
|
entry.sha256 = std::move(*digest);
|
||||||
|
entry.size = meta->size;
|
||||||
|
entry.mode = meta->mode;
|
||||||
|
entry.materialized_path = dst;
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::filesystem::path, Void::Result::Error>
|
||||||
|
write_snapshot_manifest(const InputSnapshot &snapshot,
|
||||||
|
const std::filesystem::path &snapshot_store_dir) {
|
||||||
|
using Util::json_array;
|
||||||
|
using Util::json_quote;
|
||||||
|
|
||||||
|
std::string json =
|
||||||
|
"{\"schema_version\":1,\"snapshot_id\":" + json_quote(snapshot.snapshot_id) +
|
||||||
|
",\"reproducibility_epoch\":" + std::to_string(snapshot.reproducibility_epoch) +
|
||||||
|
",\"entries\":";
|
||||||
|
std::vector<const SnapshotEntry *> entry_list;
|
||||||
|
for (const auto &[k, v] : snapshot.entries) {
|
||||||
|
entry_list.push_back(&v);
|
||||||
|
}
|
||||||
|
json += json_array(entry_list, [](const SnapshotEntry *e) {
|
||||||
|
return "{\"logical_path\":" + json_quote(e->logical_path) +
|
||||||
|
",\"sha256\":" + json_quote(e->sha256) + ",\"size\":" + std::to_string(e->size) +
|
||||||
|
",\"symlink_target\":" + json_quote(e->symlink_target) + '}';
|
||||||
|
});
|
||||||
|
json += ",\"lookup_guards\":";
|
||||||
|
json += json_array(snapshot.lookup_guards, [](const LookupGuard &g) {
|
||||||
|
return "{\"lookup_name\":" + json_quote(g.lookup_name) +
|
||||||
|
",\"matched_root_index\":" + std::to_string(g.matched_root_index) +
|
||||||
|
",\"matched_sha256\":" + json_quote(g.matched_sha256) + '}';
|
||||||
|
});
|
||||||
|
json += "}\n";
|
||||||
|
|
||||||
|
const auto manifest_path = snapshot_store_dir / "manifests" / (snapshot.snapshot_id + ".json");
|
||||||
|
auto written = Platform::atomic_write_file(manifest_path, json, true);
|
||||||
|
if (!written) {
|
||||||
|
return std::unexpected{written.error()};
|
||||||
|
}
|
||||||
|
return manifest_path;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Snapshot
|
||||||
@@ -0,0 +1,750 @@
|
|||||||
|
#include <Void/Build/State/StateStore.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <atomic>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <chrono>
|
||||||
|
#include <csignal>
|
||||||
|
#include <format>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace Void::Build::State {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
std::atomic<std::uint64_t> g_lease_seq{0};
|
||||||
|
|
||||||
|
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg, int err = 0) {
|
||||||
|
return Void::System::make_system_error(code, std::move(msg), err);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool is_valid_sha256_hex(std::string_view hex) {
|
||||||
|
if (hex.size() != 64) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return std::ranges::all_of(
|
||||||
|
hex, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); });
|
||||||
|
}
|
||||||
|
|
||||||
|
bool pid_is_alive(pid_t pid) noexcept {
|
||||||
|
if (pid <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (::kill(pid, 0) == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return errno != ESRCH;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_action(const ActionSuccessRecord &rec) {
|
||||||
|
using Util::json_array;
|
||||||
|
using Util::json_quote;
|
||||||
|
|
||||||
|
std::string out = "{\"action_key\":" + json_quote(rec.action_key) +
|
||||||
|
",\"profile_identity\":" + json_quote(rec.profile_identity) +
|
||||||
|
",\"target_name\":" + json_quote(rec.target_name) +
|
||||||
|
",\"recorded_epoch\":" + std::to_string(rec.recorded_epoch) +
|
||||||
|
",\"outputs\":{";
|
||||||
|
bool first = true;
|
||||||
|
for (const auto &[path, ref] : rec.outputs) {
|
||||||
|
if (!first) {
|
||||||
|
out += ',';
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
out += json_quote(path) + ":{\"sha256\":" + json_quote(ref.sha256) +
|
||||||
|
",\"size\":" + std::to_string(ref.size) + ",\"mode\":" + std::to_string(ref.mode) +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
out += "},\"discovered_inputs\":{";
|
||||||
|
first = true;
|
||||||
|
for (const auto &[path, digest] : rec.discovered_inputs) {
|
||||||
|
if (!first) {
|
||||||
|
out += ',';
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
out += json_quote(path) + ':' + json_quote(digest);
|
||||||
|
}
|
||||||
|
out += "},\"lookup_guards\":";
|
||||||
|
out += json_array(rec.lookup_guards, [](const Snapshot::LookupGuard &g) {
|
||||||
|
return "{\"search_roots\":" + json_array(g.search_roots, json_quote) +
|
||||||
|
",\"lookup_name\":" + json_quote(g.lookup_name) +
|
||||||
|
",\"matched_root_index\":" + std::to_string(g.matched_root_index) +
|
||||||
|
",\"matched_sha256\":" + json_quote(g.matched_sha256) + '}';
|
||||||
|
});
|
||||||
|
out += '}';
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_generation(const GraphGenerationRecord &gen) {
|
||||||
|
using Util::json_quote;
|
||||||
|
return "{\"generation_id\":" + json_quote(gen.generation_id) +
|
||||||
|
",\"profile_name\":" + json_quote(gen.profile_name) +
|
||||||
|
",\"profile_identity\":" + json_quote(gen.profile_identity) +
|
||||||
|
",\"snapshot_id\":" + json_quote(gen.snapshot_id) +
|
||||||
|
",\"status\":" + json_quote(gen.status) +
|
||||||
|
",\"diagnostic\":" + json_quote(gen.diagnostic) +
|
||||||
|
",\"sequence\":" + std::to_string(gen.sequence) + '}';
|
||||||
|
}
|
||||||
|
|
||||||
|
using JsonVal = Void::Json::Strict::Value;
|
||||||
|
|
||||||
|
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &key) {
|
||||||
|
const auto it = obj.find(key);
|
||||||
|
return it == obj.end() ? nullptr : &it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::string> get_str(const JsonVal::Object &obj, const std::string &key) {
|
||||||
|
const auto *v = find_key(obj, key);
|
||||||
|
if (!v) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&v->value);
|
||||||
|
return s ? std::optional<std::string>{*s} : std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::int64_t> get_i64(const JsonVal::Object &obj, const std::string &key) {
|
||||||
|
const auto *v = find_key(obj, key);
|
||||||
|
if (!v) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *i = std::get_if<std::int64_t>(&v->value);
|
||||||
|
return i ? std::optional<std::int64_t>{*i} : std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
LeaseHandle::~LeaseHandle() noexcept { release(); }
|
||||||
|
|
||||||
|
LeaseHandle::LeaseHandle(LeaseHandle &&other) noexcept
|
||||||
|
: lease_id{std::move(other.lease_id)}, lease_file{std::exchange(other.lease_file, {})} {}
|
||||||
|
|
||||||
|
LeaseHandle &LeaseHandle::operator=(LeaseHandle &&other) noexcept {
|
||||||
|
if (this != &other) {
|
||||||
|
release();
|
||||||
|
lease_id = std::move(other.lease_id);
|
||||||
|
lease_file = std::exchange(other.lease_file, {});
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void LeaseHandle::release() noexcept {
|
||||||
|
if (!lease_file.empty()) {
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::remove(lease_file, ec);
|
||||||
|
lease_file.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
StateStore::StateStore(std::filesystem::path root)
|
||||||
|
: root_{std::move(root)}, cas_dir_{root_ / "cas" / "blobs"}, staging_dir_{root_ / "staging"},
|
||||||
|
leases_dir_{root_ / "leases"}, db_file_{root_ / "state" / "state.v1.json"},
|
||||||
|
lock_file_{root_ / "state" / "state.lock"} {}
|
||||||
|
|
||||||
|
Void::Result::Result<StateStore, Void::Result::Error>
|
||||||
|
StateStore::open(const std::filesystem::path &vbs_dir) {
|
||||||
|
StateStore store{vbs_dir};
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::create_directories(store.cas_dir_, ec);
|
||||||
|
std::filesystem::create_directories(store.staging_dir_, ec);
|
||||||
|
std::filesystem::create_directories(store.leases_dir_, ec);
|
||||||
|
std::filesystem::create_directories(store.db_file_.parent_path(), ec);
|
||||||
|
if (ec) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::map_errno_to_system_code(ec.value()),
|
||||||
|
std::format("StateStore::open: cannot create directories under '{}': {}",
|
||||||
|
vbs_dir.string(), ec.message()),
|
||||||
|
ec.value())};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto lock = Platform::FileLock::acquire(store.lock_file_, Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (std::filesystem::exists(store.db_file_, ec)) {
|
||||||
|
auto loaded = store.load_db_locked();
|
||||||
|
if (!loaded) {
|
||||||
|
return std::unexpected{loaded.error()};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
DatabaseSnapshot initial;
|
||||||
|
auto saved = store.save_db_locked(initial);
|
||||||
|
if (!saved) {
|
||||||
|
return std::unexpected{saved.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path StateStore::cas_blob_path(std::string_view sha256) const {
|
||||||
|
if (sha256.size() < 2) {
|
||||||
|
return cas_dir_ / std::string{sha256};
|
||||||
|
}
|
||||||
|
return cas_dir_ / std::string{sha256.substr(0, 2)} / std::string{sha256};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<StateStore::DatabaseSnapshot, Void::Result::Error>
|
||||||
|
StateStore::load_db_locked() const {
|
||||||
|
auto content = Void::FileSystem::read_file_bounded(db_file_, {128ULL * 1024ULL * 1024ULL});
|
||||||
|
if (!content) {
|
||||||
|
return std::unexpected{content.error()};
|
||||||
|
}
|
||||||
|
if (!Util::is_valid_utf8(*content)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("StateStore: corrupt state database '{}' (invalid UTF-8)",
|
||||||
|
db_file_.string()))};
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*content);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("StateStore: corrupt state database '{}' (JSON parse failure)",
|
||||||
|
db_file_.string()))};
|
||||||
|
}
|
||||||
|
const auto *root_obj = std::get_if<JsonVal::Object>(&parsed->value);
|
||||||
|
if (!root_obj) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"StateStore: root state must be a JSON object")};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto version = get_i64(*root_obj, "schema_version");
|
||||||
|
if (!version) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"StateStore: missing schema_version")};
|
||||||
|
}
|
||||||
|
if (*version > kStateSchemaVersion) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format("StateStore: unsupported newer schema version {} (supported <= {})",
|
||||||
|
*version, kStateSchemaVersion))};
|
||||||
|
}
|
||||||
|
if (*version < 1) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"StateStore: invalid schema version")};
|
||||||
|
}
|
||||||
|
|
||||||
|
DatabaseSnapshot snap;
|
||||||
|
snap.schema_version = static_cast<int>(*version);
|
||||||
|
snap.next_sequence =
|
||||||
|
static_cast<std::uint64_t>(get_i64(*root_obj, "next_sequence").value_or(1));
|
||||||
|
|
||||||
|
if (const auto *actions_val = find_key(*root_obj, "actions")) {
|
||||||
|
const auto *arr = std::get_if<JsonVal::Array>(&actions_val->value);
|
||||||
|
if (!arr) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"StateStore: corrupt actions array")};
|
||||||
|
}
|
||||||
|
for (const auto &item : *arr) {
|
||||||
|
const auto *obj = std::get_if<JsonVal::Object>(&item.value);
|
||||||
|
if (!obj) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ActionSuccessRecord rec;
|
||||||
|
rec.action_key = get_str(*obj, "action_key").value_or("");
|
||||||
|
rec.profile_identity = get_str(*obj, "profile_identity").value_or("");
|
||||||
|
rec.target_name = get_str(*obj, "target_name").value_or("");
|
||||||
|
rec.recorded_epoch = get_i64(*obj, "recorded_epoch").value_or(0);
|
||||||
|
if (const auto *outs = find_key(*obj, "outputs")) {
|
||||||
|
if (const auto *oobj = std::get_if<JsonVal::Object>(&outs->value)) {
|
||||||
|
for (const auto &[path, refv] : *oobj) {
|
||||||
|
if (const auto *robj = std::get_if<JsonVal::Object>(&refv.value)) {
|
||||||
|
BlobRef ref;
|
||||||
|
ref.sha256 = get_str(*robj, "sha256").value_or("");
|
||||||
|
ref.size =
|
||||||
|
static_cast<std::uint64_t>(get_i64(*robj, "size").value_or(0));
|
||||||
|
ref.mode =
|
||||||
|
static_cast<std::uint32_t>(get_i64(*robj, "mode").value_or(0644));
|
||||||
|
rec.outputs[path] = std::move(ref);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (const auto *deps = find_key(*obj, "discovered_inputs")) {
|
||||||
|
if (const auto *dobj = std::get_if<JsonVal::Object>(&deps->value)) {
|
||||||
|
for (const auto &[path, dv] : *dobj) {
|
||||||
|
if (const auto *s = std::get_if<std::string>(&dv.value)) {
|
||||||
|
rec.discovered_inputs[path] = *s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (const auto *guards = find_key(*obj, "lookup_guards")) {
|
||||||
|
if (const auto *garr = std::get_if<JsonVal::Array>(&guards->value)) {
|
||||||
|
for (const auto &gv : *garr) {
|
||||||
|
if (const auto *gobj = std::get_if<JsonVal::Object>(&gv.value)) {
|
||||||
|
Snapshot::LookupGuard g;
|
||||||
|
g.lookup_name = get_str(*gobj, "lookup_name").value_or("");
|
||||||
|
g.matched_root_index =
|
||||||
|
static_cast<int>(get_i64(*gobj, "matched_root_index").value_or(-1));
|
||||||
|
g.matched_sha256 = get_str(*gobj, "matched_sha256").value_or("");
|
||||||
|
if (const auto *sr = find_key(*gobj, "search_roots")) {
|
||||||
|
if (const auto *sarr = std::get_if<JsonVal::Array>(&sr->value)) {
|
||||||
|
for (const auto &rv : *sarr) {
|
||||||
|
if (const auto *rs = std::get_if<std::string>(&rv.value)) {
|
||||||
|
g.search_roots.push_back(*rs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rec.lookup_guards.push_back(std::move(g));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!rec.action_key.empty()) {
|
||||||
|
snap.actions[rec.action_key] = std::move(rec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (const auto *gens_val = find_key(*root_obj, "generations")) {
|
||||||
|
const auto *arr = std::get_if<JsonVal::Array>(&gens_val->value);
|
||||||
|
if (!arr) {
|
||||||
|
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
|
||||||
|
"StateStore: corrupt generations array")};
|
||||||
|
}
|
||||||
|
for (const auto &item : *arr) {
|
||||||
|
const auto *obj = std::get_if<JsonVal::Object>(&item.value);
|
||||||
|
if (!obj) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
GraphGenerationRecord gen;
|
||||||
|
gen.generation_id = get_str(*obj, "generation_id").value_or("");
|
||||||
|
gen.profile_name = get_str(*obj, "profile_name").value_or("");
|
||||||
|
gen.profile_identity = get_str(*obj, "profile_identity").value_or("");
|
||||||
|
gen.snapshot_id = get_str(*obj, "snapshot_id").value_or("");
|
||||||
|
gen.status = get_str(*obj, "status").value_or("invalid");
|
||||||
|
gen.diagnostic = get_str(*obj, "diagnostic").value_or("");
|
||||||
|
gen.sequence = static_cast<std::uint64_t>(get_i64(*obj, "sequence").value_or(0));
|
||||||
|
snap.generations.push_back(std::move(gen));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return snap;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
StateStore::save_db_locked(const DatabaseSnapshot &db) const {
|
||||||
|
std::string json = "{\"schema_version\":" + std::to_string(db.schema_version) +
|
||||||
|
",\"next_sequence\":" + std::to_string(db.next_sequence) + ",\"actions\":[";
|
||||||
|
bool first = true;
|
||||||
|
for (const auto &[key, rec] : db.actions) {
|
||||||
|
if (!first) {
|
||||||
|
json += ',';
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
json += serialize_action(rec);
|
||||||
|
}
|
||||||
|
json += "],\"generations\":[";
|
||||||
|
first = true;
|
||||||
|
for (const auto &gen : db.generations) {
|
||||||
|
if (!first) {
|
||||||
|
json += ',';
|
||||||
|
}
|
||||||
|
first = false;
|
||||||
|
json += serialize_generation(gen);
|
||||||
|
}
|
||||||
|
json += "]}\n";
|
||||||
|
return Platform::atomic_write_file(db_file_, json, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<BlobRef, Void::Result::Error>
|
||||||
|
StateStore::store_blob_from_file(const std::filesystem::path &file_path) {
|
||||||
|
auto meta = Platform::stat_lstat(file_path);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists || !meta->is_regular) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::not_found,
|
||||||
|
std::format("StateStore: cannot store non-regular file '{}'", file_path.string()))};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto stage_path =
|
||||||
|
staging_dir_ / std::format("blob_{}_{}.stage", static_cast<long long>(::getpid()),
|
||||||
|
g_lease_seq.fetch_add(1, std::memory_order_relaxed));
|
||||||
|
auto copied = Platform::copy_isolated(file_path, stage_path, meta->mode);
|
||||||
|
if (!copied) {
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
auto digest = Util::sha256_file_hex(stage_path);
|
||||||
|
std::error_code ec;
|
||||||
|
if (!digest) {
|
||||||
|
std::filesystem::remove(stage_path, ec);
|
||||||
|
return std::unexpected{digest.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto final_path = cas_blob_path(*digest);
|
||||||
|
std::filesystem::create_directories(final_path.parent_path(), ec);
|
||||||
|
if (std::filesystem::exists(final_path, ec)) {
|
||||||
|
// Verify existing blob integrity before deduplicating.
|
||||||
|
auto existing_ok = verify_blob(*digest);
|
||||||
|
if (existing_ok && *existing_ok) {
|
||||||
|
std::filesystem::remove(stage_path, ec);
|
||||||
|
} else {
|
||||||
|
(void)::chmod(final_path.c_str(), 0644);
|
||||||
|
std::filesystem::rename(stage_path, final_path, ec);
|
||||||
|
(void)::chmod(final_path.c_str(), 0444);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
(void)::chmod(stage_path.c_str(), 0444);
|
||||||
|
std::filesystem::rename(stage_path, final_path, ec);
|
||||||
|
if (ec) {
|
||||||
|
std::filesystem::remove(stage_path, ec);
|
||||||
|
if (!std::filesystem::exists(final_path, ec)) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("StateStore: failed publishing CAS blob '{}'", *digest))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(void)Platform::fsync_directory(final_path.parent_path());
|
||||||
|
}
|
||||||
|
|
||||||
|
BlobRef ref;
|
||||||
|
ref.sha256 = std::move(*digest);
|
||||||
|
ref.size = meta->size;
|
||||||
|
ref.mode = meta->mode & 0777u;
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<bool, Void::Result::Error>
|
||||||
|
StateStore::verify_blob(std::string_view sha256) const {
|
||||||
|
if (!is_valid_sha256_hex(sha256)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto path = cas_blob_path(sha256);
|
||||||
|
auto meta = Platform::stat_lstat(path);
|
||||||
|
if (!meta) {
|
||||||
|
return std::unexpected{meta.error()};
|
||||||
|
}
|
||||||
|
if (!meta->exists || !meta->is_regular) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
auto actual = Util::sha256_file_hex(path);
|
||||||
|
if (!actual) {
|
||||||
|
return std::unexpected{actual.error()};
|
||||||
|
}
|
||||||
|
return *actual == sha256;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
StateStore::materialize_blob(const BlobRef &ref, const std::filesystem::path &destination) const {
|
||||||
|
auto ok = verify_blob(ref.sha256);
|
||||||
|
if (!ok) {
|
||||||
|
return std::unexpected{ok.error()};
|
||||||
|
}
|
||||||
|
if (!*ok) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::io_error,
|
||||||
|
std::format("StateStore: CAS blob '{}' is missing or corrupted", ref.sha256))};
|
||||||
|
}
|
||||||
|
auto copied = Platform::copy_isolated(cas_blob_path(ref.sha256), destination, ref.mode);
|
||||||
|
if (!copied) {
|
||||||
|
return std::unexpected{copied.error()};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<ActionSuccessRecord>, Void::Result::Error>
|
||||||
|
StateStore::lookup_action(std::string_view action_key) const {
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
auto db = load_db_locked();
|
||||||
|
if (!db) {
|
||||||
|
return std::unexpected{db.error()};
|
||||||
|
}
|
||||||
|
const auto it = db->actions.find(action_key);
|
||||||
|
if (it == db->actions.end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
// Verify every referenced CAS blob still exists and is intact.
|
||||||
|
for (const auto &[out_path, ref] : it->second.outputs) {
|
||||||
|
auto ok = verify_blob(ref.sha256);
|
||||||
|
if (!ok || !*ok) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
StateStore::record_action_success(const ActionSuccessRecord &record) {
|
||||||
|
// Publication invariant: all output blobs MUST be present and verified before commit.
|
||||||
|
for (const auto &[out_path, ref] : record.outputs) {
|
||||||
|
auto ok = verify_blob(ref.sha256);
|
||||||
|
if (!ok || !*ok) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::format(
|
||||||
|
"StateStore: refusing to commit action '{}' referencing unverified blob '{}'",
|
||||||
|
record.action_key, ref.sha256))};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
auto db = load_db_locked();
|
||||||
|
if (!db) {
|
||||||
|
return std::unexpected{db.error()};
|
||||||
|
}
|
||||||
|
db->actions[record.action_key] = record;
|
||||||
|
return save_db_locked(*db);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void, Void::Result::Error>
|
||||||
|
StateStore::record_generation(const GraphGenerationRecord &generation) {
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
auto db = load_db_locked();
|
||||||
|
if (!db) {
|
||||||
|
return std::unexpected{db.error()};
|
||||||
|
}
|
||||||
|
GraphGenerationRecord copy = generation;
|
||||||
|
copy.sequence = db->next_sequence++;
|
||||||
|
db->generations.push_back(std::move(copy));
|
||||||
|
// Keep bounded recent history per store.
|
||||||
|
if (db->generations.size() > 512) {
|
||||||
|
db->generations.erase(db->generations.begin(),
|
||||||
|
db->generations.begin() +
|
||||||
|
static_cast<std::ptrdiff_t>(db->generations.size() - 512));
|
||||||
|
}
|
||||||
|
return save_db_locked(*db);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<GraphGenerationRecord>, Void::Result::Error>
|
||||||
|
StateStore::list_generations(std::optional<std::string_view> profile_name) const {
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
auto db = load_db_locked();
|
||||||
|
if (!db) {
|
||||||
|
return std::unexpected{db.error()};
|
||||||
|
}
|
||||||
|
if (!profile_name) {
|
||||||
|
return db->generations;
|
||||||
|
}
|
||||||
|
std::vector<GraphGenerationRecord> filtered;
|
||||||
|
for (const auto &g : db->generations) {
|
||||||
|
if (g.profile_name == *profile_name) {
|
||||||
|
filtered.push_back(g);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return filtered;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<LeaseHandle, Void::Result::Error>
|
||||||
|
StateStore::acquire_lease(std::string_view profile_name,
|
||||||
|
const std::set<std::string> &pinned_blobs) {
|
||||||
|
using Util::json_array;
|
||||||
|
using Util::json_quote;
|
||||||
|
|
||||||
|
const auto seq = g_lease_seq.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
const auto pid = static_cast<long long>(::getpid());
|
||||||
|
LeaseHandle handle;
|
||||||
|
handle.lease_id = std::format("lease_{}_{}", pid, seq);
|
||||||
|
handle.lease_file = leases_dir_ / (handle.lease_id + ".json");
|
||||||
|
|
||||||
|
std::string payload = "{\"pid\":" + std::to_string(pid) +
|
||||||
|
",\"profile\":" + json_quote(profile_name) +
|
||||||
|
",\"blobs\":" + json_array(pinned_blobs, json_quote) + "}\n";
|
||||||
|
auto written = Platform::atomic_write_file(handle.lease_file, payload, false);
|
||||||
|
if (!written) {
|
||||||
|
return std::unexpected{written.error()};
|
||||||
|
}
|
||||||
|
return handle;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::size_t, Void::Result::Error> StateStore::recover() {
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t cleaned = 0;
|
||||||
|
std::error_code ec;
|
||||||
|
|
||||||
|
// 1. Remove uncommitted staging files inside managed staging directory only.
|
||||||
|
if (std::filesystem::is_directory(staging_dir_, ec)) {
|
||||||
|
for (const auto &entry : std::filesystem::directory_iterator(staging_dir_, ec)) {
|
||||||
|
std::filesystem::remove_all(entry.path(), ec);
|
||||||
|
if (!ec) {
|
||||||
|
++cleaned;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Reap dead-PID leases.
|
||||||
|
if (std::filesystem::is_directory(leases_dir_, ec)) {
|
||||||
|
for (const auto &entry : std::filesystem::directory_iterator(leases_dir_, ec)) {
|
||||||
|
if (!entry.is_regular_file()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto content = Void::FileSystem::read_file(entry.path());
|
||||||
|
if (!content) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*content);
|
||||||
|
if (!parsed) {
|
||||||
|
std::filesystem::remove(entry.path(), ec);
|
||||||
|
++cleaned;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
|
||||||
|
const auto pid = get_i64(*obj, "pid").value_or(0);
|
||||||
|
if (!pid_is_alive(static_cast<pid_t>(pid))) {
|
||||||
|
std::filesystem::remove(entry.path(), ec);
|
||||||
|
++cleaned;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Validate DB parses cleanly; drop action records whose CAS blobs are missing/corrupt.
|
||||||
|
auto db = load_db_locked();
|
||||||
|
if (!db) {
|
||||||
|
return std::unexpected{db.error()};
|
||||||
|
}
|
||||||
|
bool dirty = false;
|
||||||
|
for (auto it = db->actions.begin(); it != db->actions.end();) {
|
||||||
|
bool valid = true;
|
||||||
|
for (const auto &[out_path, ref] : it->second.outputs) {
|
||||||
|
auto ok = verify_blob(ref.sha256);
|
||||||
|
if (!ok || !*ok) {
|
||||||
|
valid = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!valid) {
|
||||||
|
it = db->actions.erase(it);
|
||||||
|
dirty = true;
|
||||||
|
++cleaned;
|
||||||
|
} else {
|
||||||
|
++it;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (dirty) {
|
||||||
|
auto saved = save_db_locked(*db);
|
||||||
|
if (!saved) {
|
||||||
|
return std::unexpected{saved.error()};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cleaned;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<GcStats, Void::Result::Error> StateStore::gc(std::uint64_t max_cache_bytes) {
|
||||||
|
GcStats stats;
|
||||||
|
auto cleaned_res = recover();
|
||||||
|
if (!cleaned_res) {
|
||||||
|
return std::unexpected{cleaned_res.error()};
|
||||||
|
}
|
||||||
|
stats.cleaned_staging_files = *cleaned_res;
|
||||||
|
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
|
||||||
|
if (!lock) {
|
||||||
|
return std::unexpected{lock.error()};
|
||||||
|
}
|
||||||
|
auto db = load_db_locked();
|
||||||
|
if (!db) {
|
||||||
|
return std::unexpected{db.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::set<std::string> pinned;
|
||||||
|
for (const auto &[key, rec] : db->actions) {
|
||||||
|
for (const auto &[out, ref] : rec.outputs) {
|
||||||
|
pinned.insert(ref.sha256);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect blobs pinned by live leases.
|
||||||
|
std::error_code ec;
|
||||||
|
if (std::filesystem::is_directory(leases_dir_, ec)) {
|
||||||
|
for (const auto &entry : std::filesystem::directory_iterator(leases_dir_, ec)) {
|
||||||
|
auto content = Void::FileSystem::read_file(entry.path());
|
||||||
|
if (!content) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto parsed = Void::Json::Strict::parse(*content);
|
||||||
|
if (!parsed) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
|
||||||
|
const auto pid = get_i64(*obj, "pid").value_or(0);
|
||||||
|
if (!pid_is_alive(static_cast<pid_t>(pid))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (const auto *blobs = find_key(*obj, "blobs")) {
|
||||||
|
if (const auto *arr = std::get_if<JsonVal::Array>(&blobs->value)) {
|
||||||
|
for (const auto &bv : *arr) {
|
||||||
|
if (const auto *s = std::get_if<std::string>(&bv.value)) {
|
||||||
|
pinned.insert(*s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove unpinned blobs inside cas_dir_ ONLY.
|
||||||
|
std::uint64_t retained_bytes = 0;
|
||||||
|
if (std::filesystem::is_directory(cas_dir_, ec)) {
|
||||||
|
for (const auto &bucket : std::filesystem::directory_iterator(cas_dir_, ec)) {
|
||||||
|
if (!bucket.is_directory()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const auto &entry : std::filesystem::directory_iterator(bucket.path(), ec)) {
|
||||||
|
if (!entry.is_regular_file()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const std::string sha = entry.path().filename().string();
|
||||||
|
const auto fsize = entry.file_size(ec);
|
||||||
|
if (!pinned.contains(sha)) {
|
||||||
|
(void)::chmod(entry.path().c_str(), 0644);
|
||||||
|
std::filesystem::remove(entry.path(), ec);
|
||||||
|
if (!ec) {
|
||||||
|
++stats.removed_blobs;
|
||||||
|
stats.freed_bytes += fsize;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
++stats.retained_blobs;
|
||||||
|
retained_bytes += fsize;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (max_cache_bytes > 0 && retained_bytes > max_cache_bytes) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
Void::System::SystemErrorCode::limit_exceeded,
|
||||||
|
std::format(
|
||||||
|
"StateStore::gc: active pinned cache size ({} bytes) exceeds quota ({} bytes)",
|
||||||
|
retained_bytes, max_cache_bytes))};
|
||||||
|
}
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t StateStore::recorded_action_count() const {
|
||||||
|
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
|
||||||
|
if (!lock) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
auto db = load_db_locked();
|
||||||
|
return db ? db->actions.size() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::State
|
||||||
@@ -0,0 +1,717 @@
|
|||||||
|
#include <Void/Build/Toolchain/Driver.hpp>
|
||||||
|
|
||||||
|
#include <Void/Build/Platform/FileOps.hpp>
|
||||||
|
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||||
|
#include <Void/Build/Util/Json.hpp>
|
||||||
|
#include <Void/Build/Util/Sha256.hpp>
|
||||||
|
#include <Void/Configuration/Env.hpp>
|
||||||
|
#include <Void/Data/StrictJson.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
|
#include <Void/System/TempDir.hpp>
|
||||||
|
#include <Void/System/Types.hpp>
|
||||||
|
#include <Void/Text/Str.hpp>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <format>
|
||||||
|
#include <sys/utsname.h>
|
||||||
|
|
||||||
|
namespace Void::Build::Toolchain {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Void::Result::Error make_error(std::string message) {
|
||||||
|
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||||
|
std::move(message));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string trim(std::string_view text) { return std::string{Void::Str::trim_ascii(text)}; }
|
||||||
|
|
||||||
|
std::map<std::string, std::string, std::less<>> capture_relevant_env() {
|
||||||
|
static constexpr const char *kKeys[] = {"CPATH",
|
||||||
|
"C_INCLUDE_PATH",
|
||||||
|
"CPLUS_INCLUDE_PATH",
|
||||||
|
"LIBRARY_PATH",
|
||||||
|
"COMPILER_PATH",
|
||||||
|
"GCC_EXEC_PREFIX",
|
||||||
|
"NIX_CFLAGS_COMPILE",
|
||||||
|
"NIX_LDFLAGS",
|
||||||
|
"NIX_CXXSTDLIB_COMPILE",
|
||||||
|
"NIX_CXXSTDLIB_LINK"};
|
||||||
|
std::map<std::string, std::string, std::less<>> env;
|
||||||
|
for (const char *key : kKeys) {
|
||||||
|
if (auto val = Void::Configuration::get_env(key); val) {
|
||||||
|
env[key] = std::move(*val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool probe_compile_flag(const std::filesystem::path &compiler, const std::string &sysroot,
|
||||||
|
const std::vector<std::string> &extra_flags, std::string_view source_code) {
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = compiler;
|
||||||
|
req.arguments = {"-x", "c++", "-fsyntax-only"};
|
||||||
|
if (!sysroot.empty()) {
|
||||||
|
req.arguments.push_back("--sysroot=" + sysroot);
|
||||||
|
}
|
||||||
|
req.arguments.insert(req.arguments.end(), extra_flags.begin(), extra_flags.end());
|
||||||
|
req.arguments.push_back("-");
|
||||||
|
req.stdin_data = std::string{source_code};
|
||||||
|
req.timeout = std::chrono::seconds{15};
|
||||||
|
auto res = Platform::run_supervised(req);
|
||||||
|
return res.has_value() && res->succeeded();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t estimate_argv_bytes(const std::vector<std::string> &args) {
|
||||||
|
std::size_t total = 0;
|
||||||
|
for (const auto &arg : args) {
|
||||||
|
total += arg.size() + 1;
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string cxx_standard_flag(CxxStandard standard) {
|
||||||
|
switch (standard) {
|
||||||
|
case CxxStandard::Default:
|
||||||
|
return {};
|
||||||
|
case CxxStandard::Cxx17:
|
||||||
|
return "-std=c++17";
|
||||||
|
case CxxStandard::Cxx20:
|
||||||
|
return "-std=c++20";
|
||||||
|
case CxxStandard::Cxx23:
|
||||||
|
return "-std=c++23";
|
||||||
|
case CxxStandard::Cxx26:
|
||||||
|
return "-std=c++26";
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string sanitizer_flag_value(Sanitizer s) {
|
||||||
|
switch (s) {
|
||||||
|
case Sanitizer::Address:
|
||||||
|
return "address";
|
||||||
|
case Sanitizer::Undefined:
|
||||||
|
return "undefined";
|
||||||
|
case Sanitizer::Thread:
|
||||||
|
return "thread";
|
||||||
|
case Sanitizer::Memory:
|
||||||
|
return "memory";
|
||||||
|
case Sanitizer::Leak:
|
||||||
|
return "leak";
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string serialize_capabilities(const ToolchainCapabilities &cap) {
|
||||||
|
using Util::json_array;
|
||||||
|
using Util::json_quote;
|
||||||
|
std::string out = "{";
|
||||||
|
out += "\"family\":" + json_quote(compiler_name(cap.family));
|
||||||
|
out += ",\"cxx_compiler\":" + json_quote(cap.cxx_compiler.string());
|
||||||
|
out += ",\"archiver\":" + json_quote(cap.archiver.string());
|
||||||
|
out += ",\"module_scanner\":" +
|
||||||
|
json_quote(cap.module_scanner ? cap.module_scanner->string() : std::string{});
|
||||||
|
out += ",\"version_banner\":" + json_quote(cap.version_banner);
|
||||||
|
out += ",\"target_triple\":" + json_quote(cap.target_triple);
|
||||||
|
out += ",\"sysroot\":" + json_quote(cap.sysroot);
|
||||||
|
out += ",\"compiler_sha256\":" + json_quote(cap.compiler_sha256);
|
||||||
|
out += ",\"archiver_sha256\":" + json_quote(cap.archiver_sha256);
|
||||||
|
out += ",\"supports_cxx17\":" + std::string{cap.supports_cxx17 ? "true" : "false"};
|
||||||
|
out += ",\"supports_cxx20\":" + std::string{cap.supports_cxx20 ? "true" : "false"};
|
||||||
|
out += ",\"supports_cxx23\":" + std::string{cap.supports_cxx23 ? "true" : "false"};
|
||||||
|
out += ",\"supports_cxx26\":" + std::string{cap.supports_cxx26 ? "true" : "false"};
|
||||||
|
out += ",\"supports_reflection\":" + std::string{cap.supports_reflection ? "true" : "false"};
|
||||||
|
out += ",\"supports_file_prefix_map\":" +
|
||||||
|
std::string{cap.supports_file_prefix_map ? "true" : "false"};
|
||||||
|
out += ",\"supports_macro_prefix_map\":" +
|
||||||
|
std::string{cap.supports_macro_prefix_map ? "true" : "false"};
|
||||||
|
out += ",\"supports_debug_prefix_map\":" +
|
||||||
|
std::string{cap.supports_debug_prefix_map ? "true" : "false"};
|
||||||
|
out += ",\"supports_p1689_scan\":" + std::string{cap.supports_p1689_scan ? "true" : "false"};
|
||||||
|
out += ",\"supports_pch\":" + std::string{cap.supports_pch ? "true" : "false"};
|
||||||
|
out += ",\"supports_lto_full\":" + std::string{cap.supports_lto_full ? "true" : "false"};
|
||||||
|
out += ",\"supports_lto_thin\":" + std::string{cap.supports_lto_thin ? "true" : "false"};
|
||||||
|
out += ",\"supports_asan\":" + std::string{cap.supports_asan ? "true" : "false"};
|
||||||
|
out += ",\"supports_ubsan\":" + std::string{cap.supports_ubsan ? "true" : "false"};
|
||||||
|
out += ",\"supports_tsan\":" + std::string{cap.supports_tsan ? "true" : "false"};
|
||||||
|
out += ",\"is_cross_toolchain\":" + std::string{cap.is_cross_toolchain ? "true" : "false"};
|
||||||
|
out += ",\"identity_hash\":" + json_quote(cap.identity_hash);
|
||||||
|
out += "}";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ToolchainCapabilities> deserialize_capabilities(std::string_view text) {
|
||||||
|
const auto parsed = Void::Json::Strict::parse(text);
|
||||||
|
if (!parsed) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *obj = std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
|
||||||
|
if (!obj) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
auto get_str = [&](const std::string &k) -> std::optional<std::string> {
|
||||||
|
const auto it = obj->find(k);
|
||||||
|
if (it == obj->end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *s = std::get_if<std::string>(&it->second.value);
|
||||||
|
return s ? std::optional<std::string>{*s} : std::nullopt;
|
||||||
|
};
|
||||||
|
auto get_bool = [&](const std::string &k) -> std::optional<bool> {
|
||||||
|
const auto it = obj->find(k);
|
||||||
|
if (it == obj->end()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const auto *b = std::get_if<bool>(&it->second.value);
|
||||||
|
return b ? std::optional<bool>{*b} : std::nullopt;
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
ToolchainCapabilities cap;
|
||||||
|
cap.family = parse_compiler(get_str("family").value_or(""));
|
||||||
|
cap.cxx_compiler = get_str("cxx_compiler").value_or("");
|
||||||
|
cap.archiver = get_str("archiver").value_or("");
|
||||||
|
if (auto scanner = get_str("module_scanner"); scanner && !scanner->empty()) {
|
||||||
|
cap.module_scanner = *scanner;
|
||||||
|
}
|
||||||
|
cap.version_banner = get_str("version_banner").value_or("");
|
||||||
|
cap.target_triple = get_str("target_triple").value_or("");
|
||||||
|
cap.sysroot = get_str("sysroot").value_or("");
|
||||||
|
cap.compiler_sha256 = get_str("compiler_sha256").value_or("");
|
||||||
|
cap.archiver_sha256 = get_str("archiver_sha256").value_or("");
|
||||||
|
cap.supports_cxx17 = get_bool("supports_cxx17").value_or(false);
|
||||||
|
cap.supports_cxx20 = get_bool("supports_cxx20").value_or(false);
|
||||||
|
cap.supports_cxx23 = get_bool("supports_cxx23").value_or(false);
|
||||||
|
cap.supports_cxx26 = get_bool("supports_cxx26").value_or(false);
|
||||||
|
cap.supports_reflection = get_bool("supports_reflection").value_or(false);
|
||||||
|
cap.supports_file_prefix_map = get_bool("supports_file_prefix_map").value_or(false);
|
||||||
|
cap.supports_macro_prefix_map = get_bool("supports_macro_prefix_map").value_or(false);
|
||||||
|
cap.supports_debug_prefix_map = get_bool("supports_debug_prefix_map").value_or(false);
|
||||||
|
cap.supports_p1689_scan = get_bool("supports_p1689_scan").value_or(false);
|
||||||
|
cap.supports_pch = get_bool("supports_pch").value_or(true);
|
||||||
|
cap.supports_lto_full = get_bool("supports_lto_full").value_or(false);
|
||||||
|
cap.supports_lto_thin = get_bool("supports_lto_thin").value_or(false);
|
||||||
|
cap.supports_asan = get_bool("supports_asan").value_or(false);
|
||||||
|
cap.supports_ubsan = get_bool("supports_ubsan").value_or(false);
|
||||||
|
cap.supports_tsan = get_bool("supports_tsan").value_or(false);
|
||||||
|
cap.is_cross_toolchain = get_bool("is_cross_toolchain").value_or(false);
|
||||||
|
cap.identity_hash = get_str("identity_hash").value_or("");
|
||||||
|
if (cap.identity_hash.empty() || cap.cxx_compiler.empty()) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return cap;
|
||||||
|
} catch (...) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string host_os_name() {
|
||||||
|
struct utsname u{};
|
||||||
|
if (::uname(&u) == 0) {
|
||||||
|
return std::string{u.sysname};
|
||||||
|
}
|
||||||
|
return "Linux";
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string host_architecture_name() {
|
||||||
|
struct utsname u{};
|
||||||
|
if (::uname(&u) == 0) {
|
||||||
|
return std::string{u.machine};
|
||||||
|
}
|
||||||
|
return "x86_64";
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<ToolchainCapabilities, Void::Result::Error>
|
||||||
|
discover_and_probe(const ProfileContext &context,
|
||||||
|
const std::optional<std::filesystem::path> &cache_dir) {
|
||||||
|
std::filesystem::path requested_compiler;
|
||||||
|
if (!context.compiler_path.empty()) {
|
||||||
|
requested_compiler = context.compiler_path;
|
||||||
|
} else if (context.compiler == CompilerFamily::Gcc) {
|
||||||
|
requested_compiler = "g++";
|
||||||
|
} else {
|
||||||
|
requested_compiler = "clang++";
|
||||||
|
}
|
||||||
|
|
||||||
|
auto resolved_compiler = Platform::resolve_executable(requested_compiler);
|
||||||
|
if (!resolved_compiler) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(std::format("toolchain compiler '{}' for family '{}' was not found in PATH",
|
||||||
|
requested_compiler.string(), compiler_name(context.compiler)))};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::filesystem::path> resolved_ar;
|
||||||
|
if (context.compiler == CompilerFamily::Clang) {
|
||||||
|
resolved_ar = Platform::resolve_executable("llvm-ar");
|
||||||
|
}
|
||||||
|
if (!resolved_ar) {
|
||||||
|
resolved_ar = Platform::resolve_executable("ar");
|
||||||
|
}
|
||||||
|
if (!resolved_ar) {
|
||||||
|
return std::unexpected{make_error("archiver ('ar' or 'llvm-ar') was not found in PATH")};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!context.sysroot.empty() && !std::filesystem::is_directory(context.sysroot)) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error(std::format("configured sysroot '{}' does not exist", context.sysroot))};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto comp_hash = Util::sha256_file_hex(*resolved_compiler);
|
||||||
|
if (!comp_hash) {
|
||||||
|
return std::unexpected{comp_hash.error()};
|
||||||
|
}
|
||||||
|
auto ar_hash = Util::sha256_file_hex(*resolved_ar);
|
||||||
|
if (!ar_hash) {
|
||||||
|
return std::unexpected{ar_hash.error()};
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto relevant_env = capture_relevant_env();
|
||||||
|
|
||||||
|
// Compute cache key BEFORE expensive compiler probes.
|
||||||
|
Util::Sha256Hasher key_hasher;
|
||||||
|
key_hasher.update_length_prefixed(compiler_name(context.compiler));
|
||||||
|
key_hasher.update_length_prefixed(resolved_compiler->string());
|
||||||
|
key_hasher.update_length_prefixed(*comp_hash);
|
||||||
|
key_hasher.update_length_prefixed(resolved_ar->string());
|
||||||
|
key_hasher.update_length_prefixed(*ar_hash);
|
||||||
|
key_hasher.update_length_prefixed(context.sysroot);
|
||||||
|
key_hasher.update_length_prefixed(context.os);
|
||||||
|
key_hasher.update_length_prefixed(context.architecture);
|
||||||
|
for (const auto &[k, v] : relevant_env) {
|
||||||
|
key_hasher.update_length_prefixed(k);
|
||||||
|
key_hasher.update_length_prefixed(v);
|
||||||
|
}
|
||||||
|
const std::string probe_cache_key = key_hasher.finalize_hex();
|
||||||
|
|
||||||
|
if (cache_dir) {
|
||||||
|
const auto cache_file = *cache_dir / (probe_cache_key + ".json");
|
||||||
|
if (auto cached_text = Void::FileSystem::read_file(cache_file); cached_text) {
|
||||||
|
if (auto cached = deserialize_capabilities(*cached_text); cached) {
|
||||||
|
cached->relevant_env = relevant_env;
|
||||||
|
return *cached;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ToolchainCapabilities cap;
|
||||||
|
cap.family = context.compiler;
|
||||||
|
cap.cxx_compiler = *resolved_compiler;
|
||||||
|
cap.archiver = *resolved_ar;
|
||||||
|
cap.sysroot = context.sysroot;
|
||||||
|
cap.compiler_sha256 = *comp_hash;
|
||||||
|
cap.archiver_sha256 = *ar_hash;
|
||||||
|
cap.relevant_env = relevant_env;
|
||||||
|
|
||||||
|
// Query version banner and target triple (never executes target code).
|
||||||
|
{
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = cap.cxx_compiler;
|
||||||
|
req.arguments = {"--version"};
|
||||||
|
req.timeout = std::chrono::seconds{10};
|
||||||
|
auto res = Platform::run_supervised(req);
|
||||||
|
if (!res || !res->succeeded()) {
|
||||||
|
return std::unexpected{make_error(
|
||||||
|
std::format("failed querying version of '{}'", cap.cxx_compiler.string()))};
|
||||||
|
}
|
||||||
|
const auto nl = res->stdout_data.find('\n');
|
||||||
|
cap.version_banner =
|
||||||
|
trim(nl == std::string::npos ? std::string_view{res->stdout_data}
|
||||||
|
: std::string_view{res->stdout_data}.substr(0, nl));
|
||||||
|
}
|
||||||
|
{
|
||||||
|
Platform::ProcessRequest req;
|
||||||
|
req.executable = cap.cxx_compiler;
|
||||||
|
req.arguments = {"-dumpmachine"};
|
||||||
|
req.timeout = std::chrono::seconds{10};
|
||||||
|
auto res = Platform::run_supervised(req);
|
||||||
|
if (res && res->succeeded()) {
|
||||||
|
cap.target_triple = trim(res->stdout_data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cap.is_cross_toolchain =
|
||||||
|
(!context.architecture.empty() && context.architecture != host_architecture_name()) ||
|
||||||
|
(!context.os.empty() && context.os != host_os_name());
|
||||||
|
|
||||||
|
if (cap.family == CompilerFamily::Clang) {
|
||||||
|
cap.module_scanner = Platform::resolve_executable("clang-scan-deps");
|
||||||
|
cap.supports_p1689_scan = cap.module_scanner.has_value();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Syntax-only capability probes (safe for cross-toolchains).
|
||||||
|
constexpr std::string_view kTrivialCpp = "int vbs_probe() { return 0; }\n";
|
||||||
|
cap.supports_cxx17 =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++17"}, kTrivialCpp);
|
||||||
|
cap.supports_cxx20 =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++20"}, kTrivialCpp);
|
||||||
|
cap.supports_cxx23 =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++23"}, kTrivialCpp);
|
||||||
|
cap.supports_cxx26 =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-std=c++26"}, kTrivialCpp);
|
||||||
|
cap.supports_reflection =
|
||||||
|
cap.supports_cxx26 &&
|
||||||
|
probe_compile_flag(
|
||||||
|
cap.cxx_compiler, cap.sysroot, {"-std=c++26", "-freflection"},
|
||||||
|
"#include <meta>\nconsteval bool ok(){return true;}\nstatic_assert(ok());\n");
|
||||||
|
cap.supports_file_prefix_map =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-ffile-prefix-map=/a=/b"}, kTrivialCpp);
|
||||||
|
cap.supports_macro_prefix_map = probe_compile_flag(cap.cxx_compiler, cap.sysroot,
|
||||||
|
{"-fmacro-prefix-map=/a=/b"}, kTrivialCpp);
|
||||||
|
cap.supports_debug_prefix_map = probe_compile_flag(cap.cxx_compiler, cap.sysroot,
|
||||||
|
{"-fdebug-prefix-map=/a=/b"}, kTrivialCpp);
|
||||||
|
|
||||||
|
if (cap.family == CompilerFamily::Gcc) {
|
||||||
|
cap.supports_p1689_scan = probe_compile_flag(
|
||||||
|
cap.cxx_compiler, cap.sysroot,
|
||||||
|
{"-std=c++20", "-fmodules", "-E", "-M", "-fdeps-format=p1689r5",
|
||||||
|
"-fdeps-file=/dev/null", "-fdeps-target=probe.o", "-o", "/dev/null"},
|
||||||
|
kTrivialCpp);
|
||||||
|
}
|
||||||
|
|
||||||
|
cap.supports_lto_full =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-flto"}, kTrivialCpp);
|
||||||
|
cap.supports_lto_thin =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-flto=thin"}, kTrivialCpp);
|
||||||
|
cap.supports_asan =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-fsanitize=address"}, kTrivialCpp);
|
||||||
|
cap.supports_ubsan =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-fsanitize=undefined"}, kTrivialCpp);
|
||||||
|
cap.supports_tsan =
|
||||||
|
probe_compile_flag(cap.cxx_compiler, cap.sysroot, {"-fsanitize=thread"}, kTrivialCpp);
|
||||||
|
|
||||||
|
Util::Sha256Hasher id_hasher;
|
||||||
|
id_hasher.update_length_prefixed(probe_cache_key);
|
||||||
|
id_hasher.update_length_prefixed(cap.version_banner);
|
||||||
|
id_hasher.update_length_prefixed(cap.target_triple);
|
||||||
|
cap.identity_hash = id_hasher.finalize_hex();
|
||||||
|
|
||||||
|
if (cache_dir) {
|
||||||
|
const auto cache_file = *cache_dir / (probe_cache_key + ".json");
|
||||||
|
(void)Platform::atomic_write_file(cache_file, serialize_capabilities(cap), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return cap;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string compute_profile_identity(const ProfileContext &context,
|
||||||
|
const ToolchainCapabilities &toolchain) {
|
||||||
|
Util::Sha256Hasher hasher;
|
||||||
|
hasher.update_length_prefixed("vbs-profile-v1");
|
||||||
|
hasher.update_length_prefixed(context.name);
|
||||||
|
hasher.update_length_prefixed(compiler_name(context.compiler));
|
||||||
|
hasher.update_length_prefixed(context.os);
|
||||||
|
hasher.update_length_prefixed(context.architecture);
|
||||||
|
hasher.update_length_prefixed(toolchain.identity_hash);
|
||||||
|
hasher.update_length_prefixed(cxx_standard_name(context.cxx_standard));
|
||||||
|
hasher.update_length_prefixed(lto_mode_name(context.lto));
|
||||||
|
hasher.update_length_prefixed(context.sysroot);
|
||||||
|
hasher.update_u64(static_cast<std::uint64_t>(context.reproducibility_epoch));
|
||||||
|
hasher.update_u64(context.nondeterministic ? 1u : 0u);
|
||||||
|
hasher.update_u64(context.compile_options.size());
|
||||||
|
for (const auto &opt : context.compile_options) {
|
||||||
|
hasher.update_length_prefixed(opt);
|
||||||
|
}
|
||||||
|
hasher.update_u64(context.link_options.size());
|
||||||
|
for (const auto &opt : context.link_options) {
|
||||||
|
hasher.update_length_prefixed(opt);
|
||||||
|
}
|
||||||
|
hasher.update_u64(context.defines.size());
|
||||||
|
for (const auto &def : context.defines) {
|
||||||
|
hasher.update_length_prefixed(def);
|
||||||
|
}
|
||||||
|
hasher.update_u64(context.sanitizers.size());
|
||||||
|
for (const auto s : context.sanitizers) {
|
||||||
|
hasher.update_length_prefixed(sanitizer_name(s));
|
||||||
|
}
|
||||||
|
return hasher.finalize_hex();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string escape_response_file_arg(std::string_view arg) {
|
||||||
|
bool needs_quote = arg.empty();
|
||||||
|
for (const char c : arg) {
|
||||||
|
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '"' || c == '\\' || c == '\'') {
|
||||||
|
needs_quote = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!needs_quote) {
|
||||||
|
return std::string{arg};
|
||||||
|
}
|
||||||
|
std::string out{"\""};
|
||||||
|
for (const char c : arg) {
|
||||||
|
if (c == '"' || c == '\\') {
|
||||||
|
out.push_back('\\');
|
||||||
|
}
|
||||||
|
out.push_back(c);
|
||||||
|
}
|
||||||
|
out.push_back('"');
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<LoweredCommand, Void::Result::Error>
|
||||||
|
lower_compile_command(const ToolchainCapabilities &toolchain, const CompileRequest &request) {
|
||||||
|
if (request.source_file.empty() || request.output_object.empty()) {
|
||||||
|
return std::unexpected{make_error("compile request requires source and output paths")};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate requested capabilities explicitly (never silently downgrade).
|
||||||
|
if (request.cxx_standard == CxxStandard::Cxx17 && !toolchain.supports_cxx17) {
|
||||||
|
return std::unexpected{make_error("target compiler does not support -std=c++17")};
|
||||||
|
}
|
||||||
|
if (request.cxx_standard == CxxStandard::Cxx20 && !toolchain.supports_cxx20) {
|
||||||
|
return std::unexpected{make_error("target compiler does not support -std=c++20")};
|
||||||
|
}
|
||||||
|
if (request.cxx_standard == CxxStandard::Cxx23 && !toolchain.supports_cxx23) {
|
||||||
|
return std::unexpected{make_error("target compiler does not support -std=c++23")};
|
||||||
|
}
|
||||||
|
if (request.cxx_standard == CxxStandard::Cxx26 && !toolchain.supports_cxx26) {
|
||||||
|
return std::unexpected{make_error("target compiler does not support -std=c++26")};
|
||||||
|
}
|
||||||
|
if (request.lto == LtoMode::Full && !toolchain.supports_lto_full) {
|
||||||
|
return std::unexpected{make_error("target compiler does not support full LTO (-flto)")};
|
||||||
|
}
|
||||||
|
if (request.lto == LtoMode::Thin && !toolchain.supports_lto_thin) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error("target compiler does not support thin LTO (-flto=thin)")};
|
||||||
|
}
|
||||||
|
for (const auto s : request.sanitizers) {
|
||||||
|
if (s == Sanitizer::Address && !toolchain.supports_asan) {
|
||||||
|
return std::unexpected{make_error("target compiler does not support AddressSanitizer")};
|
||||||
|
}
|
||||||
|
if (s == Sanitizer::Undefined && !toolchain.supports_ubsan) {
|
||||||
|
return std::unexpected{
|
||||||
|
make_error("target compiler does not support UndefinedBehaviorSanitizer")};
|
||||||
|
}
|
||||||
|
if (s == Sanitizer::Thread && !toolchain.supports_tsan) {
|
||||||
|
return std::unexpected{make_error("target compiler does not support ThreadSanitizer")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!request.prefix_maps.empty() && !toolchain.supports_file_prefix_map &&
|
||||||
|
!(toolchain.supports_macro_prefix_map && toolchain.supports_debug_prefix_map)) {
|
||||||
|
return std::unexpected{make_error("target compiler lacks deterministic path-prefix-map "
|
||||||
|
"support required by snapshot mode")};
|
||||||
|
}
|
||||||
|
|
||||||
|
LoweredCommand cmd;
|
||||||
|
cmd.executable = toolchain.cxx_compiler;
|
||||||
|
|
||||||
|
std::vector<std::string> args;
|
||||||
|
if (!toolchain.sysroot.empty()) {
|
||||||
|
args.push_back("--sysroot=" + toolchain.sysroot);
|
||||||
|
}
|
||||||
|
if (const auto std_flag = cxx_standard_flag(request.cxx_standard); !std_flag.empty()) {
|
||||||
|
args.push_back(std_flag);
|
||||||
|
}
|
||||||
|
if (request.position_independent) {
|
||||||
|
args.push_back("-fPIC");
|
||||||
|
}
|
||||||
|
if (request.lto == LtoMode::Full) {
|
||||||
|
args.push_back("-flto");
|
||||||
|
} else if (request.lto == LtoMode::Thin) {
|
||||||
|
args.push_back("-flto=thin");
|
||||||
|
}
|
||||||
|
if (!request.sanitizers.empty()) {
|
||||||
|
std::string list;
|
||||||
|
for (std::size_t i = 0; i < request.sanitizers.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
list += ',';
|
||||||
|
}
|
||||||
|
list += sanitizer_flag_value(request.sanitizers[i]);
|
||||||
|
}
|
||||||
|
args.push_back("-fsanitize=" + list);
|
||||||
|
args.push_back("-fno-omit-frame-pointer");
|
||||||
|
}
|
||||||
|
if (request.is_module_interface || !request.module_bmi_imports.empty() ||
|
||||||
|
request.module_mapper_file) {
|
||||||
|
if (toolchain.family == CompilerFamily::Gcc) {
|
||||||
|
args.push_back("-fmodules");
|
||||||
|
if (request.module_mapper_file) {
|
||||||
|
args.push_back("-fmodule-mapper=" + request.module_mapper_file->string());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (request.is_module_interface && request.bmi_output) {
|
||||||
|
args.push_back("--precompile");
|
||||||
|
}
|
||||||
|
for (const auto &[mod_name, bmi_path] : request.module_bmi_imports) {
|
||||||
|
if (mod_name.empty()) {
|
||||||
|
args.push_back("-fmodule-file=" + bmi_path.string());
|
||||||
|
} else {
|
||||||
|
args.push_back("-fmodule-file=" + mod_name + "=" + bmi_path.string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (request.precompiled_header) {
|
||||||
|
args.push_back("-include");
|
||||||
|
args.push_back(request.precompiled_header->string());
|
||||||
|
}
|
||||||
|
for (const auto &pm : request.prefix_maps) {
|
||||||
|
const std::string spec = pm.from.string() + "=" + pm.to.string();
|
||||||
|
if (toolchain.supports_file_prefix_map) {
|
||||||
|
args.push_back("-ffile-prefix-map=" + spec);
|
||||||
|
} else {
|
||||||
|
args.push_back("-fmacro-prefix-map=" + spec);
|
||||||
|
args.push_back("-fdebug-prefix-map=" + spec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto &[inc, is_system] : request.include_dirs) {
|
||||||
|
args.push_back(is_system ? "-isystem" : "-I");
|
||||||
|
args.push_back(inc.string());
|
||||||
|
}
|
||||||
|
for (const auto &def : request.defines) {
|
||||||
|
args.push_back("-D" + def);
|
||||||
|
}
|
||||||
|
for (const auto &opt : request.compile_options) {
|
||||||
|
args.push_back(opt);
|
||||||
|
}
|
||||||
|
const bool clang_precompile = (toolchain.family == CompilerFamily::Clang &&
|
||||||
|
request.is_module_interface && request.bmi_output.has_value());
|
||||||
|
const std::string final_output =
|
||||||
|
clang_precompile ? request.bmi_output->string() : request.output_object.string();
|
||||||
|
if (request.depfile) {
|
||||||
|
args.push_back("-MMD");
|
||||||
|
args.push_back("-MF");
|
||||||
|
args.push_back(request.depfile->string());
|
||||||
|
args.push_back("-MT");
|
||||||
|
args.push_back(final_output);
|
||||||
|
}
|
||||||
|
if (request.compile_only && !clang_precompile) {
|
||||||
|
args.push_back("-c");
|
||||||
|
}
|
||||||
|
args.push_back(request.source_file.string());
|
||||||
|
args.push_back("-o");
|
||||||
|
args.push_back(final_output);
|
||||||
|
|
||||||
|
// Deterministic compiler metadata environment (Plan 05).
|
||||||
|
if (!request.nondeterministic) {
|
||||||
|
cmd.environment["SOURCE_DATE_EPOCH"] = std::to_string(request.reproducibility_epoch);
|
||||||
|
cmd.environment["TZ"] = "UTC";
|
||||||
|
cmd.environment["LC_ALL"] = "C";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.response_file_dir && estimate_argv_bytes(args) > request.response_file_threshold) {
|
||||||
|
std::string rsp;
|
||||||
|
for (const auto &arg : args) {
|
||||||
|
rsp += escape_response_file_arg(arg);
|
||||||
|
rsp.push_back('\n');
|
||||||
|
}
|
||||||
|
const auto rsp_hash = Util::sha256_hex(rsp).substr(0, 16);
|
||||||
|
const auto rsp_path = *request.response_file_dir /
|
||||||
|
(request.output_object.filename().string() + "." + rsp_hash + ".rsp");
|
||||||
|
cmd.response_file = rsp_path;
|
||||||
|
cmd.response_file_content = std::move(rsp);
|
||||||
|
cmd.arguments = {"@" + rsp_path.string()};
|
||||||
|
} else {
|
||||||
|
cmd.arguments = std::move(args);
|
||||||
|
}
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<LoweredCommand, Void::Result::Error>
|
||||||
|
lower_archive_command(const ToolchainCapabilities &toolchain,
|
||||||
|
const std::filesystem::path &output_archive,
|
||||||
|
const std::vector<std::filesystem::path> &object_files,
|
||||||
|
const std::optional<std::filesystem::path> &response_file_dir,
|
||||||
|
std::size_t response_file_threshold) {
|
||||||
|
if (output_archive.empty()) {
|
||||||
|
return std::unexpected{make_error("archive command requires output path")};
|
||||||
|
}
|
||||||
|
LoweredCommand cmd;
|
||||||
|
cmd.executable = toolchain.archiver;
|
||||||
|
std::vector<std::string> args;
|
||||||
|
args.push_back("rcsD");
|
||||||
|
args.push_back(output_archive.string());
|
||||||
|
for (const auto &obj : object_files) {
|
||||||
|
args.push_back(obj.string());
|
||||||
|
}
|
||||||
|
cmd.environment["TZ"] = "UTC";
|
||||||
|
cmd.environment["LC_ALL"] = "C";
|
||||||
|
|
||||||
|
if (response_file_dir && estimate_argv_bytes(args) > response_file_threshold) {
|
||||||
|
std::string rsp;
|
||||||
|
for (std::size_t i = 2; i < args.size(); ++i) {
|
||||||
|
rsp += escape_response_file_arg(args[i]);
|
||||||
|
rsp.push_back('\n');
|
||||||
|
}
|
||||||
|
const auto rsp_hash = Util::sha256_hex(rsp).substr(0, 16);
|
||||||
|
const auto rsp_path =
|
||||||
|
*response_file_dir / (output_archive.filename().string() + "." + rsp_hash + ".ar.rsp");
|
||||||
|
cmd.response_file = rsp_path;
|
||||||
|
cmd.response_file_content = std::move(rsp);
|
||||||
|
cmd.arguments = {"rcsD", output_archive.string(), "@" + rsp_path.string()};
|
||||||
|
} else {
|
||||||
|
cmd.arguments = std::move(args);
|
||||||
|
}
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<LoweredCommand, Void::Result::Error>
|
||||||
|
lower_link_command(const ToolchainCapabilities &toolchain, const LinkRequest &request) {
|
||||||
|
if (request.output_file.empty()) {
|
||||||
|
return std::unexpected{make_error("link command requires output path")};
|
||||||
|
}
|
||||||
|
LoweredCommand cmd;
|
||||||
|
cmd.executable = toolchain.cxx_compiler;
|
||||||
|
|
||||||
|
std::vector<std::string> args;
|
||||||
|
if (!toolchain.sysroot.empty()) {
|
||||||
|
args.push_back("--sysroot=" + toolchain.sysroot);
|
||||||
|
}
|
||||||
|
if (request.kind == TargetKind::SharedLibrary) {
|
||||||
|
args.push_back("-shared");
|
||||||
|
}
|
||||||
|
if (request.lto == LtoMode::Full) {
|
||||||
|
args.push_back("-flto");
|
||||||
|
} else if (request.lto == LtoMode::Thin) {
|
||||||
|
args.push_back("-flto=thin");
|
||||||
|
}
|
||||||
|
if (!request.sanitizers.empty()) {
|
||||||
|
std::string list;
|
||||||
|
for (std::size_t i = 0; i < request.sanitizers.size(); ++i) {
|
||||||
|
if (i > 0) {
|
||||||
|
list += ',';
|
||||||
|
}
|
||||||
|
list += sanitizer_flag_value(request.sanitizers[i]);
|
||||||
|
}
|
||||||
|
args.push_back("-fsanitize=" + list);
|
||||||
|
}
|
||||||
|
args.push_back("-o");
|
||||||
|
args.push_back(request.output_file.string());
|
||||||
|
for (const auto &obj : request.object_files) {
|
||||||
|
args.push_back(obj.string());
|
||||||
|
}
|
||||||
|
for (const auto &lib : request.static_libraries) {
|
||||||
|
args.push_back(lib.string());
|
||||||
|
}
|
||||||
|
for (const auto &lib : request.shared_libraries) {
|
||||||
|
args.push_back(lib.string());
|
||||||
|
}
|
||||||
|
for (const auto &rpath : request.rpaths) {
|
||||||
|
args.push_back("-Wl,-rpath," + rpath.string());
|
||||||
|
}
|
||||||
|
for (const auto &opt : request.link_options) {
|
||||||
|
args.push_back(opt);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.response_file_dir && estimate_argv_bytes(args) > request.response_file_threshold) {
|
||||||
|
std::string rsp;
|
||||||
|
for (const auto &arg : args) {
|
||||||
|
rsp += escape_response_file_arg(arg);
|
||||||
|
rsp.push_back('\n');
|
||||||
|
}
|
||||||
|
const auto rsp_hash = Util::sha256_hex(rsp).substr(0, 16);
|
||||||
|
const auto rsp_path =
|
||||||
|
*request.response_file_dir /
|
||||||
|
(request.output_file.filename().string() + "." + rsp_hash + ".ld.rsp");
|
||||||
|
cmd.response_file = rsp_path;
|
||||||
|
cmd.response_file_content = std::move(rsp);
|
||||||
|
cmd.arguments = {"@" + rsp_path.string()};
|
||||||
|
} else {
|
||||||
|
cmd.arguments = std::move(args);
|
||||||
|
}
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Void::Build::Toolchain
|
||||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user