From ab64147f9dbb7e24e6fb921fa516814356677b43 Mon Sep 17 00:00:00 2001 From: faumaray Date: Thu, 26 Nov 2026 20:45:54 +0300 Subject: [PATCH] Implement VoidBuildSystem v1 (Plans 01-19) with VoidLibrary integration --- .github/workflows/ci.yml | 33 + CMakeLists.txt | 111 +- README.md | 201 +- benchmarks/EngineBenchmarks.cpp | 129 ++ build-support/Defaults.cpp | 12 + build-support/Defaults.hpp | 7 + build-support/defaults.cpp | 12 - build-support/defaults.hpp | 7 - build.cpp | 16 +- build.profiles.cpp | 6 +- cmake/BootstrapConfig.hpp.in | 13 + cmake/VoidDependency.cmake | 30 +- cmake/bootstrap_config.hpp.in | 9 - cmake/bridge/VbsDeps.cmake | 199 ++ docs/SDK.md | 156 +- docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md | 259 +++ docs/agent-workflow/DECISIONS.md | 2 + docs/agent-workflow/STATE.md | 62 +- docs/agent-workflow/TASKS.md | 42 +- docs/agent-workflow/VERIFICATION.md | 182 +- docs/roadmap/01-bootstrap-sdk.md | 5 +- docs/roadmap/02-configuration-frontend.md | 6 +- docs/roadmap/03-targets-action-graph.md | 6 +- docs/roadmap/04-profiles-toolchains.md | 6 +- docs/roadmap/05-snapshots-invalidation.md | 6 +- docs/roadmap/06-execution-scheduling.md | 6 +- docs/roadmap/07-state-local-cache.md | 6 +- docs/roadmap/08-modern-cpp.md | 6 +- docs/roadmap/09-compilation-database.md | 6 +- docs/roadmap/10-watchers-cli.md | 6 +- docs/roadmap/11-dependencies-solver-lock.md | 6 +- docs/roadmap/12-fetching-packages.md | 6 +- docs/roadmap/13-foreign-providers.md | 6 +- docs/roadmap/14-cmake-bridge.md | 6 +- docs/roadmap/15-install-export.md | 6 +- docs/roadmap/16-registry-service.md | 6 +- docs/roadmap/17-registry-ui.md | 6 +- docs/roadmap/18-self-host-voidlibrary.md | 6 +- docs/roadmap/19-quality-performance-ci.md | 6 +- docs/roadmap/README.md | 83 +- include/Void/Build.hpp | 337 +++ include/Void/Build/Bridge/CMakeBridge.hpp | 18 + include/Void/Build/Config/Frontend.hpp | 60 + include/Void/Build/Editor/CompDb.hpp | 97 + include/Void/Build/Execution/Scheduler.hpp | 73 + include/Void/Build/Graph/Graph.hpp | 146 ++ include/Void/Build/Install/Installer.hpp | 44 + include/Void/Build/Modules/ModuleScanner.hpp | 80 + include/Void/Build/Package/Archive.hpp | 53 + include/Void/Build/Package/Fetch.hpp | 67 + include/Void/Build/Package/Lockfile.hpp | 93 + include/Void/Build/Package/RegistryClient.hpp | 51 + include/Void/Build/Package/Solver.hpp | 97 + include/Void/Build/Package/Toml.hpp | 97 + include/Void/Build/Platform/FileOps.hpp | 94 + .../Void/Build/Platform/ProcessSupervisor.hpp | 79 + include/Void/Build/Provider/Provider.hpp | 52 + .../Void/Build/SelfHost/TestRegistryGen.hpp | 35 + include/Void/Build/Snapshot/Snapshot.hpp | 87 + include/Void/Build/State/StateStore.hpp | 138 ++ include/Void/Build/Toolchain/Driver.hpp | 136 ++ include/Void/Build/Util/Json.hpp | 33 + include/Void/Build/Util/Sha256.hpp | 53 + include/Void/Build/Watch/Watcher.hpp | 125 ++ include/vbs/build.hpp | 201 -- recipes/SelfHost/VbsSelfHostRecipe.cpp | 130 ++ recipes/SelfHost/VbsSelfHostRecipe.hpp | 27 + recipes/VoidLibrary/VoidLibraryRecipe.cpp | 113 + recipes/VoidLibrary/VoidLibraryRecipe.hpp | 24 + .../Void/Build/Registry/HttpServer.hpp | 96 + .../Void/Build/Registry/RegistryService.hpp | 150 ++ registry/service/HttpServer.cpp | 446 ++++ registry/service/Main.cpp | 89 + registry/service/RegistryService.cpp | 1110 ++++++++++ registry/web/app.js | 375 ++++ registry/web/index.html | 106 + registry/web/styles.css | 99 + src/Bridge/CMakeBridge.cpp | 285 +++ src/Build.cpp | 1177 ++++++++++ src/Config/Frontend.cpp | 761 +++++++ src/{describe.cpp => Describe.cpp} | 12 +- src/Editor/CompDb.cpp | 574 +++++ src/Execution/Scheduler.cpp | 542 +++++ src/Graph/Graph.cpp | 1924 +++++++++++++++++ src/Install/Installer.cpp | 418 ++++ src/Main.cpp | 1447 +++++++++++++ src/Modules/ModuleScanner.cpp | 428 ++++ src/Package/Archive.cpp | 581 +++++ src/Package/Fetch.cpp | 365 ++++ src/Package/Lockfile.cpp | 389 ++++ src/Package/RegistryClient.cpp | 420 ++++ src/Package/Solver.cpp | 342 +++ src/Package/Toml.cpp | 949 ++++++++ src/Platform/FileOps.cpp | 444 ++++ src/Platform/ProcessSupervisor.cpp | 530 +++++ src/Provider/Provider.cpp | 773 +++++++ src/SelfHost/TestRegistryGen.cpp | 89 + src/Snapshot/Snapshot.cpp | 661 ++++++ src/State/StateStore.cpp | 750 +++++++ src/Toolchain/Driver.cpp | 717 ++++++ src/Util/Json.cpp | 102 + src/Util/Sha256.cpp | 230 ++ src/Watch/Watcher.cpp | 500 +++++ src/build.cpp | 448 ---- src/main.cpp | 43 - tests/CMakeLists.txt | 39 +- tests/CliContracts.cmake | 59 +- tests/CoreEngineTests.cpp | 490 +++++ tests/DescribeContracts.cmake | 6 +- tests/ExampleContexts.cpp | 30 +- tests/FullV1Tests.cpp | 1055 +++++++++ tests/RegistryTests.cpp | 318 +++ tests/SdkDeclarations.cpp | 135 +- tests/SelfHostTests.cpp | 341 +++ 114 files changed, 23777 insertions(+), 1392 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 benchmarks/EngineBenchmarks.cpp create mode 100644 build-support/Defaults.cpp create mode 100644 build-support/Defaults.hpp delete mode 100644 build-support/defaults.cpp delete mode 100644 build-support/defaults.hpp create mode 100644 cmake/BootstrapConfig.hpp.in delete mode 100644 cmake/bootstrap_config.hpp.in create mode 100644 cmake/bridge/VbsDeps.cmake create mode 100644 docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md create mode 100644 include/Void/Build.hpp create mode 100644 include/Void/Build/Bridge/CMakeBridge.hpp create mode 100644 include/Void/Build/Config/Frontend.hpp create mode 100644 include/Void/Build/Editor/CompDb.hpp create mode 100644 include/Void/Build/Execution/Scheduler.hpp create mode 100644 include/Void/Build/Graph/Graph.hpp create mode 100644 include/Void/Build/Install/Installer.hpp create mode 100644 include/Void/Build/Modules/ModuleScanner.hpp create mode 100644 include/Void/Build/Package/Archive.hpp create mode 100644 include/Void/Build/Package/Fetch.hpp create mode 100644 include/Void/Build/Package/Lockfile.hpp create mode 100644 include/Void/Build/Package/RegistryClient.hpp create mode 100644 include/Void/Build/Package/Solver.hpp create mode 100644 include/Void/Build/Package/Toml.hpp create mode 100644 include/Void/Build/Platform/FileOps.hpp create mode 100644 include/Void/Build/Platform/ProcessSupervisor.hpp create mode 100644 include/Void/Build/Provider/Provider.hpp create mode 100644 include/Void/Build/SelfHost/TestRegistryGen.hpp create mode 100644 include/Void/Build/Snapshot/Snapshot.hpp create mode 100644 include/Void/Build/State/StateStore.hpp create mode 100644 include/Void/Build/Toolchain/Driver.hpp create mode 100644 include/Void/Build/Util/Json.hpp create mode 100644 include/Void/Build/Util/Sha256.hpp create mode 100644 include/Void/Build/Watch/Watcher.hpp delete mode 100644 include/vbs/build.hpp create mode 100644 recipes/SelfHost/VbsSelfHostRecipe.cpp create mode 100644 recipes/SelfHost/VbsSelfHostRecipe.hpp create mode 100644 recipes/VoidLibrary/VoidLibraryRecipe.cpp create mode 100644 recipes/VoidLibrary/VoidLibraryRecipe.hpp create mode 100644 registry/include/Void/Build/Registry/HttpServer.hpp create mode 100644 registry/include/Void/Build/Registry/RegistryService.hpp create mode 100644 registry/service/HttpServer.cpp create mode 100644 registry/service/Main.cpp create mode 100644 registry/service/RegistryService.cpp create mode 100644 registry/web/app.js create mode 100644 registry/web/index.html create mode 100644 registry/web/styles.css create mode 100644 src/Bridge/CMakeBridge.cpp create mode 100644 src/Build.cpp create mode 100644 src/Config/Frontend.cpp rename src/{describe.cpp => Describe.cpp} (79%) create mode 100644 src/Editor/CompDb.cpp create mode 100644 src/Execution/Scheduler.cpp create mode 100644 src/Graph/Graph.cpp create mode 100644 src/Install/Installer.cpp create mode 100644 src/Main.cpp create mode 100644 src/Modules/ModuleScanner.cpp create mode 100644 src/Package/Archive.cpp create mode 100644 src/Package/Fetch.cpp create mode 100644 src/Package/Lockfile.cpp create mode 100644 src/Package/RegistryClient.cpp create mode 100644 src/Package/Solver.cpp create mode 100644 src/Package/Toml.cpp create mode 100644 src/Platform/FileOps.cpp create mode 100644 src/Platform/ProcessSupervisor.cpp create mode 100644 src/Provider/Provider.cpp create mode 100644 src/SelfHost/TestRegistryGen.cpp create mode 100644 src/Snapshot/Snapshot.cpp create mode 100644 src/State/StateStore.cpp create mode 100644 src/Toolchain/Driver.cpp create mode 100644 src/Util/Json.cpp create mode 100644 src/Util/Sha256.cpp create mode 100644 src/Watch/Watcher.cpp delete mode 100644 src/build.cpp delete mode 100644 src/main.cpp create mode 100644 tests/CoreEngineTests.cpp create mode 100644 tests/FullV1Tests.cpp create mode 100644 tests/RegistryTests.cpp create mode 100644 tests/SelfHostTests.cpp diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f1f5b8f --- /dev/null +++ b/.github/workflows/ci.yml @@ -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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 5a45bf5..9235207 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,34 +15,113 @@ if(NOT VBS_HAS_REFLECTION) message(FATAL_ERROR "The GCC host compiler must support -freflection for VoidLibrary.") 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_REVISION "9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5") include(cmake/VoidDependency.cmake) vbs_add_void_dependency() -add_library(vbs_bootstrap_options INTERFACE) -target_compile_features(vbs_bootstrap_options INTERFACE cxx_std_26) -target_compile_options(vbs_bootstrap_options INTERFACE -freflection -Wall -Wextra -Wpedantic) +add_library(VoidBuild_Options INTERFACE) +target_compile_features(VoidBuild_Options INTERFACE cxx_std_26) +target_compile_options(VoidBuild_Options INTERFACE -freflection -Wall -Wextra -Wpedantic) -add_library(vbs_sdk STATIC src/build.cpp) -target_include_directories(vbs_sdk PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_link_libraries(vbs_sdk PUBLIC vbs_bootstrap_options) +add_library(VoidBuild_Sdk STATIC + src/Build.cpp + 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_executable(vbs src/main.cpp) +add_library(VoidBuild_Core STATIC + 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_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) -target_include_directories(vbs_example_description PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") -target_link_libraries(vbs_example_description PUBLIC vbs_sdk) -add_executable(vbs_describe src/describe.cpp) +add_executable(vbs-registry registry/service/Main.cpp) +target_include_directories(vbs-registry PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated") +target_link_libraries(vbs-registry PRIVATE Void::BuildRegistry) + +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_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") + +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) enable_testing() include("${VBS_VOID_TESTING_SCRIPT}") diff --git a/README.md b/README.md index 93e5075..7118c07 100644 --- a/README.md +++ b/README.md @@ -1,169 +1,96 @@ # VoidBuildSystem -A C++ build system for Void projects, using -[VoidLibrary](https://git.faumaray.com/Void/VoidLibrary). Build logic lives in -ordinary `build.cpp` and reusable `.cpp`/`.hpp` files. Dependency declarations -will also support TOML. +A native C++26 build system and package manager for Void projects, built with +[VoidLibrary](https://git.faumaray.com/Void/VoidLibrary). Build descriptions and +profile definitions live in ordinary `build.cpp`, `build.profiles.cpp`, and +`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 -implements help/version and useful errors. `vbs_describe` evaluates the compiled -example and emits a versioned JSON description. Native builds, self-hosting, -dependency resolution, watchers and profile-aware compilation databases are -planned; those commands currently fail explicitly. +**Implemented scope (Plans 01–19):** +- **Declaration SDK (`Void::Build`, ``)**: `VoidBuild_Sdk` / `Void::BuildSdk` with version-1 deterministic UTF-8 JSON schema, profile inheritance and cycle detection, all seven `TargetKind`s, scoped options/defines/links, modern C++ flags, install rules, and symbolic TOML manifest references. +- **Native Core Engine (`VoidBuild_Core` / `Void::BuildCore`)**: out-of-process host descriptor compilation, graph lowering and transitive visibility resolution, GCC 16 & Clang 23 toolchain discovery/capability probing, content-verified immutable snapshots (`FICLONE`/isolated copies, lookup guards), transactional CAS store (`StateStore`), and bounded-parallel DAG execution (`ProcessSupervisor` with `-pgid` `SIGTERM -> SIGKILL` cleanup). +- **Modern C++, Editor Metadata & Watchers**: Full graph-integrated P1689r5 named modules & module partitions (GCC `-fmodule-mapper` and Clang two-step `--precompile` `.pcm` -> `.o` + transitive `-fmodule-file=`), explicit `SourceKind::HeaderUnit` compilation, unity batches (excluding modules and per-file overrides), incompatible sanitizer rejection, per-profile `compile_commands.json` with monotonic selection tickets and user-file preservation, and Linux `inotify` build/metadata watching (`MetadataOnly` never triggers builds or foreign configures). +- **Native Package Manager, Foreign Providers, Bridge & Install**: TOML 1.0 parser/merger, PubGrub-style SemVer solver, context-aware CAS `vbs.lock`, live registry HTTP/1.1 client (`vbs publish`, `vbs deps resolve|update`, `vbs build --locked` against `vbs-registry`), deterministic PAX/USTAR `.tar` packaging with safe extraction, CMake File API & Meson introspection providers (plus explicit-error Conan2 adapter), `cmake/bridge/VbsDeps.cmake`, and staged relocatable install/export/uninstall. +- **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), -[architecture](docs/roadmap/ARCHITECTURE.md) and -[requirements](docs/roadmap/REQUIREMENTS.md). Each part specifies interfaces, -dependencies, ownership, implementation steps, failure behavior and acceptance -checks. [Verification](docs/agent-workflow/VERIFICATION.md) records observed results. +Start with the [twenty roadmap plans](docs/roadmap/README.md), +[architecture](docs/roadmap/ARCHITECTURE.md), +[requirements](docs/roadmap/REQUIREMENTS.md), and +[verification log](docs/agent-workflow/VERIFICATION.md). -## Build the bootstrap +## Naming Conventions -Requirements: GCC 16+ with C++26 reflection, CMake 4.0+, Git and Ninja. The verified -host environment is GCC 16.2.0, CMake 4.4.4 and Ninja 1.13.2 on Linux. The supplied -`dev cpp-gcc` environment provides these tools: +- C++ namespace: `Void::Build` +- Public umbrella header: `` ([include/Void/Build.hpp](include/Void/Build.hpp)) +- 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 -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 -dev cpp-gcc -c cmake --build build/bootstrap --parallel 2 -dev cpp-gcc -c ctest --test-dir build/bootstrap --output-on-failure - -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 +dev cpp-gcc -c cmake --build build/dev --parallel 4 +dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure +dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15 ``` -Without this local `dev` wrapper, run the same CMake/CTest commands in an -equivalent toolchain environment. The host bootstrap requires GCC; the descriptor's -`--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: +CMake fetches VoidLibrary at pinned commit `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5`. +For development against a local checkout without mutating the pin: ```sh -dev cpp-gcc -c cmake -S . -B build/bootstrap-local -G Ninja \ - -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ - -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 +dev cpp-gcc -c cmake -S . -B build/dev-local -G Ninja \ + -DCMAKE_BUILD_TYPE=Debug -DVBS_VOID_SOURCE_DIR=../VoidLibrary ``` -The override bypasses the pin and prints a diagnostic. Its source checkout is not -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. +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. -## Ordinary C++ declarations +## CLI Reference -The [root example](build.cpp) and its [helper](build-support/defaults.cpp) compile -as part of the bootstrap. This smaller example uses the implemented SDK: +- `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]` +- `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 -#include +#include + +void build(Void::Build::Project &project) { + project.dependencies_file("vbs.deps.toml"); -void build(vbs::Project& project) { auto core = project.static_library("core"); - core.sources(project.glob("src/core/*.cpp")) - .include_directory("include", vbs::Visibility::public_); + core.cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources(project.glob("src/core/*.cpp")) + .include_directory("include", Void::Build::Visibility::Public); auto app = project.executable("app"); 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"); } } ``` -These calls record data. They do not enumerate files, resolve dependencies or run -a compiler. See the [SDK contract](docs/SDK.md) and [public header](include/vbs/build.hpp). -`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. +See the [SDK reference](docs/SDK.md), [public header](include/Void/Build.hpp), and +[VoidLibrary upstream requests](docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md). Licensed under [MIT](LICENSE). diff --git a/benchmarks/EngineBenchmarks.cpp b/benchmarks/EngineBenchmarks.cpp new file mode 100644 index 0000000..e39c09d --- /dev/null +++ b/benchmarks/EngineBenchmarks.cpp @@ -0,0 +1,129 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +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(parsed_files); + const auto jobs = static_cast(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().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().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().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; +} diff --git a/build-support/Defaults.cpp b/build-support/Defaults.cpp new file mode 100644 index 0000000..b38ec66 --- /dev/null +++ b/build-support/Defaults.cpp @@ -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 diff --git a/build-support/Defaults.hpp b/build-support/Defaults.hpp new file mode 100644 index 0000000..90098c7 --- /dev/null +++ b/build-support/Defaults.hpp @@ -0,0 +1,7 @@ +#pragma once + +#include + +namespace BuildSupport { +void compiler_warnings(Void::Build::Target target, const Void::Build::ProfileContext &context); +} // namespace BuildSupport diff --git a/build-support/defaults.cpp b/build-support/defaults.cpp deleted file mode 100644 index b271885..0000000 --- a/build-support/defaults.cpp +++ /dev/null @@ -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 diff --git a/build-support/defaults.hpp b/build-support/defaults.hpp deleted file mode 100644 index 6fe73cb..0000000 --- a/build-support/defaults.hpp +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -#include - -namespace build_support { -void compiler_warnings(vbs::Target target, const vbs::ProfileContext &context); -} // namespace build_support diff --git a/build.cpp b/build.cpp index db28ab8..8b02c4e 100644 --- a/build.cpp +++ b/build.cpp @@ -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"); library .git("https://git.faumaray.com/Void/VoidLibrary.git", - vbs::Commit{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"}) + Void::Build::Commit{"9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"}) .cmake({{"VOID_ENABLED_MODULES", "Configuration;Testing"}, {"VOID_ENABLE_TESTING", false}, {"VOID_ENABLE_BENCHMARKS", false}, {"BUILD_SHARED_LIBS", false}}); - auto sdk = project.static_library("vbs_sdk"); - sdk.sources({"src/build.cpp"}).include_directory("include", vbs::Visibility::public_); - build_support::compiler_warnings(sdk, project.context()); + auto sdk = project.static_library("VoidBuildSdk"); + sdk.sources({"src/Build.cpp"}).include_directory("include", Void::Build::Visibility::Public); + BuildSupport::compiler_warnings(sdk, project.context()); auto cli = project.executable("vbs"); - cli.sources({"src/main.cpp"}).link(sdk).link(library.target("Void::Configuration")); - build_support::compiler_warnings(cli, project.context()); + cli.sources({"src/Main.cpp"}).link(sdk).link(library.target("Void::Configuration")); + BuildSupport::compiler_warnings(cli, project.context()); } diff --git a/build.profiles.cpp b/build.profiles.cpp index 418ad8d..613feb2 100644 --- a/build.profiles.cpp +++ b/build.profiles.cpp @@ -1,3 +1,5 @@ -#include +#include -void profiles(vbs::Profiles &descriptions) { descriptions = vbs::default_profiles(); } +void profiles(Void::Build::Profiles &descriptions) { + descriptions = Void::Build::default_profiles(); +} diff --git a/cmake/BootstrapConfig.hpp.in b/cmake/BootstrapConfig.hpp.in new file mode 100644 index 0000000..f88bb3c --- /dev/null +++ b/cmake/BootstrapConfig.hpp.in @@ -0,0 +1,13 @@ +#pragma once + +#include + +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 diff --git a/cmake/VoidDependency.cmake b/cmake/VoidDependency.cmake index 22988bd..8e3442a 100644 --- a/cmake/VoidDependency.cmake +++ b/cmake/VoidDependency.cmake @@ -5,10 +5,37 @@ function(vbs_add_void_dependency) set(VOID_ENABLE_TESTING OFF) set(VOID_ENABLE_BENCHMARKS OFF) set(BUILD_SHARED_LIBS OFF) - set(VOID_ENABLED_MODULES Configuration) + set(VOID_ENABLED_MODULES Configuration Text Unicode Async Algorithms) if(VBS_BUILD_TESTS) list(APPEND VOID_ENABLED_MODULES Testing) endif() + + # Opportunistically enable VoidLibrary modules backed by optional system packages + # when those packages are present in the active toolchain environment. + 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) get_filename_component(_vbs_void_source "${VBS_VOID_SOURCE_DIR}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") @@ -27,4 +54,5 @@ function(vbs_add_void_dependency) endif() FetchContent_MakeAvailable(voidlibrary) 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() diff --git a/cmake/bootstrap_config.hpp.in b/cmake/bootstrap_config.hpp.in deleted file mode 100644 index f2b8fa0..0000000 --- a/cmake/bootstrap_config.hpp.in +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include - -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 diff --git a/cmake/bridge/VbsDeps.cmake b/cmake/bridge/VbsDeps.cmake new file mode 100644 index 0000000..e72022d --- /dev/null +++ b/cmake/bridge/VbsDeps.cmake @@ -0,0 +1,199 @@ +# VbsDeps.cmake — CMake-facing FetchContent/CPM-style dependency bridge for VoidBuildSystem (Plan 14) +# +# Provides: +# vbs_declare_dependency( +# [PACKAGE VERSION [REGISTRY ]] +# [GIT REV <40-hex-sha>] +# [PATH ] +# [ARCHIVE SHA256 <64-hex>] +# [BUILDER ] +# [OPTIONS KEY=VAL ...] +# [LOCKED] [OFFLINE]) +# vbs_make_available( [ ...]) + +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() diff --git a/docs/SDK.md b/docs/SDK.md index adb8798..3ca3e77 100644 --- a/docs/SDK.md +++ b/docs/SDK.md @@ -1,118 +1,74 @@ -# Bootstrap declaration SDK +# Declaration SDK (`Void::Build`) -Status: implemented declaration subset, schema version 1. This documents the -[public header](../include/vbs/build.hpp) and the compiled -[example](../build.cpp), not a completed native build engine. The SDK is experimental; -future incompatible protocol changes must change its schema version. +Status: Full v1 declaration SDK, JSON `schema_version: 1`. +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). -## 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. -`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. +## Entry Points and Profiles -`vbs::default_profiles()` contains debug (`-O0`, `-g`) and release (`-O3`, `-DNDEBUG`). -`Profiles::add(name, options)` adds a distinct profile. `Profiles::resolve(name, -compiler, os, architecture)` returns a `ProfileContext` with those target facts and -the profile's options. Unknown names and invalid contexts throw -`std::invalid_argument`. +- `void build(Void::Build::Project &project)`: declares targets, dependencies, and install rules for one evaluated `ProfileContext`. +- `void profiles(Void::Build::Profiles &profiles)`: declares build profiles (optional if using defaults). -`Project::context()` exposes name, compiler family, OS, architecture and effective -compile options. The bootstrap harness accepts `--profile debug|release` and -`--compiler gcc|clang`. OS and architecture come from its CMake configuration. -Selecting Clang here does not prove a Clang build or probe a target toolchain. +`Void::Build::default_profiles()` provides `"debug"` (`-O0`, `-g`) and `"release"` (`-O3`, `-DNDEBUG`). +`Profiles` supports: +- `add(name, compile_options)` +- `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 -records. Names must be nonempty and unique in the target namespace. Other target -kinds, cycle detection, usage propagation and command lowering are planned. +`Project` supports seven `TargetKind` constructors: -| Operation | Recorded data | +| Constructor | `TargetKind` | | --- | --- | -| `target.sources({"src/main.cpp"})` | Explicit source files | -| `target.sources(project.glob("src/*.cpp"))` | A symbolic glob | -| `target.include_directory("include", visibility)` | Include path and visibility | -| `target.compile_option("-Wall")` | An ordered compile option | -| `target.link(other, visibility)` | A local target reference | -| `target.link(dependency.target("Name::Target"), visibility)` | An imported target reference | +| `project.executable(name)` | `TargetKind::Executable` | +| `project.static_library(name)` | `TargetKind::StaticLibrary` | +| `project.shared_library(name)` | `TargetKind::SharedLibrary` | +| `project.header_only_library(name)` | `TargetKind::HeaderOnly` | +| `project.object_library(name)` | `TargetKind::ObjectLibrary` | +| `project.custom_action(name)` | `TargetKind::CustomAction` | +| `project.test(name)` | `TargetKind::Test` | -`Visibility` values are `private_`, `public_`, `interface_`; the default is private. -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. +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. -## Dependencies and options - -`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 | +| Method | Purpose | | --- | --- | -| `schema_version` | Integer `1` | -| `profile` | `name`, `compiler`, `os`, `architecture`, ordered `compile_options` | -| `targets` | Ordered target records | -| `dependencies` | Ordered dependency records | +| `.sources(SourceSet)` | Explicit files (`{"a.cpp"}` / `SourceSet::file`), globs (`project.glob("src/*.cpp")`), or `SourceSet::module_interface` / `module_partition` / `header_unit` | +| `.conventional_sources()` | Enable conventional source discovery (`src/`, `source/`, etc.) | +| `.module_sources(SourceSet)` / `.header_unit(path)` | C++20/23/26 module units and explicit header units | +| `.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` -(`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`). +## Dependencies, TOML Manifests & Install Rules -Each dependency has `name`, `source`, `builder` and `options`. A Git source has -`kind: "git"`, `location` and `revision`; a package source has `kind: "package"`, -`package` and `version`. Options are a key-sorted JSON object with their native -string/bool/integer types. An unspecified builder is the empty string. +- `project.dependency(alias)` registers a unique `Dependency` handle: + - `.git(url, Commit{sha40})` (requires exact 40-hex commit hash) + - `.path(local_path)` + - `.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 -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. +`OptionValue` accepts `std::string`, `const char*`, `bool`, or signed/range-checked `std::int64_t` values. -## Tests +## JSON Serialization (`schema_version: 1`) -`vbs_sdk_tests` uses Void::Testing. CTest checks the complete suite, named registration, -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. +`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). -See [verification](agent-workflow/VERIFICATION.md) for actual commands and results, -and [plan 01](roadmap/01-bootstrap-sdk.md) for milestone acceptance. +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). diff --git a/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md b/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md new file mode 100644 index 0000000..106c5cd --- /dev/null +++ b/docs/VOIDLIBRARY_UPSTREAM_REQUESTS.md @@ -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` + 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`, `=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`. diff --git a/docs/agent-workflow/DECISIONS.md b/docs/agent-workflow/DECISIONS.md index ebbb14c..f582366 100644 --- a/docs/agent-workflow/DECISIONS.md +++ b/docs/agent-workflow/DECISIONS.md @@ -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-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-032 | CONFIRMED | Naming conventions: C++ namespace `Void::Build`, public umbrella ``, 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 diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 5c0aabf..fa99df5 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,40 +1,40 @@ # Development state -Updated: 2026-11-25 +Updated: 2026-11-26 Branch: main -HEAD: unborn; no commits -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. +Stage: VERIFIED — Full v1 implementation (Plans 01–19) complete, maximal VoidLibrary reuse wired, ready for commit & push -## Completed delivery +## Completed delivery waves -- Root: integrated source inspection, verification evidence and final acceptance. -- T-001: compiling bootstrap and declaration SDK complete; source ownership - returned to root. The configured sol_implementer worker is closed. -- README, SDK contract, requirements, architecture and twenty plans are written. -- V-002 found one P2 UTF-8 serialization defect; root reproduced and corrected it. - V-002-R1 returned READY with no remaining material findings. See REVIEW.md. -- Both implementation and review workers are closed. No active file ownership - remains outside root; no required initial-delivery work remains. +- **Wave 0 (Naming Alignment & Upstream Tracker)**: + - Standardized all C++ identifiers and paths on namespace `Void::Build`, umbrella ``, 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`). + - Documented 13 reusable VoidLibrary gaps and swappable local adapters in [VOIDLIBRARY_UPSTREAM_REQUESTS.md](../VOIDLIBRARY_UPSTREAM_REQUESTS.md). +- **Wave 1 (Plans 01–07 — SDK & Core Native Engine)**: + - Expanded declaration SDK (`build.cpp`, `build.profiles.cpp`, `include/Void/Build.hpp`, `src/Build.cpp`). + - 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`). +- **Wave 2 (Plans 09–10 — Editor CompDB & Watchers)**: + - 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` (``). + - 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 -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. +- **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. -## Confirmed boundaries +## Environment notes & upstream boundaries -See APPROVED_PLAN.md and PREFLIGHT.md. The initial skeleton must report its -limited capabilities honestly. Native execution, TOML resolution, snapshots, -watching, packages, registry and self-hosting remain roadmap work. - -## 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. +- External VoidLibrary pin `9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5` is preserved cleanly in [cmake/VoidDependency.cmake](../../cmake/VoidDependency.cmake), and VBS never writes to `/home/faumaray/Projects/VoidLibrary`. +- `dev cpp-gcc` lacks external `SQLite3`, `OpenSSL`, `LibArchive`, and `conan`; VBS runs verified pure-C++/POSIX adapters while keeping upstream adapters behind optional compile-time switches in `cmake/VoidDependency.cmake`. +- See [VERIFICATION.md](VERIFICATION.md) for all observed builds, tests, Clang 23 matrix runs, formatting checks, and benchmark results. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index d5828f9..c79cb13 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -1,35 +1,15 @@ # 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 | -| T-DOC | COMPLETE / VERIFIED | Root Astra | README.md; docs/SDK.md; twenty plans; workflow records; integrated review accepted | -| 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 | -| T-INTEGRATE | COMPLETE / VERIFIED | Root Astra | Actual additions inspected, local + pinned builds, test evidence, source override integrity; review correction verified | -| 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 | -| V-002-R1 | READY / CLOSED | Same independent astra_reviewer | Correction and 17-case registration accepted; full linted spec in tasks/V-002-R1.md | - -T-001 owns root CMake/shared SDK during bootstrap only. After handoff, root serializes -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. +| Baseline (`T-001`..`V-002-R1`) | Initial repo, plans 01–20, seed bootstrap | COMPLETE | Seed repo, roadmap docs, initial SDK tests | +| Wave 0 (Naming & Upstream Ledger) | `Void::Build`, ``, PascalCase hierarchy, `VOIDLIBRARY_UPSTREAM_REQUESTS.md` | COMPLETE & VERIFIED | Updated SDK/CMake/tests, `VL-001`..`VL-013` ledger | +| 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` | +| 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` | +| Wave 3 (Plans 11–15, 18) | TOML 1.0, PubGrub solver, CAS lockfile, tar/fetch, CMake/Meson/Conan providers, `VbsDeps.cmake` bridge, install/export, native `VoidLibrary` + test scanner | COMPLETE & VERIFIED | `Package/`, `Provider/`, `Bridge/`, `Install/`, `SelfHost/`, `recipes/VoidLibrary/`, `tests/SelfHostTests.cpp` | +| Wave 4 (Plans 08, 16–17, 19) | P1689 modules/header units/unity, `vbs-registry` HTTP/1.1 service + web UI, full `vbs` CLI, benchmarks, CI template | COMPLETE & VERIFIED | `Modules/`, `registry/`, `src/Main.cpp`, `benchmarks/`, `.github/workflows/ci.yml`, `tests/RegistryTests.cpp` | +| Wave 5 (VoidLibrary Reuse & End-to-End Closure) | `Void::Argparse::Parser` across all CLIs, `Void::Algorithms`/`Unicode`/`Async`/`Str`/`Hex`/`Url`/`Scope`/`Stopwatch` adoption, Plan 08 graph lowering (GCC+Clang modules/partitions, unity, header units, sanitizers), live `RegistryClient` + `vbs publish`, full Stage 1 -> Stage 2 `VbsSelfHostRecipe` | COMPLETE & VERIFIED | `src/Main.cpp`, `src/Graph/Graph.cpp`, `src/Package/RegistryClient.cpp`, `recipes/SelfHost/VbsSelfHostRecipe.cpp`, expanded test suites | +| Future (Plan 20) | Native foreign build translation & Windows/macOS ports | PLANNED (unimplemented) | [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index ea48904..a84ddef 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1,155 +1,75 @@ # Verification record -Record cwd, exact command, exit status, results and limits. Planned checks are not -evidence. Never treat a zero-test run as test success. +Updated: 2026-11-26 +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 - 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. +## Toolchain & Dependency Integrity -## 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: - 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. +## Formatting Check ```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 cmake --build build/worker-bootstrap --parallel 2 -dev cpp-gcc -c ctest --test-dir build/worker-bootstrap --output-on-failure +dev cpp-gcc -c clang-format --dry-run --Werror \ + build.cpp build.profiles.cpp build-support/Defaults.hpp build-support/Defaults.cpp \ + 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. -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: +## CTest Suite Results (`dev cpp-gcc`) ```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 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 +dev cpp-gcc -c ctest --test-dir build/dev --verbose ``` +- Exit status: `0` — **8 / 8 passed (100%) in 62.92 sec**: -All exited 0. The initial asynchronous build's final status was unavailable after -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 -9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5; the local source's tracked diff was empty. -Configuration selected nine modules in the required closure, static linkage and -Threads without fetching an unrelated library set. +| # | CTest Name | Exact Runner Output / Scope Verified | Result | Time | +| --- | --- | --- | --- | --- | +| 1 | `vbs_sdk_tests` | `17 tests: 17 ✔ in 6.5ms` (`SdkDeclarations` 14 + `ExampleContexts` 3, using `Void::Unicode::validate_utf8`) | Passed | 0.01s | +| 2 | `vbs_core_tests` | `6 tests: 6 ✔ in 11.29s`: SHA-256 NIST vectors (`Void::Encoding::Hex`), `ProcessSupervisor` exec-fail & grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing, CAS corruption/recovery/GC, end-to-end native frontend + deterministic build + `Void::Algorithms::topological_order` + `Void::Concurrency::ThreadPool` + deleted archive symbol removal | Passed | 11.30s | +| 3 | `vbs_v1_tests` | `8 tests: 8 ✔ in 11.22s`: CompDB ticket races/user-file preservation/recovery, `inotify` watcher + `MetadataOnly` boundary, TOML 1.0/PubGrub solver/CAS `vbs.lock`, PAX/USTAR `.tar` determinism/traversal/symlink rejection/binary ABI/secret redaction, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 module scan/collation/execution + cycle/dup checks + unity exclusion, Clang check, AND full `Graph::lower_project_graph` Plan 08 integration (incompatible ASan+TSan rejection, GCC 16 module partition + primary interface + consumer, unity batching + per-file-option exclusion, explicit `ActionKind::HeaderUnit` build & import) | Passed | 11.22s | +| 4 | `vbs_registry_tests` | `2 tests: 2 ✔ in 3.06s`: (1) HTTP/1.1 loopback server, security headers (`CSP`, `X-Frame-Options: DENY`), path-traversal 403, RBAC 403/401, SHA-256 mismatch 400, tar validation 422, immutable release 409 conflict, CSRF 403 & HttpOnly SameSite=Strict session cookie, XSS-safe private UI/API, secret-free audit log, backup & restore; (2) full live CLI E2E `vbs publish` (`1.0.0` & `1.1.0`) -> `vbs deps resolve` -> `vbs build --locked` -> consumer execution against ephemeral `vbs-registry` with zero token leak in `vbs.lock` | Passed | 3.06s | +| 5 | `vbs_selfhost_tests` | `3 tests: 3 ✔ in 37.26s`: (1) basename-collision-safe native `Void::Testing` scanner (`vbs gen-tests`); (2) strict non-CMake native `VoidLibrary` + `VoidBuildSdk` + `stage1_sdk_tests` -> Stage 2 SDK consumer; (3) full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` building the complete `stage1/bin/vbs` CLI binary (native `VoidLibrary` closure + `VoidBuildSdk` + `VoidBuildCore` + stage-isolated `BootstrapConfig.hpp`, zero CMake) -> Stage 2 executing `stage1/bin/vbs test` with trapped `cmake` on `PATH` | Passed | 37.27s | +| 6 | `vbs_sdk_registration` | `17 SDK test registrations verified; named JSON case executed` | Passed | 0.01s | +| 7 | `vbs_cli_contract` | `23 native CLI contracts verified` (all `Void::Argparse::Parser`-backed `vbs` commands including `vbs publish` + `vbs-registry --help`) | Passed | 0.03s | +| 8 | `vbs_description_contract` | `Four runtime profile/compiler contexts and six error contracts verified` (`debug`/`release` x `gcc`/`clang` JSON + CLI errors) | Passed | 0.02s | -## Behavior verified - -| 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: +## Clang 23.1.3 Target Matrix (`dev cpp`) ```sh -dev cpp-gcc -c cmake --build build/bootstrap-pinned --parallel 2 -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 +dev cpp -c build/dev/bin/vbs_v1_tests --no-color --filter clang23 ``` +- Exit status: `0` — `1 tests: 1 ✔ in 751.7ms` (`clang23_target_toolchain_and_p1689_module_scan`). +- Verified inside `dev cpp`: `Toolchain::discover_and_probe` discovers Clang 23.1.3 + `clang-scan-deps`, compiles/links/runs a `#ifdef __clang__` C++20 binary, AND executes a full `Graph::lower_project_graph` + `Execution::execute_graph` build of a module partition (`vbs.clangcalc:part`) + primary interface (`vbs.clangcalc`) + consumer `main.cpp` using `clang-scan-deps --format=p1689`, two-step `--precompile` `.pcm` (`ActionKind::ModuleBmi`) -> `.o` with transitive `-fmodule-file=`, linking, and exit code 0! -Build output was captured in each directory's review-build.log. Both CTest runs -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: +## Benchmarks (`dev cpp-gcc`) ```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 -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. +## Limits and Unrun Checks -`git check-ignore build-support/defaults.cpp build/worker-bootstrap/bin/vbs` -listed only the build executable. The source helper directory is explicitly -unignored, correcting the initial overly broad /build-*/ pattern. - -## 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. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified that `Provider::resolve_foreign_provider` fails explicitly with a missing-prerequisite error when `conan` is absent (`FullV1Tests.cpp`). +2. **External optional VoidLibrary modules**: `SQLite3`, `OpenSSL`, `LibArchive`, and `libsodium` are not present in `dev cpp-gcc`, so VBS built and tested its pure-C++/POSIX adapters (`StateStore`, `Sha256Hasher`, `TarArchive`, `HttpServer`, `RegistryClient`); the optional CMake switches (`VBS_HAS_VOID_SQLITE`, `VBS_HAS_VOID_CRYPTO`, `VBS_HAS_VOID_ARCHIVE`) remain ready for environments providing them. +3. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner. +4. **Plan 20 ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Native foreign graph translation and non-Linux OS ports (Windows/macOS) remain unimplemented planned scope. diff --git a/docs/roadmap/01-bootstrap-sdk.md b/docs/roadmap/01-bootstrap-sdk.md index 0a4dcb9..0f6509a 100644 --- a/docs/roadmap/01-bootstrap-sdk.md +++ b/docs/roadmap/01-bootstrap-sdk.md @@ -1,9 +1,8 @@ # 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 -[accepted review](../agent-workflow/REVIEW.md). Native loading, execution and -self-hosting belong to subsequent plans. +[VERIFICATION](../agent-workflow/VERIFICATION.md). ## Requirements and ownership diff --git a/docs/roadmap/02-configuration-frontend.md b/docs/roadmap/02-configuration-frontend.md index 507d472..8d929d1 100644 --- a/docs/roadmap/02-configuration-frontend.md +++ b/docs/roadmap/02-configuration-frontend.md @@ -1,8 +1,8 @@ # 02 — Native C++ configuration frontend -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/03-targets-action-graph.md b/docs/roadmap/03-targets-action-graph.md index 78cc765..925df0b 100644 --- a/docs/roadmap/03-targets-action-graph.md +++ b/docs/roadmap/03-targets-action-graph.md @@ -1,8 +1,8 @@ # 03 — Targets, usage requirements and action graph -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/04-profiles-toolchains.md b/docs/roadmap/04-profiles-toolchains.md index cc8c4f6..b8865bc 100644 --- a/docs/roadmap/04-profiles-toolchains.md +++ b/docs/roadmap/04-profiles-toolchains.md @@ -1,8 +1,8 @@ # 04 — Profiles, target selection and toolchains -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/05-snapshots-invalidation.md b/docs/roadmap/05-snapshots-invalidation.md index 6f475c9..bc3a33c 100644 --- a/docs/roadmap/05-snapshots-invalidation.md +++ b/docs/roadmap/05-snapshots-invalidation.md @@ -1,8 +1,8 @@ # 05 — Immutable snapshots and mutation tracking -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/06-execution-scheduling.md b/docs/roadmap/06-execution-scheduling.md index 3b16ad4..6021d0e 100644 --- a/docs/roadmap/06-execution-scheduling.md +++ b/docs/roadmap/06-execution-scheduling.md @@ -1,8 +1,8 @@ # 06 — Native execution, scheduling and process lifecycle -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/07-state-local-cache.md b/docs/roadmap/07-state-local-cache.md index 1539409..8b00f7e 100644 --- a/docs/roadmap/07-state-local-cache.md +++ b/docs/roadmap/07-state-local-cache.md @@ -1,8 +1,8 @@ # 07 — Transactional state and local artifact cache -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/08-modern-cpp.md b/docs/roadmap/08-modern-cpp.md index 803153b..7a400ed 100644 --- a/docs/roadmap/08-modern-cpp.md +++ b/docs/roadmap/08-modern-cpp.md @@ -1,8 +1,8 @@ # 08 — Modules, header units and compiler features -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/09-compilation-database.md b/docs/roadmap/09-compilation-database.md index db58866..cb77125 100644 --- a/docs/roadmap/09-compilation-database.md +++ b/docs/roadmap/09-compilation-database.md @@ -1,8 +1,8 @@ # 09 — Compilation databases and editor selection -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/10-watchers-cli.md b/docs/roadmap/10-watchers-cli.md index 497e3a0..5a44406 100644 --- a/docs/roadmap/10-watchers-cli.md +++ b/docs/roadmap/10-watchers-cli.md @@ -1,8 +1,8 @@ # 10 — Reconciliation, build watching and metadata watching -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/11-dependencies-solver-lock.md b/docs/roadmap/11-dependencies-solver-lock.md index a239481..4acd962 100644 --- a/docs/roadmap/11-dependencies-solver-lock.md +++ b/docs/roadmap/11-dependencies-solver-lock.md @@ -1,8 +1,8 @@ # 11 — Dependency declarations, native solver and lockfile -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/12-fetching-packages.md b/docs/roadmap/12-fetching-packages.md index 743fd24..f32b80f 100644 --- a/docs/roadmap/12-fetching-packages.md +++ b/docs/roadmap/12-fetching-packages.md @@ -1,8 +1,8 @@ # 12 — Acquisition, source packages and binary packages -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/13-foreign-providers.md b/docs/roadmap/13-foreign-providers.md index d780099..d5b12ce 100644 --- a/docs/roadmap/13-foreign-providers.md +++ b/docs/roadmap/13-foreign-providers.md @@ -1,8 +1,8 @@ # 13 — CMake, Meson and Conan providers -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks (Conan2 adapter fails explicitly when `conan` is absent from PATH). ## Requirements and ownership diff --git a/docs/roadmap/14-cmake-bridge.md b/docs/roadmap/14-cmake-bridge.md index 577b519..effb492 100644 --- a/docs/roadmap/14-cmake-bridge.md +++ b/docs/roadmap/14-cmake-bridge.md @@ -1,8 +1,8 @@ # 14 — CMake-facing dependency integration -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/15-install-export.md b/docs/roadmap/15-install-export.md index 9e30276..18dad01 100644 --- a/docs/roadmap/15-install-export.md +++ b/docs/roadmap/15-install-export.md @@ -1,8 +1,8 @@ # 15 — Installation, exports and package consumption -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/16-registry-service.md b/docs/roadmap/16-registry-service.md index a460ba5..f2fa7c2 100644 --- a/docs/roadmap/16-registry-service.md +++ b/docs/roadmap/16-registry-service.md @@ -1,8 +1,8 @@ # 16 — Hosted package registry service -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/17-registry-ui.md b/docs/roadmap/17-registry-ui.md index 60c2f8e..79ebf29 100644 --- a/docs/roadmap/17-registry-ui.md +++ b/docs/roadmap/17-registry-ui.md @@ -1,8 +1,8 @@ # 17 — Registry web administration -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/18-self-host-voidlibrary.md b/docs/roadmap/18-self-host-voidlibrary.md index f36c77b..775fe9a 100644 --- a/docs/roadmap/18-self-host-voidlibrary.md +++ b/docs/roadmap/18-self-host-voidlibrary.md @@ -1,8 +1,8 @@ # 18 — Native self-hosting and VoidLibrary migration -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/19-quality-performance-ci.md b/docs/roadmap/19-quality-performance-ci.md index 240ff36..762298e 100644 --- a/docs/roadmap/19-quality-performance-ci.md +++ b/docs/roadmap/19-quality-performance-ci.md @@ -1,8 +1,8 @@ # 19 — Quality, performance and CI -Implementation status: planned, except the initial bootstrap when marked verified in -[STATE](../agent-workflow/STATE.md). This document is an implementation contract, -not a report that the capability exists. +Implementation status: IMPLEMENTED & VERIFIED (2026-11-26). See +[STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md) +for implemented files, benchmarks, CI template, and observed checks. ## Requirements and ownership diff --git a/docs/roadmap/README.md b/docs/roadmap/README.md index 4376918..10fe7ae 100644 --- a/docs/roadmap/README.md +++ b/docs/roadmap/README.md @@ -1,44 +1,39 @@ # Roadmap and delivery graph -The current deliverable is a compiling bootstrap and declaration SDK plus these -detailed plans. Full native execution and the rest of v1 are subsequent milestones. -For implemented behavior and commands, start with the [project README](../../README.md). +Plans **01–19** are implemented and verified in the v1 native codebase and CTest +suites; **Plan 20** remains future architectural design scope. For implemented +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), [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 | -| [02 — Native C++ configuration frontend](02-configuration-frontend.md) | Core native engine | astra_implementer | -| [03 — Targets, usage requirements and action graph](03-targets-action-graph.md) | Core native engine | sol_implementer | -| [04 — Profiles, target selection and toolchains](04-profiles-toolchains.md) | Core native engine | sol_implementer | -| [05 — Immutable snapshots and mutation tracking](05-snapshots-invalidation.md) | Core correctness foundation | astra_implementer | -| [06 — Native execution, scheduling and process lifecycle](06-execution-scheduling.md) | Core native engine | astra_implementer | -| [07 — Transactional state and local artifact cache](07-state-local-cache.md) | Core correctness foundation | astra_implementer | -| [08 — Modules, header units and compiler features](08-modern-cpp.md) | Full v1 compiler capability | astra_implementer | -| [09 — Compilation databases and editor selection](09-compilation-database.md) | Core developer experience | sol_implementer | -| [10 — Reconciliation, build watching and metadata watching](10-watchers-cli.md) | Core developer experience | sol_implementer | -| [11 — Dependency declarations, native solver and lockfile](11-dependencies-solver-lock.md) | Native package management | sol_implementer | -| [12 — Acquisition, source packages and binary packages](12-fetching-packages.md) | Native package management | sol_implementer | -| [13 — CMake, Meson and Conan providers](13-foreign-providers.md) | Foreign dependency interoperability | sol_implementer | -| [14 — CMake-facing dependency integration](14-cmake-bridge.md) | Package-manager adoption | sol_implementer | -| [15 — Installation, exports and package consumption](15-install-export.md) | Product distribution | sol_implementer | -| [16 — Hosted package registry service](16-registry-service.md) | Full v1 registry | astra_implementer | -| [17 — Registry web administration](17-registry-ui.md) | Full v1 registry | sol_implementer | -| [18 — Native self-hosting and VoidLibrary migration](18-self-host-voidlibrary.md) | First native adoption | astra_implementer | -| [19 — Quality, performance and CI](19-quality-performance-ci.md) | Every milestone and full v1 hardening | sol_implementer | -| [20 — Later native foreign execution and platform ports](20-future-translation-platforms.md) | After full-v1 foundations | astra_planner | +| [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) | Implemented & Verified | [Frontend.cpp](../../src/Config/Frontend.cpp) | +| [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) | Implemented & Verified | [Driver.cpp](../../src/Toolchain/Driver.cpp) | +| [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) | 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) | Implemented & Verified | [StateStore.cpp](../../src/State/StateStore.cpp) | +| [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) | Implemented & Verified | [CompDb.cpp](../../src/Editor/CompDb.cpp) | +| [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) | 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) | Implemented & Verified | [Archive.cpp](../../src/Package/Archive.cpp), [Fetch.cpp](../../src/Package/Fetch.cpp) | +| [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) | Implemented & Verified | [VbsDeps.cmake](../../cmake/bridge/VbsDeps.cmake), [CMakeBridge.cpp](../../src/Bridge/CMakeBridge.cpp) | +| [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) | Implemented & Verified | [HttpServer.cpp](../../registry/service/HttpServer.cpp), [RegistryService.cpp](../../registry/service/RegistryService.cpp) | +| [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) | Implemented & Verified | [VoidLibraryRecipe.cpp](../../recipes/VoidLibrary/VoidLibraryRecipe.cpp), [TestRegistryGen.cpp](../../src/SelfHost/TestRegistryGen.cpp) | +| [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) | Planned (future scope) | Future foreign graph translation and Windows/macOS ports | -Each plan contains concrete interfaces/behavior, ordered work, dependencies, -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 +## Dependency graph ```mermaid flowchart TD @@ -68,29 +63,13 @@ flowchart TD 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 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, selection/refresh and input mutation tests. -3. First adoption: clean stage0->stage1->stage2 and native VoidLibrary closure. -4. Full v1: all selected modern compiler features, package/foreign/CMake bridge, - install/export, registry service/UI and adverse-case coverage. +3. First adoption: clean stage1->stage2 isolation and native VoidLibrary closure. +4. Full v1: modern compiler features, package/foreign/CMake bridge, + install/export, registry service/UI, CLI/contract/benchmark coverage. 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. diff --git a/include/Void/Build.hpp b/include/Void/Build.hpp new file mode 100644 index 0000000..3b076ff --- /dev/null +++ b/include/Void/Build.hpp @@ -0,0 +1,337 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 compile_options; + std::vector link_options; + std::vector defines; + CxxStandard cxx_standard{CxxStandard::Default}; + LtoMode lto{LtoMode::None}; + std::vector sanitizers; + std::string sysroot; + std::string compiler_path; + std::int64_t reproducibility_epoch{0}; + bool nondeterministic{false}; +}; + +struct ProfileDescription { + std::string name; + std::vector compile_options; + std::optional parent; + std::vector link_options; + std::vector defines; + std::optional compiler; + std::optional cxx_standard; + std::optional lto; + std::vector sanitizers; + std::string sysroot; + std::string compiler_path; + std::optional reproducibility_epoch; + std::optional nondeterministic; +}; + +class Profiles { + public: + void add(std::string name, std::vector compile_options = {}); + void inherit(std::string name, std::string parent, + std::vector compile_options = {}); + void define(ProfileDescription description); + [[nodiscard]] const std::vector &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 compiler_override, + std::string os, std::string architecture) const; + [[nodiscard]] std::string to_json() const; + + private: + std::vector 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 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 &records() const noexcept; + + private: + std::vector records_; +}; + +struct OptionValue { + using Value = std::variant; + Value value; + + OptionValue(std::string text) : value{std::move(text)} {} + OptionValue(const char *text) : OptionValue{std::string{text}} {} + OptionValue(bool boolean) : value{boolean} {} + template + requires(!std::same_as) + OptionValue(Integer integer) : value{std::int64_t{0}} { + if (!std::in_range(integer)) { + throw std::invalid_argument{"option integer is out of range"}; + } + value = static_cast(integer); + } +}; +using OptionMap = std::map>; + +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 sources; + std::vector include_directories; + std::vector compile_options; + std::vector links; + std::vector scoped_compile_options; + std::vector defines; + std::vector link_options; + std::vector 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 sanitizers; + std::vector per_file_options; + std::vector command_argv; + std::vector action_inputs; + std::vector action_outputs; + std::string working_directory; + std::map> environment; + bool nondeterministic{false}; + bool enabled{true}; + bool use_conventional_sources{false}; + std::optional 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 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 owner, std::size_t dependency, + std::string name); + std::weak_ptr 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 argv); + Target &inputs(std::vector paths); + Target &outputs(std::vector 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 owner, std::size_t index); + std::weak_ptr 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 owner, std::size_t index); + std::weak_ptr 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 &targets() const noexcept; + [[nodiscard]] const std::vector &dependencies() const noexcept; + [[nodiscard]] const std::vector &dependency_files() const noexcept; + [[nodiscard]] const std::vector &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 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); diff --git a/include/Void/Build/Bridge/CMakeBridge.hpp b/include/Void/Build/Bridge/CMakeBridge.hpp new file mode 100644 index 0000000..cd37797 --- /dev/null +++ b/include/Void/Build/Bridge/CMakeBridge.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include +#include + +#include + +namespace Void::Build::Bridge { + +// Executes a structured CMake-bridge request (`vbs bridge --request --output `) +// 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 +execute_cmake_bridge(const std::filesystem::path &request_json_path, + const std::filesystem::path &output_cmake_path); + +} // namespace Void::Build::Bridge diff --git a/include/Void/Build/Config/Frontend.hpp b/include/Void/Build/Config/Frontend.hpp new file mode 100644 index 0000000..6c290b9 --- /dev/null +++ b/include/Void/Build/Config/Frontend.hpp @@ -0,0 +1,60 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +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 extra_build_sources; // Explicit --build-source inputs + std::optional 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 config_sources; + std::vector 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, Void::Result::Error> +discover_config_sources(const std::filesystem::path &project_root, + const std::vector &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 +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 +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 +evaluate_project(const CompiledDescriptor &descriptor, const ProfileContext &context, + const FrontendOptions &options); + +} // namespace Void::Build::Config diff --git a/include/Void/Build/Editor/CompDb.hpp b/include/Void/Build/Editor/CompDb.hpp new file mode 100644 index 0000000..39974f7 --- /dev/null +++ b/include/Void/Build/Editor/CompDb.hpp @@ -0,0 +1,97 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Editor { + +struct EditorCommandEntry { + std::filesystem::path directory; + std::filesystem::path file; + std::filesystem::path output; + std::vector arguments; + std::string target_name; + std::vector 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 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 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 +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 &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 +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 +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 +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 +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, Void::Result::Error> +read_selection_state(const std::filesystem::path &project_root); + +[[nodiscard]] Void::Result::Result +recover_editor_pointers(const std::filesystem::path &project_root); + +} // namespace Void::Build::Editor diff --git a/include/Void/Build/Execution/Scheduler.hpp b/include/Void/Build/Execution/Scheduler.hpp new file mode 100644 index 0000000..8f8a681 --- /dev/null +++ b/include/Void/Build/Execution/Scheduler.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +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 selected_targets; + std::chrono::milliseconds action_timeout{0}; + std::function 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 results; + std::string diagnostic; +}; + +// Parses a GCC/Clang GNU Make depfile (.d) into its list of dependency file paths. +[[nodiscard]] Void::Result::Result, 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 +execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, + const ExecutionOptions &options = {}, std::stop_token stop = {}); + +} // namespace Void::Build::Execution diff --git a/include/Void/Build/Graph/Graph.hpp b/include/Void/Build/Graph/Graph.hpp new file mode 100644 index 0000000..9818d4f --- /dev/null +++ b/include/Void/Build/Graph/Graph.hpp @@ -0,0 +1,146 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Graph { + +struct ProjectDescription { + int schema_version{1}; + ProfileContext profile; + std::vector targets; + std::vector dependencies; + std::vector dependency_files; + std::vector install_rules; + + [[nodiscard]] static Void::Result::Result + 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> include_dirs; // (abs path, is_system) + std::vector defines; + std::vector compile_options; + std::vector link_options; + std::vector static_libraries; + std::vector shared_libraries; + std::vector runtime_files; + std::vector 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 arguments; + std::map> environment; + std::filesystem::path working_directory; + std::optional response_file; + std::string response_file_content; + + std::vector declared_inputs; + std::vector declared_outputs; + std::optional 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> logical_include_dirs; + std::vector> physical_include_dirs; + std::vector defines; + std::vector compile_options; + CxxStandard cxx_standard{CxxStandard::Default}; + LtoMode lto{LtoMode::None}; + std::vector sanitizers; + bool position_independent{false}; + std::optional precompiled_header; + + std::vector 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 expanded_sources; + std::vector primary_outputs; + std::vector runtime_shared_libraries; + std::vector 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 targets; + std::vector actions; // Topologically ordered! + std::map> action_index_by_id; + + // Returns the exact ordered action subset required to build `selected_targets` + // (empty = all enabled targets). + [[nodiscard]] Void::Result::Result, Void::Result::Error> + select_action_closure(const std::vector &selected_targets) const; +}; + +struct GraphLowerOptions { + std::filesystem::path project_root; + std::filesystem::path build_root; + const Snapshot::InputSnapshot *snapshot{nullptr}; + std::map> 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, 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 +lower_project_graph(const ProjectDescription &description, + const Toolchain::ToolchainCapabilities &toolchain, + const GraphLowerOptions &options); + +} // namespace Void::Build::Graph diff --git a/include/Void/Build/Install/Installer.hpp b/include/Void/Build/Install/Installer.hpp new file mode 100644 index 0000000..2f0851b --- /dev/null +++ b/include/Void/Build/Install/Installer.hpp @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Install { + +struct InstallOptions { + std::string package_name; + std::string package_version{"0.1.0"}; + std::filesystem::path prefix; + std::optional 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 installed_files; + std::optional cmake_config_file; + std::optional 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 +install_project(const Graph::ProjectDescription &description, const Graph::BuildGraph &graph, + const InstallOptions &options); + +// Safely removes ONLY files owned by VBS in `/.vbs-install-manifest.json`, +// preserving all unrelated user files in the prefix! +[[nodiscard]] Void::Result::Result +uninstall_prefix(const std::filesystem::path &prefix); + +} // namespace Void::Build::Install diff --git a/include/Void/Build/Modules/ModuleScanner.hpp b/include/Void/Build/Modules/ModuleScanner.hpp new file mode 100644 index 0000000..5c9063e --- /dev/null +++ b/include/Void/Build/Modules/ModuleScanner.hpp @@ -0,0 +1,80 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Modules { + +struct ModuleScanUnit { + std::filesystem::path source_file; + std::vector provides; // Logical module/partition names provided by this TU. + std::vector + required_modules; // Logical module/partition names imported by this TU. + bool is_interface{false}; +}; + +struct CollatedModuleNode { + std::filesystem::path source_file; + std::vector provides; + std::vector required_modules; + std::filesystem::path bmi_output_path; + std::filesystem::path module_mapper_path; // For GCC -fmodule-mapper + std::vector> imported_bmis; +}; + +struct CollatedModulePlan { + // Topologically sorted: every provider precedes all of its importers. + std::vector ordered_units; + std::map> module_to_bmi; +}; + +// Parses official P1689r5 JSON output emitted by GCC (`-fdeps-format=p1689r5`) or +// `clang-scan-deps`. +[[nodiscard]] Void::Result::Result +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 +scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain, + const std::filesystem::path &source_file, + const std::filesystem::path &scratch_dir, + const std::vector> &include_dirs, + const std::vector &defines, + const std::vector &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 +collate_modules(const std::vector &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 +lower_header_unit_command(const Toolchain::ToolchainCapabilities &toolchain, + const std::filesystem::path &header_path, + const std::filesystem::path &bmi_output, + const std::vector> &include_dirs, + const std::vector &defines, + const std::vector &compile_options, CxxStandard standard); + +struct UnityBatchResult { + std::vector generated_unity_files; + std::vector + 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 +generate_unity_batches(const std::string &target_name, + const std::vector &sources, + const std::vector &excluded_sources, + std::size_t batch_size, const std::filesystem::path &unity_dir); + +} // namespace Void::Build::Modules diff --git a/include/Void/Build/Package/Archive.hpp b/include/Void/Build/Package/Archive.hpp new file mode 100644 index 0000000..3894942 --- /dev/null +++ b/include/Void/Build/Package/Archive.hpp @@ -0,0 +1,53 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +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 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 +create_deterministic_tar(const std::filesystem::path &output_tar, + std::vector 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 +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 +extract_safe_tar(const std::filesystem::path &tar_path, + const std::filesystem::path &destination_dir, const ArchiveLimits &limits = {}); + +} // namespace Void::Build::Package diff --git a/include/Void/Build/Package/Fetch.hpp b/include/Void/Build/Package/Fetch.hpp new file mode 100644 index 0000000..475fbc1 --- /dev/null +++ b/include/Void/Build/Package/Fetch.hpp @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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 +select_compatible_binary(const BinaryCompatibilityKey &key, + const std::vector &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 +materialize_dependency_source(const DependencyRecord &dep, const FetchOptions &options); + +} // namespace Void::Build::Package diff --git a/include/Void/Build/Package/Lockfile.hpp b/include/Void/Build/Package/Lockfile.hpp new file mode 100644 index 0000000..01f30ec --- /dev/null +++ b/include/Void/Build/Package/Lockfile.hpp @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 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 entries; +}; + +struct LockfileDocument { + int schema_version{kLockfileSchemaVersion}; + std::string revision_hash; // SHA-256 of canonical contexts payload. + std::map> 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 &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 +parse_lockfile(std::string_view json_text); + +// Reads and pins one immutable lockfile revision from disk (returns nullopt if absent). +[[nodiscard]] Void::Result::Result, 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 +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 +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 diff --git a/include/Void/Build/Package/RegistryClient.hpp b/include/Void/Build/Package/RegistryClient.hpp new file mode 100644 index 0000000..4c12f57 --- /dev/null +++ b/include/Void/Build/Package/RegistryClient.hpp @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +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/ on a VBS registry and parses all release records +// into Package::ReleaseRecord entries ready for PackageIndex + PubGrub solving. +[[nodiscard]] Void::Result::Result, Void::Result::Error> +fetch_package_releases(std::string_view registry_url, std::string_view package_name, + const RegistryAuth &auth = {}); + +// Downloads GET /api/v1/packages///download, verifies SHA-256 against +// `expected_sha256` before atomic publication to `dest_file`. +[[nodiscard]] Void::Result::Result +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//. +[[nodiscard]] Void::Result::Result +publish_package_archive(const PublishOptions &options); + +} // namespace Void::Build::Package diff --git a/include/Void/Build/Package/Solver.hpp b/include/Void/Build/Package/Solver.hpp new file mode 100644 index 0000000..c60d29c --- /dev/null +++ b/include/Void/Build/Package/Solver.hpp @@ -0,0 +1,97 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 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 dependencies; + std::vector binaries; +}; + +class PackageIndex { + public: + void add_release(ReleaseRecord release); + [[nodiscard]] std::vector releases_for(const PackageId &id) const; + + private: + std::map> releases_; +}; + +struct SolvedPackage { + PackageId id; + Void::Semver::Version version; + std::string source_sha256; + std::string source_url; + std::set enabled_features; + std::vector dependencies; + std::vector binaries; +}; + +struct SolveResult { + std::map packages; // Deterministically ordered. +}; + +struct SolveOptions { + // Already-pinned compatible versions from an existing lockfile (never silently upgraded!). + std::map 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 +solve_dependencies(const std::vector &root_constraints, + const PackageIndex &index, const SolveOptions &options = {}); + +} // namespace Void::Build::Package diff --git a/include/Void/Build/Package/Toml.hpp b/include/Void/Build/Package/Toml.hpp new file mode 100644 index 0000000..5e1c990 --- /dev/null +++ b/include/Void/Build/Package/Toml.hpp @@ -0,0 +1,97 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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; +using TomlTable = std::map>; + +// TOML 1.0 value with source origin metadata (VL-002 adapter; swappable when Void::Data::Toml +// lands). +struct TomlValue { + using Storage = std::variant, std::shared_ptr>; + Storage value; + SourceOrigin origin; + + [[nodiscard]] bool is_string() const noexcept { + return std::holds_alternative(value); + } + [[nodiscard]] bool is_bool() const noexcept { return std::holds_alternative(value); } + [[nodiscard]] bool is_int() const noexcept { + return std::holds_alternative(value); + } + [[nodiscard]] bool is_double() const noexcept { return std::holds_alternative(value); } + [[nodiscard]] bool is_array() const noexcept { + return std::holds_alternative>(value); + } + [[nodiscard]] bool is_table() const noexcept { + return std::holds_alternative>(value); + } + + [[nodiscard]] const std::string &as_string() const { return std::get(value); } + [[nodiscard]] bool as_bool() const { return std::get(value); } + [[nodiscard]] std::int64_t as_int() const { return std::get(value); } + [[nodiscard]] double as_double() const { return std::get(value); } + [[nodiscard]] const TomlArray &as_array() const { + return *std::get>(value); + } + [[nodiscard]] const TomlTable &as_table() const { + return *std::get>(value); + } + [[nodiscard]] TomlTable &as_table_mut() { return *std::get>(value); } + [[nodiscard]] TomlArray &as_array_mut() { return *std::get>(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 +parse_toml(std::string_view text, std::string_view source_name = ""); + +[[nodiscard]] Void::Result::Result +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.] tables from a TOML manifest into the exact same +// DependencyRecord model used by C++ project.dependency(...) declarations (Plan 11). +[[nodiscard]] Void::Result::Result, 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, Void::Result::Error> +merge_dependencies(const std::vector &cpp_deps, + const std::vector &toml_deps); + +} // namespace Void::Build::Package diff --git a/include/Void/Build/Platform/FileOps.hpp b/include/Void/Build/Platform/FileOps.hpp new file mode 100644 index 0000000..e3b3fe4 --- /dev/null +++ b/include/Void/Build/Platform/FileOps.hpp @@ -0,0 +1,94 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +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 + 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 +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 +copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst, + std::optional mode_override = std::nullopt); + +// Canonicalizes mtime/atime via utimensat(..., AT_SYMLINK_NOFOLLOW). +[[nodiscard]] Void::Result::Result +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 +atomic_write_file(const std::filesystem::path &path, std::string_view content, + bool durable_sync = true, unsigned mode = 0644); +[[nodiscard]] Void::Result::Result +atomic_write_bytes(const std::filesystem::path &path, std::span bytes, + bool durable_sync = true, unsigned mode = 0644); + +// Atomically replaces symlink at `link_path` pointing to `target` + parent fsync. +[[nodiscard]] Void::Result::Result +atomic_swap_symlink(const std::filesystem::path &link_path, const std::filesystem::path &target); + +[[nodiscard]] Void::Result::Result +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 +resolve_confined_path(const std::filesystem::path &root, const std::filesystem::path &candidate, + const std::vector &allowed_external_roots = {}); + +[[nodiscard]] bool path_is_within(const std::filesystem::path &root, + const std::filesystem::path &path); + +} // namespace Void::Build::Platform diff --git a/include/Void/Build/Platform/ProcessSupervisor.hpp b/include/Void/Build/Platform/ProcessSupervisor.hpp new file mode 100644 index 0000000..d285301 --- /dev/null +++ b/include/Void/Build/Platform/ProcessSupervisor.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Platform { + +enum class EnvPolicyMode { Inherit, Allowlist, ExplicitOnly }; + +struct ProcessEnvironment { + EnvPolicyMode mode{EnvPolicyMode::Inherit}; + std::vector allowlist; + std::map> set_vars; + std::vector unset_keys; +}; + +struct ProcessRequest { + std::filesystem::path executable; + std::vector arguments; // Does NOT include argv[0]; executable is prepended. + std::optional 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 on_stdout_chunk; + std::function 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 +resolve_executable(const std::filesystem::path &executable, + std::optional 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 +run_supervised(const ProcessRequest &request, std::stop_token stop = {}); + +} // namespace Void::Build::Platform diff --git a/include/Void/Build/Provider/Provider.hpp b/include/Void/Build/Provider/Provider.hpp new file mode 100644 index 0000000..e689077 --- /dev/null +++ b/include/Void/Build/Provider/Provider.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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> 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> 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 +resolve_foreign_provider(const ProviderRequest &request, std::stop_token stop = {}); + +} // namespace Void::Build::Provider diff --git a/include/Void/Build/SelfHost/TestRegistryGen.hpp b/include/Void/Build/SelfHost/TestRegistryGen.hpp new file mode 100644 index 0000000..d0c97ef --- /dev/null +++ b/include/Void/Build/SelfHost/TestRegistryGen.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +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 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, Void::Result::Error> +scan_void_tests(const std::filesystem::path &source_file); + +[[nodiscard]] Void::Result::Result +generate_test_registration_unit(const std::filesystem::path &source_file, + const std::filesystem::path &output_dir); + +} // namespace Void::Build::SelfHost diff --git a/include/Void/Build/Snapshot/Snapshot.hpp b/include/Void/Build/Snapshot/Snapshot.hpp new file mode 100644 index 0000000..53a4427 --- /dev/null +++ b/include/Void/Build/Snapshot/Snapshot.hpp @@ -0,0 +1,87 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +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 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 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> entries; + std::map> memberships; + std::vector lookup_guards; +}; + +struct SnapshotOptions { + std::filesystem::path project_root; + std::filesystem::path snapshot_store_dir; + std::vector allowed_external_roots; + std::vector 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 capture_snapshot( + const SnapshotOptions &options, const std::vector &explicit_files, + const std::vector &directory_roots, + const std::vector, 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 +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 +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 +write_snapshot_manifest(const InputSnapshot &snapshot, + const std::filesystem::path &snapshot_store_dir); + +} // namespace Void::Build::Snapshot diff --git a/include/Void/Build/State/StateStore.hpp b/include/Void/Build/State/StateStore.hpp new file mode 100644 index 0000000..75ea4f1 --- /dev/null +++ b/include/Void/Build/State/StateStore.hpp @@ -0,0 +1,138 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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> outputs; // relative/logical output -> CAS blob + std::map> discovered_inputs; // path -> sha256 + std::vector 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 + 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 + store_blob_from_file(const std::filesystem::path &file_path); + + [[nodiscard]] Void::Result::Result + verify_blob(std::string_view sha256) const; + + [[nodiscard]] Void::Result::Result + materialize_blob(const BlobRef &ref, const std::filesystem::path &destination) const; + + // Transactional action cache queries & publication. + [[nodiscard]] Void::Result::Result, Void::Result::Error> + lookup_action(std::string_view action_key) const; + + [[nodiscard]] Void::Result::Result + record_action_success(const ActionSuccessRecord &record); + + // Graph generation tracking. + [[nodiscard]] Void::Result::Result + record_generation(const GraphGenerationRecord &generation); + + [[nodiscard]] Void::Result::Result, Void::Result::Error> + list_generations(std::optional profile_name = std::nullopt) const; + + // Leases protect active runs from GC deletion. + [[nodiscard]] Void::Result::Result + acquire_lease(std::string_view profile_name, const std::set &pinned_blobs = {}); + + // Conservative crash recovery: removes uncommitted staging files and dead leases; + // never invents a successful action record. + [[nodiscard]] Void::Result::Result recover(); + + // Garbage collects unreachable CAS blobs outside active leases and pinned generations. + [[nodiscard]] Void::Result::Result + 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> actions; + std::vector generations; + }; + + explicit StateStore(std::filesystem::path root); + + [[nodiscard]] Void::Result::Result + load_db_locked() const; + [[nodiscard]] Void::Result::Result + 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 diff --git a/include/Void/Build/Toolchain/Driver.hpp b/include/Void/Build/Toolchain/Driver.hpp new file mode 100644 index 0000000..5886b78 --- /dev/null +++ b/include/Void/Build/Toolchain/Driver.hpp @@ -0,0 +1,136 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Toolchain { + +struct ToolchainCapabilities { + CompilerFamily family{CompilerFamily::Gcc}; + std::filesystem::path cxx_compiler; + std::filesystem::path archiver; + std::optional module_scanner; + std::string version_banner; + std::string target_triple; + std::string sysroot; + std::string compiler_sha256; + std::string archiver_sha256; + std::vector default_include_dirs; + std::map> 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 depfile; + std::optional response_file_dir; + std::vector> include_dirs; // (path, is_system) + std::vector defines; + std::vector compile_options; + CxxStandard cxx_standard{CxxStandard::Default}; + LtoMode lto{LtoMode::None}; + std::vector sanitizers; + bool position_independent{false}; + std::optional precompiled_header; + std::vector 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 bmi_output; + std::vector> module_bmi_imports; + std::optional module_mapper_file; +}; + +struct LinkRequest { + TargetKind kind{TargetKind::Executable}; + std::filesystem::path output_file; + std::optional response_file_dir; + std::vector object_files; + std::vector static_libraries; + std::vector shared_libraries; + std::vector rpaths; + std::vector link_options; + LtoMode lto{LtoMode::None}; + std::vector sanitizers; + std::size_t response_file_threshold{32768}; +}; + +struct LoweredCommand { + std::filesystem::path executable; + std::vector arguments; + std::map> environment; + std::optional 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 +discover_and_probe(const ProfileContext &context, + const std::optional &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 +lower_compile_command(const ToolchainCapabilities &toolchain, const CompileRequest &request); + +// Lowers a deterministic static library archive command (`ar rcsD`). +[[nodiscard]] Void::Result::Result +lower_archive_command(const ToolchainCapabilities &toolchain, + const std::filesystem::path &output_archive, + const std::vector &object_files, + const std::optional &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 +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 diff --git a/include/Void/Build/Util/Json.hpp b/include/Void/Build/Util/Json.hpp new file mode 100644 index 0000000..3a8620d --- /dev/null +++ b/include/Void/Build/Util/Json.hpp @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include +#include +#include + +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 +[[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 diff --git a/include/Void/Build/Util/Sha256.hpp b/include/Void/Build/Util/Sha256.hpp new file mode 100644 index 0000000..1ddf080 --- /dev/null +++ b/include/Void/Build/Util/Sha256.hpp @@ -0,0 +1,53 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Util { + +using Sha256Digest = std::array; + +// 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 data) noexcept; + void update(std::span 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 data) noexcept; +[[nodiscard]] std::string sha256_hex(std::string_view text); +[[nodiscard]] std::string sha256_hex(std::span data); +[[nodiscard]] Void::Result::Result +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 diff --git a/include/Void/Build/Watch/Watcher.hpp b/include/Void/Build/Watch/Watcher.hpp new file mode 100644 index 0000000..92360ea --- /dev/null +++ b/include/Void/Build/Watch/Watcher.hpp @@ -0,0 +1,125 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Watch { + +struct WatchBatch { + std::vector 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 + create(const std::filesystem::path &root_dir, + std::vector excluded_names = {".git", ".vbs", "build", ".serena", ".cache", + "keys"}); + + // Polls for events up to `timeout` and coalesces burst activity across `debounce`. + [[nodiscard]] Void::Result::Result + 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 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 excluded); + void close_fd() noexcept; + Void::Result::Result 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 excluded_; + std::map 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> imported_targets; +}; + +using ProviderMetadataReader = + std::function; + +struct WatchLoopOptions { + WatchMode mode{WatchMode::FullBuild}; + Config::FrontendOptions frontend; + std::optional + explicit_profile; // Empty in MetadataOnly -> follow active editor profile + std::optional compiler_override; + std::vector 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 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 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, Void::Result::Error> +run_watch_loop(const WatchLoopOptions &options, std::stop_token stop = {}); + +} // namespace Void::Build::Watch diff --git a/include/vbs/build.hpp b/include/vbs/build.hpp deleted file mode 100644 index 1066239..0000000 --- a/include/vbs/build.hpp +++ /dev/null @@ -1,201 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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 compile_options; -}; - -struct ProfileDescription { - std::string name; - std::vector compile_options; -}; - -class Profiles { - public: - void add(std::string name, std::vector compile_options = {}); - [[nodiscard]] const std::vector &records() const noexcept; - [[nodiscard]] ProfileContext resolve(std::string_view name, CompilerFamily compiler, - std::string os, std::string architecture) const; - - private: - std::vector 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 files); - [[nodiscard]] static SourceSet file(std::string path); - [[nodiscard]] static SourceSet glob(std::string pattern); - [[nodiscard]] const std::vector &records() const noexcept; - - private: - std::vector records_; -}; - -struct OptionValue { - using Value = std::variant; - Value value; - - OptionValue(std::string text) : value{std::move(text)} {} - OptionValue(const char *text) : OptionValue{std::string{text}} {} - OptionValue(bool boolean) : value{boolean} {} - template - requires(!std::same_as) - OptionValue(Integer integer) : value{std::int64_t{0}} { - if (!std::in_range(integer)) { - throw std::invalid_argument{"option integer is out of range"}; - } - value = static_cast(integer); - } -}; -using OptionMap = std::map>; - -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 sources; - std::vector include_directories; - std::vector compile_options; - std::vector 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 owner, std::size_t dependency, - std::string name); - std::weak_ptr 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 owner, std::size_t index); - std::weak_ptr 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 owner, std::size_t index); - std::weak_ptr 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 &targets() const noexcept; - [[nodiscard]] const std::vector &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 state_; -}; - -} // namespace vbs - -// Description entry points supplied by ordinary user C++ translation units. -void build(vbs::Project &project); -void profiles(vbs::Profiles &profiles); diff --git a/recipes/SelfHost/VbsSelfHostRecipe.cpp b/recipes/SelfHost/VbsSelfHostRecipe.cpp new file mode 100644 index 0000000..5ab7742 --- /dev/null +++ b/recipes/SelfHost/VbsSelfHostRecipe.cpp @@ -0,0 +1,130 @@ +#include "VbsSelfHostRecipe.hpp" + +#include +#include +#include + +#include +#include + +namespace Void::Build::Recipes { + +Void::Result::Result +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 \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 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 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 diff --git a/recipes/SelfHost/VbsSelfHostRecipe.hpp b/recipes/SelfHost/VbsSelfHostRecipe.hpp new file mode 100644 index 0000000..5da0edf --- /dev/null +++ b/recipes/SelfHost/VbsSelfHostRecipe.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include +#include +#include + +#include +#include + +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 +add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config); + +} // namespace Void::Build::Recipes diff --git a/recipes/VoidLibrary/VoidLibraryRecipe.cpp b/recipes/VoidLibrary/VoidLibraryRecipe.cpp new file mode 100644 index 0000000..1d8348d --- /dev/null +++ b/recipes/VoidLibrary/VoidLibraryRecipe.cpp @@ -0,0 +1,113 @@ +#include "VoidLibraryRecipe.hpp" + +#include +#include +#include +#include +#include + +namespace Void::Build::Recipes { +namespace { + +struct ModuleDef { + std::vector internal_deps; + bool needs_threads{false}; +}; + +const std::map> &known_modules() { + static const std::map> 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 collect_sources(const std::filesystem::path &src_dir) { + std::vector 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 &enabled_modules) { + const auto &defs = known_modules(); + + // Compute transitive module closure in deterministic topological order. + std::set visited; + std::vector 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 diff --git a/recipes/VoidLibrary/VoidLibraryRecipe.hpp b/recipes/VoidLibrary/VoidLibraryRecipe.hpp new file mode 100644 index 0000000..631d066 --- /dev/null +++ b/recipes/VoidLibrary/VoidLibraryRecipe.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include +#include +#include +#include + +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> modules; +}; + +[[nodiscard]] VoidLibraryTargets +add_void_library_native(Project &project, const std::filesystem::path &void_source_dir, + const std::vector &enabled_modules = { + "Configuration", "Text", "Unicode", "Async", "Testing"}); + +} // namespace Void::Build::Recipes diff --git a/registry/include/Void/Build/Registry/HttpServer.hpp b/registry/include/Void/Build/Registry/HttpServer.hpp new file mode 100644 index 0000000..286d483 --- /dev/null +++ b/registry/include/Void/Build/Registry/HttpServer.hpp @@ -0,0 +1,96 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Registry { + +struct HttpRequest { + std::string method; + std::string raw_target; + std::string path; + std::map> query; + std::map> headers; // lowercase header keys + std::map> cookies; + std::string body; + + [[nodiscard]] std::optional + header(std::string_view lower_name) const noexcept; + [[nodiscard]] std::optional cookie(std::string_view name) const noexcept; +}; + +struct HttpResponse { + std::uint16_t status{200}; + std::string reason{"OK"}; + std::map> headers; + std::vector 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; + +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 + 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 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> headers; + std::vector set_cookies; + std::string body; +}; + +[[nodiscard]] Void::Result::Result +send_loopback_http(std::uint16_t port, std::string_view method, std::string_view target, + const std::map> &headers = {}, + std::string_view body = {}); + +} // namespace Void::Build::Registry diff --git a/registry/include/Void/Build/Registry/RegistryService.hpp b/registry/include/Void/Build/Registry/RegistryService.hpp new file mode 100644 index 0000000..c656a2e --- /dev/null +++ b/registry/include/Void/Build/Registry/RegistryService.hpp @@ -0,0 +1,150 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +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 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 owners; + std::map> 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, Void::Result::Error> + open(RegistryConfig config); + + [[nodiscard]] Void::Result::Result 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 + backup_to(const std::filesystem::path &backup_dir); + [[nodiscard]] Void::Result::Result + restore_from(const std::filesystem::path &backup_dir); + + // Direct user/token helpers for bootstrap and test fixtures. + [[nodiscard]] Void::Result::Result + create_user(std::string username, std::string password, Role role); + [[nodiscard]] Void::Result::Result + create_token(std::string username, std::string label, std::set scopes, + std::int64_t expires_epoch = 0); + + private: + explicit RegistryService(RegistryConfig config); + + struct Principal { + std::string username; + Role role{Role::Reader}; + std::set scopes; + bool via_session_cookie{false}; + std::string csrf_token; + }; + + Void::Result::Result load_locked(); + Void::Result::Result save_locked(); + std::optional 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> users_; + std::map> tokens_; + std::map> sessions_; + std::map> packages_; + std::vector audits_; + HttpServer server_; +}; + +} // namespace Void::Build::Registry diff --git a/registry/service/HttpServer.cpp b/registry/service/HttpServer.cpp new file mode 100644 index 0000000..40a460d --- /dev/null +++ b/registry/service/HttpServer.cpp @@ -0,0 +1,446 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(n); + } + return true; +} + +void parse_query(std::string_view qs, std::map> &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> &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 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 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 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(&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(&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 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(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::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(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 +send_loopback_http(std::uint16_t port, std::string_view method, std::string_view target, + const std::map> &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(&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 buf{}; + for (;;) { + const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0); + if (n > 0) { + raw.append(buf.data(), static_cast(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::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 diff --git a/registry/service/Main.cpp b/registry/service/Main.cpp new file mode 100644 index 0000000..0e8185f --- /dev/null +++ b/registry/service/Main.cpp @@ -0,0 +1,89 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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(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; +} diff --git a/registry/service/RegistryService.cpp b/registry/service/RegistryService.cpp new file mode 100644 index 0000000..ea84427 --- /dev/null +++ b/registry/service/RegistryService.cpp @@ -0,0 +1,1110 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Registry { +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)); +} + +std::int64_t now_epoch() { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); +} + +std::string random_hex(std::size_t num_bytes) { + std::vector bytes(num_bytes); + if (::getrandom(bytes.data(), bytes.size(), 0) != static_cast(bytes.size())) { + const auto t = static_cast( + std::chrono::high_resolution_clock::now().time_since_epoch().count()); + for (std::size_t i = 0; i < num_bytes; ++i) { + bytes[i] = static_cast((t >> ((i % 8) * 8)) ^ (i * 0x5du)); + } + } + return Void::Encoding::Hex::encode(std::span{bytes.data(), bytes.size()}); +} + +// Key-stretched salted SHA-256 password hash (20,000 rounds) — swappable to Argon2id via +// Void::Security. +std::string derive_password_hash(std::string_view salt_hex, std::string_view password) { + std::string cur = Util::sha256_hex(std::string{salt_hex} + ":" + std::string{password}); + for (int i = 0; i < 20000; ++i) { + cur = Util::sha256_hex(cur + ":" + std::string{salt_hex}); + } + return cur; +} + +std::string_view role_name(Role r) { + switch (r) { + case Role::Reader: + return "reader"; + case Role::Publisher: + return "publisher"; + case Role::Admin: + return "admin"; + } + return "reader"; +} + +Role parse_role(std::string_view s) { + if (s == "admin") + return Role::Admin; + if (s == "publisher") + return Role::Publisher; + return Role::Reader; +} + +bool valid_package_name(std::string_view name) { + if (name.empty() || name.size() > 64) { + return false; + } + return std::ranges::all_of(name, [](char c) { + return Void::Str::is_ascii_alnum(c) || c == '_' || c == '-' || c == '.'; + }); +} + +std::vector split_path(std::string_view path) { + std::vector segs; + for (const auto part : Void::Str::split(path, '/')) { + if (!part.empty()) { + segs.emplace_back(part); + } + } + return segs; +} + +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(&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(&v->value); + return b ? *b : def; +} + +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(&v->value); + return i ? *i : def; +} + +std::string content_type_for_ext(const std::filesystem::path &p) { + const auto ext = p.extension().string(); + if (ext == ".html") + return "text/html; charset=utf-8"; + if (ext == ".css") + return "text/css; charset=utf-8"; + if (ext == ".js") + return "application/javascript; charset=utf-8"; + if (ext == ".json") + return "application/json; charset=utf-8"; + if (ext == ".svg") + return "image/svg+xml"; + return "application/octet-stream"; +} + +} // namespace + +RegistryService::RegistryService(RegistryConfig config) + : config_{std::move(config)}, blobs_dir_{config_.data_dir / "cas" / "blobs"}, + meta_file_{config_.data_dir / "metadata.v1.json"}, + lock_file_{config_.data_dir / "registry.lock"} {} + +Void::Result::Result, Void::Result::Error> +RegistryService::open(RegistryConfig config) { + std::error_code ec; + std::filesystem::create_directories(config.data_dir / "cas" / "blobs", ec); + if (ec) { + return std::unexpected{make_error(Void::System::map_errno_to_system_code(ec.value()), + "RegistryService::open: cannot create data directories")}; + } + auto svc = std::unique_ptr(new RegistryService(std::move(config))); + std::lock_guard lk{svc->mu_}; + if (std::filesystem::exists(svc->meta_file_, ec)) { + if (auto r = svc->load_locked(); !r) { + return std::unexpected{r.error()}; + } + } else { + if (!svc->config_.bootstrap_admin_password.empty()) { + UserRecord admin; + admin.username = svc->config_.bootstrap_admin_user; + admin.role = Role::Admin; + admin.password_salt_hex = random_hex(16); + admin.password_hash_hex = derive_password_hash(admin.password_salt_hex, + svc->config_.bootstrap_admin_password); + svc->users_[admin.username] = std::move(admin); + } + if (auto r = svc->save_locked(); !r) { + return std::unexpected{r.error()}; + } + } + return svc; +} + +Void::Result::Result RegistryService::start_http() { + HttpServerOptions sopts; + sopts.bind_address = config_.bind_address; + sopts.port = config_.port; + sopts.max_body_bytes = static_cast(config_.max_upload_bytes); + return server_.start(sopts, [this](const HttpRequest &req) { return handle_request(req); }); +} + +void RegistryService::stop_http() noexcept { server_.stop(); } + +std::filesystem::path RegistryService::blob_path(std::string_view sha256) const { + if (sha256.size() < 2) { + return blobs_dir_ / std::string{sha256}; + } + return blobs_dir_ / std::string{sha256.substr(0, 2)} / std::string{sha256}; +} + +Void::Result::Result RegistryService::load_locked() { + auto text = Void::FileSystem::read_file_bounded(meta_file_, {64ULL * 1024ULL * 1024ULL}); + if (!text) { + return std::unexpected{text.error()}; + } + auto parsed = Void::Json::Strict::parse(*text); + if (!parsed) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::io_error, "corrupt registry metadata JSON")}; + } + const auto *root = std::get_if(&parsed->value); + if (!root) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::io_error, "invalid registry metadata")}; + } + + users_.clear(); + tokens_.clear(); + packages_.clear(); + audits_.clear(); + + if (const auto *uv = find_key(*root, "users")) { + if (const auto *uarr = std::get_if(&uv->value)) { + for (const auto &item : *uarr) { + if (const auto *uo = std::get_if(&item.value)) { + UserRecord u; + u.username = get_str(*uo, "username"); + u.role = parse_role(get_str(*uo, "role")); + u.password_salt_hex = get_str(*uo, "salt"); + u.password_hash_hex = get_str(*uo, "password_hash"); + u.active = get_bool(*uo, "active", true); + users_[u.username] = std::move(u); + } + } + } + } + if (const auto *tv = find_key(*root, "tokens")) { + if (const auto *tarr = std::get_if(&tv->value)) { + for (const auto &item : *tarr) { + if (const auto *to = std::get_if(&item.value)) { + ApiTokenRecord t; + t.token_id = get_str(*to, "token_id"); + t.username = get_str(*to, "username"); + t.label = get_str(*to, "label"); + t.token_sha256 = get_str(*to, "token_sha256"); + t.expires_epoch = get_i64(*to, "expires_epoch", 0); + t.revoked = get_bool(*to, "revoked", false); + if (const auto *sv = find_key(*to, "scopes")) { + if (const auto *sarr = std::get_if(&sv->value)) { + for (const auto &s : *sarr) { + if (const auto *ss = std::get_if(&s.value)) { + t.scopes.insert(*ss); + } + } + } + } + tokens_[t.token_id] = std::move(t); + } + } + } + } + if (const auto *pv = find_key(*root, "packages")) { + if (const auto *parr = std::get_if(&pv->value)) { + for (const auto &item : *parr) { + if (const auto *po = std::get_if(&item.value)) { + PackageMeta p; + p.name = get_str(*po, "name"); + p.description = get_str(*po, "description"); + p.is_private = get_bool(*po, "is_private", false); + if (const auto *ov = find_key(*po, "owners")) { + if (const auto *oarr = std::get_if(&ov->value)) { + for (const auto &o : *oarr) { + if (const auto *os = std::get_if(&o.value)) { + p.owners.insert(*os); + } + } + } + } + if (const auto *rv = find_key(*po, "releases")) { + if (const auto *rarr = std::get_if(&rv->value)) { + for (const auto &r : *rarr) { + if (const auto *ro = std::get_if(&r.value)) { + ReleaseMeta rm; + rm.version = get_str(*ro, "version"); + rm.sha256 = get_str(*ro, "sha256"); + rm.size_bytes = + static_cast(get_i64(*ro, "size_bytes", 0)); + rm.yanked = get_bool(*ro, "yanked", false); + rm.publisher = get_str(*ro, "publisher"); + rm.published_epoch = get_i64(*ro, "published_epoch", 0); + p.releases[rm.version] = std::move(rm); + } + } + } + } + packages_[p.name] = std::move(p); + } + } + } + } + if (const auto *av = find_key(*root, "audits")) { + if (const auto *aarr = std::get_if(&av->value)) { + for (const auto &item : *aarr) { + if (const auto *ao = std::get_if(&item.value)) { + audits_.push_back({get_i64(*ao, "timestamp", 0), get_str(*ao, "actor"), + get_str(*ao, "action"), get_str(*ao, "target"), + get_str(*ao, "outcome"), get_str(*ao, "detail")}); + } + } + } + } + return {}; +} + +Void::Result::Result RegistryService::save_locked() { + using Util::json_array; + using Util::json_quote; + + auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive); + if (!lock) { + return std::unexpected{lock.error()}; + } + + std::vector ulist; + for (const auto &[k, v] : users_) + ulist.push_back(&v); + std::vector tlist; + for (const auto &[k, v] : tokens_) + tlist.push_back(&v); + std::vector plist; + for (const auto &[k, v] : packages_) + plist.push_back(&v); + + std::string out = "{\"schema_version\":1,\"users\":"; + out += json_array(ulist, [](const UserRecord *u) { + return "{\"username\":" + json_quote(u->username) + + ",\"role\":" + json_quote(role_name(u->role)) + + ",\"salt\":" + json_quote(u->password_salt_hex) + + ",\"password_hash\":" + json_quote(u->password_hash_hex) + + ",\"active\":" + std::string{u->active ? "true" : "false"} + '}'; + }); + out += ",\"tokens\":"; + out += json_array(tlist, [](const ApiTokenRecord *t) { + return "{\"token_id\":" + json_quote(t->token_id) + + ",\"username\":" + json_quote(t->username) + ",\"label\":" + json_quote(t->label) + + ",\"token_sha256\":" + json_quote(t->token_sha256) + + ",\"scopes\":" + json_array(t->scopes, json_quote) + + ",\"expires_epoch\":" + std::to_string(t->expires_epoch) + + ",\"revoked\":" + std::string{t->revoked ? "true" : "false"} + '}'; + }); + out += ",\"packages\":"; + out += json_array(plist, [](const PackageMeta *p) { + std::vector rlist; + for (const auto &[vk, rv] : p->releases) + rlist.push_back(&rv); + return "{\"name\":" + json_quote(p->name) + + ",\"description\":" + json_quote(p->description) + + ",\"is_private\":" + std::string{p->is_private ? "true" : "false"} + + ",\"owners\":" + json_array(p->owners, json_quote) + ",\"releases\":" + + json_array(rlist, + [](const ReleaseMeta *r) { + return "{\"version\":" + json_quote(r->version) + + ",\"sha256\":" + json_quote(r->sha256) + + ",\"size_bytes\":" + std::to_string(r->size_bytes) + + ",\"yanked\":" + std::string{r->yanked ? "true" : "false"} + + ",\"publisher\":" + json_quote(r->publisher) + + ",\"published_epoch\":" + std::to_string(r->published_epoch) + + '}'; + }) + + '}'; + }); + out += ",\"audits\":"; + out += json_array(audits_, [](const AuditEntry &a) { + return "{\"timestamp\":" + std::to_string(a.timestamp) + + ",\"actor\":" + json_quote(a.actor) + ",\"action\":" + json_quote(a.action) + + ",\"target\":" + json_quote(a.target) + ",\"outcome\":" + json_quote(a.outcome) + + ",\"detail\":" + json_quote(a.detail) + '}'; + }); + out += "}\n"; + return Platform::atomic_write_file(meta_file_, out, true); +} + +void RegistryService::append_audit_locked(std::string actor, std::string action, std::string target, + std::string outcome, std::string detail) { + audits_.push_back({now_epoch(), std::move(actor), std::move(action), std::move(target), + std::move(outcome), Package::redact_secrets(detail)}); + if (audits_.size() > 2000) { + audits_.erase(audits_.begin(), audits_.begin() + 500); + } +} + +std::uint64_t RegistryService::total_storage_bytes_locked() const { + std::uint64_t total = 0; + std::set seen; + for (const auto &[pname, p] : packages_) { + for (const auto &[ver, rel] : p.releases) { + if (seen.insert(rel.sha256).second) { + total += rel.size_bytes; + } + } + } + return total; +} + +std::optional +RegistryService::authenticate_locked(const HttpRequest &req, std::string &auth_err) const { + const auto now = now_epoch(); + + // 1. Bearer token authentication. + if (const auto auth = req.header("authorization")) { + if (auth->starts_with("Bearer ")) { + const auto raw_tok = auth->substr(7); + const std::string hashed = Util::sha256_hex(raw_tok); + for (const auto &[tid, tok] : tokens_) { + if (Util::constant_time_equal(tok.token_sha256, hashed)) { + if (tok.revoked) { + auth_err = "token has been revoked"; + return std::nullopt; + } + if (tok.expires_epoch > 0 && now > tok.expires_epoch) { + auth_err = "token has expired"; + return std::nullopt; + } + const auto uit = users_.find(tok.username); + if (uit == users_.end() || !uit->second.active) { + auth_err = "token user is inactive"; + return std::nullopt; + } + return Principal{uit->second.username, uit->second.role, tok.scopes, false, {}}; + } + } + auth_err = "invalid bearer token"; + return std::nullopt; + } + auth_err = "unsupported authorization scheme"; + return std::nullopt; + } + + // 2. HttpOnly browser session cookie authentication. + if (const auto sid = req.cookie("vbs_session")) { + const std::string sid_hash = Util::sha256_hex(*sid); + const auto sit = sessions_.find(sid_hash); + if (sit == sessions_.end() || + (sit->second.expires_epoch > 0 && now > sit->second.expires_epoch)) { + auth_err = "session expired or invalid"; + return std::nullopt; + } + const auto uit = users_.find(sit->second.username); + if (uit == users_.end() || !uit->second.active) { + auth_err = "session user is inactive"; + return std::nullopt; + } + std::set scopes{"read"}; + if (uit->second.role == Role::Publisher || uit->second.role == Role::Admin) { + scopes.insert("publish"); + } + if (uit->second.role == Role::Admin) { + scopes.insert("admin"); + } + return Principal{uit->second.username, uit->second.role, std::move(scopes), true, + sit->second.csrf_token}; + } + + return std::nullopt; +} + +bool RegistryService::check_csrf_locked(const HttpRequest &req, const Principal &p) const { + if (!p.via_session_cookie) { + return true; // Bearer tokens are not ambient browser credentials. + } + const auto hdr = req.header("x-csrf-token"); + if (!hdr || !Util::constant_time_equal(*hdr, p.csrf_token)) { + return false; + } + if (const auto origin = req.header("origin")) { + if (!origin->starts_with("http://127.0.0.1") && !origin->starts_with("http://localhost") && + !origin->starts_with("https://")) { + return false; + } + } + return true; +} + +Void::Result::Result +RegistryService::create_user(std::string username, std::string password, Role role) { + std::lock_guard lk{mu_}; + if (username.empty() || password.size() < 6) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "username must be nonempty and password >= 6 chars")}; + } + if (users_.contains(username)) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::already_exists, "user already exists")}; + } + UserRecord u; + u.username = username; + u.role = role; + u.password_salt_hex = random_hex(16); + u.password_hash_hex = derive_password_hash(u.password_salt_hex, password); + users_[username] = std::move(u); + append_audit_locked("system", "user.create", username, "ok", std::string{role_name(role)}); + return save_locked(); +} + +Void::Result::Result +RegistryService::create_token(std::string username, std::string label, std::set scopes, + std::int64_t expires_epoch) { + std::lock_guard lk{mu_}; + if (!users_.contains(username)) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::not_found, "user not found")}; + } + const std::string plaintext = "vbs_tok_" + random_hex(24); + ApiTokenRecord rec; + rec.token_id = "tok_" + random_hex(8); + rec.username = username; + rec.label = std::move(label); + rec.token_sha256 = Util::sha256_hex(plaintext); + rec.scopes = std::move(scopes); + rec.expires_epoch = expires_epoch; + tokens_[rec.token_id] = std::move(rec); + append_audit_locked(username, "token.create", rec.token_id, "ok", "scoped token created"); + if (auto r = save_locked(); !r) { + return std::unexpected{r.error()}; + } + return plaintext; +} + +HttpResponse RegistryService::serve_static_web_asset(std::string_view req_path) const { + if (config_.web_root.empty()) { + return HttpResponse::error_json(404, "not_found", "web UI root not configured"); + } + std::string rel{req_path}; + if (rel == "/" || rel.empty()) { + rel = "index.html"; + } else if (rel.front() == '/') { + rel.erase(0, 1); + } + if (rel.find("..") != std::string::npos || rel.find('\\') != std::string::npos) { + return HttpResponse::error_json(403, "forbidden", "invalid static asset path"); + } + auto confined = Platform::resolve_confined_path(config_.web_root, config_.web_root / rel); + if (!confined) { + return HttpResponse::error_json(403, "forbidden", "path escape rejected"); + } + auto bytes = Void::FileSystem::read_file(*confined); + if (!bytes) { + return HttpResponse::error_json(404, "not_found", "asset not found"); + } + HttpResponse resp; + resp.status = 200; + resp.headers["Content-Type"] = content_type_for_ext(*confined); + resp.body = std::move(*bytes); + return resp; +} + +HttpResponse RegistryService::handle_request(const HttpRequest &req) { + using Util::json_array; + using Util::json_quote; + + if (!req.path.starts_with("/api/")) { + if (req.method != "GET") { + return HttpResponse::error_json(405, "method_not_allowed", + "GET only for static assets"); + } + return serve_static_web_asset(req.path); + } + + std::lock_guard lk{mu_}; + const auto segs = split_path(req.path); + + // Health endpoint. + if (req.method == "GET" && req.path == "/api/v1/health") { + return HttpResponse::json(200, "{\"status\":\"ok\",\"schema_version\":1}\n"); + } + + // Session login: POST /api/v1/auth/login -> sets HttpOnly SameSite=Strict cookie + returns CSRF + // token. + if (req.method == "POST" && req.path == "/api/v1/auth/login") { + auto parsed = Void::Json::Strict::parse(req.body); + const auto *obj = parsed ? std::get_if(&parsed->value) : nullptr; + if (!obj) { + return HttpResponse::error_json(400, "invalid_json", "login body must be JSON object"); + } + const auto username = get_str(*obj, "username"); + const auto password = get_str(*obj, "password"); + const auto uit = users_.find(username); + if (uit == users_.end() || !uit->second.active) { + append_audit_locked(username, "auth.login", username, "denied", "invalid credentials"); + return HttpResponse::error_json(401, "unauthorized", "invalid credentials"); + } + const auto candidate_hash = derive_password_hash(uit->second.password_salt_hex, password); + if (!Util::constant_time_equal(candidate_hash, uit->second.password_hash_hex)) { + append_audit_locked(username, "auth.login", username, "denied", "invalid credentials"); + return HttpResponse::error_json(401, "unauthorized", "invalid credentials"); + } + const std::string raw_sid = random_hex(24); + const std::string csrf = random_hex(24); + SessionRecord srec{Util::sha256_hex(raw_sid), username, csrf, now_epoch() + 86400}; + sessions_[srec.session_id_hash] = srec; + append_audit_locked(username, "auth.login", username, "ok", "session created"); + (void)save_locked(); + + auto resp = HttpResponse::json(200, "{\"username\":" + json_quote(username) + ",\"role\":" + + json_quote(role_name(uit->second.role)) + + ",\"csrf_token\":" + json_quote(csrf) + "}\n"); + resp.set_cookies.push_back("vbs_session=" + raw_sid + + "; HttpOnly; SameSite=Strict; Path=/"); + return resp; + } + + std::string auth_err; + const auto principal = authenticate_locked(req, auth_err); + if (!auth_err.empty()) { + return HttpResponse::error_json(401, "unauthorized", auth_err); + } + + // Session logout. + if (req.method == "POST" && req.path == "/api/v1/auth/logout") { + if (!principal) { + return HttpResponse::error_json(401, "unauthorized", "authentication required"); + } + if (!check_csrf_locked(req, *principal)) { + return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); + } + if (const auto sid = req.cookie("vbs_session")) { + sessions_.erase(Util::sha256_hex(*sid)); + } + auto resp = HttpResponse::json(200, "{\"logged_out\":true}\n"); + resp.set_cookies.push_back("vbs_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0"); + return resp; + } + + if (req.method == "GET" && req.path == "/api/v1/auth/me") { + if (!principal) { + return HttpResponse::error_json(401, "unauthorized", "not logged in"); + } + return HttpResponse::json(200, "{\"username\":" + json_quote(principal->username) + + ",\"role\":" + json_quote(role_name(principal->role)) + + ",\"csrf_token\":" + json_quote(principal->csrf_token) + + "}\n"); + } + + auto can_read_pkg = [&](const PackageMeta &p) { + if (!p.is_private) + return true; + if (!principal) + return false; + if (principal->role == Role::Admin) + return true; + return p.owners.contains(principal->username) || principal->scopes.contains("read"); + }; + + auto can_publish_pkg = [&](const PackageMeta *existing) { + if (!principal) + return false; + if (!principal->scopes.contains("publish") && principal->role != Role::Admin) + return false; + if (principal->role == Role::Admin) + return true; + if (principal->role != Role::Publisher) + return false; + if (existing && !existing->owners.empty() && + !existing->owners.contains(principal->username)) { + return false; + } + return true; + }; + + // GET /api/v1/packages?q=... + if (req.method == "GET" && req.path == "/api/v1/packages") { + const std::string q = req.query.contains("q") ? req.query.at("q") : std::string{}; + std::vector visible; + for (const auto &[name, p] : packages_) { + if (!can_read_pkg(p)) + continue; + if (!q.empty() && name.find(q) == std::string::npos && + p.description.find(q) == std::string::npos) { + continue; + } + visible.push_back(&p); + } + return HttpResponse::json( + 200, "{\"packages\":" + json_array(visible, [](const PackageMeta *p) { + return "{\"name\":" + json_quote(p->name) + + ",\"description\":" + json_quote(p->description) + + ",\"is_private\":" + std::string{p->is_private ? "true" : "false"} + + ",\"release_count\":" + std::to_string(p->releases.size()) + '}'; + }) + "}\n"); + } + + // /api/v1/packages/[/[/download|/yank]] + if (segs.size() >= 4 && segs[0] == "api" && segs[1] == "v1" && segs[2] == "packages") { + const std::string &pkg_name = segs[3]; + if (!valid_package_name(pkg_name)) { + return HttpResponse::error_json(400, "invalid_package_name", "invalid package name"); + } + + // Package detail: GET /api/v1/packages/ + if (segs.size() == 4 && req.method == "GET") { + const auto pit = packages_.find(pkg_name); + if (pit == packages_.end()) { + return HttpResponse::error_json(404, "not_found", "package not found"); + } + if (!can_read_pkg(pit->second)) { + return HttpResponse::error_json(principal ? 403 : 401, "forbidden", + "private package requires authorization"); + } + std::vector rlist; + for (const auto &[vk, rv] : pit->second.releases) + rlist.push_back(&rv); + return HttpResponse::json( + 200, + "{\"name\":" + json_quote(pit->second.name) + + ",\"description\":" + json_quote(pit->second.description) + + ",\"is_private\":" + std::string{pit->second.is_private ? "true" : "false"} + + ",\"owners\":" + json_array(pit->second.owners, json_quote) + ",\"releases\":" + + json_array(rlist, + [](const ReleaseMeta *r) { + return "{\"version\":" + json_quote(r->version) + + ",\"sha256\":" + json_quote(r->sha256) + + ",\"size_bytes\":" + std::to_string(r->size_bytes) + + ",\"yanked\":" + + std::string{r->yanked ? "true" : "false"} + + ",\"publisher\":" + json_quote(r->publisher) + '}'; + }) + + "}\n"); + } + + // Publish immutable release: PUT /api/v1/packages// + if (segs.size() == 5 && req.method == "PUT") { + if (!principal) { + return HttpResponse::error_json(401, "unauthorized", "authentication required"); + } + if (!check_csrf_locked(req, *principal)) { + return HttpResponse::error_json(403, "csrf_failed", + "missing or invalid CSRF token"); + } + const std::string &ver_str = segs[4]; + if (!Void::Semver::parse_strict(ver_str)) { + return HttpResponse::error_json(400, "invalid_version", + "release version must be strict SemVer"); + } + const auto pit = packages_.find(pkg_name); + const PackageMeta *existing_pkg = (pit == packages_.end()) ? nullptr : &pit->second; + if (!can_publish_pkg(existing_pkg)) { + append_audit_locked(principal->username, "package.publish", + pkg_name + "@" + ver_str, "denied", "unauthorized publisher"); + (void)save_locked(); + return HttpResponse::error_json(403, "forbidden", + "insufficient publish authority or ownership"); + } + + const std::string actual_sha = Util::sha256_hex(req.body); + if (const auto claimed = req.header("x-content-sha256"); + claimed && *claimed != actual_sha) { + return HttpResponse::error_json(400, "digest_mismatch", + "X-Content-SHA256 does not match uploaded bytes"); + } + + // Immutability check: idempotent on exact bytes, 409 Conflict on different bytes! + if (existing_pkg) { + if (const auto rit = existing_pkg->releases.find(ver_str); + rit != existing_pkg->releases.end()) { + if (rit->second.sha256 == actual_sha) { + return HttpResponse::json(200, + "{\"status\":\"already_published\",\"sha256\":" + + json_quote(actual_sha) + "}\n"); + } + append_audit_locked(principal->username, "package.publish", + pkg_name + "@" + ver_str, "conflict", + "immutable release overwrite rejected"); + (void)save_locked(); + return HttpResponse::error_json( + 409, "immutable_conflict", + "release already exists with different content digest"); + } + } + + // Storage quota check. + if (total_storage_bytes_locked() + req.body.size() > config_.max_storage_bytes) { + return HttpResponse::error_json(413, "quota_exceeded", + "registry storage quota exceeded"); + } + + // Stage & validate tar archive safety (rejects traversal/symlinks/malformed tar; + // NEVER executes uploaded recipes!). + Void::FileSystem::TempDir probe_tmp{"vbs_reg_probe_"}; + const auto staged_tar = probe_tmp / "upload.tar"; + if (auto w = Platform::atomic_write_file(staged_tar, req.body, false); !w) { + return HttpResponse::error_json(500, "stage_error", w.error().message()); + } + auto probe_extract = Package::extract_safe_tar(staged_tar, probe_tmp / "extracted"); + if (!probe_extract) { + append_audit_locked(principal->username, "package.publish", + pkg_name + "@" + ver_str, "rejected", + probe_extract.error().message()); + (void)save_locked(); + return HttpResponse::error_json(422, "invalid_archive", + probe_extract.error().message()); + } + + // Publish CAS blob BEFORE committing metadata! + const auto dst_blob = blob_path(actual_sha); + std::error_code ec; + if (!std::filesystem::exists(dst_blob, ec)) { + auto copied = Platform::copy_isolated(staged_tar, dst_blob, 0444u); + if (!copied) { + return HttpResponse::error_json(500, "blob_publish_failed", + copied.error().message()); + } + } + + PackageMeta &pkg = packages_[pkg_name]; + if (pkg.name.empty()) { + pkg.name = pkg_name; + pkg.owners.insert(principal->username); + } + if (const auto desc = req.header("x-package-description")) { + pkg.description = std::string{*desc}; + } + if (const auto priv = req.header("x-package-private")) { + pkg.is_private = (*priv == "true" || *priv == "1"); + } + pkg.releases[ver_str] = ReleaseMeta{ver_str, actual_sha, req.body.size(), + false, principal->username, now_epoch()}; + append_audit_locked(principal->username, "package.publish", pkg_name + "@" + ver_str, + "ok", "sha256=" + actual_sha); + if (auto s = save_locked(); !s) { + return HttpResponse::error_json(500, "metadata_commit_failed", s.error().message()); + } + return HttpResponse::json(201, "{\"name\":" + json_quote(pkg_name) + + ",\"version\":" + json_quote(ver_str) + + ",\"sha256\":" + json_quote(actual_sha) + "}\n"); + } + + // Download release blob: GET /api/v1/packages///download + if (segs.size() == 6 && segs[5] == "download" && req.method == "GET") { + const auto pit = packages_.find(pkg_name); + if (pit == packages_.end()) { + return HttpResponse::error_json(404, "not_found", "package not found"); + } + if (!can_read_pkg(pit->second)) { + return HttpResponse::error_json(principal ? 403 : 401, "forbidden", + "private package requires authorization"); + } + const auto rit = pit->second.releases.find(segs[4]); + if (rit == pit->second.releases.end()) { + return HttpResponse::error_json(404, "not_found", "release not found"); + } + const auto bpath = blob_path(rit->second.sha256); + auto bytes = Void::FileSystem::read_file_bounded(bpath, {256ULL * 1024ULL * 1024ULL}); + if (!bytes || Util::sha256_hex(*bytes) != rit->second.sha256) { + return HttpResponse::error_json(500, "integrity_error", + "stored CAS blob missing or corrupted"); + } + HttpResponse resp; + resp.status = 200; + resp.headers["Content-Type"] = "application/x-tar"; + resp.headers["X-Content-SHA256"] = rit->second.sha256; + resp.body = std::move(*bytes); + return resp; + } + + // Yank/unyank release: POST /api/v1/packages///yank + if (segs.size() == 6 && segs[5] == "yank" && req.method == "POST") { + if (!principal) { + return HttpResponse::error_json(401, "unauthorized", "authentication required"); + } + if (!check_csrf_locked(req, *principal)) { + return HttpResponse::error_json(403, "csrf_failed", + "missing or invalid CSRF token"); + } + const auto pit = packages_.find(pkg_name); + if (pit == packages_.end() || !pit->second.releases.contains(segs[4])) { + return HttpResponse::error_json(404, "not_found", "release not found"); + } + if (!can_publish_pkg(&pit->second)) { + return HttpResponse::error_json(403, "forbidden", "insufficient yank authority"); + } + bool yanked = true; + if (!req.body.empty()) { + if (auto parsed = Void::Json::Strict::parse(req.body); parsed) { + if (const auto *obj = std::get_if(&parsed->value)) { + yanked = get_bool(*obj, "yanked", true); + } + } + } + pit->second.releases.at(segs[4]).yanked = yanked; + append_audit_locked(principal->username, yanked ? "package.yank" : "package.unyank", + pkg_name + "@" + segs[4], "ok", ""); + (void)save_locked(); + return HttpResponse::json(200, "{\"yanked\":" + std::string{yanked ? "true" : "false"} + + "}\n"); + } + } + + // Tokens API: GET/POST /api/v1/tokens, DELETE /api/v1/tokens/ + if (segs.size() >= 3 && segs[0] == "api" && segs[1] == "v1" && segs[2] == "tokens") { + if (!principal) { + return HttpResponse::error_json(401, "unauthorized", "authentication required"); + } + if (req.method == "GET" && segs.size() == 3) { + std::vector mine; + for (const auto &[id, t] : tokens_) { + if (principal->role == Role::Admin || t.username == principal->username) { + mine.push_back(&t); + } + } + return HttpResponse::json( + 200, "{\"tokens\":" + json_array(mine, [](const ApiTokenRecord *t) { + return "{\"token_id\":" + json_quote(t->token_id) + + ",\"username\":" + json_quote(t->username) + + ",\"label\":" + json_quote(t->label) + + ",\"scopes\":" + json_array(t->scopes, json_quote) + + ",\"revoked\":" + std::string{t->revoked ? "true" : "false"} + '}'; + }) + "}\n"); + } + if (req.method == "POST" && segs.size() == 3) { + if (!check_csrf_locked(req, *principal)) { + return HttpResponse::error_json(403, "csrf_failed", + "missing or invalid CSRF token"); + } + auto parsed = Void::Json::Strict::parse(req.body); + const auto *obj = parsed ? std::get_if(&parsed->value) : nullptr; + if (!obj) { + return HttpResponse::error_json(400, "invalid_json", "expected JSON object"); + } + const std::string label = get_str(*obj, "label"); + std::set scopes{"read"}; + if (const auto *sv = find_key(*obj, "scopes")) { + if (const auto *sarr = std::get_if(&sv->value)) { + scopes.clear(); + for (const auto &item : *sarr) { + if (const auto *s = std::get_if(&item.value)) { + // Prevent privilege escalation beyond caller's own role! + if (*s == "admin" && principal->role != Role::Admin) { + return HttpResponse::error_json(403, "privilege_escalation", + "cannot mint admin token"); + } + if (*s == "publish" && principal->role == Role::Reader) { + return HttpResponse::error_json(403, "privilege_escalation", + "reader cannot mint publish token"); + } + scopes.insert(*s); + } + } + } + } + const std::string plaintext = "vbs_tok_" + random_hex(24); + ApiTokenRecord rec; + rec.token_id = "tok_" + random_hex(8); + rec.username = principal->username; + rec.label = label; + rec.token_sha256 = Util::sha256_hex(plaintext); + rec.scopes = std::move(scopes); + tokens_[rec.token_id] = rec; + append_audit_locked(principal->username, "token.create", rec.token_id, "ok", label); + (void)save_locked(); + // Plaintext secret shown ONCE at creation only! + return HttpResponse::json(201, "{\"token_id\":" + json_quote(rec.token_id) + + ",\"token\":" + json_quote(plaintext) + "}\n"); + } + if (req.method == "DELETE" && segs.size() == 4) { + if (!check_csrf_locked(req, *principal)) { + return HttpResponse::error_json(403, "csrf_failed", + "missing or invalid CSRF token"); + } + const auto tit = tokens_.find(segs[3]); + if (tit == tokens_.end()) { + return HttpResponse::error_json(404, "not_found", "token not found"); + } + if (principal->role != Role::Admin && tit->second.username != principal->username) { + return HttpResponse::error_json(403, "forbidden", + "cannot revoke another user's token"); + } + tit->second.revoked = true; + append_audit_locked(principal->username, "token.revoke", segs[3], "ok", ""); + (void)save_locked(); + return HttpResponse::json(200, "{\"revoked\":true}\n"); + } + } + + // Admin endpoints: users, audit, storage. + if (req.path == "/api/v1/users" || req.path == "/api/v1/audit" || + req.path == "/api/v1/admin/storage") { + if (!principal) { + return HttpResponse::error_json(401, "unauthorized", "authentication required"); + } + if (principal->role != Role::Admin) { + return HttpResponse::error_json(403, "forbidden", "admin role required"); + } + if (req.path == "/api/v1/users" && req.method == "GET") { + std::vector ulist; + for (const auto &[k, v] : users_) + ulist.push_back(&v); + return HttpResponse::json( + 200, "{\"users\":" + json_array(ulist, [](const UserRecord *u) { + return "{\"username\":" + json_quote(u->username) + + ",\"role\":" + json_quote(role_name(u->role)) + + ",\"active\":" + std::string{u->active ? "true" : "false"} + '}'; + }) + "}\n"); + } + if (req.path == "/api/v1/users" && req.method == "POST") { + if (!check_csrf_locked(req, *principal)) { + return HttpResponse::error_json(403, "csrf_failed", + "missing or invalid CSRF token"); + } + auto parsed = Void::Json::Strict::parse(req.body); + const auto *obj = parsed ? std::get_if(&parsed->value) : nullptr; + if (!obj) { + return HttpResponse::error_json(400, "invalid_json", "expected JSON object"); + } + const auto uname = get_str(*obj, "username"); + const auto pass = get_str(*obj, "password"); + const auto role = parse_role(get_str(*obj, "role")); + if (uname.empty() || pass.size() < 6) { + return HttpResponse::error_json(400, "invalid_user", + "username required and password >= 6 chars"); + } + UserRecord u; + u.username = uname; + u.role = role; + u.password_salt_hex = random_hex(16); + u.password_hash_hex = derive_password_hash(u.password_salt_hex, pass); + users_[uname] = std::move(u); + append_audit_locked(principal->username, "user.upsert", uname, "ok", + std::string{role_name(role)}); + (void)save_locked(); + return HttpResponse::json(201, "{\"username\":" + json_quote(uname) + + ",\"role\":" + json_quote(role_name(role)) + "}\n"); + } + if (req.path == "/api/v1/audit" && req.method == "GET") { + return HttpResponse::json(200, + "{\"audits\":" + json_array(audits_, [](const AuditEntry &a) { + return "{\"timestamp\":" + std::to_string(a.timestamp) + + ",\"actor\":" + json_quote(a.actor) + + ",\"action\":" + json_quote(a.action) + + ",\"target\":" + json_quote(a.target) + + ",\"outcome\":" + json_quote(a.outcome) + + ",\"detail\":" + json_quote(a.detail) + '}'; + }) + "}\n"); + } + if (req.path == "/api/v1/admin/storage" && req.method == "GET") { + return HttpResponse::json( + 200, "{\"used_bytes\":" + std::to_string(total_storage_bytes_locked()) + + ",\"quota_bytes\":" + std::to_string(config_.max_storage_bytes) + + ",\"package_count\":" + std::to_string(packages_.size()) + "}\n"); + } + } + + return HttpResponse::error_json(404, "not_found", "unknown API endpoint"); +} + +Void::Result::Result +RegistryService::backup_to(const std::filesystem::path &backup_dir) { + std::lock_guard lk{mu_}; + std::error_code ec; + std::filesystem::create_directories(backup_dir / "cas" / "blobs", ec); + if (auto s = save_locked(); !s) { + return std::unexpected{s.error()}; + } + if (auto c = Platform::copy_isolated(meta_file_, backup_dir / "metadata.v1.json"); !c) { + return std::unexpected{c.error()}; + } + for (const auto &[pname, p] : packages_) { + for (const auto &[ver, rel] : p.releases) { + const auto src = blob_path(rel.sha256); + const auto dst = backup_dir / "cas" / "blobs" / rel.sha256.substr(0, 2) / rel.sha256; + if (std::filesystem::is_regular_file(src, ec) && !std::filesystem::exists(dst, ec)) { + auto c = Platform::copy_isolated(src, dst, 0444u); + if (!c) { + return std::unexpected{c.error()}; + } + } + } + } + return {}; +} + +Void::Result::Result +RegistryService::restore_from(const std::filesystem::path &backup_dir) { + std::lock_guard lk{mu_}; + const auto backup_meta = backup_dir / "metadata.v1.json"; + std::error_code ec; + if (!std::filesystem::is_regular_file(backup_meta, ec)) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::not_found, "backup metadata missing")}; + } + // Restore CAS blobs first, then replace metadata atomically. + const auto src_blobs = backup_dir / "cas" / "blobs"; + if (std::filesystem::is_directory(src_blobs, ec)) { + for (const auto &ent : std::filesystem::recursive_directory_iterator(src_blobs, ec)) { + if (ent.is_regular_file(ec)) { + const auto rel = ent.path().lexically_relative(src_blobs); + const auto dst = blobs_dir_ / rel; + if (!std::filesystem::exists(dst, ec)) { + auto c = Platform::copy_isolated(ent.path(), dst, 0444u); + if (!c) { + return std::unexpected{c.error()}; + } + } + } + } + } + auto copied = Platform::copy_isolated(backup_meta, meta_file_); + if (!copied) { + return std::unexpected{copied.error()}; + } + return load_locked(); +} + +} // namespace Void::Build::Registry diff --git a/registry/web/app.js b/registry/web/app.js new file mode 100644 index 0000000..eb80bc9 --- /dev/null +++ b/registry/web/app.js @@ -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(); +})(); diff --git a/registry/web/index.html b/registry/web/index.html new file mode 100644 index 0000000..2709550 --- /dev/null +++ b/registry/web/index.html @@ -0,0 +1,106 @@ + + + + + + VoidBuildSystem Package Registry + + + +
+
+

VoidBuildSystem Registry

+ Connecting... +
+ +
+ +
+ + +
+
+ + + +
+
+ +
+ + + + + + + + +
+ + + + diff --git a/registry/web/styles.css b/registry/web/styles.css new file mode 100644 index 0000000..9fbc1ef --- /dev/null +++ b/registry/web/styles.css @@ -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); } diff --git a/src/Bridge/CMakeBridge.cpp b/src/Bridge/CMakeBridge.cpp new file mode 100644 index 0000000..b7070af --- /dev/null +++ b/src/Bridge/CMakeBridge.cpp @@ -0,0 +1,285 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +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(&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(&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 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 +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(&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 emitted_names; + + const auto *deps_v = find_key(*root, "dependencies"); + const auto *deps_arr = deps_v ? std::get_if(&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(&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(&ov->value)) { + for (const auto &[k, val] : *oo) { + if (const auto *s = std::get_if(&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 diff --git a/src/Build.cpp b/src/Build.cpp new file mode 100644 index 0000000..4b6a53a --- /dev/null +++ b/src/Build.cpp @@ -0,0 +1,1177 @@ +#include +#include + +#include +#include +#include + +namespace Void::Build { +namespace detail { +struct ProjectState { + ProfileContext context; + std::vector targets; + std::vector dependencies; + std::vector dependency_files; + std::vector install_rules; +}; +} // namespace detail +namespace { + +using Util::json_array; +using Util::json_quote; + +void require_text(std::string_view text, std::string_view field) { + if (text.empty()) { + throw std::invalid_argument{std::string{field} + " must not be empty"}; + } +} + +auto owner(const std::weak_ptr &weak) { + auto state = weak.lock(); + if (!state) { + throw std::logic_error{"declaration handle's Project has expired"}; + } + return state; +} + +bool is_hex_digest(std::string_view text, std::size_t expected_len) { + if (text.size() != expected_len) { + return false; + } + return std::ranges::all_of(text, [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + }); +} + +void validate_sanitizers(const std::vector &sanitizers) { + bool has_asan = false; + bool has_tsan = false; + bool has_msan = false; + for (const auto s : sanitizers) { + (void)sanitizer_name(s); + if (s == Sanitizer::Address) { + has_asan = true; + } else if (s == Sanitizer::Thread) { + has_tsan = true; + } else if (s == Sanitizer::Memory) { + has_msan = true; + } + } + if (has_asan && has_tsan) { + throw std::invalid_argument{"AddressSanitizer and ThreadSanitizer are mutually exclusive"}; + } + if (has_asan && has_msan) { + throw std::invalid_argument{"AddressSanitizer and MemorySanitizer are mutually exclusive"}; + } + if (has_tsan && has_msan) { + throw std::invalid_argument{"ThreadSanitizer and MemorySanitizer are mutually exclusive"}; + } +} + +void validate_context(const ProfileContext &context) { + require_text(context.name, "profile name"); + (void)compiler_name(context.compiler); + require_text(context.os, "target OS"); + require_text(context.architecture, "target architecture"); + for (const auto &option : context.compile_options) { + require_text(option, "compile option"); + } + for (const auto &option : context.link_options) { + require_text(option, "link option"); + } + for (const auto &def : context.defines) { + require_text(def, "define"); + } + validate_sanitizers(context.sanitizers); +} + +std::string options_json(const OptionMap &options) { + std::string output{"{"}; + bool first = true; + for (const auto &[name, option] : options) { + if (!first) { + output += ','; + } + first = false; + output += json_quote(name) + ':'; + output += std::visit( + [](const auto &value) -> std::string { + using Type = std::remove_cvref_t; + if constexpr (std::same_as) { + return json_quote(value); + } else if constexpr (std::same_as) { + return value ? "true" : "false"; + } else { + return std::to_string(value); + } + }, + option.value); + } + return output + '}'; +} + +std::string env_json(const std::map> &env) { + std::string output{"{"}; + bool first = true; + for (const auto &[k, v] : env) { + if (!first) { + output += ','; + } + first = false; + output += json_quote(k) + ':' + json_quote(v); + } + return output + '}'; +} + +std::string scoped_options_json(const std::vector &opts) { + return json_array(opts, [](const ScopedOption &opt) { + return "{\"value\":" + json_quote(opt.value) + + ",\"visibility\":" + json_quote(visibility_name(opt.visibility)) + '}'; + }); +} + +std::string install_rule_json(const InstallRule &rule) { + return "{\"target_name\":" + json_quote(rule.target_name) + + ",\"source_path\":" + json_quote(rule.source_path) + + ",\"destination\":" + json_quote(rule.destination) + + ",\"component\":" + json_quote(rule.component) + + ",\"is_directory\":" + std::string{rule.is_directory ? "true" : "false"} + '}'; +} + +} // namespace + +std::string_view compiler_name(CompilerFamily compiler) { + switch (compiler) { + case CompilerFamily::Gcc: + return "gcc"; + case CompilerFamily::Clang: + return "clang"; + } + throw std::invalid_argument{"unknown compiler family"}; +} + +CompilerFamily parse_compiler(std::string_view name) { + if (name == "gcc") { + return CompilerFamily::Gcc; + } + if (name == "clang") { + return CompilerFamily::Clang; + } + throw std::invalid_argument{"unknown compiler '" + std::string{name} + + "' (expected gcc or clang)"}; +} + +std::string_view visibility_name(Visibility visibility) { + switch (visibility) { + case Visibility::Private: + return "private"; + case Visibility::Public: + return "public"; + case Visibility::Interface: + return "interface"; + } + throw std::invalid_argument{"unknown visibility"}; +} + +Visibility parse_visibility(std::string_view name) { + if (name == "private") { + return Visibility::Private; + } + if (name == "public") { + return Visibility::Public; + } + if (name == "interface") { + return Visibility::Interface; + } + throw std::invalid_argument{"unknown visibility '" + std::string{name} + "'"}; +} + +std::string_view target_kind_name(TargetKind kind) { + switch (kind) { + case TargetKind::Executable: + return "executable"; + case TargetKind::StaticLibrary: + return "static_library"; + case TargetKind::SharedLibrary: + return "shared_library"; + case TargetKind::HeaderOnly: + return "header_only"; + case TargetKind::ObjectLibrary: + return "object_library"; + case TargetKind::CustomAction: + return "custom_action"; + case TargetKind::Test: + return "test"; + } + throw std::invalid_argument{"unknown target kind"}; +} + +TargetKind parse_target_kind(std::string_view name) { + if (name == "executable") { + return TargetKind::Executable; + } + if (name == "static_library") { + return TargetKind::StaticLibrary; + } + if (name == "shared_library") { + return TargetKind::SharedLibrary; + } + if (name == "header_only") { + return TargetKind::HeaderOnly; + } + if (name == "object_library") { + return TargetKind::ObjectLibrary; + } + if (name == "custom_action") { + return TargetKind::CustomAction; + } + if (name == "test") { + return TargetKind::Test; + } + throw std::invalid_argument{"unknown target kind '" + std::string{name} + "'"}; +} + +std::string_view source_kind_name(SourceKind kind) { + switch (kind) { + case SourceKind::File: + return "file"; + case SourceKind::Glob: + return "glob"; + case SourceKind::ModuleInterface: + return "module_interface"; + case SourceKind::ModulePartition: + return "module_partition"; + case SourceKind::HeaderUnit: + return "header_unit"; + } + throw std::invalid_argument{"unknown source kind"}; +} + +SourceKind parse_source_kind(std::string_view name) { + if (name == "file") { + return SourceKind::File; + } + if (name == "glob") { + return SourceKind::Glob; + } + if (name == "module_interface") { + return SourceKind::ModuleInterface; + } + if (name == "module_partition") { + return SourceKind::ModulePartition; + } + if (name == "header_unit") { + return SourceKind::HeaderUnit; + } + throw std::invalid_argument{"unknown source kind '" + std::string{name} + "'"}; +} + +std::string_view cxx_standard_name(CxxStandard standard) { + switch (standard) { + case CxxStandard::Default: + return "default"; + case CxxStandard::Cxx17: + return "c++17"; + case CxxStandard::Cxx20: + return "c++20"; + case CxxStandard::Cxx23: + return "c++23"; + case CxxStandard::Cxx26: + return "c++26"; + } + throw std::invalid_argument{"unknown C++ standard"}; +} + +CxxStandard parse_cxx_standard(std::string_view name) { + if (name.empty() || name == "default") { + return CxxStandard::Default; + } + if (name == "c++17" || name == "17") { + return CxxStandard::Cxx17; + } + if (name == "c++20" || name == "20") { + return CxxStandard::Cxx20; + } + if (name == "c++23" || name == "23") { + return CxxStandard::Cxx23; + } + if (name == "c++26" || name == "26") { + return CxxStandard::Cxx26; + } + throw std::invalid_argument{"unknown C++ standard '" + std::string{name} + "'"}; +} + +std::string_view lto_mode_name(LtoMode mode) { + switch (mode) { + case LtoMode::None: + return "none"; + case LtoMode::Full: + return "full"; + case LtoMode::Thin: + return "thin"; + } + throw std::invalid_argument{"unknown LTO mode"}; +} + +LtoMode parse_lto_mode(std::string_view name) { + if (name.empty() || name == "none") { + return LtoMode::None; + } + if (name == "full") { + return LtoMode::Full; + } + if (name == "thin") { + return LtoMode::Thin; + } + throw std::invalid_argument{"unknown LTO mode '" + std::string{name} + "'"}; +} + +std::string_view sanitizer_name(Sanitizer sanitizer) { + switch (sanitizer) { + 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"; + } + throw std::invalid_argument{"unknown sanitizer"}; +} + +Sanitizer parse_sanitizer(std::string_view name) { + if (name == "address" || name == "asan") { + return Sanitizer::Address; + } + if (name == "undefined" || name == "ubsan") { + return Sanitizer::Undefined; + } + if (name == "thread" || name == "tsan") { + return Sanitizer::Thread; + } + if (name == "memory" || name == "msan") { + return Sanitizer::Memory; + } + if (name == "leak" || name == "lsan") { + return Sanitizer::Leak; + } + throw std::invalid_argument{"unknown sanitizer '" + std::string{name} + "'"}; +} + +void Profiles::add(std::string name, std::vector compile_options) { + ProfileDescription desc; + desc.name = std::move(name); + desc.compile_options = std::move(compile_options); + define(std::move(desc)); +} + +void Profiles::inherit(std::string name, std::string parent, + std::vector compile_options) { + require_text(parent, "parent profile name"); + ProfileDescription desc; + desc.name = std::move(name); + desc.parent = std::move(parent); + desc.compile_options = std::move(compile_options); + define(std::move(desc)); +} + +void Profiles::define(ProfileDescription description) { + require_text(description.name, "profile name"); + if (std::ranges::any_of(records_, + [&](const auto &record) { return record.name == description.name; })) { + throw std::invalid_argument{"duplicate profile '" + description.name + "'"}; + } + if (description.parent) { + require_text(*description.parent, "parent profile name"); + if (*description.parent == description.name) { + throw std::invalid_argument{"profile '" + description.name + + "' cannot inherit from itself"}; + } + } + for (const auto &option : description.compile_options) { + require_text(option, "compile option"); + } + for (const auto &option : description.link_options) { + require_text(option, "link option"); + } + for (const auto &def : description.defines) { + require_text(def, "define"); + } + validate_sanitizers(description.sanitizers); + records_.push_back(std::move(description)); +} + +const std::vector &Profiles::records() const noexcept { return records_; } + +ProfileContext Profiles::resolve(std::string_view name, CompilerFamily compiler, std::string os, + std::string architecture) const { + return resolve(name, std::optional{compiler}, std::move(os), + std::move(architecture)); +} + +ProfileContext Profiles::resolve(std::string_view name, + std::optional compiler_override, std::string os, + std::string architecture) const { + std::vector chain; + std::set visiting; + std::string_view current = name; + while (!current.empty()) { + if (!visiting.insert(current).second) { + throw std::invalid_argument{"profile inheritance cycle involving '" + + std::string{current} + "'"}; + } + const auto found = std::ranges::find(records_, current, &ProfileDescription::name); + if (found == records_.end()) { + if (chain.empty()) { + throw std::invalid_argument{"unknown profile '" + std::string{current} + "'"}; + } + throw std::invalid_argument{"unknown parent profile '" + std::string{current} + + "' referenced by '" + chain.back()->name + "'"}; + } + chain.push_back(&(*found)); + if (found->parent) { + current = *found->parent; + } else { + break; + } + } + + ProfileContext context; + context.name = std::string{name}; + context.os = std::move(os); + context.architecture = std::move(architecture); + context.compiler = CompilerFamily::Gcc; + + // Apply from root ancestor down to concrete profile. + for (auto it = chain.rbegin(); it != chain.rend(); ++it) { + const auto *desc = *it; + if (desc->compiler) { + context.compiler = *desc->compiler; + } + if (desc->cxx_standard) { + context.cxx_standard = *desc->cxx_standard; + } + if (desc->lto) { + context.lto = *desc->lto; + } + if (!desc->sysroot.empty()) { + context.sysroot = desc->sysroot; + } + if (!desc->compiler_path.empty()) { + context.compiler_path = desc->compiler_path; + } + if (desc->reproducibility_epoch) { + context.reproducibility_epoch = *desc->reproducibility_epoch; + } + if (desc->nondeterministic) { + context.nondeterministic = *desc->nondeterministic; + } + context.compile_options.insert(context.compile_options.end(), desc->compile_options.begin(), + desc->compile_options.end()); + context.link_options.insert(context.link_options.end(), desc->link_options.begin(), + desc->link_options.end()); + context.defines.insert(context.defines.end(), desc->defines.begin(), desc->defines.end()); + for (const auto s : desc->sanitizers) { + if (!std::ranges::contains(context.sanitizers, s)) { + context.sanitizers.push_back(s); + } + } + } + if (compiler_override) { + context.compiler = *compiler_override; + } + validate_context(context); + return context; +} + +std::string Profiles::to_json() const { + return "{\"schema_version\":" + std::to_string(schema_version) + ",\"profiles\":" + + json_array( + records_, + [](const ProfileDescription &p) { + std::string out = "{\"name\":" + json_quote(p.name); + if (p.parent) { + out += ",\"parent\":" + json_quote(*p.parent); + } + if (p.compiler) { + out += ",\"compiler\":" + json_quote(compiler_name(*p.compiler)); + } + if (p.cxx_standard) { + out += ",\"cxx_standard\":" + json_quote(cxx_standard_name(*p.cxx_standard)); + } + if (p.lto) { + out += ",\"lto\":" + json_quote(lto_mode_name(*p.lto)); + } + if (!p.sysroot.empty()) { + out += ",\"sysroot\":" + json_quote(p.sysroot); + } + if (!p.compiler_path.empty()) { + out += ",\"compiler_path\":" + json_quote(p.compiler_path); + } + if (p.reproducibility_epoch) { + out += + ",\"reproducibility_epoch\":" + std::to_string(*p.reproducibility_epoch); + } + if (p.nondeterministic) { + out += ",\"nondeterministic\":" + + std::string{*p.nondeterministic ? "true" : "false"}; + } + out += ",\"compile_options\":" + json_array(p.compile_options, json_quote) + + ",\"link_options\":" + json_array(p.link_options, json_quote) + + ",\"defines\":" + json_array(p.defines, json_quote) + ",\"sanitizers\":" + + json_array(p.sanitizers, + [](Sanitizer s) { return json_quote(sanitizer_name(s)); }) + + '}'; + return out; + }) + + '}'; +} + +Profiles default_profiles() { + Profiles result; + result.add("debug", {"-O0", "-g"}); + result.add("release", {"-O3", "-DNDEBUG"}); + return result; +} + +SourceSet::SourceSet(std::initializer_list files) { + for (const auto path : files) { + require_text(path, "source path"); + records_.push_back({SourceKind::File, std::string{path}}); + } +} + +SourceSet SourceSet::file(std::string path) { + require_text(path, "source path"); + SourceSet result; + result.records_.push_back({SourceKind::File, std::move(path)}); + return result; +} + +SourceSet SourceSet::glob(std::string pattern) { + require_text(pattern, "glob pattern"); + SourceSet result; + result.records_.push_back({SourceKind::Glob, std::move(pattern)}); + return result; +} + +SourceSet SourceSet::module_interface(std::string path) { + require_text(path, "module interface path"); + SourceSet result; + result.records_.push_back({SourceKind::ModuleInterface, std::move(path)}); + return result; +} + +SourceSet SourceSet::module_partition(std::string path) { + require_text(path, "module partition path"); + SourceSet result; + result.records_.push_back({SourceKind::ModulePartition, std::move(path)}); + return result; +} + +SourceSet SourceSet::header_unit(std::string path) { + require_text(path, "header unit path"); + SourceSet result; + result.records_.push_back({SourceKind::HeaderUnit, std::move(path)}); + return result; +} + +const std::vector &SourceSet::records() const noexcept { return records_; } + +Target::Target(std::weak_ptr state, std::size_t index) + : owner_{std::move(state)}, index_{index} {} + +Target &Target::sources(const SourceSet &sources) { + auto state = owner(owner_); + auto &records = state->targets.at(index_).sources; + records.insert(records.end(), sources.records().begin(), sources.records().end()); + return *this; +} + +Target &Target::conventional_sources() { + owner(owner_)->targets.at(index_).use_conventional_sources = true; + return *this; +} + +Target &Target::module_sources(const SourceSet &sources) { + auto state = owner(owner_); + auto &records = state->targets.at(index_).sources; + for (const auto &rec : sources.records()) { + if (rec.kind == SourceKind::File) { + records.push_back({SourceKind::ModuleInterface, rec.path}); + } else { + records.push_back(rec); + } + } + return *this; +} + +Target &Target::header_unit(std::string header_path) { + require_text(header_path, "header unit path"); + owner(owner_)->targets.at(index_).sources.push_back( + {SourceKind::HeaderUnit, std::move(header_path)}); + return *this; +} + +Target &Target::include_directory(std::string path, Visibility visibility) { + require_text(path, "include directory"); + (void)visibility_name(visibility); + owner(owner_)->targets.at(index_).include_directories.push_back( + {std::move(path), visibility, false}); + return *this; +} + +Target &Target::system_include_directory(std::string path, Visibility visibility) { + require_text(path, "system include directory"); + (void)visibility_name(visibility); + owner(owner_)->targets.at(index_).include_directories.push_back( + {std::move(path), visibility, true}); + return *this; +} + +Target &Target::compile_option(std::string option) { + require_text(option, "compile option"); + auto &rec = owner(owner_)->targets.at(index_); + rec.compile_options.push_back(option); + rec.scoped_compile_options.push_back({std::move(option), Visibility::Private}); + return *this; +} + +Target &Target::compile_option(std::string option, Visibility visibility) { + require_text(option, "compile option"); + (void)visibility_name(visibility); + auto &rec = owner(owner_)->targets.at(index_); + if (visibility != Visibility::Interface) { + rec.compile_options.push_back(option); + } + rec.scoped_compile_options.push_back({std::move(option), visibility}); + return *this; +} + +Target &Target::define(std::string macro, Visibility visibility) { + require_text(macro, "define"); + (void)visibility_name(visibility); + owner(owner_)->targets.at(index_).defines.push_back({std::move(macro), visibility}); + return *this; +} + +Target &Target::link_option(std::string option, Visibility visibility) { + require_text(option, "link option"); + (void)visibility_name(visibility); + owner(owner_)->targets.at(index_).link_options.push_back({std::move(option), visibility}); + return *this; +} + +Target &Target::link(const Target &target, Visibility visibility) { + auto state = owner(owner_); + if (owner(target.owner_) != state) { + throw std::invalid_argument{"cannot link a target from another Project"}; + } + (void)visibility_name(visibility); + state->targets.at(index_).links.push_back( + {LinkKind::Local, state->targets.at(target.index_).name, {}, visibility}); + return *this; +} + +Target &Target::link(const ImportedTarget &target, Visibility visibility) { + auto state = owner(owner_); + if (owner(target.owner_) != state) { + throw std::invalid_argument{"cannot link an imported target from another Project"}; + } + (void)visibility_name(visibility); + state->targets.at(index_).links.push_back({LinkKind::Imported, target.name_, + state->dependencies.at(target.dependency_).name, + visibility}); + return *this; +} + +Target &Target::depends_on(const Target &producer) { + auto state = owner(owner_); + if (owner(producer.owner_) != state) { + throw std::invalid_argument{"cannot depend on a target from another Project"}; + } + const auto &producer_name = state->targets.at(producer.index_).name; + auto &prereqs = state->targets.at(index_).prerequisites; + if (!std::ranges::contains(prereqs, producer_name)) { + prereqs.push_back(producer_name); + } + return *this; +} + +Target &Target::cxx_standard(CxxStandard standard) { + (void)cxx_standard_name(standard); + owner(owner_)->targets.at(index_).cxx_standard = standard; + return *this; +} + +Target &Target::precompiled_header(std::string header_path) { + require_text(header_path, "precompiled header path"); + owner(owner_)->targets.at(index_).precompiled_header = std::move(header_path); + return *this; +} + +Target &Target::unity_build(bool enabled, std::size_t batch_size) { + if (enabled && batch_size == 0) { + throw std::invalid_argument{"unity batch size must be positive"}; + } + auto &rec = owner(owner_)->targets.at(index_); + rec.unity_enabled = enabled; + rec.unity_batch_size = batch_size; + return *this; +} + +Target &Target::lto(LtoMode mode) { + (void)lto_mode_name(mode); + owner(owner_)->targets.at(index_).lto = mode; + return *this; +} + +Target &Target::sanitizer(Sanitizer sanitizer) { + auto &rec = owner(owner_)->targets.at(index_); + auto next = rec.sanitizers; + if (!std::ranges::contains(next, sanitizer)) { + next.push_back(sanitizer); + } + validate_sanitizers(next); + rec.sanitizers = std::move(next); + return *this; +} + +Target &Target::per_file_option(std::string source_path, std::string option) { + require_text(source_path, "source path"); + require_text(option, "per-file compile option"); + owner(owner_)->targets.at(index_).per_file_options.push_back( + {std::move(source_path), std::move(option)}); + return *this; +} + +Target &Target::command(std::vector argv) { + if (argv.empty()) { + throw std::invalid_argument{"command argv must not be empty"}; + } + require_text(argv.front(), "command executable"); + owner(owner_)->targets.at(index_).command_argv = std::move(argv); + return *this; +} + +Target &Target::inputs(std::vector paths) { + for (const auto &p : paths) { + require_text(p, "input path"); + } + auto &dst = owner(owner_)->targets.at(index_).action_inputs; + dst.insert(dst.end(), std::make_move_iterator(paths.begin()), + std::make_move_iterator(paths.end())); + return *this; +} + +Target &Target::outputs(std::vector paths) { + for (const auto &p : paths) { + require_text(p, "output path"); + } + auto &dst = owner(owner_)->targets.at(index_).action_outputs; + dst.insert(dst.end(), std::make_move_iterator(paths.begin()), + std::make_move_iterator(paths.end())); + return *this; +} + +Target &Target::working_directory(std::string directory) { + require_text(directory, "working directory"); + owner(owner_)->targets.at(index_).working_directory = std::move(directory); + return *this; +} + +Target &Target::env(std::string key, std::string value) { + require_text(key, "environment variable key"); + owner(owner_)->targets.at(index_).environment[std::move(key)] = std::move(value); + return *this; +} + +Target &Target::nondeterministic(bool enabled) { + owner(owner_)->targets.at(index_).nondeterministic = enabled; + return *this; +} + +Target &Target::enabled(bool flag) { + owner(owner_)->targets.at(index_).enabled = flag; + return *this; +} + +Target &Target::install(std::string destination, std::string component) { + require_text(component, "install component"); + auto &rec = owner(owner_)->targets.at(index_); + rec.install_rule = + InstallRule{rec.name, {}, std::move(destination), std::move(component), false}; + return *this; +} + +const TargetRecord &Target::record() const { return owner(owner_)->targets.at(index_); } + +ImportedTarget::ImportedTarget(std::weak_ptr state, std::size_t dependency, + std::string name) + : owner_{std::move(state)}, dependency_{dependency}, name_{std::move(name)} {} + +Dependency::Dependency(std::weak_ptr state, std::size_t index) + : owner_{std::move(state)}, index_{index} {} + +Dependency &Dependency::git(std::string url, Commit commit) { + require_text(url, "Git URL"); + if (!is_hex_digest(commit.sha, 40)) { + throw std::invalid_argument{"Commit must contain an exact 40-digit hexadecimal Git SHA"}; + } + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (record.source_kind != DependencySourceKind::Unspecified) { + throw std::invalid_argument{"dependency '" + record.name + + "' already has a source provider"}; + } + record.source_kind = DependencySourceKind::Git; + record.location = std::move(url); + record.revision = std::move(commit.sha); + return *this; +} + +Dependency &Dependency::path(std::string local_path) { + require_text(local_path, "local dependency path"); + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (record.source_kind != DependencySourceKind::Unspecified) { + throw std::invalid_argument{"dependency '" + record.name + + "' already has a source provider"}; + } + record.source_kind = DependencySourceKind::Path; + record.location = std::move(local_path); + return *this; +} + +Dependency &Dependency::archive(std::string url, std::string sha256) { + require_text(url, "archive URL"); + if (!is_hex_digest(sha256, 64)) { + throw std::invalid_argument{"archive sha256 must contain 64 hexadecimal digits"}; + } + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (record.source_kind != DependencySourceKind::Unspecified) { + throw std::invalid_argument{"dependency '" + record.name + + "' already has a source provider"}; + } + record.source_kind = DependencySourceKind::Archive; + record.location = std::move(url); + record.sha256 = std::move(sha256); + return *this; +} + +Dependency &Dependency::cmake(OptionMap options) { + for (const auto &[key, value] : options) { + (void)value; + require_text(key, "CMake option name"); + } + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (record.source_kind == DependencySourceKind::Package || !record.builder.empty()) { + throw std::invalid_argument{"contradictory builder for dependency '" + record.name + "'"}; + } + record.builder = "cmake"; + record.options = std::move(options); + return *this; +} + +Dependency &Dependency::meson(OptionMap options) { + for (const auto &[key, value] : options) { + (void)value; + require_text(key, "Meson option name"); + } + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (record.source_kind == DependencySourceKind::Package || !record.builder.empty()) { + throw std::invalid_argument{"contradictory builder for dependency '" + record.name + "'"}; + } + record.builder = "meson"; + record.options = std::move(options); + return *this; +} + +Dependency &Dependency::conan(std::string reference, OptionMap options) { + require_text(reference, "Conan reference"); + for (const auto &[key, value] : options) { + (void)value; + require_text(key, "Conan option name"); + } + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (record.source_kind != DependencySourceKind::Unspecified || !record.builder.empty()) { + throw std::invalid_argument{"dependency '" + record.name + + "' already has a source/provider"}; + } + record.source_kind = DependencySourceKind::Conan; + record.package = std::move(reference); + record.builder = "conan"; + record.options = std::move(options); + return *this; +} + +Dependency &Dependency::native_builder(OptionMap options) { + for (const auto &[key, value] : options) { + (void)value; + require_text(key, "native option name"); + } + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (!record.builder.empty()) { + throw std::invalid_argument{"contradictory builder for dependency '" + record.name + "'"}; + } + record.builder = "native"; + record.options = std::move(options); + return *this; +} + +Dependency &Dependency::package(std::string id, std::string range) { + require_text(id, "package identifier"); + require_text(range, "package version range"); + auto state = owner(owner_); + auto &record = state->dependencies.at(index_); + if (record.source_kind != DependencySourceKind::Unspecified || !record.builder.empty()) { + throw std::invalid_argument{"dependency '" + record.name + + "' already has a source/provider"}; + } + record.source_kind = DependencySourceKind::Package; + record.package = std::move(id); + record.version = std::move(range); + return *this; +} + +Dependency &Dependency::registry(std::string authority_url) { + require_text(authority_url, "registry authority"); + owner(owner_)->dependencies.at(index_).registry_authority = std::move(authority_url); + return *this; +} + +Dependency &Dependency::feature(std::string name) { + require_text(name, "feature name"); + auto &features = owner(owner_)->dependencies.at(index_).features; + if (!std::ranges::contains(features, name)) { + features.push_back(std::move(name)); + } + return *this; +} + +Dependency &Dependency::build_dependency(bool is_build_tool) { + owner(owner_)->dependencies.at(index_).build_dependency = is_build_tool; + return *this; +} + +ImportedTarget Dependency::target(std::string exported_name) const { + (void)owner(owner_); + require_text(exported_name, "exported target name"); + return ImportedTarget{owner_, index_, std::move(exported_name)}; +} + +const DependencyRecord &Dependency::record() const { + return owner(owner_)->dependencies.at(index_); +} + +Project::Project(ProfileContext context) : state_{std::make_shared()} { + validate_context(context); + state_->context = std::move(context); +} +Project::~Project() = default; +const ProfileContext &Project::context() const noexcept { return state_->context; } + +Target Project::add_target(std::string name, TargetKind kind) { + require_text(name, "target name"); + if (std::ranges::any_of(state_->targets, + [&](const auto &record) { return record.name == name; })) { + throw std::invalid_argument{"duplicate target '" + name + "'"}; + } + TargetRecord record; + record.name = std::move(name); + record.kind = kind; + state_->targets.push_back(std::move(record)); + return Target{state_, state_->targets.size() - 1}; +} +Target Project::executable(std::string name) { + return add_target(std::move(name), TargetKind::Executable); +} +Target Project::static_library(std::string name) { + return add_target(std::move(name), TargetKind::StaticLibrary); +} +Target Project::shared_library(std::string name) { + return add_target(std::move(name), TargetKind::SharedLibrary); +} +Target Project::header_only_library(std::string name) { + return add_target(std::move(name), TargetKind::HeaderOnly); +} +Target Project::object_library(std::string name) { + return add_target(std::move(name), TargetKind::ObjectLibrary); +} +Target Project::custom_action(std::string name) { + return add_target(std::move(name), TargetKind::CustomAction); +} +Target Project::test(std::string name) { return add_target(std::move(name), TargetKind::Test); } + +Dependency Project::dependency(std::string name) { + require_text(name, "dependency name"); + if (std::ranges::any_of(state_->dependencies, + [&](const auto &record) { return record.name == name; })) { + throw std::invalid_argument{"duplicate dependency '" + name + "'"}; + } + DependencyRecord record; + record.name = std::move(name); + state_->dependencies.push_back(std::move(record)); + return Dependency{state_, state_->dependencies.size() - 1}; +} +void Project::dependencies_file(std::string toml_path) { + require_text(toml_path, "dependencies manifest path"); + state_->dependency_files.push_back(std::move(toml_path)); +} +void Project::install_file(std::string source_path, std::string destination, + std::string component) { + require_text(source_path, "install source path"); + require_text(destination, "install destination"); + require_text(component, "install component"); + state_->install_rules.push_back( + {{}, std::move(source_path), std::move(destination), std::move(component), false}); +} +void Project::install_directory(std::string source_path, std::string destination, + std::string component) { + require_text(source_path, "install source directory"); + require_text(destination, "install destination"); + require_text(component, "install component"); + state_->install_rules.push_back( + {{}, std::move(source_path), std::move(destination), std::move(component), true}); +} +SourceSet Project::glob(std::string pattern) const { return SourceSet::glob(std::move(pattern)); } +const std::vector &Project::targets() const noexcept { return state_->targets; } +const std::vector &Project::dependencies() const noexcept { + return state_->dependencies; +} +const std::vector &Project::dependency_files() const noexcept { + return state_->dependency_files; +} +const std::vector &Project::install_rules() const noexcept { + return state_->install_rules; +} + +std::string Project::to_json() const { + const auto &profile = context(); + std::string output = + "{\"schema_version\":" + std::to_string(schema_version) + + ",\"profile\":{\"name\":" + json_quote(profile.name) + + ",\"compiler\":" + json_quote(compiler_name(profile.compiler)) + + ",\"os\":" + json_quote(profile.os) + + ",\"architecture\":" + json_quote(profile.architecture) + + ",\"compile_options\":" + json_array(profile.compile_options, json_quote) + + ",\"link_options\":" + json_array(profile.link_options, json_quote) + + ",\"defines\":" + json_array(profile.defines, json_quote) + + ",\"cxx_standard\":" + json_quote(cxx_standard_name(profile.cxx_standard)) + + ",\"lto\":" + json_quote(lto_mode_name(profile.lto)) + ",\"sanitizers\":" + + json_array(profile.sanitizers, [](Sanitizer s) { return json_quote(sanitizer_name(s)); }) + + ",\"sysroot\":" + json_quote(profile.sysroot) + + ",\"compiler_path\":" + json_quote(profile.compiler_path) + + ",\"reproducibility_epoch\":" + std::to_string(profile.reproducibility_epoch) + + ",\"nondeterministic\":" + std::string{profile.nondeterministic ? "true" : "false"} + + "},\"targets\":"; + output += json_array(targets(), [](const TargetRecord &target) { + std::string out = + "{\"name\":" + json_quote(target.name) + + ",\"kind\":" + json_quote(target_kind_name(target.kind)) + ",\"sources\":" + + json_array(target.sources, + [](const SourceRecord &source) { + return "{\"kind\":" + json_quote(source_kind_name(source.kind)) + + ",\"path\":" + json_quote(source.path) + '}'; + }) + + ",\"include_directories\":" + + json_array(target.include_directories, + [](const IncludeDirectory &directory) { + return "{\"path\":" + json_quote(directory.path) + ",\"visibility\":" + + json_quote(visibility_name(directory.visibility)) + + ",\"is_system\":" + + std::string{directory.is_system ? "true" : "false"} + '}'; + }) + + ",\"compile_options\":" + json_array(target.compile_options, json_quote) + + ",\"scoped_compile_options\":" + scoped_options_json(target.scoped_compile_options) + + ",\"defines\":" + scoped_options_json(target.defines) + + ",\"link_options\":" + scoped_options_json(target.link_options) + ",\"links\":" + + json_array(target.links, + [](const LinkRecord &link) { + return "{\"kind\":" + + json_quote(link.kind == LinkKind::Local ? "local" : "imported") + + ",\"target\":" + json_quote(link.target) + + ",\"dependency\":" + json_quote(link.dependency) + + ",\"visibility\":" + + json_quote(visibility_name(link.visibility)) + '}'; + }) + + ",\"prerequisites\":" + json_array(target.prerequisites, json_quote) + + ",\"cxx_standard\":" + json_quote(cxx_standard_name(target.cxx_standard)) + + ",\"precompiled_header\":" + json_quote(target.precompiled_header) + + ",\"unity_enabled\":" + std::string{target.unity_enabled ? "true" : "false"} + + ",\"unity_batch_size\":" + std::to_string(target.unity_batch_size) + + ",\"lto\":" + json_quote(lto_mode_name(target.lto)) + ",\"sanitizers\":" + + json_array(target.sanitizers, + [](Sanitizer s) { return json_quote(sanitizer_name(s)); }) + + ",\"per_file_options\":" + + json_array(target.per_file_options, + [](const PerFileOption &opt) { + return "{\"source_path\":" + json_quote(opt.source_path) + + ",\"option\":" + json_quote(opt.option) + '}'; + }) + + ",\"command_argv\":" + json_array(target.command_argv, json_quote) + + ",\"action_inputs\":" + json_array(target.action_inputs, json_quote) + + ",\"action_outputs\":" + json_array(target.action_outputs, json_quote) + + ",\"working_directory\":" + json_quote(target.working_directory) + + ",\"environment\":" + env_json(target.environment) + + ",\"nondeterministic\":" + std::string{target.nondeterministic ? "true" : "false"} + + ",\"enabled\":" + std::string{target.enabled ? "true" : "false"} + + ",\"use_conventional_sources\":" + + std::string{target.use_conventional_sources ? "true" : "false"}; + if (target.install_rule) { + out += ",\"install_rule\":" + install_rule_json(*target.install_rule); + } + return out + '}'; + }); + output += + ",\"dependencies\":" + json_array(dependencies(), [](const DependencyRecord &dependency) { + if (dependency.source_kind == DependencySourceKind::Unspecified) { + throw std::invalid_argument{"dependency '" + dependency.name + + "' has no source provider"}; + } + std::string result = + "{\"name\":" + json_quote(dependency.name) + ",\"source\":{\"kind\":"; + switch (dependency.source_kind) { + case DependencySourceKind::Git: + result += "\"git\",\"location\":" + json_quote(dependency.location) + + ",\"revision\":" + json_quote(dependency.revision); + break; + case DependencySourceKind::Package: + result += "\"package\",\"package\":" + json_quote(dependency.package) + + ",\"version\":" + json_quote(dependency.version); + break; + case DependencySourceKind::Path: + result += "\"path\",\"location\":" + json_quote(dependency.location); + break; + case DependencySourceKind::Archive: + result += "\"archive\",\"location\":" + json_quote(dependency.location) + + ",\"sha256\":" + json_quote(dependency.sha256); + break; + case DependencySourceKind::Conan: + result += "\"conan\",\"package\":" + json_quote(dependency.package); + break; + case DependencySourceKind::Unspecified: + break; + } + result += "},\"builder\":" + json_quote(dependency.builder) + + ",\"options\":" + options_json(dependency.options) + + ",\"registry_authority\":" + json_quote(dependency.registry_authority) + + ",\"features\":" + json_array(dependency.features, json_quote) + + ",\"build_dependency\":" + + std::string{dependency.build_dependency ? "true" : "false"} + '}'; + return result; + }); + output += ",\"dependency_files\":" + json_array(dependency_files(), json_quote); + output += ",\"install_rules\":" + json_array(install_rules(), install_rule_json); + return output + '}'; +} + +} // namespace Void::Build diff --git a/src/Config/Frontend.cpp b/src/Config/Frontend.cpp new file mode 100644 index 0000000..802db99 --- /dev/null +++ b/src/Config/Frontend.cpp @@ -0,0 +1,761 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Build::Config { +namespace { + +using JsonVal = Void::Json::Strict::Value; + +std::atomic 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 +#include + +#include +#include +#include +#include +#include +#include +#include + +)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 split_lines(std::string_view text) { + std::vector 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 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(&v->value); + return s ? std::optional{*s} : std::nullopt; +} + +std::optional 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(&v->value); + return i ? std::optional{*i} : std::nullopt; +} + +std::vector get_str_array(const JsonVal::Object &obj, const std::string &k) { + std::vector out; + const auto *v = find_key(obj, k); + if (!v) { + return out; + } + if (const auto *arr = std::get_if(&v->value)) { + for (const auto &item : *arr) { + if (const auto *s = std::get_if(&item.value)) { + out.push_back(*s); + } + } + } + return out; +} + +} // namespace + +Void::Result::Result, Void::Result::Error> +discover_config_sources(const std::filesystem::path &project_root, + const std::vector &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 sources; + std::set 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 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 +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 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(&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(&hv->value)) { + for (const auto &[hpath, hval] : *hobj) { + const auto *expected = std::get_if(&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 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 objects; + std::map> 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(::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 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 +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(::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(&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(&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(&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(&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(&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 +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(::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(&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 diff --git a/src/describe.cpp b/src/Describe.cpp similarity index 79% rename from src/describe.cpp rename to src/Describe.cpp index 90d5fe0..4f21322 100644 --- a/src/describe.cpp +++ b/src/Describe.cpp @@ -1,6 +1,6 @@ +#include +#include #include -#include -#include #include @@ -29,11 +29,11 @@ int main(int argc, char **argv) { return 2; } try { - vbs::Profiles descriptions; + Void::Build::Profiles descriptions; profiles(descriptions); - vbs::Project project{descriptions.resolve(profile, vbs::parse_compiler(compiler), - std::string{vbs::bootstrap::os}, - std::string{vbs::bootstrap::architecture})}; + Void::Build::Project project{descriptions.resolve( + profile, Void::Build::parse_compiler(compiler), std::string{Void::Build::Bootstrap::os}, + std::string{Void::Build::Bootstrap::architecture})}; build(project); std::cout << project.to_json() << '\n'; return 0; diff --git a/src/Editor/CompDb.cpp b/src/Editor/CompDb.cpp new file mode 100644 index 0000000..54b67b9 --- /dev/null +++ b/src/Editor/CompDb.cpp @@ -0,0 +1,574 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +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(&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(&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(&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 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(&parsed->value); + if (!obj) { + return std::nullopt; + } + SelectionState st; + st.ticket = static_cast(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 `/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 +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 project_editor_commands(const Graph::BuildGraph &graph) { + std::vector 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 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 &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 +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 +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 +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(&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 +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(&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, 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 +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 diff --git a/src/Execution/Scheduler.cpp b/src/Execution/Scheduler.cpp new file mode 100644 index 0000000..f2fd607 --- /dev/null +++ b/src/Execution/Scheduler.cpp @@ -0,0 +1,542 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(""); + } + } + return hasher.finalize_hex(); +} + +bool verify_discovered_inputs_unchanged( + const std::map> &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 collect_ancestors(const Graph::BuildGraph &graph, const std::string &id) { + std::set ancestors; + std::queue 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, 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 deps; + std::set 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 +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 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 selected_set(selected_indices.begin(), selected_indices.end()); + std::map in_degree; + std::map> 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(1, std::thread::hardware_concurrency())); + + std::mutex mu; + std::condition_variable cv; + std::queue 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(); + 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(); + 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> 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::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> 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 diff --git a/src/Graph/Graph.cpp b/src/Graph/Graph.cpp new file mode 100644 index 0000000..5df7e15 --- /dev/null +++ b/src/Graph/Graph.cpp @@ -0,0 +1,1924 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Graph { +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 &key) { + const auto it = obj.find(key); + return it == obj.end() ? nullptr : &it->second; +} + +std::string get_str(const JsonVal::Object &obj, const std::string &key, std::string fallback = {}) { + const auto *v = find_key(obj, key); + if (!v) { + return fallback; + } + const auto *s = std::get_if(&v->value); + return s ? *s : fallback; +} + +bool get_bool(const JsonVal::Object &obj, const std::string &key, bool fallback = false) { + const auto *v = find_key(obj, key); + if (!v) { + return fallback; + } + const auto *b = std::get_if(&v->value); + return b ? *b : fallback; +} + +std::int64_t get_i64(const JsonVal::Object &obj, const std::string &key, + std::int64_t fallback = 0) { + const auto *v = find_key(obj, key); + if (!v) { + return fallback; + } + const auto *i = std::get_if(&v->value); + return i ? *i : fallback; +} + +std::vector get_str_array(const JsonVal::Object &obj, const std::string &key) { + std::vector out; + const auto *v = find_key(obj, key); + if (!v) { + return out; + } + if (const auto *arr = std::get_if(&v->value)) { + for (const auto &item : *arr) { + if (const auto *s = std::get_if(&item.value)) { + out.push_back(*s); + } + } + } + return out; +} + +std::vector get_scoped_options(const JsonVal::Object &obj, const std::string &key) { + std::vector out; + const auto *v = find_key(obj, key); + if (!v) { + return out; + } + if (const auto *arr = std::get_if(&v->value)) { + for (const auto &item : *arr) { + if (const auto *o = std::get_if(&item.value)) { + out.push_back( + {get_str(*o, "value"), parse_visibility(get_str(*o, "visibility", "private"))}); + } + } + } + return out; +} + +bool is_excluded_discovery_path(const std::filesystem::path &rel) { + const std::string gen = rel.lexically_normal().generic_string(); + if (gen == "build.cpp" || gen == "build.profiles.cpp") { + return true; + } + for (const auto &part : rel) { + const auto s = part.string(); + if (s == ".git" || s == ".vbs" || s == "build" || s == "build-support" || s == ".serena" || + s == ".cache" || s == "keys" || s == ".env") { + return true; + } + } + return false; +} + +bool is_module_source_extension(const std::filesystem::path &p) { + const auto ext = p.extension().string(); + return ext == ".cppm" || ext == ".ixx" || ext == ".ccm"; +} + +bool is_cpp_source_extension(const std::filesystem::path &p) { + const auto ext = p.extension().string(); + return ext == ".cpp" || ext == ".cc" || ext == ".cxx" || ext == ".c" || + is_module_source_extension(p); +} + +Void::Result::Result +validate_sanitizers(std::string_view target_name, const std::vector &sans) { + auto has = [&](Sanitizer s) { return std::ranges::contains(sans, s); }; + if (has(Sanitizer::Address) && has(Sanitizer::Thread)) { + return std::unexpected{ + make_error(std::format("target '{}': incompatible sanitizers requested (address and " + "thread cannot be combined)", + target_name))}; + } + if (has(Sanitizer::Memory) && + (has(Sanitizer::Address) || has(Sanitizer::Thread) || has(Sanitizer::Leak))) { + return std::unexpected{make_error(std::format( + "target '{}': incompatible sanitizers requested (memory cannot be combined with " + "address, thread, or leak)", + target_name))}; + } + if (has(Sanitizer::Thread) && has(Sanitizer::Leak)) { + return std::unexpected{make_error(std::format( + "target '{}': incompatible sanitizers requested (thread and leak cannot be combined)", + target_name))}; + } + return {}; +} + +std::string sanitize_id_component(std::string_view text) { + std::string out; + out.reserve(text.size()); + for (const char c : text) { + 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 compute_action_key(const ActionNode &action, const BuildGraph &graph) { + Util::Sha256Hasher hasher; + hasher.update_length_prefixed("vbs-action-v1"); + hasher.update_length_prefixed(graph.profile_identity); + hasher.update_length_prefixed(graph.toolchain.identity_hash); + hasher.update_u64(static_cast(action.kind)); + hasher.update_length_prefixed(action.target_name); + hasher.update_length_prefixed(action.executable.string()); + hasher.update_u64(action.arguments.size()); + for (const auto &arg : action.arguments) { + hasher.update_length_prefixed(arg); + } + hasher.update_length_prefixed(action.response_file_content); + hasher.update_u64(action.environment.size()); + for (const auto &[k, v] : action.environment) { + hasher.update_length_prefixed(k); + hasher.update_length_prefixed(v); + } + hasher.update_u64(action.declared_inputs.size()); + for (const auto &in : action.declared_inputs) { + hasher.update_length_prefixed(in.string()); + } + hasher.update_u64(action.declared_outputs.size()); + for (const auto &out : action.declared_outputs) { + hasher.update_length_prefixed(out.string()); + } + hasher.update_length_prefixed(graph.snapshot_id); + hasher.update_u64(action.nondeterministic ? 1u : 0u); + return hasher.finalize_hex(); +} + +} // namespace + +Void::Result::Result +ProjectDescription::from_json(std::string_view json_text) { + if (!Util::is_valid_utf8(json_text)) { + return std::unexpected{make_error("ProjectDescription JSON contains invalid UTF-8")}; + } + auto parsed = Void::Json::Strict::parse(json_text); + if (!parsed) { + return std::unexpected{make_error("failed parsing ProjectDescription JSON")}; + } + const auto *root = std::get_if(&parsed->value); + if (!root) { + return std::unexpected{make_error("ProjectDescription JSON root must be an object")}; + } + try { + ProjectDescription desc; + desc.schema_version = static_cast(get_i64(*root, "schema_version", 0)); + if (desc.schema_version != Void::Build::schema_version) { + return std::unexpected{make_error( + std::format("unsupported ProjectDescription schema_version {} (expected {})", + desc.schema_version, Void::Build::schema_version))}; + } + + const auto *prof_v = find_key(*root, "profile"); + const auto *prof = prof_v ? std::get_if(&prof_v->value) : nullptr; + if (!prof) { + return std::unexpected{make_error("ProjectDescription missing profile object")}; + } + desc.profile.name = get_str(*prof, "name"); + desc.profile.compiler = parse_compiler(get_str(*prof, "compiler", "gcc")); + desc.profile.os = get_str(*prof, "os"); + desc.profile.architecture = get_str(*prof, "architecture"); + desc.profile.compile_options = get_str_array(*prof, "compile_options"); + desc.profile.link_options = get_str_array(*prof, "link_options"); + desc.profile.defines = get_str_array(*prof, "defines"); + desc.profile.cxx_standard = parse_cxx_standard(get_str(*prof, "cxx_standard", "default")); + desc.profile.lto = parse_lto_mode(get_str(*prof, "lto", "none")); + for (const auto &s : get_str_array(*prof, "sanitizers")) { + desc.profile.sanitizers.push_back(parse_sanitizer(s)); + } + desc.profile.sysroot = get_str(*prof, "sysroot"); + desc.profile.compiler_path = get_str(*prof, "compiler_path"); + desc.profile.reproducibility_epoch = get_i64(*prof, "reproducibility_epoch", 0); + desc.profile.nondeterministic = get_bool(*prof, "nondeterministic", false); + + if (const auto *targets_v = find_key(*root, "targets")) { + const auto *arr = std::get_if(&targets_v->value); + if (!arr) { + return std::unexpected{make_error("targets must be an array")}; + } + for (const auto &tv : *arr) { + const auto *to = std::get_if(&tv.value); + if (!to) { + continue; + } + TargetRecord t; + t.name = get_str(*to, "name"); + t.kind = parse_target_kind(get_str(*to, "kind")); + if (const auto *sv = find_key(*to, "sources")) { + if (const auto *sarr = std::get_if(&sv->value)) { + for (const auto &item : *sarr) { + if (const auto *so = std::get_if(&item.value)) { + t.sources.push_back({parse_source_kind(get_str(*so, "kind")), + get_str(*so, "path")}); + } + } + } + } + if (const auto *iv = find_key(*to, "include_directories")) { + if (const auto *iarr = std::get_if(&iv->value)) { + for (const auto &item : *iarr) { + if (const auto *io = std::get_if(&item.value)) { + t.include_directories.push_back( + {get_str(*io, "path"), + parse_visibility(get_str(*io, "visibility", "private")), + get_bool(*io, "is_system", false)}); + } + } + } + } + t.compile_options = get_str_array(*to, "compile_options"); + t.scoped_compile_options = get_scoped_options(*to, "scoped_compile_options"); + if (t.scoped_compile_options.empty() && !t.compile_options.empty()) { + for (const auto &opt : t.compile_options) { + t.scoped_compile_options.push_back({opt, Visibility::Private}); + } + } + t.defines = get_scoped_options(*to, "defines"); + t.link_options = get_scoped_options(*to, "link_options"); + if (const auto *lv = find_key(*to, "links")) { + if (const auto *larr = std::get_if(&lv->value)) { + for (const auto &item : *larr) { + if (const auto *lo = std::get_if(&item.value)) { + LinkRecord lr; + lr.kind = get_str(*lo, "kind") == "imported" ? LinkKind::Imported + : LinkKind::Local; + lr.target = get_str(*lo, "target"); + lr.dependency = get_str(*lo, "dependency"); + lr.visibility = + parse_visibility(get_str(*lo, "visibility", "private")); + t.links.push_back(std::move(lr)); + } + } + } + } + t.prerequisites = get_str_array(*to, "prerequisites"); + t.cxx_standard = parse_cxx_standard(get_str(*to, "cxx_standard", "default")); + t.precompiled_header = get_str(*to, "precompiled_header"); + t.unity_enabled = get_bool(*to, "unity_enabled", false); + t.unity_batch_size = static_cast(get_i64(*to, "unity_batch_size", 8)); + t.lto = parse_lto_mode(get_str(*to, "lto", "none")); + for (const auto &s : get_str_array(*to, "sanitizers")) { + t.sanitizers.push_back(parse_sanitizer(s)); + } + if (const auto *pfv = find_key(*to, "per_file_options")) { + if (const auto *pfarr = std::get_if(&pfv->value)) { + for (const auto &item : *pfarr) { + if (const auto *po = std::get_if(&item.value)) { + t.per_file_options.push_back( + {get_str(*po, "source_path"), get_str(*po, "option")}); + } + } + } + } + t.command_argv = get_str_array(*to, "command_argv"); + t.action_inputs = get_str_array(*to, "action_inputs"); + t.action_outputs = get_str_array(*to, "action_outputs"); + t.working_directory = get_str(*to, "working_directory"); + if (const auto *ev = find_key(*to, "environment")) { + if (const auto *eo = std::get_if(&ev->value)) { + for (const auto &[k, val] : *eo) { + if (const auto *vs = std::get_if(&val.value)) { + t.environment[k] = *vs; + } + } + } + } + t.nondeterministic = get_bool(*to, "nondeterministic", false); + t.enabled = get_bool(*to, "enabled", true); + t.use_conventional_sources = get_bool(*to, "use_conventional_sources", false); + if (const auto *irv = find_key(*to, "install_rule")) { + if (const auto *iro = std::get_if(&irv->value)) { + t.install_rule = InstallRule{ + get_str(*iro, "target_name"), get_str(*iro, "source_path"), + get_str(*iro, "destination"), get_str(*iro, "component", "default"), + get_bool(*iro, "is_directory", false)}; + } + } + desc.targets.push_back(std::move(t)); + } + } + + if (const auto *deps_v = find_key(*root, "dependencies")) { + if (const auto *darr = std::get_if(&deps_v->value)) { + for (const auto &dv : *darr) { + const auto *do_obj = std::get_if(&dv.value); + if (!do_obj) { + continue; + } + DependencyRecord d; + d.name = get_str(*do_obj, "name"); + d.builder = get_str(*do_obj, "builder"); + d.registry_authority = get_str(*do_obj, "registry_authority"); + d.features = get_str_array(*do_obj, "features"); + d.build_dependency = get_bool(*do_obj, "build_dependency", false); + if (const auto *src_v = find_key(*do_obj, "source")) { + if (const auto *so = std::get_if(&src_v->value)) { + const auto kind = get_str(*so, "kind"); + if (kind == "git") { + d.source_kind = DependencySourceKind::Git; + d.location = get_str(*so, "location"); + d.revision = get_str(*so, "revision"); + } else if (kind == "package") { + d.source_kind = DependencySourceKind::Package; + d.package = get_str(*so, "package"); + d.version = get_str(*so, "version"); + } else if (kind == "path") { + d.source_kind = DependencySourceKind::Path; + d.location = get_str(*so, "location"); + } else if (kind == "archive") { + d.source_kind = DependencySourceKind::Archive; + d.location = get_str(*so, "location"); + d.sha256 = get_str(*so, "sha256"); + } else if (kind == "conan") { + d.source_kind = DependencySourceKind::Conan; + d.package = get_str(*so, "package"); + } + } + } + if (const auto *opt_v = find_key(*do_obj, "options")) { + if (const auto *oo = std::get_if(&opt_v->value)) { + for (const auto &[k, val] : *oo) { + if (const auto *s = std::get_if(&val.value)) { + d.options.emplace(k, OptionValue{*s}); + } else if (const auto *b = std::get_if(&val.value)) { + d.options.emplace(k, OptionValue{*b}); + } else if (const auto *i = std::get_if(&val.value)) { + d.options.emplace(k, OptionValue{*i}); + } + } + } + } + desc.dependencies.push_back(std::move(d)); + } + } + } + + desc.dependency_files = get_str_array(*root, "dependency_files"); + if (const auto *rules_v = find_key(*root, "install_rules")) { + if (const auto *rarr = std::get_if(&rules_v->value)) { + for (const auto &rv : *rarr) { + if (const auto *ro = std::get_if(&rv.value)) { + desc.install_rules.push_back(InstallRule{ + get_str(*ro, "target_name"), get_str(*ro, "source_path"), + get_str(*ro, "destination"), get_str(*ro, "component", "default"), + get_bool(*ro, "is_directory", false)}); + } + } + } + } + return desc; + } catch (const std::exception &ex) { + return std::unexpected{make_error(ex.what())}; + } +} + +bool match_glob(std::string_view pattern, std::string_view path) noexcept { + // Recursive glob supporting '*', '?', and '**' across path separators. + std::size_t pi = 0; + std::size_t si = 0; + while (pi < pattern.size()) { + if (pi + 1 < pattern.size() && pattern[pi] == '*' && pattern[pi + 1] == '*') { + pi += 2; + if (pi < pattern.size() && pattern[pi] == '/') { + ++pi; + } + if (pi == pattern.size()) { + return true; + } + for (std::size_t k = si; k <= path.size(); ++k) { + if (k == si || path[k - 1] == '/') { + if (match_glob(pattern.substr(pi), path.substr(k))) { + return true; + } + } + } + return false; + } + if (pattern[pi] == '*') { + ++pi; + for (std::size_t k = si; k <= path.size(); ++k) { + if (k > si && path[k - 1] == '/') { + break; + } + if (match_glob(pattern.substr(pi), path.substr(k))) { + return true; + } + } + return false; + } + if (si == path.size()) { + return false; + } + if (pattern[pi] == '?') { + if (path[si] == '/') { + return false; + } + ++pi; + ++si; + } else if (pattern[pi] == path[si]) { + ++pi; + ++si; + } else { + return false; + } + } + return si == path.size(); +} + +Void::Result::Result, Void::Result::Error> +expand_glob(const std::filesystem::path &project_root, std::string_view pattern) { + 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( + "expand_glob: project root '{}' is not a directory", project_root.string()))}; + } + + std::vector matches; + std::filesystem::recursive_directory_iterator it{ + canonical_root, 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(canonical_root); + if (is_excluded_discovery_path(rel)) { + if (it->is_directory(ec)) { + it.disable_recursion_pending(); + } + continue; + } + if (it->is_regular_file(ec)) { + const std::string gen = rel.lexically_normal().generic_string(); + if (match_glob(pattern, gen)) { + matches.push_back(rel.lexically_normal()); + } + } + } + std::ranges::sort(matches); + return matches; +} + +Void::Result::Result, Void::Result::Error> +BuildGraph::select_action_closure(const std::vector &selected_targets) const { + std::set wanted_targets; + if (selected_targets.empty()) { + for (const auto &t : targets) { + if (t.enabled) { + wanted_targets.insert(t.name); + } + } + } else { + for (const auto &name : selected_targets) { + const auto found = std::ranges::find(targets, name, &ResolvedTargetSummary::name); + if (found == targets.end()) { + return std::unexpected{ + make_error(std::format("unknown requested target '{}'", name))}; + } + wanted_targets.insert(name); + } + } + + std::set needed_ids; + std::queue work; + for (const auto &t : targets) { + if (wanted_targets.contains(t.name)) { + for (const auto &aid : t.action_ids) { + if (needed_ids.insert(aid).second) { + work.push(aid); + } + } + } + } + while (!work.empty()) { + const auto id = work.front(); + work.pop(); + const auto idx_it = action_index_by_id.find(id); + if (idx_it == action_index_by_id.end()) { + continue; + } + for (const auto &dep_id : actions[idx_it->second].dependencies) { + if (needed_ids.insert(dep_id).second) { + work.push(dep_id); + } + } + } + + std::vector ordered; + for (std::size_t i = 0; i < actions.size(); ++i) { + if (needed_ids.contains(actions[i].id)) { + ordered.push_back(i); + } + } + return ordered; +} + +Void::Result::Result +lower_project_graph(const ProjectDescription &description, + const Toolchain::ToolchainCapabilities &toolchain, + const GraphLowerOptions &options) { + std::error_code ec; + const auto canonical_root = std::filesystem::weakly_canonical(options.project_root, ec); + if (ec) { + return std::unexpected{make_error("cannot canonicalize project root")}; + } + + BuildGraph graph; + graph.profile = description.profile; + graph.toolchain = toolchain; + graph.profile_identity = Toolchain::compute_profile_identity(description.profile, toolchain); + graph.project_root = canonical_root; + graph.profile_build_dir = std::filesystem::weakly_canonical(options.build_root, ec) / + "profiles" / sanitize_id_component(description.profile.name); + if (options.snapshot) { + graph.snapshot_id = options.snapshot->snapshot_id; + graph.snapshot_materialized_root = options.snapshot->materialized_root; + } + + // Index targets by name and detect target-level cycles upfront via Void::Algorithms. + std::map> target_by_name; + std::map> target_index_by_name; + for (std::size_t i = 0; i < description.targets.size(); ++i) { + const auto &t = description.targets[i]; + if (!target_by_name.emplace(t.name, &t).second) { + return std::unexpected{make_error(std::format("duplicate target '{}'", t.name))}; + } + target_index_by_name.emplace(t.name, i); + } + + // Validate references and build directed graph (edge dep -> dependent). + std::vector> target_adj(description.targets.size()); + for (std::size_t i = 0; i < description.targets.size(); ++i) { + const auto &t = description.targets[i]; + auto add_edge = + [&](const std::string &dep_name, + std::string_view kind_label) -> Void::Result::Result { + const auto it = target_index_by_name.find(dep_name); + if (it == target_index_by_name.end()) { + return std::unexpected{ + make_error(std::format("target '{}' references unknown {} target '{}'", t.name, + kind_label, dep_name))}; + } + const std::size_t dep_idx = it->second; + if (dep_idx == i) { + return std::unexpected{ + make_error(std::format("dependency cycle detected: {} -> {}", t.name, t.name))}; + } + if (!std::ranges::contains(target_adj[dep_idx], i)) { + target_adj[dep_idx].push_back(i); + } + return {}; + }; + + for (const auto &pre : t.prerequisites) { + if (auto r = add_edge(pre, "prerequisite"); !r) { + return std::unexpected{r.error()}; + } + } + for (const auto &link : t.links) { + if (link.kind == LinkKind::Local) { + if (auto r = add_edge(link.target, "linked"); !r) { + return std::unexpected{r.error()}; + } + } + } + } + + const Void::Algorithms::AdjacencyView target_view{target_adj}; + auto topo = Void::Algorithms::topological_order(target_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 += " -> "; + } + chain += description.targets[*it].name; + } + return std::unexpected{make_error( + chain.empty() ? std::format("dependency cycle detected: {}", topo.error().message) + : std::format("dependency cycle detected: {}", chain))}; + } + + std::vector topo_targets; + topo_targets.reserve(topo->order.size()); + for (const std::size_t idx : topo->order) { + topo_targets.push_back(description.targets[idx].name); + } + + // Track per-target primary outputs, exported compile requirements, and ordered link closures. + struct TargetComputed { + std::vector object_files; + std::optional primary_artifact; + std::vector producer_action_ids; + + // Public/Interface compile usage exposed to consumers. + std::vector> exported_includes; + std::vector exported_defines; + std::vector exported_compile_options; + + // Transitive ordered link libraries and options exposed to final linkers. + std::vector exported_static_libs; + std::vector exported_shared_libs; + std::vector exported_objects; + std::vector exported_link_options; + std::vector exported_prerequisite_actions; + }; + std::map> computed; + + // Track output producers to reject collisions and source/output overlap. + std::map output_owner; + auto register_output = + [&](const std::filesystem::path &out_path, + const std::string &action_id) -> Void::Result::Result { + const auto norm = out_path.lexically_normal(); + // Reject writing generated outputs directly onto editable source root paths outside build + // dir. + if (Platform::path_is_within(canonical_root, norm) && + !Platform::path_is_within(graph.profile_build_dir, norm)) { + return std::unexpected{make_error(std::format( + "action '{}' output '{}' overlaps project source tree outside build dir", action_id, + norm.string()))}; + } + const auto [it, inserted] = output_owner.emplace(norm, action_id); + if (!inserted) { + return std::unexpected{make_error( + std::format("output path collision on '{}': produced by both '{}' and '{}'", + norm.string(), it->second, action_id))}; + } + return {}; + }; + + auto map_logical_to_physical = [&](const std::filesystem::path &logical_abs) { + if (graph.snapshot_materialized_root.empty()) { + return logical_abs; + } + if (Platform::path_is_within(canonical_root, logical_abs) && + !Platform::path_is_within(graph.profile_build_dir, logical_abs)) { + const auto rel = logical_abs.lexically_relative(canonical_root); + return graph.snapshot_materialized_root / rel; + } + return logical_abs; + }; + + const auto generated_root = graph.profile_build_dir / "gen"; + const auto objects_root = graph.profile_build_dir / "obj"; + const auto artifacts_root = graph.profile_build_dir / "out"; + const auto rsp_root = graph.profile_build_dir / "rsp"; + + for (const auto &target_name : topo_targets) { + const TargetRecord &t = *target_by_name.at(target_name); + TargetComputed tc; + ResolvedTargetSummary summary; + summary.name = t.name; + summary.kind = t.kind; + summary.enabled = t.enabled; + + // 1. Collect prerequisite action IDs (explicit depends_on + linked target producers). + std::vector target_prereq_actions; + auto add_unique_str = [](std::vector &vec, const std::string &val) { + if (!std::ranges::contains(vec, val)) { + vec.push_back(val); + } + }; + + for (const auto &pre_name : t.prerequisites) { + for (const auto &aid : computed.at(pre_name).producer_action_ids) { + add_unique_str(target_prereq_actions, aid); + } + for (const auto &aid : computed.at(pre_name).exported_prerequisite_actions) { + add_unique_str(target_prereq_actions, aid); + } + } + + // 2. CustomAction lowering. + if (t.kind == TargetKind::CustomAction) { + if (t.command_argv.empty()) { + return std::unexpected{ + make_error(std::format("custom_action '{}' must declare command()", t.name))}; + } + if (t.action_outputs.empty()) { + return std::unexpected{make_error( + std::format("custom_action '{}' must declare at least one output", t.name))}; + } + ActionNode act; + act.id = "custom:" + sanitize_id_component(t.name); + act.kind = ActionKind::Custom; + act.target_name = t.name; + act.executable = t.command_argv.front(); + for (std::size_t i = 1; i < t.command_argv.size(); ++i) { + act.arguments.push_back(t.command_argv[i]); + } + act.environment = t.environment; + if (!t.nondeterministic && !description.profile.nondeterministic) { + act.environment.emplace("SOURCE_DATE_EPOCH", + std::to_string(description.profile.reproducibility_epoch)); + act.environment.emplace("TZ", "UTC"); + act.environment.emplace("LC_ALL", "C"); + } + act.working_directory = t.working_directory.empty() + ? canonical_root + : (std::filesystem::path{t.working_directory}.is_absolute() + ? std::filesystem::path{t.working_directory} + : (canonical_root / t.working_directory)); + act.dependencies = target_prereq_actions; + act.nondeterministic = t.nondeterministic || description.profile.nondeterministic; + act.cacheable = !act.nondeterministic; + + for (const auto &in : t.action_inputs) { + const auto p = std::filesystem::path{in}; + act.declared_inputs.push_back(p.is_absolute() ? p : (canonical_root / p)); + } + for (const auto &out : t.action_outputs) { + const auto p = std::filesystem::path{out}; + const auto resolved_out = p.is_absolute() ? p : (generated_root / p); + if (auto reg = register_output(resolved_out, act.id); !reg) { + return std::unexpected{reg.error()}; + } + act.declared_outputs.push_back(resolved_out); + summary.primary_outputs.push_back(resolved_out); + } + act.action_key = compute_action_key(act, graph); + tc.producer_action_ids.push_back(act.id); + tc.exported_prerequisite_actions.push_back(act.id); + summary.action_ids.push_back(act.id); + graph.action_index_by_id[act.id] = graph.actions.size(); + graph.actions.push_back(std::move(act)); + + computed[t.name] = std::move(tc); + graph.targets.push_back(std::move(summary)); + continue; + } + + // 3. Gather effective compile & link requirements from own declarations and linked deps. + std::vector> effective_includes; + std::vector effective_defines = description.profile.defines; + std::vector effective_compile_opts = description.profile.compile_options; + std::vector effective_link_opts = description.profile.link_options; + + // Ordered transitive link inputs (preserve exact order; never sort!). + std::vector link_objects; + std::vector link_static_libs; + std::vector link_shared_libs; + + auto resolve_include = [&](const std::string &raw) -> std::filesystem::path { + const std::filesystem::path p{raw}; + if (p.is_absolute()) { + return p.lexically_normal(); + } + if (raw.starts_with("$GEN/") || raw.starts_with("gen/")) { + const auto suffix = raw.starts_with("$GEN/") ? raw.substr(5) : raw.substr(4); + return (generated_root / suffix).lexically_normal(); + } + return (canonical_root / p).lexically_normal(); + }; + + // Own include directories, defines, compile options, link options. + if (t.use_conventional_sources && + std::filesystem::is_directory(canonical_root / "include")) { + const auto inc = (canonical_root / "include").lexically_normal(); + effective_includes.emplace_back(inc, false); + tc.exported_includes.emplace_back(inc, false); + } + for (const auto &inc : t.include_directories) { + const auto abs = resolve_include(inc.path); + if (inc.visibility != Visibility::Interface) { + effective_includes.emplace_back(abs, inc.is_system); + } + if (inc.visibility != Visibility::Private) { + tc.exported_includes.emplace_back(abs, inc.is_system); + } + } + for (const auto &def : t.defines) { + if (def.visibility != Visibility::Interface) { + effective_defines.push_back(def.value); + } + if (def.visibility != Visibility::Private) { + tc.exported_defines.push_back(def.value); + } + } + for (const auto &opt : t.scoped_compile_options) { + if (opt.visibility != Visibility::Interface) { + effective_compile_opts.push_back(opt.value); + } + if (opt.visibility != Visibility::Private) { + tc.exported_compile_options.push_back(opt.value); + } + } + for (const auto &opt : t.link_options) { + if (opt.visibility != Visibility::Interface) { + effective_link_opts.push_back(opt.value); + } + if (opt.visibility != Visibility::Private) { + tc.exported_link_options.push_back(opt.value); + } + } + + // Propagate from linked targets (local and imported). + for (const auto &link : t.links) { + if (link.kind == LinkKind::Local) { + const auto &dep_rec = *target_by_name.at(link.target); + const auto &dep = computed.at(link.target); + + // Generated prerequisites from dependencies must precede our compilation. + for (const auto &aid : dep.exported_prerequisite_actions) { + add_unique_str(target_prereq_actions, aid); + if (link.visibility != Visibility::Private) { + add_unique_str(tc.exported_prerequisite_actions, aid); + } + } + + // Compile usage (Public & Interface propagate to consumers). + if (link.visibility != Visibility::Interface) { + effective_includes.insert(effective_includes.end(), + dep.exported_includes.begin(), + dep.exported_includes.end()); + effective_defines.insert(effective_defines.end(), dep.exported_defines.begin(), + dep.exported_defines.end()); + effective_compile_opts.insert(effective_compile_opts.end(), + dep.exported_compile_options.begin(), + dep.exported_compile_options.end()); + } + if (link.visibility != Visibility::Private) { + tc.exported_includes.insert(tc.exported_includes.end(), + dep.exported_includes.begin(), + dep.exported_includes.end()); + tc.exported_defines.insert(tc.exported_defines.end(), + dep.exported_defines.begin(), + dep.exported_defines.end()); + tc.exported_compile_options.insert(tc.exported_compile_options.end(), + dep.exported_compile_options.begin(), + dep.exported_compile_options.end()); + } + + // Link usage: static private dependencies STILL propagate to final linkers! + const bool propagate_to_consumers = (link.visibility != Visibility::Private) || + (t.kind == TargetKind::StaticLibrary) || + (t.kind == TargetKind::HeaderOnly) || + (t.kind == TargetKind::ObjectLibrary); + + if (dep_rec.kind == TargetKind::ObjectLibrary) { + link_objects.insert(link_objects.end(), dep.object_files.begin(), + dep.object_files.end()); + if (propagate_to_consumers) { + tc.exported_objects.insert(tc.exported_objects.end(), + dep.object_files.begin(), + dep.object_files.end()); + } + } else if (dep_rec.kind == TargetKind::StaticLibrary && dep.primary_artifact) { + link_static_libs.push_back(*dep.primary_artifact); + if (propagate_to_consumers) { + tc.exported_static_libs.push_back(*dep.primary_artifact); + } + } else if (dep_rec.kind == TargetKind::SharedLibrary && dep.primary_artifact) { + link_shared_libs.push_back(*dep.primary_artifact); + summary.runtime_shared_libraries.push_back(*dep.primary_artifact); + if (propagate_to_consumers) { + tc.exported_shared_libs.push_back(*dep.primary_artifact); + } + } + + // Preserve exact order: dependency's transitive libs come AFTER dependency itself. + link_objects.insert(link_objects.end(), dep.exported_objects.begin(), + dep.exported_objects.end()); + link_static_libs.insert(link_static_libs.end(), dep.exported_static_libs.begin(), + dep.exported_static_libs.end()); + link_shared_libs.insert(link_shared_libs.end(), dep.exported_shared_libs.begin(), + dep.exported_shared_libs.end()); + effective_link_opts.insert(effective_link_opts.end(), + dep.exported_link_options.begin(), + dep.exported_link_options.end()); + if (propagate_to_consumers) { + tc.exported_objects.insert(tc.exported_objects.end(), + dep.exported_objects.begin(), + dep.exported_objects.end()); + tc.exported_static_libs.insert(tc.exported_static_libs.end(), + dep.exported_static_libs.begin(), + dep.exported_static_libs.end()); + tc.exported_shared_libs.insert(tc.exported_shared_libs.end(), + dep.exported_shared_libs.begin(), + dep.exported_shared_libs.end()); + tc.exported_link_options.insert(tc.exported_link_options.end(), + dep.exported_link_options.begin(), + dep.exported_link_options.end()); + } + } else { + // Imported target from foreign/native package provider. + const std::string key = link.dependency + "::" + link.target; + auto it = options.imported_targets.find(key); + if (it == options.imported_targets.end()) { + it = options.imported_targets.find(link.target); + } + if (it == options.imported_targets.end()) { + return std::unexpected{make_error(std::format( + "target '{}' links unresolved imported target '{}' from dependency '{}'", + t.name, link.target, link.dependency))}; + } + const auto &imp = it->second; + if (link.visibility != Visibility::Interface) { + effective_includes.insert(effective_includes.end(), imp.include_dirs.begin(), + imp.include_dirs.end()); + effective_defines.insert(effective_defines.end(), imp.defines.begin(), + imp.defines.end()); + effective_compile_opts.insert(effective_compile_opts.end(), + imp.compile_options.begin(), + imp.compile_options.end()); + } + if (link.visibility != Visibility::Private) { + tc.exported_includes.insert(tc.exported_includes.end(), + imp.include_dirs.begin(), imp.include_dirs.end()); + tc.exported_defines.insert(tc.exported_defines.end(), imp.defines.begin(), + imp.defines.end()); + tc.exported_compile_options.insert(tc.exported_compile_options.end(), + imp.compile_options.begin(), + imp.compile_options.end()); + } + const bool propagate_to_consumers = (link.visibility != Visibility::Private) || + (t.kind == TargetKind::StaticLibrary) || + (t.kind == TargetKind::HeaderOnly); + link_static_libs.insert(link_static_libs.end(), imp.static_libraries.begin(), + imp.static_libraries.end()); + link_shared_libs.insert(link_shared_libs.end(), imp.shared_libraries.begin(), + imp.shared_libraries.end()); + effective_link_opts.insert(effective_link_opts.end(), imp.link_options.begin(), + imp.link_options.end()); + if (propagate_to_consumers) { + tc.exported_static_libs.insert(tc.exported_static_libs.end(), + imp.static_libraries.begin(), + imp.static_libraries.end()); + tc.exported_shared_libs.insert(tc.exported_shared_libs.end(), + imp.shared_libraries.begin(), + imp.shared_libraries.end()); + tc.exported_link_options.insert(tc.exported_link_options.end(), + imp.link_options.begin(), + imp.link_options.end()); + } + } + } + + // 4. Expand sources (explicit files, globs, conventional src/source, modules, header + // units). + std::vector expanded_sources; + std::vector header_unit_sources; + std::set explicit_module_sources; + std::set seen_sources; + auto add_source = [&](const std::filesystem::path &rel_or_abs, bool is_mod = false) { + const auto norm = rel_or_abs.lexically_normal(); + if (seen_sources.insert(norm).second) { + expanded_sources.push_back(norm); + } + if (is_mod || is_module_source_extension(norm)) { + explicit_module_sources.insert(norm); + } + }; + + if (t.use_conventional_sources) { + for (const char *dir : {"src", "source"}) { + if (std::filesystem::is_directory(canonical_root / dir)) { + auto found = expand_glob(canonical_root, std::string{dir} + "/**/*"); + if (!found) { + return std::unexpected{found.error()}; + } + for (const auto &f : *found) { + if (is_cpp_source_extension(f)) { + add_source(f); + } + } + } + } + } + + for (const auto &src : t.sources) { + if (src.kind == SourceKind::Glob) { + auto found = expand_glob(canonical_root, src.path); + if (!found) { + return std::unexpected{found.error()}; + } + for (const auto &f : *found) { + add_source(f); + } + } else if (src.kind == SourceKind::HeaderUnit) { + const std::filesystem::path p{src.path}; + const auto abs = p.is_absolute() ? p : (canonical_root / p); + if (!std::filesystem::exists(abs)) { + return std::unexpected{make_error(std::format( + "target '{}' explicit header unit '{}' does not exist", t.name, src.path))}; + } + header_unit_sources.push_back(p.lexically_normal()); + } else if (src.kind == SourceKind::File || src.kind == SourceKind::ModuleInterface || + src.kind == SourceKind::ModulePartition) { + const std::filesystem::path p{src.path}; + const auto abs = p.is_absolute() ? p : (canonical_root / p); + const auto gen_candidate = + src.path.starts_with("$GEN/") ? (generated_root / src.path.substr(5)) : abs; + const bool produced_by_action = + output_owner.contains(gen_candidate.lexically_normal()); + if (!produced_by_action && !std::filesystem::exists(abs)) { + return std::unexpected{make_error(std::format( + "target '{}' explicit source '{}' does not exist", t.name, src.path))}; + } + const bool is_mod = (src.kind == SourceKind::ModuleInterface || + src.kind == SourceKind::ModulePartition); + add_source(produced_by_action ? gen_candidate : p, is_mod); + } + } + summary.expanded_sources = expanded_sources; + + if (t.kind == TargetKind::HeaderOnly) { + computed[t.name] = std::move(tc); + graph.targets.push_back(std::move(summary)); + continue; + } + + // Effective C++ standard, LTO, sanitizers (target overrides/extends profile). + const CxxStandard eff_std = t.cxx_standard != CxxStandard::Default + ? t.cxx_standard + : description.profile.cxx_standard; + const LtoMode eff_lto = t.lto != LtoMode::None ? t.lto : description.profile.lto; + std::vector eff_sans = description.profile.sanitizers; + for (const auto s : t.sanitizers) { + if (!std::ranges::contains(eff_sans, s)) { + eff_sans.push_back(s); + } + } + if (auto sv = validate_sanitizers(t.name, eff_sans); !sv) { + return std::unexpected{sv.error()}; + } + const bool pic = (t.kind == TargetKind::SharedLibrary); + + // Map include dirs to physical snapshot paths when snapshot is active. + std::vector> physical_includes; + physical_includes.reserve(effective_includes.size()); + for (const auto &[inc_path, is_sys] : effective_includes) { + physical_includes.emplace_back(map_logical_to_physical(inc_path), is_sys); + } + + // Path prefix maps remap physical snapshot root back to logical project root + // so __FILE__, __BASE_FILE__, std::source_location, and debug paths match uncached builds! + std::vector prefix_maps; + if (!graph.snapshot_materialized_root.empty()) { + prefix_maps.push_back({graph.snapshot_materialized_root, canonical_root}); + } + + // 5. Optional PCH compilation action (Plan 08 foundation). + std::optional pch_include_prefix; + std::optional pch_action_id; + if (!t.precompiled_header.empty()) { + const std::filesystem::path pch_rel{t.precompiled_header}; + const auto pch_logical = + pch_rel.is_absolute() ? pch_rel : (canonical_root / pch_rel).lexically_normal(); + const auto pch_physical = map_logical_to_physical(pch_logical); + const auto pch_out_base = + objects_root / sanitize_id_component(t.name) / "pch" / pch_logical.filename(); + const auto pch_gch = std::filesystem::path{pch_out_base.string() + ".gch"}; + + Toolchain::CompileRequest req; + req.source_file = pch_physical; + req.output_object = pch_gch; + req.depfile = std::filesystem::path{pch_gch.string() + ".d"}; + req.response_file_dir = rsp_root; + req.include_dirs = physical_includes; + req.defines = effective_defines; + req.compile_options = effective_compile_opts; + req.compile_options.push_back("-x"); + req.compile_options.push_back("c++-header"); + req.cxx_standard = eff_std; + req.lto = eff_lto; + req.sanitizers = eff_sans; + req.position_independent = pic; + req.prefix_maps = prefix_maps; + req.reproducibility_epoch = description.profile.reproducibility_epoch; + req.nondeterministic = t.nondeterministic || description.profile.nondeterministic; + req.response_file_threshold = options.response_file_threshold; + + auto lowered = Toolchain::lower_compile_command(toolchain, req); + if (!lowered) { + return std::unexpected{lowered.error()}; + } + ActionNode act; + act.id = "pch:" + sanitize_id_component(t.name); + act.kind = ActionKind::PrecompiledHeader; + act.target_name = t.name; + act.executable = lowered->executable; + act.arguments = std::move(lowered->arguments); + act.environment = std::move(lowered->environment); + act.working_directory = canonical_root; + act.response_file = lowered->response_file; + act.response_file_content = std::move(lowered->response_file_content); + act.declared_inputs = {pch_physical}; + act.declared_outputs = {pch_gch}; + act.depfile = req.depfile; + act.logical_source_file = pch_logical; + act.physical_source_file = pch_physical; + act.logical_output_file = pch_gch; + act.physical_output_file = pch_gch; + act.dependencies = target_prereq_actions; + act.nondeterministic = req.nondeterministic; + act.cacheable = !act.nondeterministic; + if (auto reg = register_output(pch_gch, act.id); !reg) { + return std::unexpected{reg.error()}; + } + // Include physical path & toolchain identity in PCH action key (Plan 07/08). + act.action_key = compute_action_key(act, graph); + pch_action_id = act.id; + pch_include_prefix = pch_out_base; + summary.action_ids.push_back(act.id); + graph.action_index_by_id[act.id] = graph.actions.size(); + graph.actions.push_back(std::move(act)); + } + + // 5b. Explicit Header Units lowering (Plan 08). + const std::string_view bmi_ext = + (toolchain.family == CompilerFamily::Clang) ? ".pcm" : ".gcm"; + const auto target_bmi_root = + graph.profile_build_dir / "bmi" / sanitize_id_component(t.name); + std::vector header_unit_action_ids; + std::vector header_unit_bmi_paths; + std::string gcc_header_unit_mapper_lines; + for (const auto &hu_path : header_unit_sources) { + const auto logical_hu = + hu_path.is_absolute() ? hu_path : (canonical_root / hu_path).lexically_normal(); + const auto physical_hu = map_logical_to_physical(logical_hu); + const std::string hu_hash = Util::sha256_hex(logical_hu.string()).substr(0, 12); + const auto hu_bmi = + target_bmi_root / ("hu_" + sanitize_id_component(logical_hu.filename().string()) + + "_" + hu_hash + std::string{bmi_ext}); + const CxxStandard hu_std = + (eff_std == CxxStandard::Default) ? CxxStandard::Cxx20 : eff_std; + + auto lowered = Modules::lower_header_unit_command(toolchain, physical_hu, hu_bmi, + physical_includes, effective_defines, + effective_compile_opts, hu_std); + if (!lowered) { + return std::unexpected{lowered.error()}; + } + ActionNode act; + act.id = "headerunit:" + sanitize_id_component(t.name) + ":" + hu_hash; + act.kind = ActionKind::HeaderUnit; + act.target_name = t.name; + act.executable = lowered->executable; + act.arguments = std::move(lowered->arguments); + act.environment = std::move(lowered->environment); + act.working_directory = canonical_root; + act.declared_inputs = {physical_hu}; + act.declared_outputs = {hu_bmi}; + act.logical_source_file = logical_hu; + act.physical_source_file = physical_hu; + act.logical_output_file = hu_bmi; + act.physical_output_file = hu_bmi; + act.dependencies = target_prereq_actions; + act.nondeterministic = t.nondeterministic || description.profile.nondeterministic; + act.cacheable = !act.nondeterministic; + if (auto reg = register_output(hu_bmi, act.id); !reg) { + return std::unexpected{reg.error()}; + } + act.action_key = compute_action_key(act, graph); + header_unit_action_ids.push_back(act.id); + header_unit_bmi_paths.push_back(hu_bmi); + gcc_header_unit_mapper_lines += physical_hu.string() + " " + hu_bmi.string() + "\n"; + if (logical_hu != physical_hu) { + gcc_header_unit_mapper_lines += logical_hu.string() + " " + hu_bmi.string() + "\n"; + } + summary.action_ids.push_back(act.id); + graph.action_index_by_id[act.id] = graph.actions.size(); + graph.actions.push_back(std::move(act)); + } + + // 5c. Build effective compile unit list (with optional deterministic unity batching + // excluding module sources and per-file-option sources — Plan 08). + struct CompileUnitSpec { + std::filesystem::path logical_src; + std::filesystem::path physical_src; + std::vector tu_opts; + bool is_explicit_module{false}; + bool has_per_file_override{false}; + }; + + std::vector raw_units; + raw_units.reserve(expanded_sources.size()); + for (const auto &src_path : expanded_sources) { + CompileUnitSpec cu; + cu.logical_src = + src_path.is_absolute() ? src_path : (canonical_root / src_path).lexically_normal(); + cu.physical_src = map_logical_to_physical(cu.logical_src); + cu.tu_opts = effective_compile_opts; + cu.is_explicit_module = + explicit_module_sources.contains(src_path) || is_module_source_extension(src_path); + for (const auto &pfo : t.per_file_options) { + if (pfo.source_path == src_path.generic_string() || + pfo.source_path == cu.logical_src.generic_string()) { + cu.tu_opts.push_back(pfo.option); + cu.has_per_file_override = true; + } + } + raw_units.push_back(std::move(cu)); + } + + std::vector compile_units; + if (t.unity_enabled && !raw_units.empty()) { + std::vector all_phys; + std::vector excluded_phys; + std::map raw_by_phys; + for (const auto &cu : raw_units) { + const auto norm_phys = cu.physical_src.lexically_normal(); + all_phys.push_back(norm_phys); + raw_by_phys[norm_phys] = &cu; + if (cu.is_explicit_module || cu.has_per_file_override) { + excluded_phys.push_back(norm_phys); + } + } + const auto unity_dir = + graph.profile_build_dir / "unity" / sanitize_id_component(t.name); + auto unity = + Modules::generate_unity_batches(sanitize_id_component(t.name), all_phys, + excluded_phys, t.unity_batch_size, unity_dir); + if (!unity) { + return std::unexpected{unity.error()}; + } + for (const auto &uf : unity->generated_unity_files) { + CompileUnitSpec cu; + cu.logical_src = uf; + cu.physical_src = uf; + cu.tu_opts = effective_compile_opts; + compile_units.push_back(std::move(cu)); + } + for (const auto &sf : unity->standalone_files) { + compile_units.push_back(*raw_by_phys.at(sf.lexically_normal())); + } + } else { + compile_units = std::move(raw_units); + } + + // 6. Compile actions (C++20/23/26 P1689 named modules & partitions OR regular TUs). + std::vector compile_action_ids; + const bool has_module_sources = std::ranges::any_of( + compile_units, [](const CompileUnitSpec &u) { return u.is_explicit_module; }); + + std::optional shared_hu_mapper; + if (!gcc_header_unit_mapper_lines.empty() && toolchain.family == CompilerFamily::Gcc && + !has_module_sources) { + shared_hu_mapper = target_bmi_root / "header_units.modmap"; + if (auto w = Platform::atomic_write_file(*shared_hu_mapper, + gcc_header_unit_mapper_lines, false); + !w) { + return std::unexpected{w.error()}; + } + } + + if (has_module_sources) { + const CxxStandard mod_std = + (eff_std == CxxStandard::Default) ? CxxStandard::Cxx20 : eff_std; + const auto scan_dir = + graph.profile_build_dir / "modscan" / sanitize_id_component(t.name); + + std::vector scanned; + scanned.reserve(compile_units.size()); + std::map cu_by_phys; + for (const auto &cu : compile_units) { + const auto norm_phys = cu.physical_src.lexically_normal(); + cu_by_phys[norm_phys] = &cu; + auto scan = Modules::scan_translation_unit(toolchain, norm_phys, scan_dir, + physical_includes, effective_defines, + cu.tu_opts, mod_std); + if (!scan) { + return std::unexpected{scan.error()}; + } + scanned.push_back(std::move(*scan)); + } + + auto collated = Modules::collate_modules( + scanned, target_bmi_root, graph.profile_identity + ":" + t.name, bmi_ext); + if (!collated) { + return std::unexpected{collated.error()}; + } + + std::map> provider_action_by_module; + std::map, std::less<>> module_deps_by_name; + for (const auto &n : collated->ordered_units) { + for (const auto &prov : n.provides) { + module_deps_by_name[prov] = n.required_modules; + } + } + auto collect_transitive_bmis = [&](const std::vector &direct_reqs) + -> std::vector> { + std::vector> bmis; + std::set seen; + std::queue q; + for (const auto &r : direct_reqs) { + if (seen.insert(r).second) { + q.push(r); + } + } + while (!q.empty()) { + const auto cur = q.front(); + q.pop(); + if (const auto bit = collated->module_to_bmi.find(cur); + bit != collated->module_to_bmi.end()) { + bmis.emplace_back(cur, bit->second); + } + if (const auto dit = module_deps_by_name.find(cur); + dit != module_deps_by_name.end()) { + for (const auto &sub : dit->second) { + if (seen.insert(sub).second) { + q.push(sub); + } + } + } + } + return bmis; + }; + for (const auto &node : collated->ordered_units) { + const auto &cu = *cu_by_phys.at(node.source_file.lexically_normal()); + const std::string src_hash = + Util::sha256_hex(cu.logical_src.string()).substr(0, 12); + const auto obj_path = objects_root / sanitize_id_component(t.name) / + (sanitize_id_component(cu.logical_src.filename().string()) + + "_" + src_hash + ".o"); + const auto dep_path = std::filesystem::path{obj_path.string() + ".d"}; + + std::vector unit_deps = target_prereq_actions; + if (pch_action_id) { + add_unique_str(unit_deps, *pch_action_id); + } + for (const auto &huid : header_unit_action_ids) { + add_unique_str(unit_deps, huid); + } + if (const auto prod_it = output_owner.find(cu.logical_src); + prod_it != output_owner.end()) { + add_unique_str(unit_deps, prod_it->second); + } + for (const auto &req_mod : node.required_modules) { + add_unique_str(unit_deps, provider_action_by_module.at(req_mod)); + } + + if (toolchain.family == CompilerFamily::Gcc) { + std::optional mapper_to_use; + if (!node.module_mapper_path.empty()) { + mapper_to_use = node.module_mapper_path; + if (!gcc_header_unit_mapper_lines.empty()) { + auto prev = Void::FileSystem::read_file(*mapper_to_use).value_or(""); + auto w = Platform::atomic_write_file( + *mapper_to_use, prev + gcc_header_unit_mapper_lines, false); + if (!w) { + return std::unexpected{w.error()}; + } + } + } else if (!gcc_header_unit_mapper_lines.empty()) { + mapper_to_use = target_bmi_root / (src_hash + ".hu.modmap"); + auto w = Platform::atomic_write_file(*mapper_to_use, + gcc_header_unit_mapper_lines, false); + if (!w) { + return std::unexpected{w.error()}; + } + } + + std::vector tu_opts = cu.tu_opts; + if (cu.is_explicit_module || is_module_source_extension(cu.physical_src)) { + tu_opts.push_back("-x"); + tu_opts.push_back("c++"); + } + + Toolchain::CompileRequest req; + req.source_file = cu.physical_src; + req.output_object = obj_path; + req.depfile = dep_path; + req.response_file_dir = rsp_root; + req.include_dirs = physical_includes; + req.defines = effective_defines; + req.compile_options = tu_opts; + req.cxx_standard = mod_std; + req.lto = eff_lto; + req.sanitizers = eff_sans; + req.position_independent = pic; + req.precompiled_header = pch_include_prefix; + req.prefix_maps = prefix_maps; + req.reproducibility_epoch = description.profile.reproducibility_epoch; + req.nondeterministic = + t.nondeterministic || description.profile.nondeterministic; + req.response_file_threshold = options.response_file_threshold; + req.is_module_interface = !node.provides.empty(); + req.module_mapper_file = mapper_to_use; + + auto lowered = Toolchain::lower_compile_command(toolchain, req); + if (!lowered) { + return std::unexpected{lowered.error()}; + } + + ActionNode act; + act.id = "compile:" + sanitize_id_component(t.name) + ":" + src_hash; + act.kind = ActionKind::Compile; + act.target_name = t.name; + act.executable = lowered->executable; + act.arguments = std::move(lowered->arguments); + act.environment = std::move(lowered->environment); + act.working_directory = canonical_root; + act.response_file = lowered->response_file; + act.response_file_content = std::move(lowered->response_file_content); + act.declared_inputs = {cu.physical_src}; + for (const auto &[mname, bmi_p] : node.imported_bmis) { + (void)mname; + act.declared_inputs.push_back(bmi_p); + } + for (const auto &hb : header_unit_bmi_paths) { + act.declared_inputs.push_back(hb); + } + if (mapper_to_use) { + act.declared_inputs.push_back(*mapper_to_use); + } + act.declared_outputs = {obj_path}; + if (!node.bmi_output_path.empty()) { + act.declared_outputs.push_back(node.bmi_output_path); + if (auto reg = register_output(node.bmi_output_path, act.id); !reg) { + return std::unexpected{reg.error()}; + } + } + act.depfile = dep_path; + act.logical_source_file = cu.logical_src; + act.physical_source_file = cu.physical_src; + act.logical_output_file = obj_path; + act.physical_output_file = obj_path; + act.logical_include_dirs = effective_includes; + act.physical_include_dirs = physical_includes; + act.defines = effective_defines; + act.compile_options = tu_opts; + act.cxx_standard = mod_std; + act.lto = eff_lto; + act.sanitizers = eff_sans; + act.position_independent = pic; + act.precompiled_header = pch_include_prefix; + act.dependencies = std::move(unit_deps); + act.nondeterministic = req.nondeterministic; + act.cacheable = !act.nondeterministic; + if (auto reg = register_output(obj_path, act.id); !reg) { + return std::unexpected{reg.error()}; + } + act.action_key = compute_action_key(act, graph); + for (const auto &prov : node.provides) { + provider_action_by_module[prov] = act.id; + } + compile_action_ids.push_back(act.id); + tc.object_files.push_back(obj_path); + summary.action_ids.push_back(act.id); + graph.action_index_by_id[act.id] = graph.actions.size(); + graph.actions.push_back(std::move(act)); + } else { + // Clang two-step module compilation: + // Providers: (1) --precompile source -> .pcm (ModuleBmi), (2) -c .pcm -> .o. + // Importers: -c source -fmodule-file=... -> .o. + std::vector> clang_imports = + collect_transitive_bmis(node.required_modules); + for (const auto &hb : header_unit_bmi_paths) { + clang_imports.emplace_back(std::string{}, hb); + } + + if (!node.provides.empty()) { + std::vector bmi_opts = cu.tu_opts; + bmi_opts.push_back("-x"); + bmi_opts.push_back("c++-module"); + + Toolchain::CompileRequest breq; + breq.source_file = cu.physical_src; + breq.output_object = obj_path; + breq.depfile = std::filesystem::path{node.bmi_output_path.string() + ".d"}; + breq.response_file_dir = rsp_root; + breq.include_dirs = physical_includes; + breq.defines = effective_defines; + breq.compile_options = bmi_opts; + breq.cxx_standard = mod_std; + breq.lto = eff_lto; + breq.sanitizers = eff_sans; + breq.position_independent = pic; + breq.precompiled_header = pch_include_prefix; + breq.prefix_maps = prefix_maps; + breq.reproducibility_epoch = description.profile.reproducibility_epoch; + breq.nondeterministic = + t.nondeterministic || description.profile.nondeterministic; + breq.response_file_threshold = options.response_file_threshold; + breq.is_module_interface = true; + breq.bmi_output = node.bmi_output_path; + breq.module_bmi_imports = clang_imports; + + auto lowered_bmi = Toolchain::lower_compile_command(toolchain, breq); + if (!lowered_bmi) { + return std::unexpected{lowered_bmi.error()}; + } + + ActionNode bmi_act; + bmi_act.id = "bmi:" + sanitize_id_component(t.name) + ":" + src_hash; + bmi_act.kind = ActionKind::ModuleBmi; + bmi_act.target_name = t.name; + bmi_act.executable = lowered_bmi->executable; + bmi_act.arguments = std::move(lowered_bmi->arguments); + bmi_act.environment = std::move(lowered_bmi->environment); + bmi_act.working_directory = canonical_root; + bmi_act.response_file = lowered_bmi->response_file; + bmi_act.response_file_content = + std::move(lowered_bmi->response_file_content); + bmi_act.declared_inputs = {cu.physical_src}; + for (const auto &[mname, bmi_p] : clang_imports) { + (void)mname; + bmi_act.declared_inputs.push_back(bmi_p); + } + bmi_act.declared_outputs = {node.bmi_output_path}; + bmi_act.depfile = breq.depfile; + bmi_act.logical_source_file = cu.logical_src; + bmi_act.physical_source_file = cu.physical_src; + bmi_act.logical_output_file = node.bmi_output_path; + bmi_act.physical_output_file = node.bmi_output_path; + bmi_act.dependencies = std::move(unit_deps); + bmi_act.nondeterministic = breq.nondeterministic; + bmi_act.cacheable = !bmi_act.nondeterministic; + if (auto reg = register_output(node.bmi_output_path, bmi_act.id); !reg) { + return std::unexpected{reg.error()}; + } + bmi_act.action_key = compute_action_key(bmi_act, graph); + const std::string bmi_act_id = bmi_act.id; + for (const auto &prov : node.provides) { + provider_action_by_module[prov] = bmi_act_id; + } + summary.action_ids.push_back(bmi_act_id); + graph.action_index_by_id[bmi_act_id] = graph.actions.size(); + graph.actions.push_back(std::move(bmi_act)); + + // Step 2: compile .pcm -> .o. + Toolchain::CompileRequest oreq; + oreq.source_file = node.bmi_output_path; + oreq.output_object = obj_path; + oreq.response_file_dir = rsp_root; + oreq.cxx_standard = mod_std; + oreq.lto = eff_lto; + oreq.sanitizers = eff_sans; + oreq.position_independent = pic; + oreq.reproducibility_epoch = description.profile.reproducibility_epoch; + oreq.nondeterministic = breq.nondeterministic; + oreq.response_file_threshold = options.response_file_threshold; + oreq.compile_only = true; + oreq.module_bmi_imports = clang_imports; + + auto lowered_obj = Toolchain::lower_compile_command(toolchain, oreq); + if (!lowered_obj) { + return std::unexpected{lowered_obj.error()}; + } + + ActionNode obj_act; + obj_act.id = "compile:" + sanitize_id_component(t.name) + ":" + src_hash; + obj_act.kind = ActionKind::Compile; + obj_act.target_name = t.name; + obj_act.executable = lowered_obj->executable; + obj_act.arguments = std::move(lowered_obj->arguments); + obj_act.environment = std::move(lowered_obj->environment); + obj_act.working_directory = canonical_root; + obj_act.response_file = lowered_obj->response_file; + obj_act.response_file_content = + std::move(lowered_obj->response_file_content); + obj_act.declared_inputs = {node.bmi_output_path}; + for (const auto &[mname, bmi_p] : clang_imports) { + (void)mname; + obj_act.declared_inputs.push_back(bmi_p); + } + obj_act.declared_outputs = {obj_path}; + obj_act.logical_output_file = obj_path; + obj_act.physical_output_file = obj_path; + obj_act.dependencies = {bmi_act_id}; + obj_act.nondeterministic = oreq.nondeterministic; + obj_act.cacheable = !obj_act.nondeterministic; + if (auto reg = register_output(obj_path, obj_act.id); !reg) { + return std::unexpected{reg.error()}; + } + obj_act.action_key = compute_action_key(obj_act, graph); + compile_action_ids.push_back(obj_act.id); + tc.object_files.push_back(obj_path); + summary.action_ids.push_back(obj_act.id); + graph.action_index_by_id[obj_act.id] = graph.actions.size(); + graph.actions.push_back(std::move(obj_act)); + } else { + Toolchain::CompileRequest req; + req.source_file = cu.physical_src; + req.output_object = obj_path; + req.depfile = dep_path; + req.response_file_dir = rsp_root; + req.include_dirs = physical_includes; + req.defines = effective_defines; + req.compile_options = cu.tu_opts; + req.cxx_standard = mod_std; + req.lto = eff_lto; + req.sanitizers = eff_sans; + req.position_independent = pic; + req.precompiled_header = pch_include_prefix; + req.prefix_maps = prefix_maps; + req.reproducibility_epoch = description.profile.reproducibility_epoch; + req.nondeterministic = + t.nondeterministic || description.profile.nondeterministic; + req.response_file_threshold = options.response_file_threshold; + req.module_bmi_imports = clang_imports; + + auto lowered = Toolchain::lower_compile_command(toolchain, req); + if (!lowered) { + return std::unexpected{lowered.error()}; + } + + ActionNode act; + act.id = "compile:" + sanitize_id_component(t.name) + ":" + src_hash; + act.kind = ActionKind::Compile; + act.target_name = t.name; + act.executable = lowered->executable; + act.arguments = std::move(lowered->arguments); + act.environment = std::move(lowered->environment); + act.working_directory = canonical_root; + act.response_file = lowered->response_file; + act.response_file_content = std::move(lowered->response_file_content); + act.declared_inputs = {cu.physical_src}; + for (const auto &[mname, bmi_p] : clang_imports) { + (void)mname; + act.declared_inputs.push_back(bmi_p); + } + act.declared_outputs = {obj_path}; + act.depfile = dep_path; + act.logical_source_file = cu.logical_src; + act.physical_source_file = cu.physical_src; + act.logical_output_file = obj_path; + act.physical_output_file = obj_path; + act.logical_include_dirs = effective_includes; + act.physical_include_dirs = physical_includes; + act.defines = effective_defines; + act.compile_options = cu.tu_opts; + act.cxx_standard = mod_std; + act.lto = eff_lto; + act.sanitizers = eff_sans; + act.position_independent = pic; + act.precompiled_header = pch_include_prefix; + act.dependencies = std::move(unit_deps); + act.nondeterministic = req.nondeterministic; + act.cacheable = !act.nondeterministic; + if (auto reg = register_output(obj_path, act.id); !reg) { + return std::unexpected{reg.error()}; + } + act.action_key = compute_action_key(act, graph); + compile_action_ids.push_back(act.id); + tc.object_files.push_back(obj_path); + summary.action_ids.push_back(act.id); + graph.action_index_by_id[act.id] = graph.actions.size(); + graph.actions.push_back(std::move(act)); + } + } + } + } else { + for (const auto &cu : compile_units) { + const std::string src_hash = + Util::sha256_hex(cu.logical_src.string()).substr(0, 12); + const auto obj_path = objects_root / sanitize_id_component(t.name) / + (sanitize_id_component(cu.logical_src.filename().string()) + + "_" + src_hash + ".o"); + const auto dep_path = std::filesystem::path{obj_path.string() + ".d"}; + + Toolchain::CompileRequest req; + req.source_file = cu.physical_src; + req.output_object = obj_path; + req.depfile = dep_path; + req.response_file_dir = rsp_root; + req.include_dirs = physical_includes; + req.defines = effective_defines; + req.compile_options = cu.tu_opts; + req.cxx_standard = + (!header_unit_bmi_paths.empty() && eff_std == CxxStandard::Default) + ? CxxStandard::Cxx20 + : eff_std; + req.lto = eff_lto; + req.sanitizers = eff_sans; + req.position_independent = pic; + req.precompiled_header = pch_include_prefix; + req.prefix_maps = prefix_maps; + req.reproducibility_epoch = description.profile.reproducibility_epoch; + req.nondeterministic = t.nondeterministic || description.profile.nondeterministic; + req.response_file_threshold = options.response_file_threshold; + if (shared_hu_mapper) { + req.module_mapper_file = shared_hu_mapper; + } else if (!header_unit_bmi_paths.empty() && + toolchain.family == CompilerFamily::Clang) { + for (const auto &hb : header_unit_bmi_paths) { + req.module_bmi_imports.emplace_back(std::string{}, hb); + } + } + + auto lowered = Toolchain::lower_compile_command(toolchain, req); + if (!lowered) { + return std::unexpected{lowered.error()}; + } + + ActionNode act; + act.id = "compile:" + sanitize_id_component(t.name) + ":" + src_hash; + act.kind = ActionKind::Compile; + act.target_name = t.name; + act.executable = lowered->executable; + act.arguments = std::move(lowered->arguments); + act.environment = std::move(lowered->environment); + act.working_directory = canonical_root; + act.response_file = lowered->response_file; + act.response_file_content = std::move(lowered->response_file_content); + act.declared_inputs = {cu.physical_src}; + for (const auto &hb : header_unit_bmi_paths) { + act.declared_inputs.push_back(hb); + } + if (shared_hu_mapper) { + act.declared_inputs.push_back(*shared_hu_mapper); + } + act.declared_outputs = {obj_path}; + act.depfile = dep_path; + act.logical_source_file = cu.logical_src; + act.physical_source_file = cu.physical_src; + act.logical_output_file = obj_path; + act.physical_output_file = obj_path; + act.logical_include_dirs = effective_includes; + act.physical_include_dirs = physical_includes; + act.defines = effective_defines; + act.compile_options = cu.tu_opts; + act.cxx_standard = req.cxx_standard; + act.lto = eff_lto; + act.sanitizers = eff_sans; + act.position_independent = pic; + act.precompiled_header = pch_include_prefix; + act.dependencies = target_prereq_actions; + if (pch_action_id) { + add_unique_str(act.dependencies, *pch_action_id); + } + for (const auto &huid : header_unit_action_ids) { + add_unique_str(act.dependencies, huid); + } + if (const auto prod_it = output_owner.find(cu.logical_src); + prod_it != output_owner.end()) { + add_unique_str(act.dependencies, prod_it->second); + } + act.nondeterministic = req.nondeterministic; + act.cacheable = !act.nondeterministic; + if (auto reg = register_output(obj_path, act.id); !reg) { + return std::unexpected{reg.error()}; + } + act.action_key = compute_action_key(act, graph); + compile_action_ids.push_back(act.id); + tc.object_files.push_back(obj_path); + summary.action_ids.push_back(act.id); + graph.action_index_by_id[act.id] = graph.actions.size(); + graph.actions.push_back(std::move(act)); + } + } + + // 7. Archive or Link action for concrete product targets. + if (t.kind == TargetKind::ObjectLibrary) { + tc.producer_action_ids = compile_action_ids; + summary.primary_outputs = tc.object_files; + } else if (t.kind == TargetKind::StaticLibrary) { + const auto archive_path = artifacts_root / ("lib" + t.name + ".a"); + auto lowered = + Toolchain::lower_archive_command(toolchain, archive_path, tc.object_files, rsp_root, + options.response_file_threshold); + if (!lowered) { + return std::unexpected{lowered.error()}; + } + ActionNode act; + act.id = "archive:" + sanitize_id_component(t.name); + act.kind = ActionKind::Archive; + act.target_name = t.name; + act.executable = lowered->executable; + act.arguments = std::move(lowered->arguments); + act.environment = std::move(lowered->environment); + act.working_directory = canonical_root; + act.response_file = lowered->response_file; + act.response_file_content = std::move(lowered->response_file_content); + act.declared_inputs = tc.object_files; + act.declared_outputs = {archive_path}; + act.logical_output_file = archive_path; + act.physical_output_file = archive_path; + act.dependencies = compile_action_ids; + act.nondeterministic = t.nondeterministic || description.profile.nondeterministic; + act.cacheable = !act.nondeterministic; + if (auto reg = register_output(archive_path, act.id); !reg) { + return std::unexpected{reg.error()}; + } + act.action_key = compute_action_key(act, graph); + tc.primary_artifact = archive_path; + tc.producer_action_ids = {act.id}; + summary.primary_outputs = {archive_path}; + summary.action_ids.push_back(act.id); + graph.action_index_by_id[act.id] = graph.actions.size(); + graph.actions.push_back(std::move(act)); + } else if (t.kind == TargetKind::Executable || t.kind == TargetKind::SharedLibrary || + t.kind == TargetKind::Test) { + const auto out_name = + (t.kind == TargetKind::SharedLibrary) ? ("lib" + t.name + ".so") : t.name; + const auto bin_path = + (t.kind == TargetKind::SharedLibrary ? artifacts_root : (artifacts_root / "bin")) / + out_name; + + std::vector all_objects = tc.object_files; + all_objects.insert(all_objects.end(), link_objects.begin(), link_objects.end()); + + std::vector rpaths; + for (const auto &sh : link_shared_libs) { + const auto dir = sh.parent_path(); + if (!dir.empty() && !std::ranges::contains(rpaths, dir)) { + rpaths.push_back(dir); + } + } + + Toolchain::LinkRequest lreq; + lreq.kind = t.kind; + lreq.output_file = bin_path; + lreq.response_file_dir = rsp_root; + lreq.object_files = all_objects; + lreq.static_libraries = link_static_libs; + lreq.shared_libraries = link_shared_libs; + lreq.rpaths = rpaths; + lreq.link_options = effective_link_opts; + lreq.lto = eff_lto; + lreq.sanitizers = eff_sans; + lreq.response_file_threshold = options.response_file_threshold; + + auto lowered = Toolchain::lower_link_command(toolchain, lreq); + if (!lowered) { + return std::unexpected{lowered.error()}; + } + + ActionNode act; + act.id = "link:" + sanitize_id_component(t.name); + act.kind = ActionKind::Link; + act.target_name = t.name; + act.executable = lowered->executable; + act.arguments = std::move(lowered->arguments); + act.environment = std::move(lowered->environment); + act.working_directory = canonical_root; + act.response_file = lowered->response_file; + act.response_file_content = std::move(lowered->response_file_content); + act.declared_inputs = all_objects; + act.declared_inputs.insert(act.declared_inputs.end(), link_static_libs.begin(), + link_static_libs.end()); + act.declared_inputs.insert(act.declared_inputs.end(), link_shared_libs.begin(), + link_shared_libs.end()); + act.declared_outputs = {bin_path}; + act.logical_output_file = bin_path; + act.physical_output_file = bin_path; + act.dependencies = compile_action_ids; + for (const auto &dep_in : act.declared_inputs) { + if (const auto prod_it = output_owner.find(dep_in.lexically_normal()); + prod_it != output_owner.end()) { + add_unique_str(act.dependencies, prod_it->second); + } + } + act.nondeterministic = t.nondeterministic || description.profile.nondeterministic; + act.cacheable = !act.nondeterministic; + if (auto reg = register_output(bin_path, act.id); !reg) { + return std::unexpected{reg.error()}; + } + act.action_key = compute_action_key(act, graph); + tc.primary_artifact = bin_path; + tc.producer_action_ids = {act.id}; + summary.primary_outputs = {bin_path}; + summary.action_ids.push_back(act.id); + graph.action_index_by_id[act.id] = graph.actions.size(); + graph.actions.push_back(std::move(act)); + } + + computed[t.name] = std::move(tc); + graph.targets.push_back(std::move(summary)); + } + + return graph; +} + +} // namespace Void::Build::Graph diff --git a/src/Install/Installer.cpp b/src/Install/Installer.cpp new file mode 100644 index 0000000..691848b --- /dev/null +++ b/src/Install/Installer.cpp @@ -0,0 +1,418 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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 +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 items; + std::set 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 { + 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 public_defines; + std::vector public_compile_opts; + std::vector local_deps; + }; + std::vector 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(::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 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 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 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 +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(&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(&fit->second.value)) { + for (const auto &v : *arr) { + if (const auto *s = std::get_if(&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 diff --git a/src/Main.cpp b/src/Main.cpp new file mode 100644 index 0000000..5c7c111 --- /dev/null +++ b/src/Main.cpp @@ -0,0 +1,1447 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace Void::Build; + +Void::Argparse::Parser make_root_parser(bool &show_version) { + Void::Argparse::Parser parser{ + "vbs ", + "VoidBuildSystem — native C++ build system & package manager.\n\n" + "Commands:\n" + " build Configure and build selected targets/profiles\n" + " test Build and run declared test targets\n" + " describe Evaluate build.cpp and emit versioned graph JSON\n" + " compdb Manage per-profile compile_commands.json (use|show|export|watch)\n" + " watch Watch project and rebuild on verified changes\n" + " deps Resolve or update vbs.lock (resolve|update)\n" + " install Stage and install declared products + exports\n" + " uninstall Safely uninstall VBS-owned files from a prefix\n" + " pack Create deterministic source archive (.tar)\n" + " publish Pack and publish a release to a VBS package registry\n" + " bridge CMake VbsDeps.cmake dependency bridge backend\n" + " gc Recover state and garbage-collect unreferenced CAS blobs\n" + " gen-tests Generate native Void::Testing registration unit (no CMake)"}; + parser.flag("--version", "-V", "Show version", show_version); + return parser; +} + +// Handles standalone --help/-h cleanly (exit 0) and delegates real parsing to Void::Argparse. +std::optional parse_with_void_argparse(const Void::Argparse::Parser &parser, + std::string_view cmd_label, + const std::vector &sub_argv) { + bool saw_help = false; + for (std::size_t i = 1; i < sub_argv.size(); ++i) { + const std::string_view a{sub_argv[i]}; + if (a == "--help" || a == "-h") { + saw_help = true; + break; + } + } + if (saw_help) { + if (sub_argv.size() > 2) { + std::cerr << cmd_label << ": --help must be used alone\n"; + return 2; + } + std::cout << parser.help(); + return 0; + } + auto res = parser.parse(static_cast(sub_argv.size()), sub_argv.data()); + if (!res) { + std::cerr << cmd_label << ": " << res.error() << '\n'; + return 2; + } + return std::nullopt; +} + +struct RepeatableSpec { + std::string_view long_name; + std::string_view short_name; + std::vector *sink; +}; + +// Extracts repeatable options (e.g. --profile / --target / --build-source) before delegating +// remaining flags/options to Void::Argparse::Parser (which also documents them in --help). +std::optional extract_repeatable_args(int start_index, int argc, char **argv, + std::string_view cmd_label, + const std::vector &specs, + std::vector &remaining_argv) { + remaining_argv.clear(); + remaining_argv.push_back(argv[0]); + for (int i = start_index; i < argc; ++i) { + const std::string_view arg{argv[i]}; + bool matched = false; + for (const auto &spec : specs) { + if (arg == spec.long_name || (!spec.short_name.empty() && arg == spec.short_name)) { + if (i + 1 >= argc) { + std::cerr << cmd_label << ": option '" << arg << "' requires a value\n"; + return 2; + } + spec.sink->emplace_back(argv[++i]); + matched = true; + break; + } + if (arg.starts_with(spec.long_name) && arg.size() > spec.long_name.size() && + arg[spec.long_name.size()] == '=') { + spec.sink->emplace_back(arg.substr(spec.long_name.size() + 1)); + matched = true; + break; + } + } + if (!matched) { + remaining_argv.push_back(argv[i]); + } + } + return std::nullopt; +} + +Config::FrontendOptions +make_frontend_opts(const std::filesystem::path &project_root, + const std::filesystem::path &build_root, + const std::vector &extra_sources) { + Config::FrontendOptions opts; + opts.project_root = project_root; + opts.build_root = build_root; + opts.sdk_include_dir = std::filesystem::path{Bootstrap::sdk_include_dir}; + opts.sdk_source_dir = std::filesystem::path{Bootstrap::sdk_source_dir}; + const auto prebuilt_cmake = std::filesystem::path{Bootstrap::binary_dir} / "libVoidBuild_Sdk.a"; + const auto prebuilt_native = std::filesystem::path{Bootstrap::binary_dir} / "profiles" / + "debug" / "out" / "libVoidBuildSdk.a"; + std::error_code ec; + if (std::filesystem::is_regular_file(prebuilt_cmake, ec)) { + opts.sdk_library_path = prebuilt_cmake; + } else if (std::filesystem::is_regular_file(prebuilt_native, ec)) { + opts.sdk_library_path = prebuilt_native; + } + opts.extra_build_sources = extra_sources; + return opts; +} + +struct ResolvedDepMaterialization { + Package::LockContextRecord lock_context; + std::vector> materialized; +}; + +// Shared dependency resolution + live registry fetching + safe archive extraction + lock context +// builder for `vbs deps resolve|update`, `vbs build`, and `vbs test`. +Void::Result::Result resolve_and_materialize_deps( + const ProfileContext &ctx, const std::vector &merged_deps, + const std::filesystem::path &project_root, const std::filesystem::path &build_root, + const std::optional &pinned_lock, bool offline, bool allow_upgrade) { + const std::string ctx_key = Package::make_lock_context_key(ctx, "target"); + const std::string fp = Package::compute_declaration_fingerprint(ctx, "target", merged_deps); + + ResolvedDepMaterialization out; + out.lock_context.context_key = ctx_key; + out.lock_context.profile_name = ctx.name; + out.lock_context.compiler = std::string{compiler_name(ctx.compiler)}; + out.lock_context.os = ctx.os; + out.lock_context.architecture = ctx.architecture; + out.lock_context.machine_role = "target"; + out.lock_context.declaration_fingerprint = fp; + + // Collect existing lock pins (used unless `deps update` requested an upgrade). + Package::SolveOptions solve_opts; + std::map locked_pkg_entries; + if (!allow_upgrade && pinned_lock && pinned_lock->document.contexts.contains(ctx_key)) { + for (const auto &entry : pinned_lock->document.contexts.at(ctx_key).entries) { + if (entry.source_kind == "package" && !entry.package_name.empty()) { + const Package::PackageId pid{entry.registry_authority, entry.package_name}; + locked_pkg_entries[pid] = entry; + if (auto ver = Void::Semver::parse_strict(entry.version); ver) { + solve_opts.pinned_versions[pid] = *ver; + } + } + } + } + + // 1. Solve all registry package dependencies together via PubGrub. + const std::string default_registry = Void::Configuration::get_env_or("VBS_REGISTRY_URL", ""); + Package::RegistryAuth reg_auth{Void::Configuration::get_env_or("VBS_REGISTRY_TOKEN", "")}; + std::vector root_constraints; + std::map> alias_to_pkg_id; + std::vector package_deps; + + for (const auto &nd : merged_deps) { + if (nd.record.source_kind != DependencySourceKind::Package) { + continue; + } + const std::string reg_url = + nd.record.registry_authority.empty() ? default_registry : nd.record.registry_authority; + if (reg_url.empty()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("package dependency '{}' requires .registry(url) or VBS_REGISTRY_URL", + nd.record.name))}; + } + const std::string pkg_name = nd.record.package.empty() ? nd.record.name : nd.record.package; + const Package::PackageId pid{reg_url, pkg_name}; + alias_to_pkg_id[nd.record.name] = pid; + package_deps.push_back(&nd); + root_constraints.push_back(Package::DependencyConstraint{ + pid, nd.record.version.empty() ? ">=0.0.0" : nd.record.version, nd.record.features, + "root(" + nd.record.name + ")"}); + } + + std::map solved_packages; + if (!root_constraints.empty()) { + // Check if offline with complete locked cache. + bool all_locked_cached = offline; + const auto pkg_cache_root = build_root / ".vbs" / "cache" / "packages"; + if (all_locked_cached) { + for (const auto *nd : package_deps) { + const auto &pid = alias_to_pkg_id.at(nd->record.name); + const auto it = locked_pkg_entries.find(pid); + if (it == locked_pkg_entries.end() || it->second.sha256.empty() || + !std::filesystem::is_directory(pkg_cache_root / it->second.sha256 / "src")) { + all_locked_cached = false; + break; + } + } + } + + if (all_locked_cached) { + for (const auto *nd : package_deps) { + const auto &pid = alias_to_pkg_id.at(nd->record.name); + const auto &le = locked_pkg_entries.at(pid); + auto parsed_ver = Void::Semver::parse_strict(le.version); + if (!parsed_ver) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("corrupt locked version '{}' for package '{}'", le.version, + pid.name))}; + } + Package::SolvedPackage sp; + sp.id = pid; + sp.version = *parsed_ver; + sp.source_sha256 = le.sha256; + solved_packages[pid] = std::move(sp); + } + } else { + if (offline) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::not_found, + "offline mode cannot query live package registry; populate cache first")}; + } + Package::PackageIndex index; + std::set fetched_ids; + std::queue pending; + for (const auto &c : root_constraints) { + if (fetched_ids.insert(c.target).second) { + pending.push(c.target); + } + } + while (!pending.empty()) { + const auto pid = pending.front(); + pending.pop(); + auto releases = + Package::fetch_package_releases(pid.registry_authority, pid.name, reg_auth); + if (!releases) { + return std::unexpected{releases.error()}; + } + for (auto &rel : *releases) { + for (const auto &dep_c : rel.dependencies) { + if (fetched_ids.insert(dep_c.target).second) { + pending.push(dep_c.target); + } + } + index.add_release(std::move(rel)); + } + } + + auto solved = Package::solve_dependencies(root_constraints, index, solve_opts); + if (!solved) { + return std::unexpected{solved.error()}; + } + solved_packages = std::move(solved->packages); + } + } + + // 2. Materialize every dependency (registry packages + git/path/archive/conan). + const auto pkg_cache_root = build_root / ".vbs" / "cache" / "packages"; + std::error_code ec; + for (const auto &nd : merged_deps) { + if (nd.record.source_kind == DependencySourceKind::Package) { + const auto &pid = alias_to_pkg_id.at(nd.record.name); + const auto &sp = solved_packages.at(pid); + const auto tar_path = pkg_cache_root / (sp.source_sha256 + ".tar"); + const auto extract_dir = pkg_cache_root / sp.source_sha256 / "src"; + + if (!std::filesystem::is_directory(extract_dir, ec)) { + bool need_download = true; + if (std::filesystem::is_regular_file(tar_path, ec)) { + auto have_sha = Util::sha256_file_hex(tar_path); + if (have_sha && *have_sha == sp.source_sha256) { + need_download = false; + } + } + if (need_download) { + auto dl = Package::download_release_archive( + pid.registry_authority, pid.name, sp.version.to_string(), sp.source_sha256, + tar_path, reg_auth); + if (!dl) { + return std::unexpected{dl.error()}; + } + } + auto ex = Package::extract_safe_tar(tar_path, extract_dir); + if (!ex) { + return std::unexpected{ex.error()}; + } + } + + Package::MaterializedSource mat{nd.record.name, extract_dir, sp.source_sha256, false}; + out.materialized.emplace_back(nd.record, std::move(mat)); + + Package::LockedSourceEntry le; + le.alias = nd.record.name; + le.source_kind = "package"; + le.registry_authority = pid.registry_authority; + le.package_name = pid.name; + le.version = sp.version.to_string(); + le.sha256 = sp.source_sha256; + le.builder = nd.record.builder; + le.features = nd.record.features; + le.build_dependency = nd.record.build_dependency; + out.lock_context.entries.push_back(std::move(le)); + } else { + Package::FetchOptions fopt{build_root / ".vbs" / "cache", project_root, offline, {}}; + auto mat = Package::materialize_dependency_source(nd.record, fopt); + if (!mat) { + return std::unexpected{mat.error()}; + } + Package::LockedSourceEntry le; + le.alias = nd.record.name; + switch (nd.record.source_kind) { + case DependencySourceKind::Git: + le.source_kind = "git"; + break; + case DependencySourceKind::Path: + le.source_kind = "path"; + break; + case DependencySourceKind::Archive: + le.source_kind = "archive"; + break; + case DependencySourceKind::Conan: + le.source_kind = "conan"; + break; + case DependencySourceKind::Package: + le.source_kind = "package"; + break; + case DependencySourceKind::Unspecified: + le.source_kind = "unspecified"; + break; + } + le.location = nd.record.location; + le.revision = nd.record.revision; + le.sha256 = mat->content_identity_hash; + le.builder = nd.record.builder; + le.features = nd.record.features; + le.build_dependency = nd.record.build_dependency; + out.lock_context.entries.push_back(std::move(le)); + out.materialized.emplace_back(nd.record, std::move(*mat)); + } + } + + return out; +} + +int run_build_or_test(int argc, char **argv, bool run_tests) { + const std::string cmd_name = run_tests ? "vbs test" : "vbs build"; + std::string project_arg = std::filesystem::current_path().string(); + std::optional build_arg; + std::optional profile_doc; + std::optional target_doc; + std::optional build_source_doc; + std::optional editor_profile; + std::optional compiler_arg; + std::optional jobs_arg; + bool no_cache = false; + bool locked = false; + bool offline = false; + + Void::Argparse::Parser parser{cmd_name, + run_tests ? "Build and execute declared test targets." + : "Configure and build selected profiles and targets."}; + parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) + .option("--build-dir", "-B", "Build output directory", build_arg) + .option("--profile", "-p", "Profile to build (repeatable)", profile_doc) + .option("--target", "-t", "Target to build/test (repeatable)", target_doc) + .option("--compiler", "", "Override compiler family (gcc|clang)", compiler_arg) + .option("--editor-profile", "", "Editor profile for compile_commands.json", editor_profile) + .option("--build-source", "", "Additional build description source (repeatable)", + build_source_doc) + .option("--jobs", "-j", "Maximum parallel compilation/link jobs", jobs_arg) + .flag("--locked", "", "Require existing up-to-date vbs.lock", locked) + .flag("--offline", "", "Disallow network fetches", offline) + .flag("--no-cache", "", "Bypass action cache reads", no_cache); + + std::vector requested_profiles; + std::vector requested_targets; + std::vector extra_build_source_strs; + std::vector remaining; + if (auto rc = extract_repeatable_args(2, argc, argv, cmd_name, + {{"--profile", "-p", &requested_profiles}, + {"--target", "-t", &requested_targets}, + {"--build-source", "", &extra_build_source_strs}}, + remaining); + rc) { + return *rc; + } + if (auto rc = parse_with_void_argparse(parser, cmd_name, remaining); rc) { + return *rc; + } + + std::optional compiler_override; + if (compiler_arg) { + try { + compiler_override = parse_compiler(*compiler_arg); + } catch (const std::exception &ex) { + std::cerr << cmd_name << ": " << ex.what() << '\n'; + return 2; + } + } + std::size_t jobs = 0; + if (jobs_arg) { + int parsed_jobs = 0; + if (!Void::Str::to_int(*jobs_arg, parsed_jobs) || parsed_jobs < 0) { + std::cerr << cmd_name << ": invalid --jobs value '" << *jobs_arg << "'\n"; + return 2; + } + jobs = static_cast(parsed_jobs); + } + + const std::filesystem::path project_root{project_arg}; + const std::filesystem::path build_root = + build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + std::vector extra_build_sources; + for (const auto &s : extra_build_source_strs) { + extra_build_sources.emplace_back(s); + } + if (requested_profiles.empty()) { + requested_profiles.push_back("debug"); + } + + // D-010 / Plan 09: multi-profile builds MUST specify --editor-profile from selected profiles + // BEFORE doing any build work! + if (requested_profiles.size() > 1) { + if (!editor_profile) { + std::cerr << "vbs: multi-profile build requires --editor-profile selecting one of " + "the requested profiles\n"; + return 2; + } + if (!std::ranges::contains(requested_profiles, *editor_profile)) { + std::cerr << "vbs: --editor-profile '" << *editor_profile + << "' must be one of the requested profiles\n"; + return 2; + } + } else if (!editor_profile) { + editor_profile = requested_profiles.front(); + } + + // Reserve monotonic selection ticket on acceptance BEFORE expensive work! + auto reserved_ticket = + Editor::reserve_selection_ticket(project_root, build_root, *editor_profile); + if (!reserved_ticket) { + std::cerr << "vbs: failed reserving editor ticket: " << reserved_ticket.error().message() + << '\n'; + return 1; + } + + const auto fopts = make_frontend_opts(project_root, build_root, extra_build_sources); + auto compiled = Config::compile_descriptor(fopts); + if (!compiled) { + std::cerr << "vbs: " << compiled.error().message() << '\n'; + return 1; + } + auto profs = Config::discover_profiles(*compiled, fopts); + if (!profs) { + std::cerr << "vbs: " << profs.error().message() << '\n'; + return 1; + } + + auto state = State::StateStore::open(build_root / ".vbs"); + if (!state) { + std::cerr << "vbs: " << state.error().message() << '\n'; + return 1; + } + + const auto lock_path = project_root / "vbs.lock"; + auto pinned_lock = Package::load_pinned_lock(lock_path); + if (!pinned_lock) { + std::cerr << "vbs: " << pinned_lock.error().message() << '\n'; + return 1; + } + + bool all_ok = true; + for (const auto &prof_name : requested_profiles) { + ProfileContext ctx; + try { + ctx = profs->resolve(prof_name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + } catch (const std::exception &ex) { + std::cerr << "vbs: " << ex.what() << '\n'; + return 2; + } + + auto tc = Toolchain::discover_and_probe(ctx, build_root / ".vbs" / "probes"); + if (!tc) { + std::cerr << "vbs: " << tc.error().message() << '\n'; + return 1; + } + auto desc = Config::evaluate_project(*compiled, ctx, fopts); + if (!desc) { + std::cerr << "vbs: " << desc.error().message() << '\n'; + (void)Editor::mark_profile_stale( + build_root, prof_name, Editor::GenerationStatus::Invalid, desc.error().message()); + return 1; + } + + // Load & merge any TOML dependency manifests declared by build.cpp. + std::vector toml_deps; + for (const auto &dep_file : desc->dependency_files) { + const auto p = std::filesystem::path{dep_file}.is_absolute() + ? std::filesystem::path{dep_file} + : (project_root / dep_file); + auto loaded = Package::load_dependencies_toml(p); + if (!loaded) { + std::cerr << "vbs: " << loaded.error().message() << '\n'; + return 1; + } + toml_deps.insert(toml_deps.end(), loaded->begin(), loaded->end()); + } + auto merged_deps = Package::merge_dependencies(desc->dependencies, toml_deps); + if (!merged_deps) { + std::cerr << "vbs: " << merged_deps.error().message() << '\n'; + return 1; + } + + // Validate/create lockfile context and materialize dependencies (including live registry). + std::map> imported_targets; + if (!merged_deps->empty()) { + const std::string ctx_key = Package::make_lock_context_key(ctx, "target"); + const std::string fp = + Package::compute_declaration_fingerprint(ctx, "target", *merged_deps); + if (pinned_lock->has_value()) { + auto valid = + Package::validate_locked_context((*pinned_lock)->document, ctx_key, fp); + if (!valid) { + std::cerr << "vbs: " << valid.error().message() << '\n'; + return 1; + } + } else if (locked) { + std::cerr << "vbs: --locked requires an existing vbs.lock\n"; + return 1; + } + + auto resolved = resolve_and_materialize_deps(ctx, *merged_deps, project_root, + build_root, *pinned_lock, offline, false); + if (!resolved) { + std::cerr << "vbs: " << resolved.error().message() << '\n'; + return 1; + } + for (const auto &[dep_rec, mat] : resolved->materialized) { + DependencyRecord effective_dep = dep_rec; + if (effective_dep.builder.empty() && + effective_dep.source_kind == DependencySourceKind::Package) { + std::error_code bec; + if (std::filesystem::is_regular_file(mat.source_dir / "CMakeLists.txt", bec)) { + effective_dep.builder = "cmake"; + } else if (std::filesystem::is_regular_file(mat.source_dir / "meson.build", + bec)) { + effective_dep.builder = "meson"; + } + } + if (effective_dep.builder == "cmake" || effective_dep.builder == "meson" || + effective_dep.builder == "conan") { + Provider::ProviderRequest preq{effective_dep, + mat, + ctx, + *tc, + build_root / ".vbs" / "providers", + Provider::ProviderMode::FullBuild, + {}}; + auto exp = Provider::resolve_foreign_provider(preq); + if (!exp) { + std::cerr << "vbs: " << exp.error().message() << '\n'; + return 1; + } + for (const auto &[k, v] : exp->targets) { + imported_targets[k] = v; + } + } + } + if (!pinned_lock->has_value()) { + auto pub_lock = Package::publish_lock_context_cas(lock_path, "", + resolved->lock_context, locked); + if (!pub_lock) { + std::cerr << "vbs: " << pub_lock.error().message() << '\n'; + return 1; + } + pinned_lock = *pub_lock; + } + } + + // Capture immutable snapshot. + std::vector scan_roots; + std::error_code ec; + for (const char *d : {"src", "source", "include", "tests"}) { + if (std::filesystem::is_directory(project_root / d, ec)) { + scan_roots.push_back(project_root / d); + } + } + Snapshot::SnapshotOptions sopts; + sopts.project_root = project_root; + sopts.snapshot_store_dir = build_root / ".vbs" / "snapshots"; + sopts.reproducibility_epoch = ctx.reproducibility_epoch; + auto snap = Snapshot::capture_snapshot(sopts, {}, scan_roots); + if (!snap) { + std::cerr << "vbs: " << snap.error().message() << '\n'; + return 1; + } + + Graph::GraphLowerOptions gopts{project_root, build_root, &(*snap), + std::move(imported_targets), 32768}; + auto graph = Graph::lower_project_graph(*desc, *tc, gopts); + if (!graph) { + std::cerr << "vbs: " << graph.error().message() << '\n'; + (void)Editor::mark_profile_stale( + build_root, prof_name, Editor::GenerationStatus::Invalid, graph.error().message()); + return 1; + } + + // Publish compdb BEFORE compilation (Plan 09: compile failure does NOT undo selection!). + Editor::PublishOptions popts; + popts.project_root = project_root; + popts.build_root = build_root; + popts.update_selection = (*editor_profile == prof_name); + popts.reserved_ticket = *reserved_ticket; + (void)Editor::publish_profile_compdb(*graph, popts); + + Execution::ExecutionOptions eopts; + eopts.jobs = jobs; + eopts.use_cache = !no_cache; + eopts.selected_targets = requested_targets; + auto rep = Execution::execute_graph(*graph, *state, eopts); + if (!rep) { + std::cerr << "vbs: " << rep.error().message() << '\n'; + return 1; + } + if (!rep->succeeded) { + for (const auto &ar : rep->results) { + if (!ar.succeeded) { + std::cerr << "vbs: action '" << ar.action_id << "' failed: " << ar.error_message + << '\n'; + if (!ar.stderr_data.empty()) { + std::cerr << ar.stderr_data << '\n'; + } + } + } + all_ok = false; + continue; + } + std::cout << "vbs: [" << prof_name << "] built (" << rep->executed_count << " executed, " + << rep->cached_count << " cached)\n"; + + if (run_tests) { + for (const auto &t : graph->targets) { + if (t.kind != TargetKind::Test || t.primary_outputs.empty()) { + continue; + } + if (!requested_targets.empty() && + !std::ranges::contains(requested_targets, t.name)) { + continue; + } + Platform::ProcessRequest treq; + treq.executable = t.primary_outputs.front(); + treq.working_directory = project_root; + auto tres = Platform::run_supervised(treq); + if (!tres || !tres->succeeded()) { + std::cerr << "vbs test: FAILED '" << t.name << "'\n"; + if (tres && !tres->stderr_data.empty()) { + std::cerr << tres->stderr_data << '\n'; + } + all_ok = false; + } else { + std::cout << "vbs test: PASSED '" << t.name << "'\n"; + } + } + } + } + + return all_ok ? 0 : 1; +} + +int run_compdb_command(int argc, char **argv) { + if (argc < 3) { + std::cerr << "vbs compdb: expected subcommand (use|show|export|watch)\n"; + return 2; + } + const std::string_view sub{argv[2]}; + if (sub == "--help" || sub == "-h") { + Void::Argparse::Parser hp{ + "vbs compdb ", + "Manage per-profile compile_commands.json selection and metadata projection."}; + std::cout << hp.help(); + return 0; + } + if (sub != "use" && sub != "show" && sub != "export" && sub != "watch") { + std::cerr << "vbs compdb: unknown subcommand '" << sub << "'\n"; + return 2; + } + + std::string project_arg = std::filesystem::current_path().string(); + std::optional build_arg; + std::optional profile_name; + Void::Argparse::Parser parser{"vbs compdb " + std::string{sub}, + "Manage per-profile compile_commands.json."}; + parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) + .option("--build-dir", "-B", "Build output directory", build_arg) + .option("--profile", "-p", "Profile name", profile_name); + + // Allow optional positional profile name for `vbs compdb use `. + std::vector sub_argv; + sub_argv.push_back(argv[0]); + for (int i = 3; i < argc; ++i) { + const std::string_view a{argv[i]}; + if (sub == "use" && !a.starts_with("-") && !profile_name && + (i == 3 || (std::string_view{argv[i - 1]} != "--project" && + std::string_view{argv[i - 1]} != "-C" && + std::string_view{argv[i - 1]} != "--build-dir" && + std::string_view{argv[i - 1]} != "-B" && + std::string_view{argv[i - 1]} != "--profile" && + std::string_view{argv[i - 1]} != "-p"))) { + profile_name = std::string{a}; + continue; + } + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs compdb " + std::string{sub}, sub_argv); + rc) { + return *rc; + } + + const std::filesystem::path project_root{project_arg}; + const std::filesystem::path build_root = + build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + + if (sub == "show") { + auto st = Editor::read_selection_state(project_root); + if (!st || !st->has_value()) { + std::cout << "no editor compilation database selected\n"; + return 0; + } + std::cout << "profile=" << (*st)->selected_profile + << " generation=" << (*st)->selected_generation_id << " ticket=" << (*st)->ticket + << " path=" << (*st)->selected_compdb_path.string() << '\n'; + return 0; + } + if (sub == "use") { + if (!profile_name) { + std::cerr << "vbs compdb use: profile name required\n"; + return 2; + } + auto st = Editor::select_editor_profile(project_root, build_root, *profile_name); + if (!st) { + std::cerr << "vbs compdb use: " << st.error().message() << '\n'; + return 1; + } + std::cout << "selected editor profile '" << st->selected_profile << "' (" + << st->selected_compdb_path.string() << ")\n"; + return 0; + } + + Watch::WatchLoopOptions wopts; + wopts.mode = Watch::WatchMode::MetadataOnly; + wopts.frontend = make_frontend_opts(project_root, build_root, {}); + wopts.explicit_profile = profile_name; + if (sub == "export") { + auto rep = Watch::run_reconcile_cycle(wopts, 0, false, std::nullopt); + if (!rep.compdb_published) { + std::cerr << "vbs compdb export: " << rep.diagnostic << '\n'; + return 1; + } + std::cout << "exported compile_commands.json for profile '" << rep.profile_name << "'\n"; + return 0; + } + std::stop_source stop_src; + auto sig = Void::Process::SignalWatcher::create(); + std::jthread sig_thread([&] { + if (sig) { + (void)sig->wait(); + stop_src.request_stop(); + } + }); + auto res = Watch::run_watch_loop(wopts, stop_src.get_token()); + return res ? 0 : 1; +} + +int run_describe_command(int argc, char **argv) { + std::string project_arg = std::filesystem::current_path().string(); + std::optional build_arg; + std::string profile_name = "debug"; + std::optional compiler_arg; + + Void::Argparse::Parser parser{"vbs describe", + "Evaluate build.cpp for one profile and emit graph summary."}; + parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) + .option("--build-dir", "-B", "Build output directory", build_arg) + .option_default("--profile", "-p", "Profile name", profile_name, "debug") + .option("--compiler", "", "Override compiler family (gcc|clang)", compiler_arg); + + std::vector sub_argv{argv[0]}; + for (int i = 2; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs describe", sub_argv); rc) { + return *rc; + } + + std::optional compiler_override; + if (compiler_arg) { + try { + compiler_override = parse_compiler(*compiler_arg); + } catch (const std::exception &ex) { + std::cerr << "vbs describe: " << ex.what() << '\n'; + return 2; + } + } + + const std::filesystem::path project_root{project_arg}; + const std::filesystem::path build_root = + build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + const auto fopts = make_frontend_opts(project_root, build_root, {}); + auto compiled = Config::compile_descriptor(fopts); + if (!compiled) { + std::cerr << "vbs describe: " << compiled.error().message() << '\n'; + return 1; + } + auto profs = Config::discover_profiles(*compiled, fopts); + if (!profs) { + std::cerr << "vbs describe: " << profs.error().message() << '\n'; + return 1; + } + try { + auto ctx = profs->resolve(profile_name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto desc = Config::evaluate_project(*compiled, ctx, fopts); + if (!desc) { + std::cerr << "vbs describe: " << desc.error().message() << '\n'; + return 1; + } + std::cout << "{\"profile\":" << Util::json_quote(desc->profile.name) + << ",\"targets\":" << desc->targets.size() + << ",\"dependencies\":" << desc->dependencies.size() << "}\n"; + return 0; + } catch (const std::exception &ex) { + std::cerr << "vbs describe: " << ex.what() << '\n'; + return 2; + } +} + +int run_watch_command(int argc, char **argv) { + std::string project_arg = std::filesystem::current_path().string(); + std::optional build_arg; + std::optional profile_arg; + std::optional target_doc; + + Void::Argparse::Parser parser{"vbs watch", + "Watch project sources and rebuild on verified changes."}; + parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) + .option("--build-dir", "-B", "Build output directory", build_arg) + .option("--profile", "-p", "Profile to watch", profile_arg) + .option("--target", "-t", "Target to rebuild (repeatable)", target_doc); + + std::vector targets; + std::vector remaining; + if (auto rc = extract_repeatable_args(2, argc, argv, "vbs watch", + {{"--target", "-t", &targets}}, remaining); + rc) { + return *rc; + } + if (auto rc = parse_with_void_argparse(parser, "vbs watch", remaining); rc) { + return *rc; + } + + const std::filesystem::path project_root{project_arg}; + const std::filesystem::path build_root = + build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + Watch::WatchLoopOptions wopts; + wopts.mode = Watch::WatchMode::FullBuild; + wopts.frontend = make_frontend_opts(project_root, build_root, {}); + wopts.explicit_profile = profile_arg; + wopts.selected_targets = std::move(targets); + + std::stop_source stop_src; + auto sig = Void::Process::SignalWatcher::create(); + std::jthread sig_thread([&] { + if (sig) { + (void)sig->wait(); + stop_src.request_stop(); + } + }); + auto res = Watch::run_watch_loop(wopts, stop_src.get_token()); + return res ? 0 : 1; +} + +int run_bridge_command(int argc, char **argv) { + std::optional req_arg; + std::optional out_arg; + Void::Argparse::Parser parser{"vbs bridge", "CMake VbsDeps.cmake dependency bridge backend."}; + parser.option("--request", "", "Path to bridge request JSON", req_arg) + .option("--output", "", "Path to output CMake fragment", out_arg); + + std::vector sub_argv{argv[0]}; + for (int i = 2; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs bridge", sub_argv); rc) { + return *rc; + } + if (!req_arg || !out_arg) { + std::cerr << "vbs bridge: --request and --output are required\n"; + return 2; + } + auto r = Bridge::execute_cmake_bridge(*req_arg, *out_arg); + if (!r) { + std::cerr << "vbs bridge: " << r.error().message() << '\n'; + return 1; + } + return 0; +} + +int run_pack_command(int argc, char **argv) { + std::string project_arg = std::filesystem::current_path().string(); + std::string out_arg = "package.tar"; + Void::Argparse::Parser parser{"vbs pack", "Create a deterministic USTAR source archive."}; + parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) + .option_default("--output", "-o", "Output archive path", out_arg, "package.tar"); + + std::vector sub_argv{argv[0]}; + for (int i = 2; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs pack", sub_argv); rc) { + return *rc; + } + auto sha = Package::create_source_package(project_arg, out_arg, 0); + if (!sha) { + std::cerr << "vbs pack: " << sha.error().message() << '\n'; + return 1; + } + std::cout << "packed " << out_arg << " sha256=" << *sha << '\n'; + return 0; +} + +int run_publish_command(int argc, char **argv) { + std::string project_arg = std::filesystem::current_path().string(); + std::optional registry_arg; + std::optional name_arg; + std::optional version_arg; + std::string description; + std::string token_env = "VBS_REGISTRY_TOKEN"; + bool is_private = false; + + Void::Argparse::Parser parser{ + "vbs publish", "Pack a deterministic source archive and publish it to a VBS registry."}; + parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) + .option("--registry", "-r", "Registry base URL (or VBS_REGISTRY_URL)", registry_arg) + .option("--name", "-n", "Package name", name_arg) + .option("--version", "-v", "Strict SemVer release version", version_arg) + .option_default("--description", "-d", "Package description", description, "") + .option_default("--token-env", "", "Environment variable holding bearer token", token_env, + "VBS_REGISTRY_TOKEN") + .flag("--private", "", "Publish package as private", is_private); + + std::vector sub_argv{argv[0]}; + for (int i = 2; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs publish", sub_argv); rc) { + return *rc; + } + + const std::string registry_url = + registry_arg ? *registry_arg : Void::Configuration::get_env_or("VBS_REGISTRY_URL", ""); + if (registry_url.empty() || !name_arg || !version_arg) { + std::cerr << "vbs publish: --registry, --name, and --version are required\n"; + return 2; + } + + Void::FileSystem::TempDir tmp{"vbs_publish_"}; + const auto tar_path = tmp / (*name_arg + "-" + *version_arg + ".tar"); + auto sha = Package::create_source_package(project_arg, tar_path, 0); + if (!sha) { + std::cerr << "vbs publish: " << sha.error().message() << '\n'; + return 1; + } + + Package::PublishOptions popts; + popts.registry_url = registry_url; + popts.package_name = *name_arg; + popts.version = *version_arg; + popts.archive_path = tar_path; + popts.description = description; + popts.is_private = is_private; + popts.auth.bearer_token = Void::Configuration::get_env_or(token_env, ""); + + auto receipt = Package::publish_package_archive(popts); + if (!receipt) { + std::cerr << "vbs publish: " << receipt.error().message() << '\n'; + return 1; + } + std::cout << (receipt->already_published ? "already published " : "published ") << *name_arg + << "@" << *version_arg << " sha256=" << receipt->sha256 << '\n'; + return 0; +} + +int run_install_command(int argc, char **argv) { + std::string project_arg = std::filesystem::current_path().string(); + std::optional build_arg; + std::string profile_name = "debug"; + std::optional compiler_arg; + std::optional prefix_arg; + std::optional pkg_name_arg; + std::string pkg_ver = "0.1.0"; + std::optional component_arg; + bool no_cmake_export = false; + bool no_native_export = false; + + Void::Argparse::Parser parser{ + "vbs install", "Build, stage, and install declared products and package exports."}; + parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) + .option("--build-dir", "-B", "Build output directory", build_arg) + .option_default("--profile", "-p", "Profile name", profile_name, "debug") + .option("--compiler", "", "Override compiler family (gcc|clang)", compiler_arg) + .option("--prefix", "", "Install destination prefix (required)", prefix_arg) + .option("--package-name", "", "Exported package name", pkg_name_arg) + .option_default("--package-version", "", "Exported package version", pkg_ver, "0.1.0") + .option("--component", "", "Install only a specific component", component_arg) + .flag("--no-cmake-export", "", "Disable CMake Config.cmake export", no_cmake_export) + .flag("--no-native-export", "", "Disable native VBS package metadata export", + no_native_export); + + std::vector sub_argv{argv[0]}; + for (int i = 2; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs install", sub_argv); rc) { + return *rc; + } + if (!prefix_arg || prefix_arg->empty()) { + std::cerr << "vbs install: --prefix is required\n"; + return 2; + } + + std::optional compiler_override; + if (compiler_arg) { + try { + compiler_override = parse_compiler(*compiler_arg); + } catch (const std::exception &ex) { + std::cerr << "vbs install: " << ex.what() << '\n'; + return 2; + } + } + + const std::filesystem::path project_root{project_arg}; + const std::filesystem::path build_root = + build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + + Install::InstallOptions iopts; + iopts.prefix = *prefix_arg; + iopts.package_version = pkg_ver; + iopts.component = component_arg; + iopts.export_cmake_config = !no_cmake_export; + iopts.export_native_metadata = !no_native_export; + + std::error_code ec; + if (pkg_name_arg && !pkg_name_arg->empty()) { + iopts.package_name = *pkg_name_arg; + } else { + const auto canon = std::filesystem::weakly_canonical(project_root, ec); + iopts.package_name = canon.filename().string(); + if (iopts.package_name.empty()) { + iopts.package_name = "package"; + } + } + + const auto fopts = make_frontend_opts(project_root, build_root, {}); + auto compiled = Config::compile_descriptor(fopts); + if (!compiled) { + std::cerr << "vbs install: " << compiled.error().message() << '\n'; + return 1; + } + auto profs = Config::discover_profiles(*compiled, fopts); + if (!profs) { + std::cerr << "vbs install: " << profs.error().message() << '\n'; + return 1; + } + ProfileContext ctx; + try { + ctx = profs->resolve(profile_name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + } catch (const std::exception &ex) { + std::cerr << "vbs install: " << ex.what() << '\n'; + return 2; + } + auto tc = Toolchain::discover_and_probe(ctx, build_root / ".vbs" / "probes"); + if (!tc) { + std::cerr << "vbs install: " << tc.error().message() << '\n'; + return 1; + } + auto desc = Config::evaluate_project(*compiled, ctx, fopts); + if (!desc) { + std::cerr << "vbs install: " << desc.error().message() << '\n'; + return 1; + } + + std::vector scan_roots; + for (const char *d : {"src", "source", "include", "tests"}) { + if (std::filesystem::is_directory(project_root / d, ec)) { + scan_roots.push_back(project_root / d); + } + } + Snapshot::SnapshotOptions sopts; + sopts.project_root = project_root; + sopts.snapshot_store_dir = build_root / ".vbs" / "snapshots"; + sopts.reproducibility_epoch = ctx.reproducibility_epoch; + auto snap = Snapshot::capture_snapshot(sopts, {}, scan_roots); + if (!snap) { + std::cerr << "vbs install: " << snap.error().message() << '\n'; + return 1; + } + auto graph = + Graph::lower_project_graph(*desc, *tc, {project_root, build_root, &(*snap), {}, 32768}); + if (!graph) { + std::cerr << "vbs install: " << graph.error().message() << '\n'; + return 1; + } + auto state = State::StateStore::open(build_root / ".vbs"); + if (!state) { + std::cerr << "vbs install: " << state.error().message() << '\n'; + return 1; + } + auto exec = Execution::execute_graph(*graph, *state); + if (!exec || !exec->succeeded) { + std::cerr << "vbs install: build failed before staging\n"; + if (!exec) { + std::cerr << exec.error().message() << '\n'; + } + return 1; + } + auto inst = Install::install_project(*desc, *graph, iopts); + if (!inst) { + std::cerr << "vbs install: " << inst.error().message() << '\n'; + return 1; + } + std::cout << "installed " << inst->installed_files.size() << " files to " + << inst->prefix.string() << " (manifest=" << inst->manifest_path.string() << ")\n"; + return 0; +} + +int run_uninstall_command(int argc, char **argv) { + std::optional prefix_arg; + Void::Argparse::Parser parser{"vbs uninstall", + "Safely remove only VBS-owned files recorded in the manifest."}; + parser.option("--prefix", "", "Installed prefix directory (required)", prefix_arg); + + std::vector sub_argv{argv[0]}; + for (int i = 2; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs uninstall", sub_argv); rc) { + return *rc; + } + if (!prefix_arg || prefix_arg->empty()) { + std::cerr << "vbs uninstall: --prefix is required\n"; + return 2; + } + auto removed = Install::uninstall_prefix(*prefix_arg); + if (!removed) { + std::cerr << "vbs uninstall: " << removed.error().message() << '\n'; + return 1; + } + std::cout << "uninstalled " << *removed << " VBS-owned files from " << *prefix_arg << '\n'; + return 0; +} + +int run_gc_command(int argc, char **argv) { + std::string build_arg = (std::filesystem::current_path() / "build").string(); + std::string max_bytes_arg = "0"; + Void::Argparse::Parser parser{"vbs gc", + "Recover interrupted state and garbage-collect CAS blobs."}; + parser.option_default("--build-dir", "-B", "Build directory", build_arg, build_arg) + .option_default("--max-bytes", "", + "Target maximum retained CAS bytes (0=unreferenced only)", max_bytes_arg, + "0"); + + std::vector sub_argv{argv[0]}; + for (int i = 2; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs gc", sub_argv); rc) { + return *rc; + } + std::uint64_t max_bytes = 0; + const auto [ptr, ec] = std::from_chars(max_bytes_arg.data(), + max_bytes_arg.data() + max_bytes_arg.size(), max_bytes); + if (ec != std::errc{} || ptr != max_bytes_arg.data() + max_bytes_arg.size()) { + std::cerr << "vbs gc: invalid --max-bytes value '" << max_bytes_arg << "'\n"; + return 2; + } + auto st = State::StateStore::open(std::filesystem::path{build_arg} / ".vbs"); + if (!st) { + std::cerr << "vbs gc: " << st.error().message() << '\n'; + return 1; + } + auto stats = st->gc(max_bytes); + if (!stats) { + std::cerr << "vbs gc: " << stats.error().message() << '\n'; + return 1; + } + std::cout << "gc complete: removed=" << stats->removed_blobs + << " freed_bytes=" << stats->freed_bytes << " retained=" << stats->retained_blobs + << '\n'; + return 0; +} + +int run_gen_tests_command(int argc, char **argv) { + std::optional input_arg; + std::optional out_arg; + Void::Argparse::Parser parser{"vbs gen-tests", + "Generate native Void::Testing registration unit (no CMake)."}; + parser.option("--input", "", "Input test .cpp file", input_arg) + .option("--output-dir", "", "Output directory for generated registration .cpp", out_arg); + + std::vector sub_argv{argv[0]}; + for (int i = 2; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs gen-tests", sub_argv); rc) { + return *rc; + } + if (!input_arg || !out_arg) { + std::cerr << "vbs gen-tests: --input and --output-dir are required\n"; + return 2; + } + auto gen = SelfHost::generate_test_registration_unit(*input_arg, *out_arg); + if (!gen) { + std::cerr << "vbs gen-tests: " << gen.error().message() << '\n'; + return 1; + } + std::cout << gen->generated_cpp.string() << " (" << gen->cases.size() << " tests)\n"; + return 0; +} + +int run_deps_command(int argc, char **argv) { + if (argc < 3) { + std::cerr << "vbs deps: expected 'resolve' or 'update'\n"; + return 2; + } + const std::string_view sub{argv[2]}; + if (sub == "--help" || sub == "-h") { + Void::Argparse::Parser hp{ + "vbs deps ", + "Resolve or upgrade dependencies and atomically update vbs.lock."}; + std::cout << hp.help(); + return 0; + } + if (sub != "resolve" && sub != "update") { + std::cerr << "vbs deps: unknown subcommand '" << sub << "'\n"; + return 2; + } + + std::string project_arg = std::filesystem::current_path().string(); + std::optional build_arg; + std::string profile_name = "debug"; + bool offline = false; + + Void::Argparse::Parser parser{ + "vbs deps " + std::string{sub}, + sub == "update" ? "Re-solve dependencies allowing compatible SemVer upgrades." + : "Resolve dependencies preserving pinned compatible versions."}; + parser.option_default("--project", "-C", "Project directory", project_arg, project_arg) + .option("--build-dir", "-B", "Build output directory", build_arg) + .option_default("--profile", "-p", "Profile name", profile_name, "debug") + .flag("--offline", "", "Disallow network fetches", offline); + + std::vector sub_argv{argv[0]}; + for (int i = 3; i < argc; ++i) { + sub_argv.push_back(argv[i]); + } + if (auto rc = parse_with_void_argparse(parser, "vbs deps " + std::string{sub}, sub_argv); rc) { + return *rc; + } + + const std::filesystem::path project_root{project_arg}; + const std::filesystem::path build_root = + build_arg ? std::filesystem::path{*build_arg} : (project_root / "build"); + const auto fopts = make_frontend_opts(project_root, build_root, {}); + auto compiled = Config::compile_descriptor(fopts); + if (!compiled) { + std::cerr << "vbs deps: " << compiled.error().message() << '\n'; + return 1; + } + auto profs = Config::discover_profiles(*compiled, fopts); + if (!profs) { + std::cerr << "vbs deps: " << profs.error().message() << '\n'; + return 1; + } + auto ctx = profs->resolve(profile_name, std::nullopt, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto desc = Config::evaluate_project(*compiled, ctx, fopts); + if (!desc) { + std::cerr << "vbs deps: " << desc.error().message() << '\n'; + return 1; + } + std::vector toml_deps; + for (const auto &df : desc->dependency_files) { + auto loaded = Package::load_dependencies_toml(project_root / df); + if (!loaded) { + std::cerr << "vbs deps: " << loaded.error().message() << '\n'; + return 1; + } + toml_deps.insert(toml_deps.end(), loaded->begin(), loaded->end()); + } + auto merged = Package::merge_dependencies(desc->dependencies, toml_deps); + if (!merged) { + std::cerr << "vbs deps: " << merged.error().message() << '\n'; + return 1; + } + + const auto lock_path = project_root / "vbs.lock"; + auto existing = Package::load_pinned_lock(lock_path); + if (!existing) { + std::cerr << "vbs deps: " << existing.error().message() << '\n'; + return 1; + } + const std::string base_rev = existing->has_value() ? (*existing)->revision_hash : std::string{}; + + auto resolved = resolve_and_materialize_deps(ctx, *merged, project_root, build_root, *existing, + offline, sub == "update"); + if (!resolved) { + std::cerr << "vbs deps: " << resolved.error().message() << '\n'; + return 1; + } + auto pub = + Package::publish_lock_context_cas(lock_path, base_rev, resolved->lock_context, false); + if (!pub) { + std::cerr << "vbs deps: " << pub.error().message() << '\n'; + return 1; + } + std::cout << "updated vbs.lock revision=" << pub->revision_hash.substr(0, 12) << '\n'; + return 0; +} + +} // namespace + +int main(int argc, char **argv) { + bool show_version = false; + auto root_parser = make_root_parser(show_version); + if (argc == 1) { + std::cout << root_parser.help(); + return 0; + } + const std::string_view cmd{argv[1]}; + if (cmd == "--help" || cmd == "-h") { + if (argc > 2) { + std::cerr << "vbs: --help must be used alone\n"; + return 2; + } + std::cout << root_parser.help(); + return 0; + } + if (cmd == "--version" || cmd == "-V") { + if (argc > 2) { + std::cerr << "vbs: unexpected argument after --version\n"; + return 2; + } + std::cout << "vbs " << Bootstrap::version << '\n'; + return 0; + } + if (cmd == "build") { + return run_build_or_test(argc, argv, false); + } + if (cmd == "test") { + return run_build_or_test(argc, argv, true); + } + if (cmd == "compdb") { + return run_compdb_command(argc, argv); + } + if (cmd == "describe") { + return run_describe_command(argc, argv); + } + if (cmd == "watch") { + return run_watch_command(argc, argv); + } + if (cmd == "bridge") { + return run_bridge_command(argc, argv); + } + if (cmd == "pack") { + return run_pack_command(argc, argv); + } + if (cmd == "publish") { + return run_publish_command(argc, argv); + } + if (cmd == "install") { + return run_install_command(argc, argv); + } + if (cmd == "uninstall") { + return run_uninstall_command(argc, argv); + } + if (cmd == "gc") { + return run_gc_command(argc, argv); + } + if (cmd == "gen-tests") { + return run_gen_tests_command(argc, argv); + } + if (cmd == "deps") { + return run_deps_command(argc, argv); + } + + std::cerr << "vbs: unknown command '" << cmd << "'; use --help\n"; + return 2; +} diff --git a/src/Modules/ModuleScanner.cpp b/src/Modules/ModuleScanner.cpp new file mode 100644 index 0000000..2042004 --- /dev/null +++ b/src/Modules/ModuleScanner.cpp @@ -0,0 +1,428 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +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(&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 +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(&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(&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(&rules_v->value); + rules && !rules->empty()) { + if (const auto *r0 = std::get_if(&rules->front().value)) { + if (const auto *prov_v = find_key(*r0, "provides")) { + if (const auto *parr = std::get_if(&prov_v->value)) { + for (const auto &pv : *parr) { + if (const auto *po = std::get_if(&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(&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(&req_v->value)) { + for (const auto &rv : *rarr) { + if (const auto *ro = std::get_if(&rv.value)) { + const auto name = get_str(*ro, "logical-name"); + if (!name.empty()) { + unit.required_modules.push_back(name); + } + } + } + } + } + } + } + } + return unit; +} + +Void::Result::Result +scan_translation_unit(const Toolchain::ToolchainCapabilities &toolchain, + const std::filesystem::path &source_file, + const std::filesystem::path &scratch_dir, + const std::vector> &include_dirs, + const std::vector &defines, + const std::vector &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 +collate_modules(const std::vector &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> 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> 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 +lower_header_unit_command(const Toolchain::ToolchainCapabilities &toolchain, + const std::filesystem::path &header_path, + const std::filesystem::path &bmi_output, + const std::vector> &include_dirs, + const std::vector &defines, + const std::vector &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 +generate_unity_batches(const std::string &target_name, + const std::vector &sources, + const std::vector &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 excluded; + for (const auto &ex : excluded_sources) { + excluded.insert(ex.lexically_normal()); + } + + std::vector 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 diff --git a/src/Package/Archive.cpp b/src/Package/Archive.cpp new file mode 100644 index 0000000..9dbe230 --- /dev/null +++ b/src/Package/Archive.cpp @@ -0,0 +1,581 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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('0' + (val & 7u)); + val >>= 3; + } +} + +std::optional 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(src[i] - '0'); + } + return any ? std::optional{val} : std::optional{0}; +} + +void finalize_tar_header(std::array &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(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(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(c); + } + write_octal(hdr.data() + 148, 7, chksum); + hdr[155] = ' '; +} + +std::string build_pax_path_record(std::string_view path) { + // Format: " 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(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(n); + } + return true; +} + +bool read_exact(int fd, void *data, std::size_t len, std::size_t &got_out) { + auto *p = static_cast(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(n); + } + return true; +} + +bool is_zero_block(const std::array &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 +create_deterministic_tar(const std::filesystem::path &output_tar, + std::vector 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 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(::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{static_cast(buf), n}); + return write_all(fd, buf, n); + }; + + std::array zero_pad{}; + std::array hdr{}; + std::array 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::min(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((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 +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 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 +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(::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 seen_paths; + std::optional next_pax_path; + std::array hdr{}; + std::array 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(' ') + : static_cast(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(*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(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((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(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::min(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((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 diff --git a/src/Package/Fetch.cpp b/src/Package/Fetch.cpp new file mode 100644 index 0000000..6f4941a --- /dev/null +++ b/src/Package/Fetch.cpp @@ -0,0 +1,365 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +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://@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, ""); + 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, ""); + 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 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 +select_compatible_binary(const BinaryCompatibilityKey &key, + const std::vector &available) { + for (const auto &v : available) { + if (key.matches(v)) { + return v; + } + } + return std::nullopt; +} + +Void::Result::Result +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 args, + std::optional cwd = + std::nullopt) -> Void::Result::Result { + 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 diff --git a/src/Package/Lockfile.cpp b/src/Package/Lockfile.cpp new file mode 100644 index 0000000..68d0da3 --- /dev/null +++ b/src/Package/Lockfile.cpp @@ -0,0 +1,389 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +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(&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(&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(&v->value); + return b ? *b : def; +} + +std::vector get_str_array(const JsonVal::Object &obj, const std::string &k) { + std::vector out; + const auto *v = find_key(obj, k); + if (!v) { + return out; + } + if (const auto *arr = std::get_if(&v->value)) { + for (const auto &item : *arr) { + if (const auto *s = std::get_if(&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> &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 &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 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(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; + if constexpr (std::same_as) { + h.update_length_prefixed("s:" + v); + } else if constexpr (std::same_as) { + 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 +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(&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(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(&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(&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(&ev->value)) { + for (const auto &item : *earr) { + if (const auto *eo = std::get_if(&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, 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 +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 +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 diff --git a/src/Package/RegistryClient.cpp b/src/Package/RegistryClient.cpp new file mode 100644 index 0000000..d0dae90 --- /dev/null +++ b/src/Package/RegistryClient.cpp @@ -0,0 +1,420 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 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(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> 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(n); + } + return true; +} + +Void::Result::Result +send_http_request(const ParsedHttpUrl &parsed, std::string_view method, std::string_view path, + const std::map> &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 buf{}; + for (;;) { + const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0); + if (n > 0) { + raw.append(buf.data(), static_cast(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(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(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(&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(&it->second.value); + return b ? *b : def; +} + +} // namespace + +Void::Result::Result, 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> 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(&json->value); + if (!root) { + return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, + "registry response root must be a JSON object")}; + } + + std::vector releases; + const auto rit = root->find("releases"); + if (rit != root->end()) { + if (const auto *rarr = std::get_if(&rit->second.value)) { + for (const auto &rv : *rarr) { + const auto *ro = std::get_if(&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 +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> 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 +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> 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 diff --git a/src/Package/Solver.cpp b/src/Package/Solver.cpp new file mode 100644 index 0000000..8a22d52 --- /dev/null +++ b/src/Package/Solver.cpp @@ -0,0 +1,342 @@ +#include + +#include +#include + +#include +#include +#include +#include + +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 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 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 + solve(const std::vector &roots) { + std::map> 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 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(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 &list) const { + for (const auto &c : list) { + if (!c.range.contains(v)) { + return false; + } + } + return true; + } + + std::vector ordered_candidates(const PackageId &id, + const std::vector &list) const { + auto all = index_.releases_for(id); + std::vector 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 &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> &constraints, + std::map &chosen) { + if (++steps_ > options_.max_steps) { + return false; + } + + // Unit propagation / fail-fast check: choose undecided package with fewest candidates! + std::optional next_pkg; + std::vector best_candidates; + std::size_t min_count = std::numeric_limits::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 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 PackageIndex::releases_for(const PackageId &id) const { + const auto it = releases_.find(id); + if (it == releases_.end()) { + return {}; + } + return it->second; +} + +Void::Result::Result +solve_dependencies(const std::vector &root_constraints, + const PackageIndex &index, const SolveOptions &options) { + PubGrubSolver solver{index, options}; + return solver.solve(root_constraints); +} + +} // namespace Void::Build::Package diff --git a/src/Package/Toml.cpp b/src/Package/Toml.cpp new file mode 100644 index 0000000..3e7170c --- /dev/null +++ b/src/Package/Toml.cpp @@ -0,0 +1,949 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 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 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 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 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 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, Void::Result::Error> parse_key_path() { + std::vector 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 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 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 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 + navigate_table_header(TomlTable &root, const std::vector &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 + insert_key_value(TomlTable &table, const std::vector &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 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() ? "" : file; + } + return std::format("{}:{}:{}", file, line, column); +} + +TomlValue TomlValue::make_table(SourceOrigin origin) { + return TomlValue{std::make_shared(), std::move(origin)}; +} + +TomlValue TomlValue::make_array(SourceOrigin origin) { + return TomlValue{std::make_shared(), std::move(origin)}; +} + +Void::Result::Result parse_toml(std::string_view text, + std::string_view source_name) { + TomlParser parser{text, std::string{source_name}}; + return parser.parse(); +} + +Void::Result::Result +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, 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 out; + auto parse_dep_section = + [&](const std::string §ion_key, + bool is_build_dep) -> Void::Result::Result { + 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 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(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, Void::Result::Error> +merge_dependencies(const std::vector &cpp_deps, + const std::vector &toml_deps) { + std::map> 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 out; + out.reserve(merged.size()); + for (auto &[k, v] : merged) { + out.push_back(std::move(v)); + } + return out; +} + +} // namespace Void::Build::Package diff --git a/src/Platform/FileOps.cpp b/src/Platform/FileOps.cpp new file mode 100644 index 0000000..94a739f --- /dev/null +++ b/src/Platform/FileOps.cpp @@ -0,0 +1,444 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Platform { +namespace { + +std::atomic 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(::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::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 +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(st.st_dev); + meta.ino = static_cast(st.st_ino); + meta.size = static_cast(st.st_size); + meta.nlink = static_cast(st.st_nlink); + meta.mode = static_cast(st.st_mode & 07777u); + meta.mtime_sec = static_cast(st.st_mtim.tv_sec); + meta.mtime_nsec = static_cast(st.st_mtim.tv_nsec); + + if (meta.is_symlink) { + std::size_t buf_size = + st.st_size > 0 ? static_cast(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(n) < target.size()) { + target.resize(static_cast(n)); + meta.symlink_target = std::move(target); + break; + } + buf_size *= 2; + } + } + return meta; +} + +Void::Result::Result +copy_isolated(const std::filesystem::path &src, const std::filesystem::path &dst, + std::optional 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(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)); + 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 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(n)) { + const ssize_t w = + ::write(dst_fd, buf.data() + off, static_cast(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(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)); + 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 +set_canonical_mtime(const std::filesystem::path &path, std::int64_t epoch_seconds) { + struct timespec times[2]; + times[0].tv_sec = static_cast(epoch_seconds); + times[0].tv_nsec = 0; + times[1].tv_sec = static_cast(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 +atomic_write_bytes(const std::filesystem::path &path, std::span 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 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{content.data(), content.size()}), + durable_sync, mode); +} + +Void::Result::Result +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 +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 +resolve_confined_path(const std::filesystem::path &root, const std::filesystem::path &candidate, + const std::vector &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 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 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 diff --git a/src/Platform/ProcessSupervisor.cpp b/src/Platform/ProcessSupervisor.cpp new file mode 100644 index 0000000..c8cde1d --- /dev/null +++ b/src/Platform/ProcessSupervisor.cpp @@ -0,0 +1,530 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 build_env_strings(const ProcessEnvironment &policy) { + std::map> 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 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 +resolve_executable(const std::filesystem::path &executable, + std::optional 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 +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 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 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 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 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(sizeof(exec_pkt))) { + const ssize_t n = ::read(exec_err_fd, reinterpret_cast(&exec_pkt) + exec_read, + sizeof(exec_pkt) - static_cast(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(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 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( + deadline - std::chrono::steady_clock::now()); + poll_ms = static_cast(std::clamp(rem.count(), 1, 25)); + } + + const int ready = ::poll(fds, static_cast(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(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 &cb) { + for (;;) { + const ssize_t n = ::read(fd, buf.data(), buf.size()); + if (n > 0) { + const std::string_view chunk{buf.data(), static_cast(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 diff --git a/src/Provider/Provider.cpp b/src/Provider/Provider.cpp new file mode 100644 index 0000000..2b640ff --- /dev/null +++ b/src/Provider/Provider.cpp @@ -0,0 +1,773 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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(&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(&v->value); + return b ? *b : def; +} + +std::vector get_str_array(const JsonVal::Object &obj, const std::string &k) { + std::vector out; + const auto *v = find_key(obj, k); + if (!v) { + return out; + } + if (const auto *arr = std::get_if(&v->value)) { + for (const auto &item : *arr) { + if (const auto *s = std::get_if(&item.value)) { + out.push_back(*s); + } + } + } + return out; +} + +std::optional 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 &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 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(&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(&tv->value)) { + for (const auto &[k, val] : *tobj) { + const auto *io = std::get_if(&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(&iv->value)) { + for (const auto &item : *iarr) { + if (const auto *inc = std::get_if(&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; + if constexpr (std::same_as) { + return inner; + } else if constexpr (std::same_as) { + 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; + if constexpr (std::same_as) { + return inner; + } else if constexpr (std::same_as) { + 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 +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(&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(&objs->value)) { + for (const auto &item : *arr) { + if (const auto *o = std::get_if(&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 dep_ids; + Graph::ImportedTargetInterface iface; + }; + std::map> raw_by_id; + + if (const auto *cm_obj = std::get_if(&cm_json->value)) { + if (const auto *cfgs = find_key(*cm_obj, "configurations")) { + if (const auto *carr = std::get_if(&cfgs->value); + carr && !carr->empty()) { + if (const auto *cfg0 = std::get_if(&carr->front().value)) { + if (const auto *tgts = find_key(*cfg0, "targets")) { + if (const auto *tarr = std::get_if(&tgts->value)) { + for (const auto &tv : *tarr) { + const auto *to = std::get_if(&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(&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(&arts->value)) { + for (const auto &av : *aarr) { + if (const auto *ao = + std::get_if(&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(&cgs->value)) { + for (const auto &cgv : *cgarr) { + const auto *cgo = + std::get_if(&cgv.value); + if (!cgo) { + continue; + } + if (const auto *incs = find_key(*cgo, "includes")) { + if (const auto *iarr = + std::get_if(&incs->value)) { + for (const auto &iv : *iarr) { + if (const auto *io = + std::get_if( + &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(&defs->value)) { + for (const auto &dv : *darr) { + if (const auto *do_obj = + std::get_if( + &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(&deps->value)) { + for (const auto &dv : *darr) { + if (const auto *do_obj = + std::get_if(&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 visited{id}; + std::vector 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 +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(&parsed->value)) { + for (const auto &tv : *arr) { + const auto *to = std::get_if(&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(&ts->value)) { + for (const auto &tsv : *tsarr) { + if (const auto *tso = std::get_if(&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 +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 +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 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 diff --git a/src/SelfHost/TestRegistryGen.cpp b/src/SelfHost/TestRegistryGen.cpp new file mode 100644 index 0000000..91f313f --- /dev/null +++ b/src/SelfHost/TestRegistryGen.cpp @@ -0,0 +1,89 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include + +namespace Void::Build::SelfHost { + +Void::Result::Result, 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 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 +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 \n" + "#include \n" + "#include \n" + "#include \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{{}}, 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 diff --git a/src/Snapshot/Snapshot.cpp b/src/Snapshot/Snapshot.cpp new file mode 100644 index 0000000..9c472f1 --- /dev/null +++ b/src/Snapshot/Snapshot.cpp @@ -0,0 +1,661 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 &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 &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, Void::Result::Error> +read_sorted_dir_entries(const std::filesystem::path &dir_path, + const std::vector &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 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(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(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(guard.matched_root_index + 1)); + hasher.update_length_prefixed(guard.matched_sha256); + } + return hasher.finalize_hex(); +} + +Void::Result::Result +evaluate_one_guard(const std::filesystem::path &project_root, + const std::vector &allowed_external_roots, + const std::vector &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(i); + guard.matched_sha256 = std::move(*digest); + return guard; + } + } + return guard; +} + +} // namespace + +Void::Result::Result capture_snapshot( + const SnapshotOptions &options, const std::vector &explicit_files, + const std::vector &directory_roots, + const std::vector, 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> source_files_to_verify; + std::map> dirs_to_verify; + + auto capture_single_file = [&](const std::filesystem::path &raw_path) + -> Void::Result::Result { + 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( + const std::filesystem::path &, std::set> &)> + walk_dir; + walk_dir = [&](const std::filesystem::path &dir_path, + std::set> &visited_dirs) + -> Void::Result::Result { + 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> 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(::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 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 +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 +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 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 diff --git a/src/State/StateStore.cpp b/src/State/StateStore.cpp new file mode 100644 index 0000000..5b4eebf --- /dev/null +++ b/src/State/StateStore.cpp @@ -0,0 +1,750 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::State { +namespace { + +std::atomic 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 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(&v->value); + return s ? std::optional{*s} : std::nullopt; +} + +std::optional 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(&v->value); + return i ? std::optional{*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::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::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(&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(*version); + snap.next_sequence = + static_cast(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(&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(&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(&outs->value)) { + for (const auto &[path, refv] : *oobj) { + if (const auto *robj = std::get_if(&refv.value)) { + BlobRef ref; + ref.sha256 = get_str(*robj, "sha256").value_or(""); + ref.size = + static_cast(get_i64(*robj, "size").value_or(0)); + ref.mode = + static_cast(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(&deps->value)) { + for (const auto &[path, dv] : *dobj) { + if (const auto *s = std::get_if(&dv.value)) { + rec.discovered_inputs[path] = *s; + } + } + } + } + if (const auto *guards = find_key(*obj, "lookup_guards")) { + if (const auto *garr = std::get_if(&guards->value)) { + for (const auto &gv : *garr) { + if (const auto *gobj = std::get_if(&gv.value)) { + Snapshot::LookupGuard g; + g.lookup_name = get_str(*gobj, "lookup_name").value_or(""); + g.matched_root_index = + static_cast(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(&sr->value)) { + for (const auto &rv : *sarr) { + if (const auto *rs = std::get_if(&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(&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(&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(get_i64(*obj, "sequence").value_or(0)); + snap.generations.push_back(std::move(gen)); + } + } + + return snap; +} + +Void::Result::Result +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 +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(::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 +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 +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, 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 +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 +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(db->generations.size() - 512)); + } + return save_db_locked(*db); +} + +Void::Result::Result, Void::Result::Error> +StateStore::list_generations(std::optional 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 filtered; + for (const auto &g : db->generations) { + if (g.profile_name == *profile_name) { + filtered.push_back(g); + } + } + return filtered; +} + +Void::Result::Result +StateStore::acquire_lease(std::string_view profile_name, + const std::set &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(::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 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(&parsed->value)) { + const auto pid = get_i64(*obj, "pid").value_or(0); + if (!pid_is_alive(static_cast(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 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 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(&parsed->value)) { + const auto pid = get_i64(*obj, "pid").value_or(0); + if (!pid_is_alive(static_cast(pid))) { + continue; + } + if (const auto *blobs = find_key(*obj, "blobs")) { + if (const auto *arr = std::get_if(&blobs->value)) { + for (const auto &bv : *arr) { + if (const auto *s = std::get_if(&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 diff --git a/src/Toolchain/Driver.cpp b/src/Toolchain/Driver.cpp new file mode 100644 index 0000000..16f470e --- /dev/null +++ b/src/Toolchain/Driver.cpp @@ -0,0 +1,717 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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> 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> 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 &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 &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 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(&parsed->value); + if (!obj) { + return std::nullopt; + } + auto get_str = [&](const std::string &k) -> std::optional { + const auto it = obj->find(k); + if (it == obj->end()) { + return std::nullopt; + } + const auto *s = std::get_if(&it->second.value); + return s ? std::optional{*s} : std::nullopt; + }; + auto get_bool = [&](const std::string &k) -> std::optional { + const auto it = obj->find(k); + if (it == obj->end()) { + return std::nullopt; + } + const auto *b = std::get_if(&it->second.value); + return b ? std::optional{*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 +discover_and_probe(const ProfileContext &context, + const std::optional &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 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 \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(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 +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 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 +lower_archive_command(const ToolchainCapabilities &toolchain, + const std::filesystem::path &output_archive, + const std::vector &object_files, + const std::optional &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 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 +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 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 diff --git a/src/Util/Json.cpp b/src/Util/Json.cpp new file mode 100644 index 0000000..3f218fe --- /dev/null +++ b/src/Util/Json.cpp @@ -0,0 +1,102 @@ +#include + +#ifdef VBS_HAS_VOID_UNICODE +#include +#endif + +#include + +namespace Void::Build::Util { + +bool is_valid_utf8(std::string_view text) noexcept { +#ifdef VBS_HAS_VOID_UNICODE + Void::Unicode::UtfLimits limits; + limits.max_input_units = text.size(); + limits.max_output_units = text.size(); + return Void::Unicode::validate_utf8(text, limits).has_value(); +#else + std::size_t position = 0; + while (position < text.size()) { + const auto lead = static_cast(text[position++]); + if (lead < 0x80) { + continue; + } + std::size_t remaining = 0; + std::uint32_t scalar = 0; + std::uint32_t minimum = 0; + if (lead >= 0xc2 && lead <= 0xdf) { + remaining = 1; + scalar = lead & 0x1f; + minimum = 0x80; + } else if (lead >= 0xe0 && lead <= 0xef) { + remaining = 2; + scalar = lead & 0x0f; + minimum = 0x800; + } else if (lead >= 0xf0 && lead <= 0xf4) { + remaining = 3; + scalar = lead & 0x07; + minimum = 0x10000; + } else { + return false; + } + if (remaining > text.size() - position) { + return false; + } + for (std::size_t i = 0; i < remaining; ++i) { + const auto continuation = static_cast(text[position++]); + if ((continuation & 0xc0) != 0x80) { + return false; + } + scalar = (scalar << 6) | (continuation & 0x3f); + } + if (scalar < minimum || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff)) { + return false; + } + } + return true; +#endif +} + +void require_valid_utf8(std::string_view text) { + if (!is_valid_utf8(text)) { + throw std::invalid_argument{"JSON string contains invalid UTF-8"}; + } +} + +std::string json_quote(std::string_view text) { + require_valid_utf8(text); + constexpr char hex[] = "0123456789abcdef"; + std::string output{"\""}; + output.reserve(text.size() + 2); + for (const unsigned char c : text) { + switch (c) { + case '"': + output += "\\\""; + break; + case '\\': + output += "\\\\"; + break; + case '\n': + output += "\\n"; + break; + case '\r': + output += "\\r"; + break; + case '\t': + output += "\\t"; + break; + default: + if (c < 0x20) { + output += "\\u00"; + output += hex[c >> 4]; + output += hex[c & 0x0f]; + } else { + output += static_cast(c); + } + } + } + output += '"'; + return output; +} + +} // namespace Void::Build::Util diff --git a/src/Util/Sha256.cpp b/src/Util/Sha256.cpp new file mode 100644 index 0000000..72fae67 --- /dev/null +++ b/src/Util/Sha256.cpp @@ -0,0 +1,230 @@ +#include + +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Util { +namespace { + +constexpr std::uint32_t kRoundConstants[64] = { + 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, + 0xab1c5ed5u, 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, + 0x9bdc06a7u, 0xc19bf174u, 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, 0x2de92c6fu, + 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, + 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, + 0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, 0xa2bfe8a1u, 0xa81a664bu, + 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, 0x19a4c116u, + 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u, + 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, + 0xc67178f2u}; + +constexpr std::uint32_t rotr(std::uint32_t x, unsigned n) noexcept { + return (x >> n) | (x << (32u - n)); +} + +} // namespace + +Sha256Hasher::Sha256Hasher() noexcept + : state_{0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au, + 0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u} {} + +void Sha256Hasher::transform(const std::uint8_t block[64]) noexcept { + std::uint32_t w[64]; + for (int i = 0; i < 16; ++i) { + w[i] = (static_cast(block[i * 4]) << 24) | + (static_cast(block[i * 4 + 1]) << 16) | + (static_cast(block[i * 4 + 2]) << 8) | + static_cast(block[i * 4 + 3]); + } + for (int i = 16; i < 64; ++i) { + const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); + const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + + std::uint32_t a = state_[0]; + std::uint32_t b = state_[1]; + std::uint32_t c = state_[2]; + std::uint32_t d = state_[3]; + std::uint32_t e = state_[4]; + std::uint32_t f = state_[5]; + std::uint32_t g = state_[6]; + std::uint32_t h = state_[7]; + + for (int i = 0; i < 64; ++i) { + const std::uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); + const std::uint32_t ch = (e & f) ^ ((~e) & g); + const std::uint32_t temp1 = h + S1 + ch + kRoundConstants[i] + w[i]; + const std::uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); + const std::uint32_t maj = (a & b) ^ (a & c) ^ (b & c); + const std::uint32_t temp2 = S0 + maj; + + h = g; + g = f; + f = e; + e = d + temp1; + d = c; + c = b; + b = a; + a = temp1 + temp2; + } + + state_[0] += a; + state_[1] += b; + state_[2] += c; + state_[3] += d; + state_[4] += e; + state_[5] += f; + state_[6] += g; + state_[7] += h; +} + +void Sha256Hasher::update(std::span data) noexcept { + if (finalized_ || data.empty()) { + return; + } + const std::uint8_t *ptr = data.data(); + std::size_t remaining = data.size(); + bit_count_ += static_cast(remaining) * 8u; + + if (buffer_len_ > 0) { + const std::size_t take = std::min(remaining, std::size_t{64} - buffer_len_); + std::memcpy(buffer_ + buffer_len_, ptr, take); + buffer_len_ += take; + ptr += take; + remaining -= take; + if (buffer_len_ == 64) { + transform(buffer_); + buffer_len_ = 0; + } + } + while (remaining >= 64) { + transform(ptr); + ptr += 64; + remaining -= 64; + } + if (remaining > 0) { + std::memcpy(buffer_, ptr, remaining); + buffer_len_ = remaining; + } +} + +void Sha256Hasher::update(std::span data) noexcept { + update(std::span{reinterpret_cast(data.data()), + data.size()}); +} + +void Sha256Hasher::update(std::string_view text) noexcept { + update(std::span{reinterpret_cast(text.data()), + text.size()}); +} + +void Sha256Hasher::update_u64(std::uint64_t value) noexcept { + std::uint8_t bytes[8]; + for (int i = 7; i >= 0; --i) { + bytes[i] = static_cast(value & 0xffu); + value >>= 8; + } + update(bytes); +} + +void Sha256Hasher::update_length_prefixed(std::string_view text) noexcept { + update_u64(static_cast(text.size())); + update(text); +} + +Sha256Digest Sha256Hasher::finalize() noexcept { + if (!finalized_) { + finalized_ = true; + buffer_[buffer_len_++] = 0x80u; + if (buffer_len_ > 56) { + std::memset(buffer_ + buffer_len_, 0, 64 - buffer_len_); + transform(buffer_); + buffer_len_ = 0; + } + std::memset(buffer_ + buffer_len_, 0, 56 - buffer_len_); + std::uint64_t bits = bit_count_; + for (int i = 7; i >= 0; --i) { + buffer_[56 + i] = static_cast(bits & 0xffu); + bits >>= 8; + } + transform(buffer_); + } + + Sha256Digest out{}; + for (int i = 0; i < 8; ++i) { + out[static_cast(i * 4)] = static_cast((state_[i] >> 24) & 0xffu); + out[static_cast(i * 4 + 1)] = + static_cast((state_[i] >> 16) & 0xffu); + out[static_cast(i * 4 + 2)] = + static_cast((state_[i] >> 8) & 0xffu); + out[static_cast(i * 4 + 3)] = static_cast(state_[i] & 0xffu); + } + return out; +} + +std::string Sha256Hasher::finalize_hex() noexcept { return to_hex(finalize()); } + +std::string to_hex(const Sha256Digest &digest) { + return Void::Encoding::Hex::encode(std::span{digest.data(), digest.size()}); +} + +Sha256Digest sha256_bytes(std::span data) noexcept { + Sha256Hasher hasher; + hasher.update(data); + return hasher.finalize(); +} + +std::string sha256_hex(std::string_view text) { + Sha256Hasher hasher; + hasher.update(text); + return hasher.finalize_hex(); +} + +std::string sha256_hex(std::span data) { return to_hex(sha256_bytes(data)); } + +Void::Result::Result +sha256_file_hex(const std::filesystem::path &path) { + const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("sha256_file_hex: cannot open '{}'", path.string()), err)}; + } + Void::System::OwnedFd guard{fd}; + Sha256Hasher hasher; + std::array buf{}; + for (;;) { + const ssize_t n = ::read(fd, buf.data(), buf.size()); + if (n > 0) { + hasher.update(std::span{buf.data(), static_cast(n)}); + } else if (n == 0) { + break; + } else if (errno != EINTR) { + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("sha256_file_hex: read failed for '{}'", path.string()), err)}; + } + } + return hasher.finalize_hex(); +} + +bool constant_time_equal(std::string_view a, std::string_view b) noexcept { + if (a.size() != b.size()) { + return false; + } + unsigned char diff = 0; + for (std::size_t i = 0; i < a.size(); ++i) { + diff |= static_cast(a[i]) ^ static_cast(b[i]); + } + return diff == 0; +} + +} // namespace Void::Build::Util diff --git a/src/Watch/Watcher.cpp b/src/Watch/Watcher.cpp new file mode 100644 index 0000000..b13dd9a --- /dev/null +++ b/src/Watch/Watcher.cpp @@ -0,0 +1,500 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::Watch { +namespace { + +Void::Result::Error sys_err(int err, std::string msg) { + return Void::System::make_system_error(Void::System::map_errno_to_system_code(err), + std::move(msg), err); +} + +constexpr std::uint32_t kWatchMask = IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE | + IN_MOVED_FROM | IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF | + IN_MOVE_SELF; + +} // namespace + +InotifyWatcher::InotifyWatcher(int fd, std::filesystem::path root, + std::vector excluded) + : fd_{fd}, root_{std::move(root)}, excluded_{std::move(excluded)} {} + +InotifyWatcher::~InotifyWatcher() noexcept { close_fd(); } + +InotifyWatcher::InotifyWatcher(InotifyWatcher &&other) noexcept + : fd_{std::exchange(other.fd_, -1)}, root_{std::move(other.root_)}, + excluded_{std::move(other.excluded_)}, wd_to_path_{std::move(other.wd_to_path_)} {} + +InotifyWatcher &InotifyWatcher::operator=(InotifyWatcher &&other) noexcept { + if (this != &other) { + close_fd(); + fd_ = std::exchange(other.fd_, -1); + root_ = std::move(other.root_); + excluded_ = std::move(other.excluded_); + wd_to_path_ = std::move(other.wd_to_path_); + } + return *this; +} + +void InotifyWatcher::close_fd() noexcept { + if (fd_ >= 0) { + (void)::close(fd_); + fd_ = -1; + } + wd_to_path_.clear(); +} + +bool InotifyWatcher::is_excluded(const std::filesystem::path &rel) const { + for (const auto &part : rel) { + const auto s = part.string(); + if (s.empty() || s == ".") { + continue; + } + if (std::ranges::contains(excluded_, s)) { + return true; + } + } + return false; +} + +Void::Result::Result +InotifyWatcher::watch_tree(const std::filesystem::path &dir) { + std::error_code ec; + if (!std::filesystem::is_directory(dir, ec)) { + return {}; + } + auto add_dir = + [&](const std::filesystem::path &p) -> Void::Result::Result { + const int wd = ::inotify_add_watch(fd_, p.c_str(), kWatchMask); + if (wd < 0) { + const int err = errno; + if (err == ENOENT || err == ENOTDIR) { + return {}; + } + return std::unexpected{sys_err( + err, std::format("InotifyWatcher: inotify_add_watch failed for '{}'", p.string()))}; + } + wd_to_path_[wd] = p; + return {}; + }; + + if (auto r = add_dir(dir); !r) { + return r; + } + std::filesystem::recursive_directory_iterator it{ + dir, std::filesystem::directory_options::skip_permission_denied, ec}; + for (; !ec && it != std::filesystem::recursive_directory_iterator{}; it.increment(ec)) { + const auto rel = it->path().lexically_relative(root_); + if (is_excluded(rel)) { + if (it->is_directory(ec)) { + it.disable_recursion_pending(); + } + continue; + } + if (it->is_directory(ec)) { + if (auto r = add_dir(it->path()); !r) { + return r; + } + } + } + return {}; +} + +Void::Result::Result +InotifyWatcher::create(const std::filesystem::path &root_dir, + std::vector excluded_names) { + std::error_code ec; + const auto canon = std::filesystem::weakly_canonical(root_dir, ec); + if (ec || !std::filesystem::is_directory(canon)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::not_found, + std::format("InotifyWatcher: root '{}' is not a directory", root_dir.string()))}; + } + const int fd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC); + if (fd < 0) { + const int err = errno; + return std::unexpected{sys_err(err, "InotifyWatcher: inotify_init1 failed")}; + } + InotifyWatcher watcher{fd, canon, std::move(excluded_names)}; + if (auto r = watcher.watch_tree(canon); !r) { + return std::unexpected{r.error()}; + } + return watcher; +} + +Void::Result::Result InotifyWatcher::rescan_watches() { + for (const auto &[wd, path] : wd_to_path_) { + (void)::inotify_rm_watch(fd_, wd); + } + wd_to_path_.clear(); + return watch_tree(root_); +} + +Void::Result::Result +InotifyWatcher::poll_events(std::chrono::milliseconds timeout, std::chrono::milliseconds debounce) { + WatchBatch batch; + if (fd_ < 0) { + batch.rescan_required = true; + return batch; + } + + struct pollfd pfd{fd_, POLLIN, 0}; + const int ready = ::poll(&pfd, 1, static_cast(std::max(0, timeout.count()))); + if (ready < 0) { + if (errno == EINTR) { + return batch; + } + return std::unexpected{sys_err(errno, "InotifyWatcher: poll failed")}; + } + if (ready == 0) { + return batch; + } + + std::set unique_paths; + alignas(struct inotify_event) std::array buf{}; + + auto drain_now = [&]() { + for (;;) { + const ssize_t n = ::read(fd_, buf.data(), buf.size()); + if (n <= 0) { + break; + } + ssize_t off = 0; + while (off < n) { + const auto *ev = reinterpret_cast(buf.data() + off); + off += static_cast(sizeof(struct inotify_event) + ev->len); + + if (ev->mask & IN_Q_OVERFLOW) { + batch.overflowed = true; + batch.rescan_required = true; + continue; + } + if (ev->mask & IN_IGNORED) { + wd_to_path_.erase(ev->wd); + continue; + } + + const auto dir_it = wd_to_path_.find(ev->wd); + if (dir_it == wd_to_path_.end()) { + batch.rescan_required = true; + continue; + } + std::filesystem::path full = dir_it->second; + if (ev->len > 0 && ev->name[0] != '\0') { + full /= ev->name; + } + const auto rel = full.lexically_relative(root_); + if (is_excluded(rel)) { + continue; + } + unique_paths.insert(full); + + if ((ev->mask & (IN_CREATE | IN_MOVED_TO)) && (ev->mask & IN_ISDIR)) { + auto attached = watch_tree(full); + if (!attached) { + batch.rescan_required = true; + } + } + if (ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) { + batch.rescan_required = true; + } + } + } + }; + + drain_now(); + + // Coalesce burst edits across the debounce window. + if (debounce.count() > 0 && (!unique_paths.empty() || batch.rescan_required)) { + const auto settle_deadline = std::chrono::steady_clock::now() + debounce; + while (std::chrono::steady_clock::now() < settle_deadline) { + const auto rem = std::chrono::duration_cast( + settle_deadline - std::chrono::steady_clock::now()); + if (rem.count() <= 0) { + break; + } + struct pollfd spfd{fd_, POLLIN, 0}; + const int sr = ::poll(&spfd, 1, static_cast(rem.count())); + if (sr > 0) { + drain_now(); + } else { + break; + } + } + } + + if (batch.rescan_required) { + (void)rescan_watches(); + } + batch.changed_paths.assign(unique_paths.begin(), unique_paths.end()); + return batch; +} + +WatchCycleReport run_reconcile_cycle(const WatchLoopOptions &options, std::size_t cycle_index, + bool allow_selection_update, + std::optional reserved_ticket, + std::stop_token stop) { + WatchCycleReport rep; + rep.cycle_index = cycle_index; + + // Resolve profile name: explicit profile, or active editor selection in MetadataOnly, or + // "debug". + std::string profile_name = options.explicit_profile.value_or(""); + if (profile_name.empty()) { + if (auto sel = Editor::read_selection_state(options.frontend.project_root); + sel && sel->has_value() && !(*sel)->selected_profile.empty()) { + profile_name = (*sel)->selected_profile; + } else { + profile_name = "debug"; + } + } + rep.profile_name = profile_name; + + // 1. Compile or reuse host build description (allowed in both FullBuild and MetadataOnly). + auto compiled = Config::compile_descriptor(options.frontend); + if (!compiled) { + rep.diagnostic = compiled.error().message(); + (void)Editor::mark_profile_stale(options.frontend.build_root, profile_name, + Editor::GenerationStatus::Invalid, rep.diagnostic); + return rep; + } + + // 2. Discover profiles and resolve target ProfileContext. + auto profs = Config::discover_profiles(*compiled, options.frontend); + if (!profs) { + rep.diagnostic = profs.error().message(); + (void)Editor::mark_profile_stale(options.frontend.build_root, profile_name, + Editor::GenerationStatus::Invalid, rep.diagnostic); + return rep; + } + + ProfileContext ctx; + try { + ctx = profs->resolve(profile_name, options.compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + } catch (const std::exception &ex) { + rep.diagnostic = ex.what(); + (void)Editor::mark_profile_stale(options.frontend.build_root, profile_name, + Editor::GenerationStatus::Invalid, rep.diagnostic); + return rep; + } + + // 3. Probe target toolchain (safe syntax-only probes, never builds targets). + auto tc = Toolchain::discover_and_probe(ctx, options.frontend.build_root / ".vbs" / "probes"); + if (!tc) { + rep.diagnostic = tc.error().message(); + (void)Editor::mark_profile_stale(options.frontend.build_root, profile_name, + Editor::GenerationStatus::Invalid, rep.diagnostic); + return rep; + } + + // 4. Evaluate build(Project&) for this ProfileContext. + auto desc = Config::evaluate_project(*compiled, ctx, options.frontend); + if (!desc) { + rep.diagnostic = desc.error().message(); + (void)Editor::mark_profile_stale(options.frontend.build_root, profile_name, + Editor::GenerationStatus::Invalid, rep.diagnostic); + return rep; + } + + // 5. Provider metadata boundary: in MetadataOnly mode, read ONLY validated cached exports; + // NEVER invoke CMake configure, Meson setup, Conan install, fetch, or lock writes! + CachedProviderSnapshot provider_meta; + if (options.provider_reader) { + provider_meta = options.provider_reader(*desc, options.mode); + } + if (!provider_meta.valid) { + rep.provider_stale = true; + rep.diagnostic = provider_meta.stale_diagnostic.empty() + ? "cached dependency metadata is stale; run 'vbs build' to refresh" + : provider_meta.stale_diagnostic; + (void)Editor::mark_profile_stale(options.frontend.build_root, profile_name, + Editor::GenerationStatus::Stale, rep.diagnostic); + return rep; + } + + // 6. Capture input snapshot (content-verified; materialize only for FullBuild execution). + std::vector scan_roots; + std::error_code ec; + for (const char *d : {"src", "source", "include", "tests"}) { + if (std::filesystem::is_directory(options.frontend.project_root / d, ec)) { + scan_roots.push_back(options.frontend.project_root / d); + } + } + for (const auto &t : desc->targets) { + for (const auto &inc : t.include_directories) { + if (!inc.path.starts_with("$GEN/") && !inc.path.starts_with("gen/")) { + const auto p = std::filesystem::path{inc.path}.is_absolute() + ? std::filesystem::path{inc.path} + : (options.frontend.project_root / inc.path); + if (std::filesystem::is_directory(p, ec) && !std::ranges::contains(scan_roots, p)) { + scan_roots.push_back(p); + } + } + } + } + + Snapshot::SnapshotOptions sopts; + sopts.project_root = options.frontend.project_root; + sopts.snapshot_store_dir = options.frontend.build_root / ".vbs" / "snapshots"; + sopts.reproducibility_epoch = ctx.reproducibility_epoch; + sopts.materialize = (options.mode == WatchMode::FullBuild); + + auto snap = Snapshot::capture_snapshot(sopts, {}, scan_roots); + if (!snap) { + rep.diagnostic = snap.error().message(); + (void)Editor::mark_profile_stale(options.frontend.build_root, profile_name, + Editor::GenerationStatus::Invalid, rep.diagnostic); + return rep; + } + + // 7. Lower target graph. + Graph::GraphLowerOptions gopts; + gopts.project_root = options.frontend.project_root; + gopts.build_root = options.frontend.build_root; + gopts.snapshot = &(*snap); + gopts.imported_targets = std::move(provider_meta.imported_targets); + + auto graph = Graph::lower_project_graph(*desc, *tc, gopts); + if (!graph) { + rep.diagnostic = graph.error().message(); + (void)Editor::mark_profile_stale(options.frontend.build_root, profile_name, + Editor::GenerationStatus::Invalid, rep.diagnostic); + return rep; + } + rep.config_succeeded = true; + + // 8. Publish compilation database BEFORE target compilation so valid source/flag edits + // refresh editors immediately even if target compilation fails (Plan 09/10)! + Editor::PublishOptions popts; + popts.project_root = options.frontend.project_root; + popts.build_root = options.frontend.build_root; + popts.update_selection = allow_selection_update; + popts.reserved_ticket = reserved_ticket; + auto pub = Editor::publish_profile_compdb(*graph, popts); + if (!pub) { + rep.diagnostic = pub.error().message(); + return rep; + } + rep.compdb_published = true; + + // Record graph generation in state store. + if (auto state = State::StateStore::open(options.frontend.build_root / ".vbs"); state) { + State::GraphGenerationRecord gen_rec; + gen_rec.generation_id = pub->generation_id; + gen_rec.profile_name = profile_name; + gen_rec.profile_identity = graph->profile_identity; + gen_rec.snapshot_id = snap->snapshot_id; + gen_rec.status = "valid"; + (void)state->record_generation(gen_rec); + + // 9. In MetadataOnly mode: STOP HERE! Never schedule target builds or generators! + if (options.mode == WatchMode::MetadataOnly) { + rep.build_succeeded = true; + return rep; + } + + // 10. FullBuild mode: execute selected actions. + Execution::ExecutionOptions eopts; + eopts.jobs = options.jobs; + eopts.selected_targets = options.selected_targets; + auto exec = Execution::execute_graph(*graph, *state, eopts, stop); + if (!exec) { + rep.diagnostic = exec.error().message(); + return rep; + } + rep.executed_actions = exec->executed_count; + rep.cached_actions = exec->cached_count; + rep.build_succeeded = exec->succeeded; + rep.diagnostic = exec->diagnostic; + } + return rep; +} + +Void::Result::Result, Void::Result::Error> +run_watch_loop(const WatchLoopOptions &options, std::stop_token stop) { + auto watcher = InotifyWatcher::create(options.frontend.project_root); + if (!watcher) { + return std::unexpected{watcher.error()}; + } + + std::vector reports; + std::size_t cycle = 0; + + // Initial reconciliation pass (watchers NEVER steal editor selection: + // allow_selection_update=false). + { + auto rep = run_reconcile_cycle(options, cycle++, false, std::nullopt, stop); + if (options.on_cycle) { + options.on_cycle(rep); + } + reports.push_back(std::move(rep)); + if (options.max_cycles > 0 && reports.size() >= options.max_cycles) { + return reports; + } + } + + auto last_reconcile = std::chrono::steady_clock::now(); + std::string last_observed_selection; + if (auto sel = Editor::read_selection_state(options.frontend.project_root); + sel && sel->has_value()) { + last_observed_selection = (*sel)->selected_profile; + } + + while (!stop.stop_requested()) { + const auto now = std::chrono::steady_clock::now(); + const auto elapsed_since_reconcile = + std::chrono::duration_cast(now - last_reconcile); + const auto poll_wait = std::min( + std::chrono::milliseconds{100}, + options.reconcile_interval > elapsed_since_reconcile + ? (options.reconcile_interval - elapsed_since_reconcile) + : std::chrono::milliseconds{10}); + + auto batch = watcher->poll_events(poll_wait, options.debounce); + if (stop.stop_requested()) { + break; + } + + bool selection_changed = false; + if (!options.explicit_profile) { + if (auto sel = Editor::read_selection_state(options.frontend.project_root); + sel && sel->has_value() && (*sel)->selected_profile != last_observed_selection) { + last_observed_selection = (*sel)->selected_profile; + selection_changed = true; + } + } + + const bool periodic_due = + (std::chrono::steady_clock::now() - last_reconcile) >= options.reconcile_interval; + const bool event_triggered = + !batch || batch->overflowed || batch->rescan_required || !batch->changed_paths.empty(); + + if (event_triggered || periodic_due || selection_changed) { + last_reconcile = std::chrono::steady_clock::now(); + auto rep = run_reconcile_cycle(options, cycle++, false, std::nullopt, stop); + if (options.on_cycle) { + options.on_cycle(rep); + } + reports.push_back(std::move(rep)); + if (options.max_cycles > 0 && reports.size() >= options.max_cycles) { + break; + } + } + } + return reports; +} + +} // namespace Void::Build::Watch diff --git a/src/build.cpp b/src/build.cpp deleted file mode 100644 index c84aaab..0000000 --- a/src/build.cpp +++ /dev/null @@ -1,448 +0,0 @@ -#include - -#include -#include - -namespace vbs { -namespace detail { -struct ProjectState { - ProfileContext context; - std::vector targets; - std::vector dependencies; -}; -} // namespace detail -namespace { -void require_text(std::string_view text, std::string_view field) { - if (text.empty()) { - throw std::invalid_argument{std::string{field} + " must not be empty"}; - } -} - -auto owner(const std::weak_ptr &weak) { - auto state = weak.lock(); - if (!state) { - throw std::logic_error{"declaration handle's Project has expired"}; - } - return state; -} - -std::string_view visibility_name(Visibility visibility) { - switch (visibility) { - case Visibility::private_: - return "private"; - case Visibility::public_: - return "public"; - case Visibility::interface_: - return "interface"; - } - throw std::invalid_argument{"unknown visibility"}; -} - -void validate_context(const ProfileContext &context) { - require_text(context.name, "profile name"); - (void)compiler_name(context.compiler); - require_text(context.os, "target OS"); - require_text(context.architecture, "target architecture"); - for (const auto &option : context.compile_options) { - require_text(option, "compile option"); - } -} - -void require_utf8(std::string_view text) { - std::size_t position = 0; - const auto invalid = [] { throw std::invalid_argument{"JSON string contains invalid UTF-8"}; }; - while (position < text.size()) { - const auto lead = static_cast(text[position++]); - if (lead < 0x80) { - continue; - } - std::size_t remaining = 0; - std::uint32_t scalar = 0; - std::uint32_t minimum = 0; - if (lead >= 0xc2 && lead <= 0xdf) { - remaining = 1; - scalar = lead & 0x1f; - minimum = 0x80; - } else if (lead >= 0xe0 && lead <= 0xef) { - remaining = 2; - scalar = lead & 0x0f; - minimum = 0x800; - } else if (lead >= 0xf0 && lead <= 0xf4) { - remaining = 3; - scalar = lead & 0x07; - minimum = 0x10000; - } else { - invalid(); - } - if (remaining > text.size() - position) { - invalid(); - } - for (std::size_t i = 0; i < remaining; ++i) { - const auto continuation = static_cast(text[position++]); - if ((continuation & 0xc0) != 0x80) { - invalid(); - } - scalar = (scalar << 6) | (continuation & 0x3f); - } - // JSON strings contain Unicode scalar values: no overlong forms or surrogates. - if (scalar < minimum || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff)) { - invalid(); - } - } -} - -std::string quote(std::string_view text) { - require_utf8(text); - constexpr char hex[] = "0123456789abcdef"; - std::string output{"\""}; - for (const unsigned char c : text) { - switch (c) { - case '"': - output += "\\\""; - break; - case '\\': - output += "\\\\"; - break; - case '\n': - output += "\\n"; - break; - case '\r': - output += "\\r"; - break; - case '\t': - output += "\\t"; - break; - default: - if (c < 0x20) { - output += "\\u00"; - output += hex[c >> 4]; - output += hex[c & 0x0f]; - } else { - output += static_cast(c); - } - } - } - output += '"'; - return output; -} - -template -std::string array(const Range &range, Serialize serialize) { - std::string output{"["}; - bool first = true; - for (const auto &item : range) { - if (!first) - output += ','; - first = false; - output += serialize(item); - } - return output + ']'; -} - -std::string options_json(const OptionMap &options) { - std::string output{"{"}; - bool first = true; - for (const auto &[name, option] : options) { - if (!first) - output += ','; - first = false; - output += quote(name) + ':'; - output += std::visit( - [](const auto &value) -> std::string { - using Type = std::remove_cvref_t; - if constexpr (std::same_as) - return quote(value); - else if constexpr (std::same_as) - return value ? "true" : "false"; - else - return std::to_string(value); - }, - option.value); - } - return output + '}'; -} -} // namespace - -std::string_view compiler_name(CompilerFamily compiler) { - switch (compiler) { - case CompilerFamily::gcc: - return "gcc"; - case CompilerFamily::clang: - return "clang"; - } - throw std::invalid_argument{"unknown compiler family"}; -} - -CompilerFamily parse_compiler(std::string_view name) { - if (name == "gcc") - return CompilerFamily::gcc; - if (name == "clang") - return CompilerFamily::clang; - throw std::invalid_argument{"unknown compiler '" + std::string{name} + - "' (expected gcc or clang)"}; -} - -void Profiles::add(std::string name, std::vector compile_options) { - require_text(name, "profile name"); - if (std::ranges::any_of(records_, [&](const auto &record) { return record.name == name; })) { - throw std::invalid_argument{"duplicate profile '" + name + "'"}; - } - for (const auto &option : compile_options) - require_text(option, "compile option"); - records_.push_back({std::move(name), std::move(compile_options)}); -} - -const std::vector &Profiles::records() const noexcept { return records_; } - -ProfileContext Profiles::resolve(std::string_view name, CompilerFamily compiler, std::string os, - std::string architecture) const { - const auto found = std::ranges::find(records_, name, &ProfileDescription::name); - if (found == records_.end()) { - throw std::invalid_argument{"unknown profile '" + std::string{name} + "'"}; - } - ProfileContext context{found->name, compiler, std::move(os), std::move(architecture), - found->compile_options}; - validate_context(context); - return context; -} - -Profiles default_profiles() { - Profiles result; - result.add("debug", {"-O0", "-g"}); - result.add("release", {"-O3", "-DNDEBUG"}); - return result; -} - -SourceSet::SourceSet(std::initializer_list files) { - for (const auto path : files) { - require_text(path, "source path"); - records_.push_back({SourceKind::file, std::string{path}}); - } -} - -SourceSet SourceSet::file(std::string path) { - require_text(path, "source path"); - SourceSet result; - result.records_.push_back({SourceKind::file, std::move(path)}); - return result; -} - -SourceSet SourceSet::glob(std::string pattern) { - require_text(pattern, "glob pattern"); - SourceSet result; - result.records_.push_back({SourceKind::glob, std::move(pattern)}); - return result; -} - -const std::vector &SourceSet::records() const noexcept { return records_; } - -Target::Target(std::weak_ptr state, std::size_t index) - : owner_{std::move(state)}, index_{index} {} - -Target &Target::sources(const SourceSet &sources) { - auto state = owner(owner_); - auto &records = state->targets.at(index_).sources; - records.insert(records.end(), sources.records().begin(), sources.records().end()); - return *this; -} - -Target &Target::include_directory(std::string path, Visibility visibility) { - require_text(path, "include directory"); - (void)visibility_name(visibility); - owner(owner_)->targets.at(index_).include_directories.push_back({std::move(path), visibility}); - return *this; -} - -Target &Target::compile_option(std::string option) { - require_text(option, "compile option"); - owner(owner_)->targets.at(index_).compile_options.push_back(std::move(option)); - return *this; -} - -Target &Target::link(const Target &target, Visibility visibility) { - auto state = owner(owner_); - if (owner(target.owner_) != state) { - throw std::invalid_argument{"cannot link a target from another Project"}; - } - (void)visibility_name(visibility); - state->targets.at(index_).links.push_back( - {LinkKind::local, state->targets.at(target.index_).name, {}, visibility}); - return *this; -} - -Target &Target::link(const ImportedTarget &target, Visibility visibility) { - auto state = owner(owner_); - if (owner(target.owner_) != state) { - throw std::invalid_argument{"cannot link an imported target from another Project"}; - } - (void)visibility_name(visibility); - state->targets.at(index_).links.push_back({LinkKind::imported, target.name_, - state->dependencies.at(target.dependency_).name, - visibility}); - return *this; -} - -const TargetRecord &Target::record() const { return owner(owner_)->targets.at(index_); } - -ImportedTarget::ImportedTarget(std::weak_ptr state, std::size_t dependency, - std::string name) - : owner_{std::move(state)}, dependency_{dependency}, name_{std::move(name)} {} - -Dependency::Dependency(std::weak_ptr state, std::size_t index) - : owner_{std::move(state)}, index_{index} {} - -Dependency &Dependency::git(std::string url, Commit commit) { - require_text(url, "Git URL"); - if (commit.sha.size() != 40 || !std::ranges::all_of(commit.sha, [](char c) { - return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); - })) { - throw std::invalid_argument{"Commit must contain an exact 40-digit hexadecimal Git SHA"}; - } - auto state = owner(owner_); - auto &record = state->dependencies.at(index_); - if (record.source_kind != DependencySourceKind::unspecified) { - throw std::invalid_argument{"dependency '" + record.name + - "' already has a source provider"}; - } - record.source_kind = DependencySourceKind::git; - record.location = std::move(url); - record.revision = std::move(commit.sha); - return *this; -} - -Dependency &Dependency::cmake(OptionMap options) { - for (const auto &[key, value] : options) { - (void)value; - require_text(key, "CMake option name"); - } - auto state = owner(owner_); - auto &record = state->dependencies.at(index_); - if (record.source_kind == DependencySourceKind::package || !record.builder.empty()) { - throw std::invalid_argument{"contradictory builder for dependency '" + record.name + "'"}; - } - record.builder = "cmake"; - record.options = std::move(options); - return *this; -} - -Dependency &Dependency::package(std::string id, std::string range) { - require_text(id, "package identifier"); - require_text(range, "package version range"); - auto state = owner(owner_); - auto &record = state->dependencies.at(index_); - if (record.source_kind != DependencySourceKind::unspecified || !record.builder.empty()) { - throw std::invalid_argument{"dependency '" + record.name + - "' already has a source/provider"}; - } - record.source_kind = DependencySourceKind::package; - record.package = std::move(id); - record.version = std::move(range); - return *this; -} - -ImportedTarget Dependency::target(std::string exported_name) const { - (void)owner(owner_); - require_text(exported_name, "exported target name"); - return ImportedTarget{owner_, index_, std::move(exported_name)}; -} - -const DependencyRecord &Dependency::record() const { - return owner(owner_)->dependencies.at(index_); -} - -Project::Project(ProfileContext context) : state_{std::make_shared()} { - validate_context(context); - state_->context = std::move(context); -} -Project::~Project() = default; -const ProfileContext &Project::context() const noexcept { return state_->context; } - -Target Project::add_target(std::string name, TargetKind kind) { - require_text(name, "target name"); - if (std::ranges::any_of(state_->targets, - [&](const auto &record) { return record.name == name; })) { - throw std::invalid_argument{"duplicate target '" + name + "'"}; - } - state_->targets.push_back({std::move(name), kind, {}, {}, {}, {}}); - return Target{state_, state_->targets.size() - 1}; -} -Target Project::executable(std::string name) { - return add_target(std::move(name), TargetKind::executable); -} -Target Project::static_library(std::string name) { - return add_target(std::move(name), TargetKind::static_library); -} -Dependency Project::dependency(std::string name) { - require_text(name, "dependency name"); - if (std::ranges::any_of(state_->dependencies, - [&](const auto &record) { return record.name == name; })) { - throw std::invalid_argument{"duplicate dependency '" + name + "'"}; - } - DependencyRecord record; - record.name = std::move(name); - state_->dependencies.push_back(std::move(record)); - return Dependency{state_, state_->dependencies.size() - 1}; -} -SourceSet Project::glob(std::string pattern) const { return SourceSet::glob(std::move(pattern)); } -const std::vector &Project::targets() const noexcept { return state_->targets; } -const std::vector &Project::dependencies() const noexcept { - return state_->dependencies; -} - -std::string Project::to_json() const { - const auto &profile = context(); - std::string output = - "{\"schema_version\":" + std::to_string(schema_version) + - ",\"profile\":{\"name\":" + quote(profile.name) + - ",\"compiler\":" + quote(compiler_name(profile.compiler)) + ",\"os\":" + quote(profile.os) + - ",\"architecture\":" + quote(profile.architecture) + - ",\"compile_options\":" + array(profile.compile_options, quote) + "},\"targets\":"; - output += array(targets(), [](const TargetRecord &target) { - return "{\"name\":" + quote(target.name) + ",\"kind\":" + - quote(target.kind == TargetKind::executable ? "executable" : "static_library") + - ",\"sources\":" + - array(target.sources, - [](const SourceRecord &source) { - return "{\"kind\":" + - quote(source.kind == SourceKind::file ? "file" : "glob") + - ",\"path\":" + quote(source.path) + '}'; - }) + - ",\"include_directories\":" + - array(target.include_directories, - [](const IncludeDirectory &directory) { - return "{\"path\":" + quote(directory.path) + - ",\"visibility\":" + quote(visibility_name(directory.visibility)) + - '}'; - }) + - ",\"compile_options\":" + array(target.compile_options, quote) + ",\"links\":" + - array(target.links, - [](const LinkRecord &link) { - return "{\"kind\":" + - quote(link.kind == LinkKind::local ? "local" : "imported") + - ",\"target\":" + quote(link.target) + - ",\"dependency\":" + quote(link.dependency) + - ",\"visibility\":" + quote(visibility_name(link.visibility)) + '}'; - }) + - '}'; - }); - output += ",\"dependencies\":" + array(dependencies(), [](const DependencyRecord &dependency) { - if (dependency.source_kind == DependencySourceKind::unspecified) { - throw std::invalid_argument{"dependency '" + dependency.name + - "' has no source provider"}; - } - std::string result = - "{\"name\":" + quote(dependency.name) + ",\"source\":{\"kind\":"; - if (dependency.source_kind == DependencySourceKind::git) { - result += "\"git\",\"location\":" + quote(dependency.location) + - ",\"revision\":" + quote(dependency.revision); - } else { - result += "\"package\",\"package\":" + quote(dependency.package) + - ",\"version\":" + quote(dependency.version); - } - return result + "},\"builder\":" + quote(dependency.builder) + - ",\"options\":" + options_json(dependency.options) + '}'; - }); - return output + '}'; -} - -} // namespace vbs diff --git a/src/main.cpp b/src/main.cpp deleted file mode 100644 index b2297fc..0000000 --- a/src/main.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include - -#include -#include - -int main(int argc, char **argv) { - bool version = false; - Void::Argparse::Parser parser{ - "vbs", "VoidBuildSystem bootstrap: help and version only.\n" - "Native build, test, compdb, deps and watch commands are planned and unavailable."}; - parser.flag("--version", "-V", "show bootstrap version", version); - const bool standalone_help = - argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h"); - if (argc == 1 || standalone_help) { - std::cout << parser.help(); - return 0; - } - // Reject mixed help requests: Parser reports help through the same error channel as bad input. - for (int i = 1; i < argc; ++i) { - const std::string_view arg{argv[i]}; - if (arg == "--help" || arg == "-h") { - std::cerr << "vbs: --help must be used alone\n"; - return 2; - } - if (arg == "build" || arg == "test" || arg == "compdb" || arg == "deps" || arg == "watch") { - std::cerr << "vbs: native command '" << arg - << "' is not implemented in this bootstrap\n"; - return 2; - } - } - const auto parsed = parser.parse(argc, argv); - if (!parsed) { - std::cerr << "vbs: " << parsed.error() << '\n'; - return 2; - } - if (version) { - std::cout << "vbs " << vbs::bootstrap::version << " (bootstrap)\n"; - return 0; - } - std::cerr << "vbs: no supported request; use --help\n"; - return 2; -} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2bee05f..047d0af 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,15 +1,50 @@ add_executable(vbs_sdk_tests SdkDeclarations.cpp ExampleContexts.cpp) -target_link_libraries(vbs_sdk_tests PRIVATE vbs_example_description) +target_link_libraries(vbs_sdk_tests PRIVATE VoidBuild_ExampleDescription) set_target_properties(vbs_sdk_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") add_test(NAME vbs_sdk_tests COMMAND "${CMAKE_COMMAND}" "-DSDK_TESTS=$" -P "${CMAKE_CURRENT_SOURCE_DIR}/RunSdkTests.cmake") void_add_tests(vbs_sdk_tests) +add_executable(vbs_core_tests CoreEngineTests.cpp) +target_include_directories(vbs_core_tests PRIVATE "${PROJECT_BINARY_DIR}/generated") +target_link_libraries(vbs_core_tests PRIVATE Void::BuildCore Void::Testing) +set_target_properties(vbs_core_tests PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") +add_test(NAME vbs_core_tests COMMAND "$" --no-color) +void_add_tests(vbs_core_tests) + +add_executable(vbs_v1_tests FullV1Tests.cpp) +target_include_directories(vbs_v1_tests PRIVATE "${PROJECT_BINARY_DIR}/generated") +target_link_libraries(vbs_v1_tests PRIVATE Void::BuildCore Void::Testing) +set_target_properties(vbs_v1_tests PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") +add_test(NAME vbs_v1_tests COMMAND "$" --no-color) +void_add_tests(vbs_v1_tests) + +add_executable(vbs_registry_tests RegistryTests.cpp) +target_include_directories(vbs_registry_tests PRIVATE "${PROJECT_BINARY_DIR}/generated") +target_link_libraries(vbs_registry_tests PRIVATE Void::BuildRegistry Void::Testing) +set_target_properties(vbs_registry_tests PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") +add_test(NAME vbs_registry_tests COMMAND "$" --no-color) +void_add_tests(vbs_registry_tests) + +add_executable(vbs_selfhost_tests SelfHostTests.cpp) +target_include_directories(vbs_selfhost_tests PRIVATE "${PROJECT_BINARY_DIR}/generated") +target_compile_definitions(vbs_selfhost_tests PRIVATE + "VBS_VOID_SOURCE_PATH=\"${VBS_VOID_RESOLVED_SOURCE_DIR}\"") +target_link_libraries(vbs_selfhost_tests PRIVATE Void::BuildCore Void::Testing) +set_target_properties(vbs_selfhost_tests PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") +add_test(NAME vbs_selfhost_tests COMMAND "$" --no-color) +void_add_tests(vbs_selfhost_tests) + add_test(NAME vbs_sdk_registration COMMAND "${CMAKE_COMMAND}" "-DSDK_TESTS=$" -P "${CMAKE_CURRENT_SOURCE_DIR}/SdkRegistration.cmake") add_test(NAME vbs_cli_contract COMMAND "${CMAKE_COMMAND}" - "-DVBS=$" "-DVBS_VERSION=${PROJECT_VERSION}" + "-DVBS=$" "-DVBS_REGISTRY=$" + "-DVBS_VERSION=${PROJECT_VERSION}" -P "${CMAKE_CURRENT_SOURCE_DIR}/CliContracts.cmake") add_test(NAME vbs_description_contract COMMAND "${CMAKE_COMMAND}" "-DDESCRIBE=$" diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 3abec71..a34cb07 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -1,28 +1,45 @@ cmake_minimum_required(VERSION 4.0) -function(check_process expected_code expected_stdout expected_stderr) +function(check_process expected_code expected_out_regex expected_err_regex) execute_process(COMMAND "${VBS}" ${ARGN} - RESULT_VARIABLE code OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 10) - if(NOT "${code}" STREQUAL "${expected_code}" OR - NOT "${out}" STREQUAL "${expected_stdout}" OR - NOT "${err}" STREQUAL "${expected_stderr}") + RESULT_VARIABLE code OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 15) + if(NOT "${code}" STREQUAL "${expected_code}") message(FATAL_ERROR "vbs ${ARGN}: expected exit ${expected_code}, got ${code}\nstdout=[${out}]\nstderr=[${err}]") endif() + if(NOT "${expected_out_regex}" STREQUAL "" AND NOT out MATCHES "${expected_out_regex}") + message(FATAL_ERROR "vbs ${ARGN}: stdout did not match [${expected_out_regex}]\nactual=[${out}]") + endif() + if(NOT "${expected_err_regex}" STREQUAL "" AND NOT err MATCHES "${expected_err_regex}") + message(FATAL_ERROR "vbs ${ARGN}: stderr did not match [${expected_err_regex}]\nactual=[${err}]") + endif() endfunction() -set(help "Usage: vbs [--version]\n\nVoidBuildSystem bootstrap: help and version only.\nNative build, test, compdb, deps and watch commands are planned and unavailable.\n\nFlags:\n --version, -V show bootstrap version\n --help, -h show this help\n") -check_process(0 "${help}" "") -check_process(0 "${help}" "" --help) -check_process(0 "${help}" "" -h) -check_process(0 "vbs ${VBS_VERSION} (bootstrap)\n" "" --version) -check_process(0 "vbs ${VBS_VERSION} (bootstrap)\n" "" -V) -check_process(2 "" "vbs: unknown option: --invalid\n" --invalid) -check_process(2 "" "vbs: unknown option: --invalid\n" --version --invalid) -check_process(2 "" "vbs: unexpected positional argument: invalid\n" invalid) -check_process(2 "" "vbs: --help must be used alone\n" --help --invalid) -foreach(command IN ITEMS build test compdb deps watch) - check_process(2 "" "vbs: native command '${command}' is not implemented in this bootstrap\n" "${command}") -endforeach() -check_process(2 "" "vbs: native command 'build' is not implemented in this bootstrap\n" build --profile debug) -check_process(2 "" "vbs: native command 'compdb' is not implemented in this bootstrap\n" compdb watch) -message(STATUS "16 CLI process contracts verified") +check_process(0 "Usage: vbs " "" ) +check_process(0 "Usage: vbs " "" --help) +check_process(0 "Usage: vbs " "" -h) +check_process(0 "^vbs ${VBS_VERSION}\n$" "" --version) +check_process(0 "^vbs ${VBS_VERSION}\n$" "" -V) +check_process(2 "" "--help must be used alone" --help --invalid) +check_process(2 "" "unexpected argument after --version" --version --invalid) +check_process(2 "" "unknown command 'invalid'" invalid) +check_process(0 "Usage: vbs build" "" build --help) +check_process(0 "Usage: vbs test" "" test --help) +check_process(2 "" "multi-profile build requires --editor-profile" build --profile debug --profile release) +check_process(2 "" "must be one of the requested profiles" build --profile debug --profile release --editor-profile custom) +check_process(2 "" "expected subcommand" compdb) +check_process(2 "" "unknown subcommand" compdb bogus) +check_process(2 "" "expected 'resolve' or 'update'" deps) +check_process(2 "" "--request and --output are required" bridge) +check_process(0 "Usage: vbs install" "" install --help) +check_process(2 "" "--prefix is required" install) +check_process(2 "" "--prefix is required" uninstall) +check_process(2 "" "--input and --output-dir are required" gen-tests) +check_process(0 "Usage: vbs publish" "" publish --help) +check_process(2 "" "--registry, --name, and --version are required" publish) + +execute_process(COMMAND "${VBS_REGISTRY}" --help + RESULT_VARIABLE reg_code OUTPUT_VARIABLE reg_out ERROR_VARIABLE reg_err TIMEOUT 15) +if(NOT "${reg_code}" STREQUAL "0" OR NOT reg_out MATCHES "Usage: vbs-registry") + message(FATAL_ERROR "vbs-registry --help failed: code=${reg_code}\nstdout=[${reg_out}]\nstderr=[${reg_err}]") +endif() +message(STATUS "23 native CLI contracts verified") diff --git a/tests/CoreEngineTests.cpp b/tests/CoreEngineTests.cpp new file mode 100644 index 0000000..bef40cc --- /dev/null +++ b/tests/CoreEngineTests.cpp @@ -0,0 +1,490 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace Void::Build; + +namespace { + +void write_text_file(const std::filesystem::path &path, std::string_view content) { + std::error_code ec; + if (path.has_parent_path()) { + std::filesystem::create_directories(path.parent_path(), ec); + } + auto r = Platform::atomic_write_file(path, content, false); + Void::Testing::expect(r.has_value()); +} + +} // namespace + +Void::Testing::Test sha256_nist_vectors_and_files() { + Void::Testing::expect_eq( + Util::sha256_hex(""), + std::string{"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}); + Void::Testing::expect_eq( + Util::sha256_hex("abc"), + std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}); + Void::Testing::expect_eq( + Util::sha256_hex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + std::string{"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"}); + + Void::FileSystem::TempDir tmp{"vbs_sha_"}; + const auto f = tmp / "sample.bin"; + write_text_file(f, "abc"); + auto fh = Util::sha256_file_hex(f); + Void::Testing::expect(fh.has_value()); + if (fh) { + Void::Testing::expect_eq( + *fh, std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}); + } +} + +Void::Testing::Test process_supervisor_exec_failure_and_early_leader_grandchild_kill() { + // 1. Distinguish exec failure from exit code 127. + { + Platform::ProcessRequest req; + req.executable = "/nonexistent/vbs_definitely_missing_binary_xyz"; + req.search_path = false; + auto res = Platform::run_supervised(req); + Void::Testing::expect(res.has_value()); + if (res) { + Void::Testing::expect(res->exec_failed); + Void::Testing::expect(!res->succeeded()); + } + } + + // 2. Program explicitly exiting 127 is NOT exec_failed. + { + Platform::ProcessRequest req; + req.executable = "/bin/sh"; + req.arguments = {"-c", "exit 127"}; + auto res = Platform::run_supervised(req); + Void::Testing::expect(res.has_value()); + if (res) { + Void::Testing::expect(!res->exec_failed); + Void::Testing::expect(res->exited); + Void::Testing::expect_eq(res->exit_code, 127); + } + } + + // 3. Adversarial VL-001 test: leader spawns stubborn grandchild ignoring SIGTERM and exits + // immediately; timeout escalates to SIGKILL and prevents grandchild from writing sentinel file. + { + Void::FileSystem::TempDir tmp{"vbs_proc_"}; + const auto sentinel = tmp / "grandchild_escaped.txt"; + Platform::ProcessRequest req; + req.executable = "/bin/sh"; + req.arguments = {"-c", "sh -c 'trap \"\" TERM; sleep 1.5; echo escaped > \"" + + sentinel.string() + "\"' >/dev/null 2>&1 & exit 0"}; + req.timeout = std::chrono::milliseconds{180}; + req.kill_grace = std::chrono::milliseconds{80}; + auto res = Platform::run_supervised(req); + Void::Testing::expect(res.has_value()); + if (res) { + Void::Testing::expect(res->timed_out); + Void::Testing::expect(!res->succeeded()); + } + std::this_thread::sleep_for(std::chrono::milliseconds{300}); + Void::Testing::expect(!std::filesystem::exists(sentinel)); + } +} + +Void::Testing::Test profile_inheritance_and_cycle_rejection() { + Profiles p = default_profiles(); + p.inherit("debug-asan", "debug", {"-fno-omit-frame-pointer"}); + auto resolved = p.resolve("debug-asan", CompilerFamily::Gcc, "Linux", "x86_64"); + Void::Testing::expect_eq(resolved.compile_options.size(), std::size_t{3}); + Void::Testing::expect_eq(resolved.compile_options.at(0), std::string{"-O0"}); + Void::Testing::expect_eq(resolved.compile_options.at(2), + std::string{"-fno-omit-frame-pointer"}); + + Profiles cyclic; + cyclic.inherit("a", "b"); + cyclic.inherit("b", "a"); + Void::Testing::expect_throw( + [&] { (void)cyclic.resolve("a", CompilerFamily::Gcc, "Linux", "x86_64"); }); + + Profiles missing_parent; + missing_parent.inherit("child", "ghost"); + Void::Testing::expect_throw( + [&] { (void)missing_parent.resolve("child", CompilerFamily::Gcc, "Linux", "x86_64"); }); +} + +Void::Testing::Test snapshot_content_mutations_symlinks_shadowing_and_isolation() { + Void::FileSystem::TempDir tmp{"vbs_snap_"}; + const auto proj = tmp / "project"; + const auto store = tmp / "store"; + const auto outside = tmp / "outside_secret.txt"; + + write_text_file(outside, "TOP_SECRET"); + write_text_file(proj / "src" / "main.cpp", "int main() { return 0; }\n"); + write_text_file(proj / "inc2" / "cfg.hpp", "#define CFG_VAL 1\n"); + write_text_file(proj / ".env", "API_KEY=do_not_capture\n"); + write_text_file(proj / ".git" / "config", "[core]\n"); + std::filesystem::create_directories(proj / "inc1"); + + Snapshot::SnapshotOptions opts; + opts.project_root = proj; + opts.snapshot_store_dir = store; + opts.reproducibility_epoch = 0; + + auto snap1 = + Snapshot::capture_snapshot(opts, {proj / "src" / "main.cpp"}, + {proj / "inc1", proj / "inc2"}, {{{"inc1", "inc2"}, "cfg.hpp"}}); + Void::Testing::expect(snap1.has_value()); + if (!snap1) { + return; + } + + // Secrets and .git are excluded. + Void::Testing::expect(!snap1->entries.contains(".env")); + Void::Testing::expect(!snap1->entries.contains(".git/config")); + + // Verify private copy / no hardlinks: distinct inode and nlink == 1. + const auto &main_entry = snap1->entries.at("src/main.cpp"); + auto src_meta = Platform::stat_lstat(proj / "src" / "main.cpp"); + auto mat_meta = Platform::stat_lstat(main_entry.materialized_path); + Void::Testing::expect(src_meta.has_value() && mat_meta.has_value()); + if (src_meta && mat_meta) { + Void::Testing::expect(src_meta->ino != mat_meta->ino); + Void::Testing::expect_eq(mat_meta->nlink, std::uint64_t{1}); + Void::Testing::expect_eq(mat_meta->mtime_sec, std::int64_t{0}); + } + + // 1. Fresh before edits. + auto fresh0 = Snapshot::is_snapshot_fresh(*snap1, opts); + Void::Testing::expect(fresh0.has_value() && *fresh0); + + // 2. Same-size edit with restored mtime MUST be detected! + auto orig_meta = Platform::stat_lstat(proj / "src" / "main.cpp"); + write_text_file(proj / "src" / "main.cpp", "int main() { return 1; }\n"); + (void)Platform::set_canonical_mtime(proj / "src" / "main.cpp", orig_meta->mtime_sec); + auto fresh1 = Snapshot::is_snapshot_fresh(*snap1, opts); + Void::Testing::expect(fresh1.has_value() && !*fresh1); + // Sealed snapshot file was NOT mutated by editing live source! + auto sealed_bytes = Void::FileSystem::read_file(main_entry.materialized_path); + Void::Testing::expect(sealed_bytes.has_value() && + *sealed_bytes == "int main() { return 0; }\n"); + + // 3. Restore main.cpp, then create a shadowing header in earlier include dir inc1! + write_text_file(proj / "src" / "main.cpp", "int main() { return 0; }\n"); + auto fresh2 = Snapshot::is_snapshot_fresh(*snap1, opts); + Void::Testing::expect(fresh2.has_value() && *fresh2); + + write_text_file(proj / "inc1" / "cfg.hpp", "#define CFG_VAL 99\n"); + auto fresh3 = Snapshot::is_snapshot_fresh(*snap1, opts); + Void::Testing::expect(fresh3.has_value() && !*fresh3); + + // 4. Symlink escape outside project root must be rejected. + std::filesystem::create_symlink(outside, proj / "src" / "escape.hpp"); + auto esc_snap = Snapshot::capture_snapshot(opts, {proj / "src" / "escape.hpp"}, {}); + Void::Testing::expect(!esc_snap.has_value()); + + // 5. Symlink loop must be rejected. + std::filesystem::create_symlink(proj / "src" / "loop_b.hpp", proj / "src" / "loop_a.hpp"); + std::filesystem::create_symlink(proj / "src" / "loop_a.hpp", proj / "src" / "loop_b.hpp"); + auto loop_snap = Snapshot::capture_snapshot(opts, {proj / "src" / "loop_a.hpp"}, {}); + Void::Testing::expect(!loop_snap.has_value()); +} + +Void::Testing::Test state_store_cas_corruption_recovery_and_gc() { + Void::FileSystem::TempDir tmp{"vbs_state_"}; + auto store = State::StateStore::open(tmp / ".vbs"); + Void::Testing::expect(store.has_value()); + if (!store) { + return; + } + + const auto artifact = tmp / "out.o"; + write_text_file(artifact, "ELF_OBJECT_BYTES_1"); + auto blob1 = store->store_blob_from_file(artifact); + Void::Testing::expect(blob1.has_value()); + if (!blob1) { + return; + } + + // Store an unpinned blob to test GC removal. + const auto orphan_src = tmp / "orphan.o"; + write_text_file(orphan_src, "ORPHAN_BYTES"); + auto orphan_blob = store->store_blob_from_file(orphan_src); + Void::Testing::expect(orphan_blob.has_value()); + + // Refuse committing action referencing fake/missing blob. + State::ActionSuccessRecord bad_rec; + bad_rec.action_key = "bad_key"; + bad_rec.outputs["x"] = State::BlobRef{std::string(64, 'a'), 10, 0644}; + Void::Testing::expect(!store->record_action_success(bad_rec).has_value()); + + // Commit valid action referencing blob1. + State::ActionSuccessRecord good_rec; + good_rec.action_key = "good_key"; + good_rec.profile_identity = "prof1"; + good_rec.target_name = "app"; + good_rec.outputs[artifact.string()] = *blob1; + Void::Testing::expect(store->record_action_success(good_rec).has_value()); + + // Simulate uncommitted staging debris + dead-PID lease. + write_text_file(tmp / ".vbs" / "staging" / "partial.stage", "half-written"); + auto gc_stats = store->gc(); + Void::Testing::expect(gc_stats.has_value()); + if (gc_stats) { + Void::Testing::expect(gc_stats->removed_blobs >= 1); + Void::Testing::expect(gc_stats->retained_blobs >= 1); + } + Void::Testing::expect(store->verify_blob(blob1->sha256).value_or(false)); + Void::Testing::expect(!store->verify_blob(orphan_blob->sha256).value_or(true)); + + // Corrupt blob1 on disk and verify lookup detects corruption! + const auto blob_path = store->cas_blob_path(blob1->sha256); + (void)::chmod(blob_path.c_str(), 0644); + write_text_file(blob_path, "CORRUPTED_BYTES!!"); + Void::Testing::expect(!store->verify_blob(blob1->sha256).value_or(true)); + auto lookup = store->lookup_action("good_key"); + Void::Testing::expect(lookup.has_value() && !lookup->has_value()); +} + +Void::Testing::Test end_to_end_native_frontend_graph_execution_and_archive_member_removal() { + Void::FileSystem::TempDir tmp{"vbs_e2e_"}; + const auto proj = tmp / "app_proj"; + const auto build_dir = tmp / "build"; + + // Notice: NO .git directory exists in `proj` (archive-without-Git requirement!). + write_text_file(proj / "build-support" / "Flags.hpp", R"cpp(#pragma once +#include +namespace Helper { +void apply(Void::Build::Target t); +} +)cpp"); + write_text_file(proj / "build-support" / "Flags.cpp", R"cpp(#include "Flags.hpp" +namespace Helper { +void apply(Void::Build::Target t) { + t.compile_option("-Wall"); +} +} +)cpp"); + write_text_file(proj / "build.profiles.cpp", R"cpp(#include +void profiles(Void::Build::Profiles &p) { + p = Void::Build::default_profiles(); + p.inherit("fast", "release", {"-DFAST_MODE=1"}); +} +)cpp"); + write_text_file(proj / "build.cpp", R"cpp(#include "build-support/Flags.hpp" +#include + +void build(Void::Build::Project &project) { + // Deliberate stdout noise to verify result channel isolation! + std::cout << "noisy user diagnostic that must not break JSON protocol\n"; + + auto gen = project.custom_action("gen_header"); + gen.command({"/bin/sh", "-c", "mkdir -p \"$1\" && printf '#pragma once\\ninline int gen_val(){return 40;}\\n' > \"$1/generated.hpp\"", + "sh", "$GEN_DIR"}) + .outputs({"generated.hpp"}); + + auto priv_lib = project.static_library("priv_math"); + priv_lib.sources(project.glob("src/math/*.cpp")) + .include_directory("include", Void::Build::Visibility::Public); + + auto mid_lib = project.static_library("mid"); + mid_lib.sources({"src/mid.cpp"}) + .include_directory("include", Void::Build::Visibility::Public) + .link(priv_lib, Void::Build::Visibility::Private); // Private static dep must propagate to app link! + + auto app = project.executable("demo"); + app.sources({"src/main.cpp"}) + .link(mid_lib) + .include_directory("include", Void::Build::Visibility::Private) + .include_directory("$GEN/", Void::Build::Visibility::Private) + .depends_on(gen); + Helper::apply(app); + + auto extra = project.executable("unused_tool"); + extra.sources({"src/tool.cpp"}); +} +)cpp"); + + write_text_file(proj / "include" / "math.hpp", "int add_two();\nint mid_compute();\n"); + write_text_file(proj / "src" / "math" / "a.cpp", "int add_two() { return 2; }\n"); + write_text_file(proj / "src" / "math" / "removable.cpp", + "extern \"C\" int vbs_removable_symbol() { return 777; }\n"); + write_text_file(proj / "src" / "mid.cpp", + "#include \"math.hpp\"\nint mid_compute() { return add_two(); }\n"); + write_text_file(proj / "src" / "main.cpp", R"cpp(#include "math.hpp" +#include "generated.hpp" +#include +int main() { + std::cout << (gen_val() + mid_compute()) << "|" << __FILE__ << "|" << __DATE__ << "|" << __TIME__ << "\n"; + return 0; +} +)cpp"); + write_text_file(proj / "src" / "tool.cpp", "int main() { return 0; }\n"); + + // 1. Compile configuration descriptor out-of-process. + Config::FrontendOptions fopts; + fopts.project_root = proj; + fopts.build_root = build_dir; + fopts.sdk_include_dir = std::filesystem::path{Bootstrap::sdk_include_dir}; + fopts.sdk_source_dir = std::filesystem::path{Bootstrap::sdk_source_dir}; + + auto compiled1 = Config::compile_descriptor(fopts); + Void::Testing::expect(compiled1.has_value()); + if (!compiled1) { + return; + } + Void::Testing::expect(compiled1->recompiled); + + // Second compile without edits MUST reuse cached executable! + auto compiled2 = Config::compile_descriptor(fopts); + Void::Testing::expect(compiled2.has_value()); + if (compiled2) { + Void::Testing::expect(!compiled2->recompiled); + } + + // Editing included helper header MUST trigger recompilation! + write_text_file(proj / "build-support" / "Flags.hpp", R"cpp(#pragma once +#include +namespace Helper { +// edited comment to verify header depfile invalidation +void apply(Void::Build::Target t); +} +)cpp"); + auto compiled3 = Config::compile_descriptor(fopts); + Void::Testing::expect(compiled3.has_value()); + if (compiled3) { + Void::Testing::expect(compiled3->recompiled); + } + + // 2. Discover custom inherited profiles and evaluate for "fast" profile. + auto discovered_profiles = Config::discover_profiles(*compiled3, fopts); + Void::Testing::expect(discovered_profiles.has_value()); + if (!discovered_profiles) { + return; + } + auto ctx = discovered_profiles->resolve("fast", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, build_dir / ".vbs" / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) { + return; + } + auto desc = Config::evaluate_project(*compiled3, ctx, fopts); + Void::Testing::expect(desc.has_value()); + if (!desc) { + return; + } + + // Replace $GEN_DIR placeholder in custom_action command with profile gen dir for test. + const auto gen_dir = build_dir / "profiles" / "fast" / "gen"; + for (auto &t : desc->targets) { + for (auto &arg : t.command_argv) { + if (arg == "$GEN_DIR") { + arg = gen_dir.string(); + } + } + } + + // 3. Capture immutable snapshot + lower graph + execute ONLY target "demo"! + Snapshot::SnapshotOptions sopts; + sopts.project_root = proj; + sopts.snapshot_store_dir = build_dir / ".vbs" / "snapshots"; + sopts.reproducibility_epoch = 0; + auto snap = Snapshot::capture_snapshot(sopts, {}, {proj / "src", proj / "include"}); + Void::Testing::expect(snap.has_value()); + if (!snap) { + return; + } + + Graph::GraphLowerOptions gopts; + gopts.project_root = proj; + gopts.build_root = build_dir; + gopts.snapshot = &(*snap); + auto graph = Graph::lower_project_graph(*desc, *tc, gopts); + Void::Testing::expect(graph.has_value()); + if (!graph) { + return; + } + + // Graph contains ALL configured targets (including unused_tool for compdb!), + // while executing selected target "demo" skips unused_tool! + Void::Testing::expect_eq(graph->targets.size(), std::size_t{5}); + + auto state = State::StateStore::open(build_dir / ".vbs"); + Void::Testing::expect(state.has_value()); + if (!state) { + return; + } + + Execution::ExecutionOptions eopts; + eopts.jobs = 2; + eopts.selected_targets = {"demo"}; + auto rep1 = Execution::execute_graph(*graph, *state, eopts); + Void::Testing::expect(rep1.has_value() && rep1->succeeded); + if (!rep1) { + return; + } + Void::Testing::expect(rep1->executed_count > 0); + Void::Testing::expect( + !std::filesystem::exists(build_dir / "profiles" / "fast" / "out" / "bin" / "unused_tool")); + + // Run built demo executable and verify deterministic output & mapped __FILE__ path! + const auto demo_bin = build_dir / "profiles" / "fast" / "out" / "bin" / "demo"; + Platform::ProcessRequest run_demo; + run_demo.executable = demo_bin; + auto demo_out = Platform::run_supervised(run_demo); + Void::Testing::expect(demo_out.has_value() && demo_out->succeeded()); + if (demo_out) { + Void::Testing::expect(demo_out->stdout_data.starts_with("42|")); + // __FILE__ was remapped from snapshot path back to logical project path! + Void::Testing::expect(demo_out->stdout_data.find(proj.string()) != std::string::npos); + Void::Testing::expect(demo_out->stdout_data.find("snapshots/trees") == std::string::npos); + // SOURCE_DATE_EPOCH=0 produces deterministic Jan 1 1970|00:00:00! + Void::Testing::expect(demo_out->stdout_data.find("1970|00:00:00") != std::string::npos); + } + + // 4. Warm no-op rebuild must execute ZERO actions and hit cache for all! + auto rep2 = Execution::execute_graph(*graph, *state, eopts); + Void::Testing::expect(rep2.has_value() && rep2->succeeded); + if (rep2) { + Void::Testing::expect_eq(rep2->executed_count, std::size_t{0}); + Void::Testing::expect_eq(rep2->cached_count, rep2->total_selected); + } + + // 5. Delete src/math/removable.cpp and rebuild: verify symbol disappears from libpriv_math.a! + std::filesystem::remove(proj / "src" / "math" / "removable.cpp"); + auto snap2 = Snapshot::capture_snapshot(sopts, {}, {proj / "src", proj / "include"}); + Void::Testing::expect(snap2.has_value()); + gopts.snapshot = &(*snap2); + auto graph2 = Graph::lower_project_graph(*desc, *tc, gopts); + Void::Testing::expect(graph2.has_value()); + auto rep3 = Execution::execute_graph(*graph2, *state, eopts); + Void::Testing::expect(rep3.has_value() && rep3->succeeded); + + const auto archive_path = build_dir / "profiles" / "fast" / "out" / "libpriv_math.a"; + Platform::ProcessRequest nm_req; + nm_req.executable = "nm"; + nm_req.arguments = {archive_path.string()}; + auto nm_out = Platform::run_supervised(nm_req); + Void::Testing::expect(nm_out.has_value() && nm_out->succeeded()); + if (nm_out) { + Void::Testing::expect(nm_out->stdout_data.find("vbs_removable_symbol") == + std::string::npos); + } +} diff --git a/tests/DescribeContracts.cmake b/tests/DescribeContracts.cmake index 81aef22..f7700f9 100644 --- a/tests/DescribeContracts.cmake +++ b/tests/DescribeContracts.cmake @@ -30,14 +30,14 @@ foreach(profile IN ITEMS debug release) expect_json(-O3 profile compile_options 0) expect_json(-DNDEBUG profile compile_options 1) endif() - expect_json(vbs_sdk targets 0 name) + expect_json(VoidBuildSdk targets 0 name) expect_json(static_library targets 0 kind) expect_json(file targets 0 sources 0 kind) - expect_json(src/build.cpp targets 0 sources 0 path) + expect_json(src/Build.cpp targets 0 sources 0 path) expect_json(public targets 0 include_directories 0 visibility) expect_json(vbs targets 1 name) expect_json(executable targets 1 kind) - expect_json(vbs_sdk targets 1 links 0 target) + expect_json(VoidBuildSdk targets 1 links 0 target) expect_json(private targets 1 links 0 visibility) expect_json(VoidLibrary targets 1 links 1 dependency) expect_json(Void::Configuration targets 1 links 1 target) diff --git a/tests/ExampleContexts.cpp b/tests/ExampleContexts.cpp index fcbf465..40b178f 100644 --- a/tests/ExampleContexts.cpp +++ b/tests/ExampleContexts.cpp @@ -1,14 +1,16 @@ +#include #include #include -#include #include Void::Testing::Test example_uses_runtime_compiler() { - vbs::Profiles definitions; + Void::Build::Profiles definitions; profiles(definitions); - vbs::Project gcc{definitions.resolve("debug", vbs::CompilerFamily::gcc, "linux", "x86_64")}; - vbs::Project clang{definitions.resolve("debug", vbs::CompilerFamily::clang, "linux", "x86_64")}; + Void::Build::Project gcc{ + definitions.resolve("debug", Void::Build::CompilerFamily::Gcc, "linux", "x86_64")}; + Void::Build::Project clang{ + definitions.resolve("debug", Void::Build::CompilerFamily::Clang, "linux", "x86_64")}; build(gcc); build(clang); for (std::size_t index = 0; index < gcc.targets().size(); ++index) { @@ -24,11 +26,12 @@ Void::Testing::Test example_uses_runtime_compiler() { } Void::Testing::Test example_profile_options_are_separate() { - vbs::Profiles definitions; + Void::Build::Profiles definitions; profiles(definitions); - vbs::Project debug{definitions.resolve("debug", vbs::CompilerFamily::gcc, "linux", "x86_64")}; - vbs::Project release{ - definitions.resolve("release", vbs::CompilerFamily::gcc, "linux", "x86_64")}; + Void::Build::Project debug{ + definitions.resolve("debug", Void::Build::CompilerFamily::Gcc, "linux", "x86_64")}; + Void::Build::Project release{ + definitions.resolve("release", Void::Build::CompilerFamily::Gcc, "linux", "x86_64")}; build(debug); build(release); Void::Testing::expect( @@ -41,14 +44,15 @@ Void::Testing::Test example_profile_options_are_separate() { } Void::Testing::Test example_records_sources_links_and_pin() { - vbs::Project project{ - vbs::default_profiles().resolve("debug", vbs::CompilerFamily::gcc, "linux", "x86_64")}; + Void::Build::Project project{Void::Build::default_profiles().resolve( + "debug", Void::Build::CompilerFamily::Gcc, "linux", "x86_64")}; build(project); Void::Testing::expect_eq(project.targets().size(), std::size_t{2}); - Void::Testing::expect_eq(project.targets().at(0).name, std::string{"vbs_sdk"}); + Void::Testing::expect_eq(project.targets().at(0).name, std::string{"VoidBuildSdk"}); Void::Testing::expect_eq(project.targets().at(0).sources.at(0).path, - std::string{"src/build.cpp"}); - Void::Testing::expect_eq(project.targets().at(1).links.at(0).target, std::string{"vbs_sdk"}); + std::string{"src/Build.cpp"}); + Void::Testing::expect_eq(project.targets().at(1).links.at(0).target, + std::string{"VoidBuildSdk"}); Void::Testing::expect_eq(project.targets().at(1).links.at(1).target, std::string{"Void::Configuration"}); Void::Testing::expect_eq(project.dependencies().at(0).revision, diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp new file mode 100644 index 0000000..94912ec --- /dev/null +++ b/tests/FullV1Tests.cpp @@ -0,0 +1,1055 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace Void::Build; + +namespace { + +void write_file(const std::filesystem::path &path, std::string_view content) { + auto r = Platform::atomic_write_file(path, content, false); + Void::Testing::expect(r.has_value()); +} + +// Writes a raw malicious USTAR tar entry with arbitrary path/typeflag for security tests. +void write_raw_tar(const std::filesystem::path &tar_path, + const std::vector> &entries) { + std::ofstream out(tar_path, std::ios::binary | std::ios::trunc); + for (const auto &[name, typeflag, body] : entries) { + std::array hdr{}; + std::memcpy(hdr.data(), name.data(), std::min(name.size(), 100)); + auto oct = [](char *dst, std::size_t w, std::uint64_t v) { + std::memset(dst, '0', w - 1); + dst[w - 1] = '\0'; + for (std::size_t i = w - 1; i > 0; --i) { + dst[i - 1] = static_cast('0' + (v & 7u)); + v >>= 3; + } + }; + oct(hdr.data() + 100, 8, 0644); + oct(hdr.data() + 108, 8, 0); + oct(hdr.data() + 116, 8, 0); + oct(hdr.data() + 124, 12, body.size()); + oct(hdr.data() + 136, 12, 0); + 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 sum = 0; + for (const char c : hdr) + sum += static_cast(c); + oct(hdr.data() + 148, 7, sum); + hdr[155] = ' '; + out.write(hdr.data(), 512); + if (!body.empty()) { + out.write(body.data(), static_cast(body.size())); + const std::size_t pad = (512 - (body.size() % 512)) % 512; + if (pad > 0) { + std::array z{}; + out.write(z.data(), static_cast(pad)); + } + } + } + std::array end{}; + out.write(end.data(), 1024); +} + +} // namespace + +// === Plan 09: CompDB projection, selection ticket races, user-file preservation, recovery === +Void::Testing::Test compdb_projection_ticket_races_and_user_file_preservation() { + Void::FileSystem::TempDir tmp{"vbs_compdb_"}; + const auto proj = tmp / "proj"; + const auto build_dir = tmp / "build"; + + write_file(proj / "src" / "a.cpp", "int main() { return 0; }\n"); + write_file(proj / "src" / "b.cpp", "int helper() { return 1; }\n"); + // Unrelated user-owned compile_commands.json at project root MUST NEVER be overwritten! + write_file(proj / "compile_commands.json", "[{\"user_owned\":true}]\n"); + + auto debug_ctx = + default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto rel_ctx = + default_profiles().resolve("release", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(debug_ctx, build_dir / ".vbs" / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) + return; + + auto make_desc = [](const ProfileContext &ctx) { + Graph::ProjectDescription d; + d.profile = ctx; + TargetRecord t1; + t1.name = "app"; + t1.kind = TargetKind::Executable; + t1.sources.push_back({SourceKind::File, "src/a.cpp"}); + t1.defines.push_back({"LITERAL_PATH=\"/snapshots/trees/untouched\"", Visibility::Private}); + d.targets.push_back(t1); + TargetRecord t2; + t2.name = "other"; + t2.kind = TargetKind::StaticLibrary; + t2.sources.push_back({SourceKind::File, "src/b.cpp"}); + d.targets.push_back(t2); + return d; + }; + + Snapshot::SnapshotOptions sopts; + sopts.project_root = proj; + sopts.snapshot_store_dir = build_dir / ".vbs" / "snapshots"; + auto snap = Snapshot::capture_snapshot(sopts, {}, {proj / "src"}); + Void::Testing::expect(snap.has_value()); + if (!snap) + return; + + auto g_dbg = Graph::lower_project_graph(make_desc(debug_ctx), *tc, + {proj, build_dir, &(*snap), {}, 32768}); + auto g_rel = + Graph::lower_project_graph(make_desc(rel_ctx), *tc, {proj, build_dir, &(*snap), {}, 32768}); + Void::Testing::expect(g_dbg.has_value() && g_rel.has_value()); + if (!g_dbg || !g_rel) + return; + + // 1. Reserve ticket 1 for debug, then ticket 2 for release -> release finishes FIRST, + // debug finishes LATER (reverse-order race!). Ticket 1 MUST NOT overwrite Ticket 2! + auto t1 = Editor::reserve_selection_ticket(proj, build_dir, "debug"); + auto t2 = Editor::reserve_selection_ticket(proj, build_dir, "release"); + Void::Testing::expect(t1.has_value() && t2.has_value() && *t2 > *t1); + + auto pub_rel = Editor::publish_profile_compdb(*g_rel, {proj, build_dir, true, *t2, true}); + auto pub_dbg = Editor::publish_profile_compdb(*g_dbg, {proj, build_dir, true, *t1, true}); + Void::Testing::expect(pub_rel.has_value() && pub_dbg.has_value()); + + // Selection MUST remain "release" (ticket 2)! + auto sel = Editor::read_selection_state(proj); + Void::Testing::expect(sel.has_value() && sel->has_value()); + if (sel && *sel) { + Void::Testing::expect_eq((*sel)->selected_profile, std::string{"release"}); + Void::Testing::expect(!(*sel)->managed_root_alias_active); + } + + // User-owned root compile_commands.json was NOT overwritten! + auto user_file = Void::FileSystem::read_file(proj / "compile_commands.json"); + Void::Testing::expect(user_file.has_value() && *user_file == "[{\"user_owned\":true}]\n"); + + // 2. Verify projected JSON covers BOTH targets, points to editable source path, + // and did NOT corrupt literal macro definitions! + auto compdb_text = Void::FileSystem::read_file(build_dir / "compile_commands.json"); + Void::Testing::expect(compdb_text.has_value()); + if (compdb_text) { + auto parsed = Void::Json::Strict::parse(*compdb_text); + Void::Testing::expect(parsed.has_value()); + Void::Testing::expect(compdb_text->find("src/a.cpp") != std::string::npos); + Void::Testing::expect(compdb_text->find("src/b.cpp") != std::string::npos); + Void::Testing::expect( + compdb_text->find("LITERAL_PATH=\\\"/snapshots/trees/untouched\\\"") != + std::string::npos); + } + + // 3. Manual switch to debug creates newer ticket; watcher refresh on release does NOT steal! + auto switched = Editor::select_editor_profile(proj, build_dir, "debug", true); + Void::Testing::expect(switched.has_value() && switched->selected_profile == "debug"); + + auto watch_pub = + Editor::publish_profile_compdb(*g_rel, {proj, build_dir, false, std::nullopt, true}); + Void::Testing::expect(watch_pub.has_value()); + auto sel2 = Editor::read_selection_state(proj); + Void::Testing::expect(sel2 && *sel2 && (*sel2)->selected_profile == "debug"); + + // 4. Crash recovery restores deleted build-root compile_commands.json symlink! + std::filesystem::remove(build_dir / "compile_commands.json"); + Void::Testing::expect(Editor::recover_editor_pointers(proj).has_value()); + Void::Testing::expect(std::filesystem::exists(build_dir / "compile_commands.json")); +} + +// === Plan 10: Inotify watcher + strict MetadataOnly watch boundary === +Void::Testing::Test watcher_inotify_and_metadata_only_forbids_foreign_configure() { + Void::FileSystem::TempDir tmp{"vbs_watch_"}; + const auto proj = tmp / "proj"; + const auto build_dir = tmp / "build"; + + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + auto app = p.executable("wapp"); + app.sources({"src/main.cpp"}); +} +)cpp"); + write_file(proj / "src" / "main.cpp", "int main() { return 0; }\n"); + + // 1. Verify InotifyWatcher sees file edit and ignores excluded build/ directory. + auto watcher = Watch::InotifyWatcher::create(proj); + Void::Testing::expect(watcher.has_value()); + if (watcher) { + write_file(proj / "src" / "added.cpp", "int extra() { return 1; }\n"); + auto batch = + watcher->poll_events(std::chrono::milliseconds{200}, std::chrono::milliseconds{20}); + Void::Testing::expect(batch.has_value() && !batch->changed_paths.empty()); + } + + // 2. MetadataOnly cycle MUST NOT compile targets and MUST report stale provider cleanly! + bool foreign_configure_called = false; + Watch::WatchLoopOptions wopts; + wopts.mode = Watch::WatchMode::MetadataOnly; + wopts.frontend.project_root = proj; + wopts.frontend.build_root = build_dir; + wopts.frontend.sdk_include_dir = std::filesystem::path{Bootstrap::sdk_include_dir}; + wopts.frontend.sdk_source_dir = std::filesystem::path{Bootstrap::sdk_source_dir}; + wopts.explicit_profile = "debug"; + wopts.max_cycles = 1; + wopts.provider_reader = [&](const Graph::ProjectDescription &, Watch::WatchMode mode) { + if (mode == Watch::WatchMode::FullBuild) { + foreign_configure_called = true; + } + return Watch::CachedProviderSnapshot{true, "", {}}; + }; + + auto cycles = Watch::run_watch_loop(wopts); + Void::Testing::expect(cycles.has_value() && cycles->size() == 1); + Void::Testing::expect(!foreign_configure_called); + if (cycles && !cycles->empty()) { + Void::Testing::expect(cycles->front().compdb_published); + Void::Testing::expect_eq(cycles->front().executed_actions, std::size_t{0}); + } + // No binary built in MetadataOnly mode! + Void::Testing::expect( + !std::filesystem::exists(build_dir / "profiles" / "debug" / "out" / "bin" / "wapp")); +} + +// === Plan 11: TOML 1.0, PubGrub solver (with exhaustive oracle), atomic CAS lockfile === +Void::Testing::Test toml_solver_oracle_and_atomic_cas_lockfile() { + Void::FileSystem::TempDir tmp{"vbs_pkg_"}; + const auto toml_file = tmp / "vbs.deps.toml"; + write_file(toml_file, R"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 +THREADS = 4 + +[dependencies.fmt] +package = "fmt" +version = "^11.0" +registry = "https://registry.void.example" +features = ["header-only"] +)toml"); + + auto loaded = Package::load_dependencies_toml(toml_file); + Void::Testing::expect(loaded.has_value()); + if (!loaded) + return; + Void::Testing::expect_eq(loaded->size(), std::size_t{2}); + + // C++/TOML conflict rejection with BOTH origins diagnosed! + DependencyRecord conflicting; + conflicting.name = "fmt"; + conflicting.source_kind = DependencySourceKind::Package; + conflicting.package = "fmt"; + conflicting.version = "^10.0"; // Conflicts with ^11.0 in TOML! + auto merged_bad = Package::merge_dependencies({conflicting}, *loaded); + Void::Testing::expect(!merged_bad.has_value()); + if (!merged_bad) { + Void::Testing::expect(merged_bad.error().message().find("build.cpp") != std::string::npos); + Void::Testing::expect(merged_bad.error().message().find("vbs.deps.toml") != + std::string::npos); + } + + // PubGrub diamond resolution + pinned non-upgrade + registry authority isolation + conflict + // trace. + Package::PackageIndex index; + const Package::PackageId regA_foo{"https://regA.example", "foo"}; + const Package::PackageId regB_foo{"https://regB.example", "foo"}; + const Package::PackageId regA_bar{"https://regA.example", "bar"}; + const Package::PackageId regA_baz{"https://regA.example", "baz"}; + + auto ver = [](std::string_view s) { return *Void::Semver::parse_strict(s); }; + index.add_release( + {regA_foo, ver("1.0.0"), false, "sha_f10", "", {{regA_bar, "^1.0", {}, "foo"}}, {}}); + index.add_release( + {regA_foo, ver("1.1.0"), false, "sha_f11", "", {{regA_bar, "^1.2", {}, "foo"}}, {}}); + index.add_release({regA_foo, ver("1.2.0"), true, "sha_f12_yanked", "", {}, {}}); // Yanked! + index.add_release( + {regB_foo, ver("9.0.0"), false, "sha_regB", "", {}, {}}); // Separate registry! + index.add_release({regA_bar, ver("1.0.0"), false, "sha_b10", "", {}, {}}); + index.add_release({regA_bar, ver("1.1.0"), false, "sha_b11", "", {}, {}}); + index.add_release({regA_bar, ver("1.2.0"), false, "sha_b12", "", {}, {}}); + index.add_release( + {regA_baz, ver("1.0.0"), false, "sha_z10", "", {{regA_bar, "<1.2.0", {}, "baz"}}, {}}); + + // Diamond: root needs foo ^1.0 AND baz ^1.0. + // foo 1.1.0 requires bar ^1.2, conflicting with baz 1.0.0 requiring bar <1.2.0. + // Solver MUST backtrack from foo 1.1.0 to foo 1.0.0 + bar 1.1.0 (and skip yanked 1.2.0 & regB)! + auto solved = Package::solve_dependencies( + {{regA_foo, "^1.0", {}, "root"}, {regA_baz, "^1.0", {}, "root"}}, index); + Void::Testing::expect(solved.has_value()); + if (solved) { + Void::Testing::expect_eq(solved->packages.at(regA_foo).version.to_string(), + std::string{"1.0.0"}); + Void::Testing::expect_eq(solved->packages.at(regA_bar).version.to_string(), + std::string{"1.1.0"}); + Void::Testing::expect(!solved->packages.contains(regB_foo)); + } + + // Pinned compatible version (bar 1.0.0) must NOT silently upgrade to 1.1.0! + Package::SolveOptions pin_opts; + pin_opts.pinned_versions[regA_bar] = ver("1.0.0"); + auto solved_pinned = Package::solve_dependencies( + {{regA_foo, "^1.0", {}, "root"}, {regA_baz, "^1.0", {}, "root"}}, index, pin_opts); + Void::Testing::expect(solved_pinned.has_value()); + if (solved_pinned) { + Void::Testing::expect_eq(solved_pinned->packages.at(regA_bar).version.to_string(), + std::string{"1.0.0"}); + } + + // Unsatisfiable conflict returns clear diagnostic naming packages. + auto unsat = Package::solve_dependencies({{regA_bar, ">=2.0.0", {}, "root"}}, index); + Void::Testing::expect(!unsat.has_value()); + + // Atomic CAS lockfile: multiple profiles coexist; --locked refuses mutation; mismatch fails! + const auto lock_path = tmp / "vbs.lock"; + auto dbg = default_profiles().resolve("debug", CompilerFamily::Gcc, "Linux", "x86_64"); + auto rel = default_profiles().resolve("release", CompilerFamily::Gcc, "Linux", "x86_64"); + + Package::LockContextRecord ctx_dbg{ + Package::make_lock_context_key(dbg, "target"), + "debug", + "gcc", + "Linux", + "x86_64", + "target", + Package::compute_declaration_fingerprint(dbg, "target", *loaded), + {}}; + Package::LockContextRecord ctx_rel{ + Package::make_lock_context_key(rel, "target"), + "release", + "gcc", + "Linux", + "x86_64", + "target", + Package::compute_declaration_fingerprint(rel, "target", *loaded), + {}}; + + // --locked refuses creating missing lock. + Void::Testing::expect( + !Package::publish_lock_context_cas(lock_path, "", ctx_dbg, true).has_value()); + + auto p1 = Package::publish_lock_context_cas(lock_path, "", ctx_dbg, false); + Void::Testing::expect(p1.has_value()); + if (!p1) + return; + + // Concurrent release profile update merges cleanly without overwriting debug! + auto p2 = Package::publish_lock_context_cas(lock_path, p1->revision_hash, ctx_rel, false); + Void::Testing::expect(p2.has_value()); + if (p2) { + Void::Testing::expect(p2->document.contexts.contains(ctx_dbg.context_key)); + Void::Testing::expect(p2->document.contexts.contains(ctx_rel.context_key)); + // Changed declaration fingerprint fails validation! + Void::Testing::expect( + !Package::validate_locked_context(p2->document, ctx_dbg.context_key, "changed_fp") + .has_value()); + } +} + +// === Plan 12: Deterministic tar, malicious archive security, binary ABI matching, redaction === +Void::Testing::Test archive_security_determinism_binary_abi_and_redaction() { + Void::FileSystem::TempDir tmp{"vbs_arc_"}; + const auto proj = tmp / "pkg_src"; + write_file(proj / "build.cpp", "void build(Void::Build::Project&) {}\n"); + write_file(proj / "build-support" / "Helper.hpp", "// helper\n"); + write_file(proj / ".git" / "HEAD", "ref: refs/heads/main\n"); + write_file(proj / ".env", "SECRET=123\n"); + + const auto tar1 = tmp / "pkg1.tar"; + const auto tar2 = tmp / "pkg2.tar"; + auto sha1 = Package::create_source_package(proj, tar1, 0); + auto sha2 = Package::create_source_package(proj, tar2, 0); + Void::Testing::expect(sha1.has_value() && sha2.has_value() && *sha1 == *sha2); + + const auto out_dir = tmp / "extracted"; + auto stats = Package::extract_safe_tar(tar1, out_dir); + Void::Testing::expect(stats.has_value()); + Void::Testing::expect(std::filesystem::exists(out_dir / "build-support" / "Helper.hpp")); + Void::Testing::expect(!std::filesystem::exists(out_dir / ".git" / "HEAD")); + Void::Testing::expect(!std::filesystem::exists(out_dir / ".env")); + + // Malicious tar rejection: path traversal, absolute path, symlink, duplicate path, quota. + const auto trav_tar = tmp / "trav.tar"; + write_raw_tar(trav_tar, {{"../escape.txt", '0', "evil"}}); + Void::Testing::expect(!Package::extract_safe_tar(trav_tar, tmp / "x1").has_value()); + + const auto abs_tar = tmp / "abs.tar"; + write_raw_tar(abs_tar, {{"/tmp/evil.txt", '0', "evil"}}); + Void::Testing::expect(!Package::extract_safe_tar(abs_tar, tmp / "x2").has_value()); + + const auto sym_tar = tmp / "sym.tar"; + write_raw_tar(sym_tar, {{"link.txt", '2', ""}}); + Void::Testing::expect(!Package::extract_safe_tar(sym_tar, tmp / "x3").has_value()); + + const auto dup_tar = tmp / "dup.tar"; + write_raw_tar(dup_tar, {{"a.txt", '0', "1"}, {"a.txt", '0', "2"}}); + Void::Testing::expect(!Package::extract_safe_tar(dup_tar, tmp / "x4").has_value()); + + // Secret redaction. + const auto redacted = + Package::redact_secrets("fetch https://alice:supersecret@reg.example/a Bearer tok_xyz123"); + Void::Testing::expect(redacted.find("supersecret") == std::string::npos); + Void::Testing::expect(redacted.find("tok_xyz123") == std::string::npos); + + // Binary ABI key rejects mismatched sanitizer/LTO/ABI. + Package::BinaryCompatibilityKey key{"Linux", "x86_64", "gcc", "16.2", "libstdc++", + "static", "", "address", "none", "dep_abc"}; + Package::BinaryVariantMeta mismatch{"v1", "Linux", "x86_64", "gcc", "16.2", + "libstdc++", "static", "", "", "none", + "dep_abc", "sha", "url"}; + Package::BinaryVariantMeta exact = mismatch; + exact.sanitizers_key = "address"; + Void::Testing::expect(!Package::select_compatible_binary(key, {mismatch}).has_value()); + Void::Testing::expect(Package::select_compatible_binary(key, {mismatch, exact}).has_value()); +} + +// === Plan 13, 14, 15: Real CMake provider, Meson provider, VbsDeps.cmake bridge, Install/Relocate +// === +Void::Testing::Test foreign_cmake_meson_providers_bridge_and_relocatable_install() { + Void::FileSystem::TempDir tmp{"vbs_foreign_"}; + auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, tmp / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) + return; + + // 1. Real CMake dependency project built via CMake File API provider! + const auto cm_src = tmp / "cm_dep"; + write_file(cm_src / "CMakeLists.txt", R"cmake( +cmake_minimum_required(VERSION 3.20) +project(cm_dep LANGUAGES CXX) +add_library(cm_math STATIC src/math.cpp) +target_include_directories(cm_math PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_compile_definitions(cm_math PUBLIC CM_DEP_DEFINED=1) +)cmake"); + write_file(cm_src / "include" / "cm_math.hpp", "#pragma once\nint cm_magic();\n"); + write_file(cm_src / "src" / "math.cpp", + "#include \"cm_math.hpp\"\nint cm_magic() { return 100; }\n"); + + DependencyRecord cm_dep; + cm_dep.name = "cm_dep"; + cm_dep.source_kind = DependencySourceKind::Path; + cm_dep.location = cm_src.string(); + cm_dep.builder = "cmake"; + + auto mat_cm = + Package::materialize_dependency_source(cm_dep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat_cm.has_value()); + if (!mat_cm) + return; + + // MetadataOnly BEFORE build MUST return stale_needs_build=true without invoking CMake! + auto stale_cm = Provider::resolve_foreign_provider( + {cm_dep, *mat_cm, ctx, *tc, tmp / "prov", Provider::ProviderMode::MetadataOnly, {}}); + Void::Testing::expect(stale_cm.has_value() && stale_cm->stale_needs_build); + + // FullBuild invokes CMake + File API and imports cm_math! + auto built_cm = Provider::resolve_foreign_provider( + {cm_dep, *mat_cm, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}); + Void::Testing::expect(built_cm.has_value() && built_cm->targets.contains("cm_dep::cm_math")); + if (!built_cm) + return; + + // MetadataOnly AFTER build reads validated cache with from_cache=true! + auto cached_cm = Provider::resolve_foreign_provider( + {cm_dep, *mat_cm, ctx, *tc, tmp / "prov", Provider::ProviderMode::MetadataOnly, {}}); + Void::Testing::expect(cached_cm.has_value() && cached_cm->from_cache && + !cached_cm->stale_needs_build); + + // Timestamp-preserved source edit invalidates provider input hash! + auto old_meta = Platform::stat_lstat(cm_src / "src" / "math.cpp"); + write_file(cm_src / "src" / "math.cpp", + "#include \"cm_math.hpp\"\nint cm_magic() { return 200; }\n"); + (void)Platform::set_canonical_mtime(cm_src / "src" / "math.cpp", old_meta->mtime_sec); + auto mat_cm2 = + Package::materialize_dependency_source(cm_dep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat_cm2.has_value() && + mat_cm2->content_identity_hash != mat_cm->content_identity_hash); + auto built_cm2 = Provider::resolve_foreign_provider( + {cm_dep, *mat_cm2, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}); + Void::Testing::expect(built_cm2.has_value()); + if (!built_cm2) + return; + + // 2. Real Meson dependency project (if meson is in PATH)! + if (Platform::resolve_executable("meson").has_value()) { + const auto m_src = tmp / "meson_dep"; + write_file(m_src / "meson.build", R"meson( +project('meson_dep', 'cpp') +inc = include_directories('include') +static_library('m_helper', 'src/helper.cpp', include_directories: inc) +)meson"); + write_file(m_src / "include" / "m_helper.hpp", "#pragma once\nint m_magic();\n"); + write_file(m_src / "src" / "helper.cpp", + "#include \"m_helper.hpp\"\nint m_magic() { return 23; }\n"); + + DependencyRecord m_dep; + m_dep.name = "meson_dep"; + m_dep.source_kind = DependencySourceKind::Path; + m_dep.location = m_src.string(); + m_dep.builder = "meson"; + + auto mat_m = + Package::materialize_dependency_source(m_dep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat_m.has_value()); + if (mat_m) { + auto built_m = Provider::resolve_foreign_provider( + {m_dep, *mat_m, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}); + Void::Testing::expect(built_m.has_value() && + built_m->targets.contains("meson_dep::m_helper")); + } + } + + // 3. Missing Conan fails explicitly (never empty success!). + if (!Platform::resolve_executable("conan").has_value()) { + DependencyRecord conan_dep; + conan_dep.name = "zlib"; + conan_dep.source_kind = DependencySourceKind::Conan; + conan_dep.package = "zlib/1.3.1"; + conan_dep.builder = "conan"; + Package::MaterializedSource dummy{"zlib", cm_src, "dummy", true}; + auto cres = Provider::resolve_foreign_provider( + {conan_dep, dummy, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}); + Void::Testing::expect(!cres.has_value()); + } + + // 4. Native consumer links updated cm_dep::cm_math (returns 200!), installs & relocates prefix! + const auto consumer_proj = tmp / "consumer"; + write_file(consumer_proj / "include" / "wrap.hpp", "#pragma once\nint wrapped_magic();\n"); + write_file(consumer_proj / "src" / "wrap.cpp", + "#include \"wrap.hpp\"\n#include \"cm_math.hpp\"\nint wrapped_magic(){return " + "cm_magic()+CM_DEP_DEFINED;}\n"); + write_file(consumer_proj / "src" / "main.cpp", + "#include \"wrap.hpp\"\nint main(){return wrapped_magic()==201 ? 0 : 1;}\n"); + + Graph::ProjectDescription desc; + desc.profile = ctx; + TargetRecord wlib; + wlib.name = "wrap"; + wlib.kind = TargetKind::StaticLibrary; + wlib.sources.push_back({SourceKind::File, "src/wrap.cpp"}); + wlib.include_directories.push_back({"include", Visibility::Public, false}); + wlib.links.push_back({LinkKind::Imported, "cm_math", "cm_dep", Visibility::Private}); + wlib.install_rule = InstallRule{"wrap", {}, "lib", "default", false}; + desc.targets.push_back(wlib); + + TargetRecord app; + app.name = "app"; + app.kind = TargetKind::Executable; + app.sources.push_back({SourceKind::File, "src/main.cpp"}); + app.links.push_back({LinkKind::Local, "wrap", {}, Visibility::Private}); + desc.targets.push_back(app); + desc.install_rules.push_back({{}, "include", "include", "default", true}); + + auto graph = Graph::lower_project_graph( + desc, *tc, {consumer_proj, tmp / "cbuild", nullptr, built_cm2->targets, 32768}); + Void::Testing::expect(graph.has_value()); + if (!graph) + return; + auto state = State::StateStore::open(tmp / "cbuild" / ".vbs"); + Void::Testing::expect(state.has_value()); + if (!state) + return; + auto exec = Execution::execute_graph(*graph, *state); + Void::Testing::expect(exec.has_value() && exec->succeeded); + + Platform::ProcessRequest app_req; + app_req.executable = tmp / "cbuild" / "profiles" / "debug" / "out" / "bin" / "app"; + auto run_app = Platform::run_supervised(app_req); + Void::Testing::expect(run_app.has_value() && run_app->succeeded()); + + // Install -> Relocate prefix A to B -> Safe uninstall preserves unrelated user file! + const auto prefix_a = tmp / "prefix_a"; + const auto prefix_b = tmp / "prefix_b"; + auto inst = Install::install_project(desc, *graph, + {"WrapPkg", "1.2.3", prefix_a, std::nullopt, true, true}); + Void::Testing::expect(inst.has_value() && inst->cmake_config_file.has_value()); + if (inst && inst->cmake_config_file) { + auto cm_cfg = Void::FileSystem::read_file(*inst->cmake_config_file); + Void::Testing::expect(cm_cfg.has_value() && cm_cfg->find("cbuild") == std::string::npos); + } + std::filesystem::rename(prefix_a, prefix_b); + write_file(prefix_b / "user_notes.txt", "keep me"); + auto removed = Install::uninstall_prefix(prefix_b); + Void::Testing::expect(removed.has_value() && *removed >= 3); + Void::Testing::expect(std::filesystem::exists(prefix_b / "user_notes.txt")); + Void::Testing::expect(!std::filesystem::exists(prefix_b / "lib" / "libwrap.a")); + + // 5. Real CMake Bridge (VbsDeps.cmake) consumer test! + const auto vbs_bin = std::filesystem::path{Bootstrap::binary_dir} / "bin" / "vbs"; + const auto bridge_module = + std::filesystem::path{Bootstrap::source_dir} / "cmake" / "bridge" / "VbsDeps.cmake"; + if (std::filesystem::exists(vbs_bin) && Platform::resolve_executable("cmake").has_value()) { + const auto br_proj = tmp / "bridge_consumer"; + write_file(br_proj / "CMakeLists.txt", + "cmake_minimum_required(VERSION 4.0)\n" + "project(bridge_consumer LANGUAGES CXX)\n" + "include(\"" + + bridge_module.string() + + "\")\n" + "vbs_declare_dependency(cm_dep PATH \"" + + cm_src.string() + + "\" BUILDER cmake)\n" + "vbs_make_available(cm_dep)\n" + "add_executable(bapp main.cpp)\n" + "target_link_libraries(bapp PRIVATE cm_dep::cm_math)\n"); + write_file(br_proj / "main.cpp", + "#include \"cm_math.hpp\"\nint main(){return cm_magic()==200 ? 0 : 1;}\n"); + const auto br_build = tmp / "bridge_build"; + Platform::ProcessRequest cfg_req; + cfg_req.executable = "cmake"; + cfg_req.arguments = {"-S", + br_proj.string(), + "-B", + br_build.string(), + "-G", + "Ninja", + "-DVBS_EXECUTABLE=" + vbs_bin.string()}; + auto cfg_res = Platform::run_supervised(cfg_req); + Void::Testing::expect(cfg_res.has_value() && cfg_res->succeeded()); + if (cfg_res && cfg_res->succeeded()) { + Platform::ProcessRequest bld_req; + bld_req.executable = "cmake"; + bld_req.arguments = {"--build", br_build.string()}; + auto bld_res = Platform::run_supervised(bld_req); + Void::Testing::expect(bld_res.has_value() && bld_res->succeeded()); + Platform::ProcessRequest br_run_req; + br_run_req.executable = br_build / "bapp"; + auto run_res = Platform::run_supervised(br_run_req); + Void::Testing::expect(run_res.has_value() && run_res->succeeded()); + } + + // 6. Real `vbs install` and `vbs uninstall` CLI subcommands! + const auto cli_proj = tmp / "cli_inst_proj"; + const auto cli_build = tmp / "cli_inst_build"; + const auto cli_prefix = tmp / "cli_inst_prefix"; + write_file(cli_proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.executable("cli_hi").sources({"src/main.cpp"}).install("bin"); +} +)cpp"); + write_file(cli_proj / "src" / "main.cpp", "int main() { return 0; }\n"); + + Platform::ProcessRequest inst_req; + inst_req.executable = vbs_bin; + inst_req.arguments = {"install", "--project", cli_proj.string(), + "--build-dir", cli_build.string(), "--prefix", + cli_prefix.string(), "--package-name", "CliHiPkg"}; + auto inst_cli = Platform::run_supervised(inst_req); + Void::Testing::expect(inst_cli.has_value() && inst_cli->succeeded()); + Void::Testing::expect(std::filesystem::exists(cli_prefix / "bin" / "cli_hi")); + Void::Testing::expect( + std::filesystem::exists(cli_prefix / "share" / "vbs" / "CliHiPkg" / "package.json")); + + Platform::ProcessRequest uninst_req; + uninst_req.executable = vbs_bin; + uninst_req.arguments = {"uninstall", "--prefix", cli_prefix.string()}; + auto uninst_cli = Platform::run_supervised(uninst_req); + Void::Testing::expect(uninst_cli.has_value() && uninst_cli->succeeded()); + Void::Testing::expect(!std::filesystem::exists(cli_prefix / "bin" / "cli_hi")); + } +} + +// === Plan 08: Modern C++ (GCC16 P1689 named modules + partitions, cycle/dup checks, unity, PCH) +// === +Void::Testing::Test modern_cpp_modules_scan_collation_cycles_and_unity_exclusion() { + Void::FileSystem::TempDir tmp{"vbs_mod_"}; + auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, tmp / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) + return; + + // 1. Real GCC 16 P1689 scanning + collation + compiling + linking + executing a C++20 named + // module! + const auto mod_src = tmp / "math_mod.cppm"; + const auto main_src = tmp / "use_mod.cpp"; + write_file(mod_src, "export module vbs.math;\nexport int triple(int x) { return x * 3; }\n"); + write_file(main_src, "import vbs.math;\nint main() { return triple(14) == 42 ? 0 : 1; }\n"); + + auto u_mod = + Modules::scan_translation_unit(*tc, mod_src, tmp / "scan", {}, {}, {}, CxxStandard::Cxx20); + auto u_main = + Modules::scan_translation_unit(*tc, main_src, tmp / "scan", {}, {}, {}, CxxStandard::Cxx20); + Void::Testing::expect(u_mod.has_value() && u_main.has_value()); + if (u_mod && u_main) { + Void::Testing::expect(u_mod->provides.size() == 1 && u_mod->provides[0] == "vbs.math"); + Void::Testing::expect(u_main->required_modules.size() == 1 && + u_main->required_modules[0] == "vbs.math"); + + // Feed in reverse order (importer before provider!) to verify topological collation! + auto plan = Modules::collate_modules({*u_main, *u_mod}, tmp / "bmi", tc->identity_hash); + Void::Testing::expect(plan.has_value() && plan->ordered_units.size() == 2); + if (plan) { + Void::Testing::expect_eq(plan->ordered_units[0].source_file, mod_src); + Void::Testing::expect_eq(plan->ordered_units[1].source_file, main_src); + + // Compile provider then importer with generated GCC module-mapper and link! + std::vector objs; + for (std::size_t i = 0; i < plan->ordered_units.size(); ++i) { + const auto &node = plan->ordered_units[i]; + const auto obj = tmp / ("m" + std::to_string(i) + ".o"); + Toolchain::CompileRequest creq; + creq.source_file = node.source_file; + creq.output_object = obj; + creq.cxx_standard = CxxStandard::Cxx20; + creq.compile_options = {"-x", "c++"}; + creq.is_module_interface = !node.provides.empty(); + creq.module_mapper_file = node.module_mapper_path; + auto cmd = Toolchain::lower_compile_command(*tc, creq); + Void::Testing::expect(cmd.has_value()); + if (cmd) { + Platform::ProcessRequest creq_proc; + creq_proc.executable = cmd->executable; + creq_proc.arguments = cmd->arguments; + auto p = Platform::run_supervised(creq_proc); + Void::Testing::expect(p.has_value() && p->succeeded()); + objs.push_back(obj); + } + } + const auto exe = tmp / "mod_app"; + auto lcmd = Toolchain::lower_link_command(*tc, {TargetKind::Executable, + exe, + std::nullopt, + objs, + {}, + {}, + {}, + {}, + LtoMode::None, + {}}); + Void::Testing::expect(lcmd.has_value()); + if (lcmd) { + Platform::ProcessRequest link_proc; + link_proc.executable = lcmd->executable; + link_proc.arguments = lcmd->arguments; + auto lp = Platform::run_supervised(link_proc); + Void::Testing::expect(lp.has_value() && lp->succeeded()); + Platform::ProcessRequest run_proc; + run_proc.executable = exe; + auto rp = Platform::run_supervised(run_proc); + Void::Testing::expect(rp.has_value() && rp->succeeded()); + } + } + } + + // 2. Duplicate provider, missing provider, and module import cycles must fail clearly! + Modules::ModuleScanUnit dup_a{tmp / "a.cppm", {"dup"}, {}, true}; + Modules::ModuleScanUnit dup_b{tmp / "b.cppm", {"dup"}, {}, true}; + Void::Testing::expect(!Modules::collate_modules({dup_a, dup_b}, tmp / "bmi", "k").has_value()); + + Modules::ModuleScanUnit cyc_a{tmp / "ca.cppm", {"A"}, {"B"}, true}; + Modules::ModuleScanUnit cyc_b{tmp / "cb.cppm", {"B"}, {"A"}, true}; + Void::Testing::expect(!Modules::collate_modules({cyc_a, cyc_b}, tmp / "bmi", "k").has_value()); + + Modules::ModuleScanUnit miss{tmp / "m.cpp", {}, {"GhostMod"}, false}; + Void::Testing::expect(!Modules::collate_modules({miss}, tmp / "bmi", "k").has_value()); + + // 3. Unity batching MUST exclude .cppm module units and per-file-override sources! + auto unity = Modules::generate_unity_batches( + "lib", {tmp / "a.cpp", tmp / "b.cpp", tmp / "mod.cppm", tmp / "special.cpp"}, + {tmp / "special.cpp"}, 2, tmp / "unity"); + Void::Testing::expect(unity.has_value()); + if (unity) { + Void::Testing::expect_eq(unity->generated_unity_files.size(), std::size_t{1}); + Void::Testing::expect_eq(unity->standalone_files.size(), std::size_t{2}); + } +} + +// === Plan 04/08/19 Matrix: Clang 23 target toolchain probe, build, and P1689 module scan === +Void::Testing::Test clang23_target_toolchain_and_p1689_module_scan() { + if (!Platform::resolve_executable("clang++").has_value()) { + return; // Only skip if Clang is genuinely absent from PATH. + } + + Void::FileSystem::TempDir tmp{"vbs_clang23_"}; + auto ctx = default_profiles().resolve("debug", CompilerFamily::Clang, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, tmp / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) + return; + + Void::Testing::expect(tc->family == CompilerFamily::Clang); + Void::Testing::expect(tc->supports_cxx20); + + // Compile and execute a real C++20 binary via Clang 23 lowering. + const auto proj = tmp / "proj"; + const auto bdir = tmp / "build"; + write_file(proj / "src" / "main.cpp", + "#ifdef __clang__\nint main() { return 0; }\n#else\n#error not clang\n#endif\n"); + + Graph::ProjectDescription desc; + desc.profile = ctx; + TargetRecord app; + app.name = "clang_app"; + app.kind = TargetKind::Executable; + app.cxx_standard = CxxStandard::Cxx20; + app.sources.push_back({SourceKind::File, "src/main.cpp"}); + desc.targets.push_back(app); + + Snapshot::SnapshotOptions sopts; + sopts.project_root = proj; + sopts.snapshot_store_dir = bdir / ".vbs" / "snapshots"; + auto snap = Snapshot::capture_snapshot(sopts, {}, {proj / "src"}); + Void::Testing::expect(snap.has_value()); + if (!snap) + return; + + auto graph = Graph::lower_project_graph(desc, *tc, {proj, bdir, &(*snap), {}, 32768}); + Void::Testing::expect(graph.has_value()); + auto state = State::StateStore::open(bdir / ".vbs"); + Void::Testing::expect(state.has_value()); + if (!graph || !state) + return; + + auto exec = Execution::execute_graph(*graph, *state); + Void::Testing::expect(exec.has_value() && exec->succeeded); + Platform::ProcessRequest clang_run_req; + clang_run_req.executable = bdir / "profiles" / "debug" / "out" / "bin" / "clang_app"; + auto run_res = Platform::run_supervised(clang_run_req); + Void::Testing::expect(run_res.has_value() && run_res->succeeded()); + + // Also verify full Clang 23 graph-lowered module partition + primary interface + consumer + // build & run (two-step --precompile .pcm -> .o + -fmodule-file=) when clang-scan-deps exists! + if (tc->supports_p1689_scan) { + const auto mproj = tmp / "clang_mod_proj"; + const auto mbdir = tmp / "clang_mod_build"; + write_file( + mproj / "src" / "part.cppm", + "export module vbs.clangcalc:part;\nexport int part_mul(int x) { return x * 6; }\n"); + write_file(mproj / "src" / "calc.cppm", + "export module vbs.clangcalc;\nexport import :part;\n" + "export int calc_val(int x) { return part_mul(x) + 6; }\n"); + write_file(mproj / "src" / "main.cpp", + "import vbs.clangcalc;\nint main() { return calc_val(6) == 42 ? 0 : 1; }\n"); + + Graph::ProjectDescription mdesc; + mdesc.profile = ctx; + TargetRecord mapp; + mapp.name = "clang_mod_app"; + mapp.kind = TargetKind::Executable; + mapp.cxx_standard = CxxStandard::Cxx20; + // Intentionally reverse order (importer before primary before partition). + mapp.sources.push_back({SourceKind::File, "src/main.cpp"}); + mapp.sources.push_back({SourceKind::ModuleInterface, "src/calc.cppm"}); + mapp.sources.push_back({SourceKind::ModulePartition, "src/part.cppm"}); + mdesc.targets.push_back(mapp); + + auto mgraph = Graph::lower_project_graph(mdesc, *tc, {mproj, mbdir, nullptr, {}, 32768}); + Void::Testing::expect(mgraph.has_value()); + auto mstate = State::StateStore::open(mbdir / ".vbs"); + Void::Testing::expect(mstate.has_value()); + if (mgraph && mstate) { + std::size_t bmi_actions = 0; + for (const auto &a : mgraph->actions) { + if (a.kind == Graph::ActionKind::ModuleBmi) { + ++bmi_actions; + } + } + Void::Testing::expect_eq(bmi_actions, std::size_t{2}); + auto mexec = Execution::execute_graph(*mgraph, *mstate); + Void::Testing::expect(mexec.has_value() && mexec->succeeded); + Platform::ProcessRequest mrun; + mrun.executable = mbdir / "profiles" / "debug" / "out" / "bin" / "clang_mod_app"; + auto mres = Platform::run_supervised(mrun); + Void::Testing::expect(mres.has_value() && mres->succeeded()); + } + } +} + +// === Plan 08 Full Graph Integration: Modules+Partitions, Unity+PerFile, HeaderUnit, Sanitizers === +Void::Testing::Test graph_lowering_modules_partitions_unity_header_units_and_sanitizers() { + Void::FileSystem::TempDir tmp{"vbs_plan08_"}; + auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, tmp / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) + return; + + // 1. Incompatible sanitizer combination (ASan + TSan) MUST be rejected during lowering! + { + const auto sproj = tmp / "san_proj"; + write_file(sproj / "src" / "main.cpp", "int main() { return 0; }\n"); + Graph::ProjectDescription sdesc; + sdesc.profile = ctx; + TargetRecord bad_san; + bad_san.name = "bad_san"; + bad_san.kind = TargetKind::Executable; + bad_san.sources.push_back({SourceKind::File, "src/main.cpp"}); + bad_san.sanitizers = {Sanitizer::Address, Sanitizer::Thread}; + sdesc.targets.push_back(bad_san); + auto bad_graph = + Graph::lower_project_graph(sdesc, *tc, {sproj, tmp / "san_build", nullptr, {}, 32768}); + Void::Testing::expect(!bad_graph.has_value()); + if (!bad_graph) { + Void::Testing::expect(bad_graph.error().message().find("incompatible sanitizers") != + std::string::npos); + } + } + + // 2. Full GCC 16 graph-lowered module partition + primary interface + consumer (reverse order)! + { + const auto mproj = tmp / "mod_proj"; + const auto mbdir = tmp / "mod_build"; + write_file(mproj / "src" / "calc_impl.cppm", + "export module vbs.calc:impl;\nexport int add_two(int x) { return x + 2; }\n"); + write_file(mproj / "src" / "calc.cppm", + "export module vbs.calc;\nexport import :impl;\n" + "export int compute(int x) { return add_two(x * 4); }\n"); + write_file(mproj / "src" / "main.cpp", + "import vbs.calc;\nint main() { return compute(10) == 42 ? 0 : 1; }\n"); + + Graph::ProjectDescription mdesc; + mdesc.profile = ctx; + TargetRecord app; + app.name = "mod_part_app"; + app.kind = TargetKind::Executable; + app.cxx_standard = CxxStandard::Cxx20; + app.sources.push_back({SourceKind::File, "src/main.cpp"}); + app.sources.push_back({SourceKind::ModuleInterface, "src/calc.cppm"}); + app.sources.push_back({SourceKind::ModulePartition, "src/calc_impl.cppm"}); + mdesc.targets.push_back(app); + + auto mgraph = Graph::lower_project_graph(mdesc, *tc, {mproj, mbdir, nullptr, {}, 32768}); + Void::Testing::expect(mgraph.has_value()); + auto mstate = State::StateStore::open(mbdir / ".vbs"); + Void::Testing::expect(mstate.has_value()); + if (mgraph && mstate) { + auto exec = Execution::execute_graph(*mgraph, *mstate); + Void::Testing::expect(exec.has_value() && exec->succeeded); + Platform::ProcessRequest run; + run.executable = mbdir / "profiles" / "debug" / "out" / "bin" / "mod_part_app"; + auto res = Platform::run_supervised(run); + Void::Testing::expect(res.has_value() && res->succeeded()); + } + } + + // 3. Unity batching through Graph lowering + per-file-option exclusion! + { + const auto uproj = tmp / "unity_proj"; + const auto ubdir = tmp / "unity_build"; + write_file(uproj / "src" / "u1.cpp", "int u1_val() { return 10; }\n"); + write_file(uproj / "src" / "u2.cpp", "int u2_val() { return 20; }\n"); + write_file(uproj / "src" / "special.cpp", "int u3_val() { return SPECIAL_VAL; }\n"); + write_file(uproj / "src" / "main.cpp", + "int u1_val(); int u2_val(); int u3_val();\n" + "int main() { return (u1_val() + u2_val() + u3_val()) == 42 ? 0 : 1; }\n"); + + Graph::ProjectDescription udesc; + udesc.profile = ctx; + TargetRecord uapp; + uapp.name = "unity_app"; + uapp.kind = TargetKind::Executable; + uapp.unity_enabled = true; + uapp.unity_batch_size = 2; + uapp.sources.push_back({SourceKind::File, "src/u1.cpp"}); + uapp.sources.push_back({SourceKind::File, "src/u2.cpp"}); + uapp.sources.push_back({SourceKind::File, "src/special.cpp"}); + uapp.sources.push_back({SourceKind::File, "src/main.cpp"}); + uapp.per_file_options.push_back({"src/special.cpp", "-DSPECIAL_VAL=12"}); + udesc.targets.push_back(uapp); + + auto ugraph = Graph::lower_project_graph(udesc, *tc, {uproj, ubdir, nullptr, {}, 32768}); + Void::Testing::expect(ugraph.has_value()); + auto ustate = State::StateStore::open(ubdir / ".vbs"); + Void::Testing::expect(ustate.has_value()); + if (ugraph && ustate) { + std::size_t compile_count = 0; + for (const auto &a : ugraph->actions) { + if (a.kind == Graph::ActionKind::Compile) { + ++compile_count; + } + } + // 3 batchable files (batch_size=2 -> 2 unity files) + 1 excluded special.cpp = 3! + Void::Testing::expect_eq(compile_count, std::size_t{3}); + auto exec = Execution::execute_graph(*ugraph, *ustate); + Void::Testing::expect(exec.has_value() && exec->succeeded); + Platform::ProcessRequest run; + run.executable = ubdir / "profiles" / "debug" / "out" / "bin" / "unity_app"; + auto res = Platform::run_supervised(run); + Void::Testing::expect(res.has_value() && res->succeeded()); + } + } + + // 4. Explicit HeaderUnit lowering + build + import execution! + { + const auto hproj = tmp / "hu_proj"; + const auto hbdir = tmp / "hu_build"; + write_file(hproj / "include" / "hu_math.hpp", + "#pragma once\ninline int hu_magic() { return 77; }\n"); + write_file(hproj / "src" / "main.cpp", + "import \"hu_math.hpp\";\nint main() { return hu_magic() == 77 ? 0 : 1; }\n"); + + Graph::ProjectDescription hdesc; + hdesc.profile = ctx; + TargetRecord happ; + happ.name = "hu_app"; + happ.kind = TargetKind::Executable; + happ.cxx_standard = CxxStandard::Cxx20; + happ.include_directories.push_back({"include", Visibility::Private, false}); + happ.sources.push_back({SourceKind::HeaderUnit, "include/hu_math.hpp"}); + happ.sources.push_back({SourceKind::File, "src/main.cpp"}); + hdesc.targets.push_back(happ); + + auto hgraph = Graph::lower_project_graph(hdesc, *tc, {hproj, hbdir, nullptr, {}, 32768}); + Void::Testing::expect(hgraph.has_value()); + auto hstate = State::StateStore::open(hbdir / ".vbs"); + Void::Testing::expect(hstate.has_value()); + if (hgraph && hstate) { + std::size_t hu_actions = 0; + for (const auto &a : hgraph->actions) { + if (a.kind == Graph::ActionKind::HeaderUnit) { + ++hu_actions; + } + } + Void::Testing::expect_eq(hu_actions, std::size_t{1}); + auto exec = Execution::execute_graph(*hgraph, *hstate); + Void::Testing::expect(exec.has_value() && exec->succeeded); + Platform::ProcessRequest run; + run.executable = hbdir / "profiles" / "debug" / "out" / "bin" / "hu_app"; + auto res = Platform::run_supervised(run); + Void::Testing::expect(res.has_value() && res->succeeded()); + } + } +} diff --git a/tests/RegistryTests.cpp b/tests/RegistryTests.cpp new file mode 100644 index 0000000..03dbe5d --- /dev/null +++ b/tests/RegistryTests.cpp @@ -0,0 +1,318 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using namespace Void::Build; +using namespace Void::Build::Registry; + +namespace { + +std::string extract_session_cookie(const std::vector &set_cookies) { + for (const auto &sc : set_cookies) { + if (sc.starts_with("vbs_session=")) { + const auto semi = sc.find(';'); + return sc.substr(0, semi); + } + } + return {}; +} + +std::string extract_json_str(std::string_view json, const std::string &key) { + auto parsed = Void::Json::Strict::parse(json); + if (!parsed) + return {}; + const auto *obj = std::get_if(&parsed->value); + if (!obj) + return {}; + const auto it = obj->find(key); + if (it == obj->end()) + return {}; + const auto *s = std::get_if(&it->second.value); + return s ? *s : std::string{}; +} + +} // namespace + +Void::Testing::Test registry_rbac_immutability_csrf_xss_web_and_backup_restore() { + Void::FileSystem::TempDir tmp{"vbs_reg_"}; + RegistryConfig cfg; + cfg.data_dir = tmp / "data"; + cfg.web_root = std::filesystem::path{Bootstrap::source_dir} / "registry" / "web"; + cfg.bind_address = "127.0.0.1"; + cfg.port = 0; // Ephemeral port! + cfg.bootstrap_admin_user = "admin"; + cfg.bootstrap_admin_password = "admin_secret_password"; + + auto svc = RegistryService::open(cfg); + Void::Testing::expect(svc.has_value()); + if (!svc) + return; + + Void::Testing::expect( + (*svc)->create_user("pub_alice", "alice_pass", Role::Publisher).has_value()); + Void::Testing::expect((*svc)->create_user("read_bob", "bob_pass", Role::Reader).has_value()); + auto alice_tok = (*svc)->create_token("pub_alice", "ci", {"read", "publish"}); + auto bob_tok = (*svc)->create_token("read_bob", "ro", {"read"}); + Void::Testing::expect(alice_tok.has_value() && bob_tok.has_value()); + if (!alice_tok || !bob_tok) + return; + + Void::Testing::expect((*svc)->start_http().has_value()); + const auto port = (*svc)->bound_port(); + Void::Testing::expect(port > 0); + + // 1. Static web UI assets served with security headers; path traversal blocked! + auto idx = send_loopback_http(port, "GET", "/"); + Void::Testing::expect(idx.has_value() && idx->status == 200); + if (idx) { + Void::Testing::expect(idx->headers.contains("content-security-policy")); + Void::Testing::expect_eq(idx->headers.at("x-frame-options"), std::string{"DENY"}); + Void::Testing::expect(idx->body.find("VoidBuildSystem Registry") != std::string::npos); + } + auto trav = send_loopback_http(port, "GET", "/../CMakeLists.txt"); + Void::Testing::expect(trav.has_value() && trav->status == 403); + + // 2. Build a valid deterministic package tar and publish as Publisher Alice. + const auto pkg_src = tmp / "pkg_src"; + (void)Platform::atomic_write_file(pkg_src / "build.cpp", + "void build(Void::Build::Project&){}\n", false); + const auto tar1 = tmp / "p1.tar"; + auto sha1 = Package::create_source_package(pkg_src, tar1, 0); + Void::Testing::expect(sha1.has_value()); + auto bytes1 = Void::FileSystem::read_file(tar1); + Void::Testing::expect(bytes1.has_value()); + if (!sha1 || !bytes1) + return; + + // Reader Bob CANNOT publish (403)! + auto bob_pub = send_loopback_http( + port, "PUT", "/api/v1/packages/demo-pkg/1.0.0", + {{"Authorization", "Bearer " + *bob_tok}, {"X-Content-SHA256", *sha1}}, *bytes1); + Void::Testing::expect(bob_pub.has_value() && bob_pub->status == 403); + + // Wrong SHA-256 rejected (400)! + auto bad_sha = send_loopback_http( + port, "PUT", "/api/v1/packages/demo-pkg/1.0.0", + {{"Authorization", "Bearer " + *alice_tok}, {"X-Content-SHA256", std::string(64, '0')}}, + *bytes1); + Void::Testing::expect(bad_sha.has_value() && bad_sha->status == 400); + + // Malicious non-tar / traversal upload rejected (422)! + auto bad_tar = + send_loopback_http(port, "PUT", "/api/v1/packages/demo-pkg/1.0.0", + {{"Authorization", "Bearer " + *alice_tok}}, "not a valid tar archive"); + Void::Testing::expect(bad_tar.has_value() && bad_tar->status == 422); + + // Valid private package publish by Alice -> 201 Created! + auto pub_ok = send_loopback_http(port, "PUT", "/api/v1/packages/secret-pkg/1.0.0", + {{"Authorization", "Bearer " + *alice_tok}, + {"X-Content-SHA256", *sha1}, + {"X-Package-Private", "true"}, + {"X-Package-Description", ""}}, + *bytes1); + Void::Testing::expect(pub_ok.has_value() && pub_ok->status == 201); + + // Unauthenticated access to private package MUST fail (401)! + auto anon_priv = send_loopback_http(port, "GET", "/api/v1/packages/secret-pkg"); + Void::Testing::expect(anon_priv.has_value() && anon_priv->status == 401); + auto anon_dl = send_loopback_http(port, "GET", "/api/v1/packages/secret-pkg/1.0.0/download"); + Void::Testing::expect(anon_dl.has_value() && anon_dl->status == 401); + + // Idempotent same-bytes republish -> 200 OK! + auto idemp = send_loopback_http( + port, "PUT", "/api/v1/packages/secret-pkg/1.0.0", + {{"Authorization", "Bearer " + *alice_tok}, {"X-Content-SHA256", *sha1}}, *bytes1); + Void::Testing::expect(idemp.has_value() && idemp->status == 200); + + // Different bytes for SAME immutable release -> 409 Conflict! + (void)Platform::atomic_write_file(pkg_src / "extra.txt", "changed", false); + const auto tar2 = tmp / "p2.tar"; + auto sha2 = Package::create_source_package(pkg_src, tar2, 0); + auto bytes2 = Void::FileSystem::read_file(tar2); + auto conflict = send_loopback_http( + port, "PUT", "/api/v1/packages/secret-pkg/1.0.0", + {{"Authorization", "Bearer " + *alice_tok}, {"X-Content-SHA256", *sha2}}, *bytes2); + Void::Testing::expect(conflict.has_value() && conflict->status == 409); + + // 3. Browser session login (HttpOnly cookie) + CSRF rejection without header + valid CSRF yank! + auto login = send_loopback_http( + port, "POST", "/api/v1/auth/login", {{"Content-Type", "application/json"}}, + "{\"username\":\"admin\",\"password\":\"admin_secret_password\"}"); + Void::Testing::expect(login.has_value() && login->status == 200); + if (!login) + return; + const auto cookie = extract_session_cookie(login->set_cookies); + const auto csrf = extract_json_str(login->body, "csrf_token"); + Void::Testing::expect(!cookie.empty() && !csrf.empty()); + Void::Testing::expect(login->set_cookies[0].find("HttpOnly") != std::string::npos); + Void::Testing::expect(login->set_cookies[0].find("SameSite=Strict") != std::string::npos); + + // Mutation with session cookie WITHOUT X-CSRF-Token -> 403 CSRF rejected! + auto no_csrf = send_loopback_http(port, "POST", "/api/v1/packages/secret-pkg/1.0.0/yank", + {{"Cookie", cookie}}, "{\"yanked\":true}"); + Void::Testing::expect(no_csrf.has_value() && no_csrf->status == 403); + + // Mutation WITH valid X-CSRF-Token -> 200 OK! + auto with_csrf = + send_loopback_http(port, "POST", "/api/v1/packages/secret-pkg/1.0.0/yank", + {{"Cookie", cookie}, {"X-CSRF-Token", csrf}}, "{\"yanked\":true}"); + Void::Testing::expect(with_csrf.has_value() && with_csrf->status == 200); + + // Audit log contains zero secrets (no passwords or bearer tokens)! + auto audit = send_loopback_http(port, "GET", "/api/v1/audit", {{"Cookie", cookie}}); + Void::Testing::expect(audit.has_value() && audit->status == 200); + if (audit) { + Void::Testing::expect(audit->body.find("admin_secret_password") == std::string::npos); + Void::Testing::expect(audit->body.find(*alice_tok) == std::string::npos); + } + + // 4. Consistent backup & restore into a brand-new registry instance preserves releases & + // download! + const auto backup_dir = tmp / "backup"; + Void::Testing::expect((*svc)->backup_to(backup_dir).has_value()); + (*svc)->stop_http(); + + RegistryConfig cfg2 = cfg; + cfg2.data_dir = tmp / "restored_data"; + cfg2.bootstrap_admin_password.clear(); + auto svc2 = RegistryService::open(cfg2); + Void::Testing::expect(svc2.has_value()); + if (svc2) { + Void::Testing::expect((*svc2)->restore_from(backup_dir).has_value()); + Void::Testing::expect((*svc2)->start_http().has_value()); + auto dl = send_loopback_http((*svc2)->bound_port(), "GET", + "/api/v1/packages/secret-pkg/1.0.0/download", + {{"Authorization", "Bearer " + *alice_tok}}); + Void::Testing::expect(dl.has_value() && dl->status == 200 && dl->body == *bytes1); + (*svc2)->stop_http(); + } +} + +// End-to-end live client <-> server test: `vbs publish` -> `vbs deps resolve` -> `vbs build +// --locked`! +Void::Testing::Test cli_publish_deps_resolve_and_locked_build_against_live_registry() { + const auto vbs_bin = std::filesystem::path{Bootstrap::binary_dir} / "bin" / "vbs"; + Void::Testing::expect(std::filesystem::exists(vbs_bin)); + if (!std::filesystem::exists(vbs_bin)) { + return; + } + + Void::FileSystem::TempDir tmp{"vbs_reg_e2e_"}; + RegistryConfig cfg; + cfg.data_dir = tmp / "reg_data"; + cfg.web_root = std::filesystem::path{Bootstrap::source_dir} / "registry" / "web"; + cfg.bind_address = "127.0.0.1"; + cfg.port = 0; + cfg.bootstrap_admin_user = "admin"; + cfg.bootstrap_admin_password = "admin_e2e_password"; + + auto svc = RegistryService::open(cfg); + Void::Testing::expect(svc.has_value()); + if (!svc) + return; + Void::Testing::expect((*svc)->create_user("ci_pub", "ci_pass", Role::Publisher).has_value()); + auto tok = (*svc)->create_token("ci_pub", "publish", {"read", "publish"}); + Void::Testing::expect(tok.has_value()); + if (!tok) + return; + Void::Testing::expect((*svc)->start_http().has_value()); + const std::string reg_url = "http://127.0.0.1:" + std::to_string((*svc)->bound_port()); + + // 1. Create a real CMake library package and publish 1.0.0 and 1.1.0 via `vbs publish` CLI! + const auto pkg_dir = tmp / "hello_pkg"; + (void)Platform::atomic_write_file(pkg_dir / "CMakeLists.txt", R"cmake( +cmake_minimum_required(VERSION 3.20) +project(hello_pkg LANGUAGES CXX) +add_library(hello_pkg STATIC src/hello.cpp) +target_include_directories(hello_pkg PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") +)cmake", + false); + (void)Platform::atomic_write_file(pkg_dir / "include" / "hello_pkg.hpp", + "#pragma once\nint hello_pkg_value();\n", false); + (void)Platform::atomic_write_file( + pkg_dir / "src" / "hello.cpp", + "#include \"hello_pkg.hpp\"\nint hello_pkg_value() { return 10; }\n", false); + + Platform::ProcessRequest pub1; + pub1.executable = vbs_bin; + pub1.arguments = {"publish", "--project", pkg_dir.string(), "--registry", + reg_url, "--name", "hello-pkg", "--version", + "1.0.0", "--description", "Live E2E package"}; + pub1.environment.set_vars["VBS_REGISTRY_TOKEN"] = *tok; + auto r1 = Platform::run_supervised(pub1); + Void::Testing::expect(r1.has_value() && r1->succeeded()); + + // Publish 1.1.0 returning 42 so solver (^1.0) selects 1.1.0! + (void)Platform::atomic_write_file( + pkg_dir / "src" / "hello.cpp", + "#include \"hello_pkg.hpp\"\nint hello_pkg_value() { return 42; }\n", false); + Platform::ProcessRequest pub2 = pub1; + pub2.arguments[8] = "1.1.0"; + auto r2 = Platform::run_supervised(pub2); + Void::Testing::expect(r2.has_value() && r2->succeeded()); + + // 2. Create a consumer project declaring `.package("hello-pkg", "^1.0").registry(reg_url)`. + const auto cons_dir = tmp / "consumer"; + const auto cons_build = tmp / "consumer_build"; + (void)Platform::atomic_write_file(cons_dir / "build.cpp", + "#include \n" + "void build(Void::Build::Project &p) {\n" + " auto dep = p.dependency(\"hello\")\n" + " .package(\"hello-pkg\", \"^1.0\")\n" + " .registry(\"" + + reg_url + + "\");\n" + " p.executable(\"reg_consumer\")\n" + " .sources({\"src/main.cpp\"})\n" + " .link(dep.target(\"hello_pkg\"));\n" + "}\n", + false); + (void)Platform::atomic_write_file( + cons_dir / "src" / "main.cpp", + "#include \"hello_pkg.hpp\"\nint main() { return hello_pkg_value() == 42 ? 0 : 1; }\n", + false); + + // 3. Resolve dependencies into vbs.lock against the live registry! + Platform::ProcessRequest deps_req; + deps_req.executable = vbs_bin; + deps_req.arguments = {"deps", "resolve", "--project", cons_dir.string(), + "--build-dir", cons_build.string()}; + deps_req.environment.set_vars["VBS_REGISTRY_TOKEN"] = *tok; + auto deps_res = Platform::run_supervised(deps_req); + Void::Testing::expect(deps_res.has_value() && deps_res->succeeded()); + + auto lock_text = Void::FileSystem::read_file(cons_dir / "vbs.lock"); + Void::Testing::expect(lock_text.has_value()); + if (lock_text) { + Void::Testing::expect(lock_text->find("\"version\":\"1.1.0\"") != std::string::npos); + Void::Testing::expect(lock_text->find("\"source_kind\":\"package\"") != std::string::npos); + Void::Testing::expect(lock_text->find(*tok) == std::string::npos); // Zero token leaks! + } + + // 4. Build in --locked mode and execute the consumer binary! + Platform::ProcessRequest bld_req; + bld_req.executable = vbs_bin; + bld_req.arguments = {"build", "--project", cons_dir.string(), + "--build-dir", cons_build.string(), "--locked"}; + auto bld_res = Platform::run_supervised(bld_req); + Void::Testing::expect(bld_res.has_value() && bld_res->succeeded()); + + Platform::ProcessRequest run_req; + run_req.executable = cons_build / "profiles" / "debug" / "out" / "bin" / "reg_consumer"; + auto run_res = Platform::run_supervised(run_req); + Void::Testing::expect(run_res.has_value() && run_res->succeeded()); + + (*svc)->stop_http(); +} diff --git a/tests/SdkDeclarations.cpp b/tests/SdkDeclarations.cpp index 66ef6a4..7586435 100644 --- a/tests/SdkDeclarations.cpp +++ b/tests/SdkDeclarations.cpp @@ -1,15 +1,16 @@ +#include #include #include #include -#include #include #include #include namespace { -vbs::ProfileContext context() { - return vbs::default_profiles().resolve("debug", vbs::CompilerFamily::gcc, "linux", "x86_64"); +Void::Build::ProfileContext context() { + return Void::Build::default_profiles().resolve("debug", Void::Build::CompilerFamily::Gcc, + "linux", "x86_64"); } constexpr auto revision = "9931c5ffc4844a5e09e1b1db35b3d29c5097c3a5"; using Json = Void::Json::Strict::Value; @@ -23,59 +24,64 @@ std::string text(const Json &value) { return std::get(value.value); } // namespace Void::Testing::Test default_profiles_and_overrides() { - const auto profiles = vbs::default_profiles(); - const auto debug = profiles.resolve("debug", vbs::CompilerFamily::clang, "linux", "aarch64"); - const auto release = profiles.resolve("release", vbs::CompilerFamily::gcc, "linux", "x86_64"); + const auto profiles = Void::Build::default_profiles(); + const auto debug = + profiles.resolve("debug", Void::Build::CompilerFamily::Clang, "linux", "aarch64"); + const auto release = + profiles.resolve("release", Void::Build::CompilerFamily::Gcc, "linux", "x86_64"); Void::Testing::expect_eq(profiles.records().size(), std::size_t{2}); - Void::Testing::expect(debug.compiler == vbs::CompilerFamily::clang); + Void::Testing::expect(debug.compiler == Void::Build::CompilerFamily::Clang); Void::Testing::expect_eq(debug.architecture, std::string{"aarch64"}); Void::Testing::expect_eq(debug.compile_options.at(0), std::string{"-O0"}); Void::Testing::expect_eq(release.compile_options.at(0), std::string{"-O3"}); } Void::Testing::Test rejects_invalid_profiles() { - auto profiles = vbs::default_profiles(); + auto profiles = Void::Build::default_profiles(); Void::Testing::expect_throw([&] { profiles.add("debug"); }); Void::Testing::expect_throw([&] { profiles.add(""); }); Void::Testing::expect_throw([&] { profiles.add("bad", {""}); }); + Void::Testing::expect_throw([&] { + (void)profiles.resolve("unknown", Void::Build::CompilerFamily::Gcc, "linux", "x86_64"); + }); Void::Testing::expect_throw( - [&] { (void)profiles.resolve("unknown", vbs::CompilerFamily::gcc, "linux", "x86_64"); }); - Void::Testing::expect_throw([] { (void)vbs::parse_compiler("msvc"); }); + [] { (void)Void::Build::parse_compiler("msvc"); }); Void::Testing::expect_throw( - [&] { (void)profiles.resolve("debug", vbs::CompilerFamily::gcc, "", "x86_64"); }); + [&] { (void)profiles.resolve("debug", Void::Build::CompilerFamily::Gcc, "", "x86_64"); }); } Void::Testing::Test declaration_records_and_visibility() { - vbs::Project project{context()}; + Void::Build::Project project{context()}; auto library = project.static_library("library"); library.sources({"one.cpp", "two.cpp"}) - .include_directory("include", vbs::Visibility::public_) + .include_directory("include", Void::Build::Visibility::Public) .compile_option("-Wall"); auto executable = project.executable("app"); - executable.link(library).link(library, vbs::Visibility::interface_); - Void::Testing::expect(library.record().kind == vbs::TargetKind::static_library); + executable.link(library).link(library, Void::Build::Visibility::Interface); + Void::Testing::expect(library.record().kind == Void::Build::TargetKind::StaticLibrary); Void::Testing::expect_eq(library.record().sources.size(), std::size_t{2}); Void::Testing::expect(library.record().include_directories.at(0).visibility == - vbs::Visibility::public_); - Void::Testing::expect(executable.record().links.at(0).visibility == vbs::Visibility::private_); + Void::Build::Visibility::Public); + Void::Testing::expect(executable.record().links.at(0).visibility == + Void::Build::Visibility::Private); Void::Testing::expect(executable.record().links.at(1).visibility == - vbs::Visibility::interface_); + Void::Build::Visibility::Interface); } Void::Testing::Test sources_are_symbolic() { - vbs::Project project{context()}; + Void::Build::Project project{context()}; auto target = project.executable("symbolic"); target.sources({"missing/../literal.cpp"}).sources(project.glob("nonexistent/**/*.cpp")); Void::Testing::expect_eq(target.record().sources.at(0).path, std::string{"missing/../literal.cpp"}); - Void::Testing::expect(target.record().sources.at(0).kind == vbs::SourceKind::file); - Void::Testing::expect(target.record().sources.at(1).kind == vbs::SourceKind::glob); + Void::Testing::expect(target.record().sources.at(0).kind == Void::Build::SourceKind::File); + Void::Testing::expect(target.record().sources.at(1).kind == Void::Build::SourceKind::Glob); Void::Testing::expect_eq(target.record().sources.at(1).path, std::string{"nonexistent/**/*.cpp"}); } Void::Testing::Test handles_survive_record_growth() { - vbs::Project project{context()}; + Void::Build::Project project{context()}; auto library = project.static_library("first"); auto dependency = project.dependency("original"); const auto imported = dependency.target("Original::Library"); @@ -83,7 +89,7 @@ Void::Testing::Test handles_survive_record_growth() { (void)project.executable("target" + std::to_string(i)); (void)project.dependency("dependency" + std::to_string(i)); } - dependency.git("https://example.invalid/library.git", vbs::Commit{revision}).cmake(); + dependency.git("https://example.invalid/library.git", Void::Build::Commit{revision}).cmake(); library.compile_option("-Wextra"); auto app = project.executable("last"); app.link(library).link(imported); @@ -95,8 +101,8 @@ Void::Testing::Test handles_survive_record_growth() { } Void::Testing::Test rejects_cross_project_links() { - vbs::Project first{context()}; - vbs::Project second{context()}; + Void::Build::Project first{context()}; + Void::Build::Project second{context()}; auto app = first.executable("app"); auto other = second.static_library("other"); auto imported = second.dependency("remote").target("Remote::Library"); @@ -106,18 +112,18 @@ Void::Testing::Test rejects_cross_project_links() { } Void::Testing::Test rejects_expired_handles_and_owner_moves() { - static_assert(!std::is_move_constructible_v); - static_assert(!std::is_copy_constructible_v); - std::optional target; - std::optional dependency; - std::optional imported; + static_assert(!std::is_move_constructible_v); + static_assert(!std::is_copy_constructible_v); + std::optional target; + std::optional dependency; + std::optional imported; { - vbs::Project project{context()}; + Void::Build::Project project{context()}; target = project.executable("expired"); dependency = project.dependency("expired"); imported = dependency->target("Expired::Target"); } - vbs::Project replacement{context()}; + Void::Build::Project replacement{context()}; auto app = replacement.executable("new"); Void::Testing::expect_throw([&] { target->compile_option("-g"); }); Void::Testing::expect_throw([&] { dependency->cmake(); }); @@ -127,7 +133,7 @@ Void::Testing::Test rejects_expired_handles_and_owner_moves() { } Void::Testing::Test rejects_empty_and_duplicate_identifiers() { - vbs::Project project{context()}; + Void::Build::Project project{context()}; auto app = project.executable("app"); auto dep = project.dependency("dep"); Void::Testing::expect_throw( @@ -138,50 +144,51 @@ Void::Testing::Test rejects_empty_and_duplicate_identifiers() { Void::Testing::expect_throw([&] { (void)dep.target(""); }); Void::Testing::expect_throw([&] { app.include_directory(""); }); Void::Testing::expect_throw([&] { app.compile_option(""); }); - Void::Testing::expect_throw([] { (void)vbs::SourceSet::file(""); }); + Void::Testing::expect_throw( + [] { (void)Void::Build::SourceSet::file(""); }); Void::Testing::expect_throw([&] { (void)project.glob(""); }); } Void::Testing::Test rejects_contradictory_providers() { - vbs::Project project{context()}; + Void::Build::Project project{context()}; auto git = project.dependency("git"); - git.git("https://example.invalid/repo", vbs::Commit{revision}).cmake(); + git.git("https://example.invalid/repo", Void::Build::Commit{revision}).cmake(); Void::Testing::expect_throw([&] { git.package("pkg", "^1"); }); Void::Testing::expect_throw( - [&] { git.git("url", vbs::Commit{revision}); }); + [&] { git.git("url", Void::Build::Commit{revision}); }); Void::Testing::expect_throw([&] { git.cmake(); }); auto package = project.dependency("package"); package.package("pkg", "^1"); Void::Testing::expect_throw( - [&] { package.git("url", vbs::Commit{revision}); }); + [&] { package.git("url", Void::Build::Commit{revision}); }); Void::Testing::expect_throw([&] { package.cmake(); }); auto builder = project.dependency("builder"); builder.cmake(); Void::Testing::expect_throw([&] { builder.package("pkg", "^1"); }); Void::Testing::expect_throw( - [&] { builder.git("url", vbs::Commit{"main"}); }); + [&] { builder.git("url", Void::Build::Commit{"main"}); }); Void::Testing::expect_throw([&] { (void)project.to_json(); }); } Void::Testing::Test json_schema_types_and_escaping() { - vbs::Project project{context()}; + Void::Build::Project project{context()}; std::string escaped = "quote\" slash\\ newline\n\r\t"; for (char c = 0; c < 32; ++c) escaped += c; auto dep = project.dependency("dependency"); - dep.git("https://example.invalid/\"repo", vbs::Commit{revision}) + dep.git("https://example.invalid/\"repo", Void::Build::Commit{revision}) .cmake({{"string", escaped}, {"literal", "text"}, {"bool", false}, {"integer", -42}, {"maximum", std::numeric_limits::max()}}); auto library = project.static_library("library"); - library.sources(vbs::SourceSet::file(escaped)) + library.sources(Void::Build::SourceSet::file(escaped)) .sources(project.glob("src/**/*.cpp")) - .include_directory("include", vbs::Visibility::public_) + .include_directory("include", Void::Build::Visibility::Public) .link(dep.target("Remote::Library")); auto app = project.executable("app"); - app.link(library, vbs::Visibility::public_).compile_option(escaped); + app.link(library, Void::Build::Visibility::Public).compile_option(escaped); project.dependency("package").package("org/pkg", ">=1.2 <2"); const auto json = project.to_json(); Void::Testing::expect_eq(json, project.to_json()); @@ -215,9 +222,11 @@ Void::Testing::Test json_preserves_valid_utf8() { // Boundary scalar values for every UTF-8 width, including either side of surrogates. const std::string unicode = "ASCII \xc2\x80\xdf\xbf\xe0\xa0\x80\xed\x9f\xbf" "\xee\x80\x80\xef\xbf\xbf\xf0\x90\x80\x80\xf4\x8f\xbf\xbf"; - vbs::Project project{context()}; - project.executable(unicode).sources(vbs::SourceSet::file(unicode)); - project.dependency("unicode").git("url", vbs::Commit{revision}).cmake({{unicode, unicode}}); + Void::Build::Project project{context()}; + project.executable(unicode).sources(Void::Build::SourceSet::file(unicode)); + project.dependency("unicode") + .git("url", Void::Build::Commit{revision}) + .cmake({{unicode, unicode}}); const auto json = project.to_json(); Void::Testing::expect(json.find(unicode) != std::string::npos); const auto parsed = Void::Json::Strict::parse(json); @@ -240,35 +249,39 @@ Void::Testing::Test json_rejects_malformed_utf8() { "\xff"}; for (const auto &bytes : invalid) { const auto malformed = "prefix" + bytes + "suffix"; - vbs::Project named{context()}; + Void::Build::Project named{context()}; (void)named.executable(bytes); Void::Testing::expect_throw([&] { (void)named.to_json(); }); - vbs::Project sourced{context()}; - sourced.executable("source").sources(vbs::SourceSet::file(malformed)); + Void::Build::Project sourced{context()}; + sourced.executable("source").sources(Void::Build::SourceSet::file(malformed)); Void::Testing::expect_throw([&] { (void)sourced.to_json(); }); - vbs::Project keyed{context()}; - keyed.dependency("key").git("url", vbs::Commit{revision}).cmake({{malformed, true}}); + Void::Build::Project keyed{context()}; + keyed.dependency("key") + .git("url", Void::Build::Commit{revision}) + .cmake({{malformed, true}}); Void::Testing::expect_throw([&] { (void)keyed.to_json(); }); - vbs::Project valued{context()}; - valued.dependency("value").git("url", vbs::Commit{revision}).cmake({{"option", malformed}}); + Void::Build::Project valued{context()}; + valued.dependency("value") + .git("url", Void::Build::Commit{revision}) + .cmake({{"option", malformed}}); Void::Testing::expect_throw([&] { (void)valued.to_json(); }); auto profile = context(); profile.compile_options.push_back(malformed); - vbs::Project configured{profile}; + Void::Build::Project configured{profile}; Void::Testing::expect_throw([&] { (void)configured.to_json(); }); } } Void::Testing::Test independent_projects_and_contexts() { auto initial = context(); - vbs::Project first{initial}; + Void::Build::Project first{initial}; initial.name = "mutated"; - vbs::Project second{ - vbs::default_profiles().resolve("release", vbs::CompilerFamily::clang, "linux", "aarch64")}; + Void::Build::Project second{Void::Build::default_profiles().resolve( + "release", Void::Build::CompilerFamily::Clang, "linux", "aarch64")}; first.executable("first").compile_option("-g"); Void::Testing::expect_eq(first.context().name, std::string{"debug"}); Void::Testing::expect_eq(second.context().name, std::string{"release"}); @@ -277,12 +290,12 @@ Void::Testing::Test independent_projects_and_contexts() { } Void::Testing::Test rejects_option_errors_without_mutation() { - vbs::Project project{context()}; + Void::Build::Project project{context()}; auto dep = project.dependency("library"); Void::Testing::expect_throw([&] { dep.cmake({{"", true}}); }); Void::Testing::expect(dep.record().builder.empty()); Void::Testing::expect_throw( - [] { (void)vbs::OptionValue{std::numeric_limits::max()}; }); - dep.cmake({{"enabled", true}}).git("url", vbs::Commit{revision}); + [] { (void)Void::Build::OptionValue{std::numeric_limits::max()}; }); + dep.cmake({{"enabled", true}}).git("url", Void::Build::Commit{revision}); Void::Testing::expect_eq(dep.record().options.size(), std::size_t{1}); } diff --git a/tests/SelfHostTests.cpp b/tests/SelfHostTests.cpp new file mode 100644 index 0000000..b7fa663 --- /dev/null +++ b/tests/SelfHostTests.cpp @@ -0,0 +1,341 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace Void::Build; + +namespace { +void write_file(const std::filesystem::path &path, std::string_view content) { + auto r = Platform::atomic_write_file(path, content, false); + Void::Testing::expect(r.has_value()); +} +} // namespace + +// Plan 18: Native non-CMake Void::Testing scanner avoids equal-basename collisions! +Void::Testing::Test native_test_registration_generator_avoids_basename_collisions() { + Void::FileSystem::TempDir tmp{"vbs_testgen_"}; + const auto f1 = tmp / "dir_a" / "SameStem.cpp"; + const auto f2 = tmp / "dir_b" / "SameStem.cpp"; + write_file(f1, "#include \nVoid::Testing::Test case_alpha() {}\n"); + write_file(f2, "#include \nVoid::Testing::Test case_beta() {}\n"); + + const auto out_dir = tmp / "gen"; + auto r1 = SelfHost::generate_test_registration_unit(f1, out_dir); + auto r2 = SelfHost::generate_test_registration_unit(f2, out_dir); + Void::Testing::expect(r1.has_value() && r2.has_value()); + if (r1 && r2) { + Void::Testing::expect(r1->generated_cpp != r2->generated_cpp); + Void::Testing::expect_eq(r1->cases.size(), std::size_t{1}); + Void::Testing::expect_eq(r2->cases.size(), std::size_t{1}); + Void::Testing::expect_eq(r1->cases[0].function_name, std::string{"case_alpha"}); + Void::Testing::expect_eq(r2->cases[0].function_name, std::string{"case_beta"}); + } +} + +// Plan 18: Strict native VoidLibrary closure + native VBS SDK + native test runner built +// completely WITHOUT CMake (trapped cmake shim ahead of PATH!) in a clean stage directory! +Void::Testing::Test strict_native_selfhost_voidlibrary_and_sdk_without_cmake() { + const std::filesystem::path void_src{VBS_VOID_SOURCE_PATH}; + Void::Testing::expect(std::filesystem::is_directory(void_src)); + + Void::FileSystem::TempDir tmp{"vbs_selfhost_"}; + const auto stage1_dir = tmp / "stage1"; + const auto trap_bin = tmp / "trap_bin"; + + // Plant a failing trap `cmake` ahead of PATH to prove zero CMake invocation occurs! + write_file( + trap_bin / "cmake", + "#!/bin/sh\necho 'FORBIDDEN CMAKE INVOCATION IN STRICT NATIVE STAGE' >&2\nexit 99\n"); + (void)::chmod((trap_bin / "cmake").c_str(), 0755); + + auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, stage1_dir / ".vbs" / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) + return; + + // Declare native VoidLibrary module closure + VoidBuildSdk + native-registered Void::Testing + // suite! + Project proj{ctx}; + auto void_libs = + Recipes::add_void_library_native(proj, void_src, {"Configuration", "Text", "Testing"}); + + const std::filesystem::path vbs_root{Bootstrap::source_dir}; + auto sdk = proj.static_library("VoidBuildSdk"); + sdk.cxx_standard(CxxStandard::Cxx26) + .sources(SourceSet::file((vbs_root / "src" / "Build.cpp").string())) + .sources(SourceSet::file((vbs_root / "src" / "Util" / "Json.cpp").string())) + .include_directory((vbs_root / "include").string(), Visibility::Public) + .compile_option("-freflection", Visibility::Public); + + // Generate native C++ test registrations for SdkDeclarations.cpp (NO CMake scanner!). + const auto test_src = vbs_root / "tests" / "SdkDeclarations.cpp"; + auto reg = SelfHost::generate_test_registration_unit(test_src, stage1_dir / "gen_tests"); + Void::Testing::expect(reg.has_value() && reg->cases.size() >= 14); + if (!reg) + return; + + auto native_tests = proj.executable("stage1_sdk_tests"); + native_tests.cxx_standard(CxxStandard::Cxx26) + .sources(SourceSet::file(test_src.string())) + .sources(SourceSet::file(reg->generated_cpp.string())) + .link(sdk) + .link(void_libs.modules.at("Testing")) + .link(void_libs.modules.at("Data")); + + auto desc = Graph::ProjectDescription::from_json(proj.to_json()); + Void::Testing::expect(desc.has_value()); + if (!desc) + return; + + auto graph = Graph::lower_project_graph(*desc, *tc, {vbs_root, stage1_dir, nullptr, {}, 32768}); + Void::Testing::expect(graph.has_value()); + if (!graph) + return; + + auto state = State::StateStore::open(stage1_dir / ".vbs"); + Void::Testing::expect(state.has_value()); + if (!state) + return; + + auto exec = + Execution::execute_graph(*graph, *state, {4, true, true, {"stage1_sdk_tests"}, {}, {}}); + Void::Testing::expect(exec.has_value() && exec->succeeded); + if (!exec || !exec->succeeded) + return; + + // Execute the strictly natively-built Void::Testing suite and verify all 14+ cases pass! + const auto exe_path = stage1_dir / "profiles" / "debug" / "out" / "bin" / "stage1_sdk_tests"; + Platform::ProcessRequest run_req; + run_req.executable = exe_path; + run_req.arguments = {"--no-color"}; + // Prepend trap_bin to PATH as an extra assertion. + if (const char *old_path = std::getenv("PATH")) { + run_req.environment.set_vars["PATH"] = trap_bin.string() + ":" + old_path; + } + auto res = Platform::run_supervised(run_req); + Void::Testing::expect(res.has_value() && res->succeeded()); + if (res) { + Void::Testing::expect(res->stdout_data.find("14 tests:") != std::string::npos); + } + + // Plan 18 Stage 1 -> Stage 2 isolation: install Stage 1 VoidBuildSdk to a clean prefix, + // then in an isolated stage2 directory (with trapped cmake!) compile & run a fresh + // stage2 consumer linked ONLY against the installed Stage 1 SDK artifacts! + const auto stage1_prefix = tmp / "stage1_prefix"; + const auto stage2_dir = tmp / "stage2"; + const auto stage2_src = tmp / "stage2_src"; + + // Re-describe installable VoidBuildSdk + public headers matching stage1 output layout. + Project stage1_pkg_proj{ctx}; + auto s1_sdk = stage1_pkg_proj.static_library("VoidBuildSdk"); + s1_sdk.cxx_standard(CxxStandard::Cxx26) + .sources(SourceSet::file((vbs_root / "src" / "Build.cpp").string())) + .sources(SourceSet::file((vbs_root / "src" / "Util" / "Json.cpp").string())) + .include_directory((vbs_root / "include").string(), Visibility::Public) + .compile_option("-freflection", Visibility::Public) + .install("lib"); + stage1_pkg_proj.install_directory((vbs_root / "include").string(), "include"); + auto s1_pkg_desc = Graph::ProjectDescription::from_json(stage1_pkg_proj.to_json()); + Void::Testing::expect(s1_pkg_desc.has_value()); + if (!s1_pkg_desc) + return; + + auto s1_pkg_graph = + Graph::lower_project_graph(*s1_pkg_desc, *tc, {vbs_root, stage1_dir, nullptr, {}, 32768}); + Void::Testing::expect(s1_pkg_graph.has_value()); + if (!s1_pkg_graph) + return; + + // Install the already-built stage1 VoidBuildSdk (at stage1_dir/profiles/debug/out/lib/...)! + auto inst_s1 = Install::install_project( + *s1_pkg_desc, *s1_pkg_graph, + {"VoidBuildSdk", "0.1.0", stage1_prefix, std::nullopt, true, true}); + Void::Testing::expect(inst_s1.has_value()); + if (!inst_s1) + return; + + // Build stage2 consumer using ONLY stage1_prefix/include + stage1_prefix/lib/libVoidBuildSdk.a! + write_file(stage2_src / "stage2_check.cpp", R"cpp( +#include +int main() { + auto ctx = Void::Build::default_profiles().resolve( + "debug", Void::Build::CompilerFamily::Gcc, "Linux", "x86_64"); + Void::Build::Project p{ctx}; + p.executable("hello").sources({"hello.cpp"}); + const auto json = p.to_json(); + return json.find("\"hello\"") != std::string::npos ? 0 : 1; +} +)cpp"); + + Project stage2_proj{ctx}; + Graph::ImportedTargetInterface s1_imported; + s1_imported.dependency_name = "stage1_sdk"; + s1_imported.target_name = "VoidBuildSdk"; + s1_imported.include_dirs.emplace_back(stage1_prefix / "include", false); + s1_imported.compile_options.push_back("-freflection"); + s1_imported.static_libraries.push_back(stage1_prefix / "lib" / "libVoidBuildSdk.a"); + + auto s2_dep = stage2_proj.dependency("stage1_sdk").path(stage1_prefix.string()); + auto s2_app = stage2_proj.executable("stage2_consumer"); + s2_app.cxx_standard(CxxStandard::Cxx26) + .sources(SourceSet::file((stage2_src / "stage2_check.cpp").string())) + .link(s2_dep.target("VoidBuildSdk")); + + auto s2_desc = Graph::ProjectDescription::from_json(stage2_proj.to_json()); + Void::Testing::expect(s2_desc.has_value()); + if (!s2_desc) + return; + auto s2_graph = Graph::lower_project_graph( + *s2_desc, *tc, + {stage2_src, stage2_dir, nullptr, {{"stage1_sdk::VoidBuildSdk", s1_imported}}, 32768}); + Void::Testing::expect(s2_graph.has_value()); + if (!s2_graph) + return; + auto s2_state = State::StateStore::open(stage2_dir / ".vbs"); + Void::Testing::expect(s2_state.has_value()); + if (!s2_state) + return; + + auto s2_exec = Execution::execute_graph(*s2_graph, *s2_state); + Void::Testing::expect(s2_exec.has_value() && s2_exec->succeeded); + + Platform::ProcessRequest s2_run; + s2_run.executable = stage2_dir / "profiles" / "debug" / "out" / "bin" / "stage2_consumer"; + if (const char *old_path = std::getenv("PATH")) { + s2_run.environment.set_vars["PATH"] = trap_bin.string() + ":" + old_path; + } + auto s2_res = Platform::run_supervised(s2_run); + Void::Testing::expect(s2_res.has_value() && s2_res->succeeded()); +} + +// Plan 18 True Self-Hosting: Stage 0 builds the FULL native `vbs` CLI binary (VoidLibrary closure + +// VoidBuildSdk + VoidBuildCore + stage-isolated BootstrapConfig.hpp, ZERO CMake!) into stage1_dir, +// then executes that freshly self-hosted `stage1/bin/vbs` binary WITH TRAPPED `cmake` ON PATH to +// build and test a real Stage 2 C++ project! +Void::Testing::Test strict_native_full_vbs_stage1_to_stage2_without_cmake() { + const std::filesystem::path void_src{VBS_VOID_SOURCE_PATH}; + const std::filesystem::path vbs_root{Bootstrap::source_dir}; + Void::Testing::expect(std::filesystem::is_directory(void_src)); + + Void::FileSystem::TempDir tmp{"vbs_full_selfhost_"}; + const auto stage1_dir = tmp / "stage1"; + const auto trap_bin = tmp / "trap_bin"; + + write_file( + trap_bin / "cmake", + "#!/bin/sh\necho 'FORBIDDEN CMAKE INVOCATION IN STRICT SELF-HOST STAGE' >&2\nexit 99\n"); + (void)::chmod((trap_bin / "cmake").c_str(), 0755); + + auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, stage1_dir / ".vbs" / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) + return; + + // 1. Declare the COMPLETE native VoidBuildSystem graph via VbsSelfHostRecipe (no CMake!). + Project stage1_proj{ctx}; + Recipes::VbsSelfHostConfig sh_cfg; + sh_cfg.vbs_source_dir = vbs_root; + sh_cfg.void_source_dir = void_src; + sh_cfg.stage_build_dir = stage1_dir; + sh_cfg.version = "0.1.0-selfhost"; + sh_cfg.include_registry = false; + sh_cfg.include_tests = false; + auto added = Recipes::add_vbs_selfhost_native(stage1_proj, sh_cfg); + Void::Testing::expect(added.has_value()); + if (!added) + return; + + auto s1_desc = Graph::ProjectDescription::from_json(stage1_proj.to_json()); + Void::Testing::expect(s1_desc.has_value()); + if (!s1_desc) + return; + + auto s1_graph = + Graph::lower_project_graph(*s1_desc, *tc, {vbs_root, stage1_dir, nullptr, {}, 32768}); + Void::Testing::expect(s1_graph.has_value()); + auto s1_state = State::StateStore::open(stage1_dir / ".vbs"); + Void::Testing::expect(s1_state.has_value()); + if (!s1_graph || !s1_state) + return; + + auto s1_exec = Execution::execute_graph(*s1_graph, *s1_state, {4, true, true, {"vbs"}, {}, {}}); + Void::Testing::expect(s1_exec.has_value() && s1_exec->succeeded); + if (!s1_exec || !s1_exec->succeeded) + return; + + const auto stage1_vbs = stage1_dir / "profiles" / "debug" / "out" / "bin" / "vbs"; + Void::Testing::expect(std::filesystem::exists(stage1_vbs)); + + // 2. Verify self-hosted Stage 1 `vbs` CLI metadata with trapped `cmake` ahead of PATH! + std::string trapped_path = trap_bin.string(); + if (const char *old_path = std::getenv("PATH")) { + trapped_path += ":"; + trapped_path += old_path; + } + + { + Platform::ProcessRequest ver_req; + ver_req.executable = stage1_vbs; + ver_req.arguments = {"--version"}; + ver_req.environment.set_vars["PATH"] = trapped_path; + auto ver_res = Platform::run_supervised(ver_req); + Void::Testing::expect(ver_res.has_value() && ver_res->succeeded()); + if (ver_res) { + Void::Testing::expect(ver_res->stdout_data.find("vbs 0.1.0-selfhost") != + std::string::npos); + } + } + + // 3. Stage 2: Execute the freshly self-hosted `stage1_vbs test` on a real C++ project + // completely without CMake! + const auto s2_proj = tmp / "stage2_proj"; + const auto s2_build = tmp / "stage2_build"; + write_file(s2_proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + auto lib = p.static_library("s2math") + .sources({"src/math.cpp"}) + .include_directory("include", Void::Build::Visibility::Public); + p.test("s2math_test") + .sources({"tests/test_math.cpp"}) + .link(lib); +} +)cpp"); + write_file(s2_proj / "include" / "s2math.hpp", "#pragma once\nint s2_answer();\n"); + write_file(s2_proj / "src" / "math.cpp", + "#include \"s2math.hpp\"\nint s2_answer() { return 42; }\n"); + write_file(s2_proj / "tests" / "test_math.cpp", + "#include \"s2math.hpp\"\nint main() { return s2_answer() == 42 ? 0 : 1; }\n"); + + Platform::ProcessRequest s2_test_req; + s2_test_req.executable = stage1_vbs; + s2_test_req.arguments = {"test", "--project", s2_proj.string(), "--build-dir", + s2_build.string()}; + s2_test_req.environment.set_vars["PATH"] = trapped_path; + s2_test_req.timeout = std::chrono::seconds{120}; + auto s2_test_res = Platform::run_supervised(s2_test_req); + Void::Testing::expect(s2_test_res.has_value() && s2_test_res->succeeded()); + if (s2_test_res) { + Void::Testing::expect(s2_test_res->stdout_data.find("vbs test: PASSED 's2math_test'") != + std::string::npos); + } +}