From bba5c8a39a6170c6e1c2cd0427a58b4454a583c5 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov Date: Fri, 22 May 2026 02:40:32 +0300 Subject: [PATCH] initial commit Signed-off-by: Aleksey Selihov --- .gitignore | 1 + .gitlab-ci.yml | 326 +++++++ CMakeLists.txt | 127 +++ Testing/Temporary/CTestCostData.txt | 1 + Testing/Temporary/LastTest.log | 3 + cmake/VoidLibCAutoVLC.cmake | 676 +++++++++++++ cmake/VoidLibCConfig.cmake.in | 11 + cmake/toolchains/host-macos.cmake | 21 + cmake/toolchains/host-windows.cmake | 24 + cmake/toolchains/linux.cmake | 29 + cmake/toolchains/macos.cmake | 26 + cmake/toolchains/windows.cmake | 30 + cmake/zigcc/FindZig.cmake | 30 + cmake/zigcc/linux-musl.cmake | 25 + cmake/zigcc/macos.cmake | 24 + cmake/zigcc/windows-mingw.cmake | 30 + data/symlib_linux.txt | 487 ++++++++++ data/symlib_macos.txt | 359 +++++++ data/symlib_windows.txt | 458 +++++++++ docs/format.md | 204 ++++ format/reloc_ir.hpp | 66 ++ format/vlc_format.hpp | 162 ++++ installer/linux/binfmt.d/vlc.conf | 14 + installer/linux/install.sh | 101 ++ installer/linux/magic/vlc.magic | 29 + installer/linux/register_binfmt.sh | 38 + installer/linux/uninstall.sh | 47 + installer/macos/install.sh | 58 ++ installer/macos/uninstall.sh | 18 + installer/windows/install.ps1 | 87 ++ installer/windows/uninstall.ps1 | 37 + libvoid/CMakeLists.txt | 24 + libvoid/api.cpp | 464 +++++++++ libvoid/internal.h | 10 + loader/CMakeLists.txt | 4 + loader/common/CMakeLists.txt | 14 + loader/common/elf64.hpp | 216 +++++ loader/common/elf_synth.cpp | 816 ++++++++++++++++ loader/common/elf_synth.hpp | 77 ++ loader/linux/CMakeLists.txt | 13 + loader/linux/handoff.cpp | 136 +++ loader/linux/handoff.hpp | 25 + loader/macos/CMakeLists.txt | 15 + loader/macos/handoff.cpp | 76 ++ loader/macos/handoff.hpp | 23 + loader/macos/macho_synth.cpp | 677 +++++++++++++ loader/macos/macho_synth.hpp | 62 ++ loader/windows/CMakeLists.txt | 10 + loader/windows/handoff.cpp | 73 ++ loader/windows/handoff.hpp | 26 + loader/windows/pe_synth.cpp | 571 +++++++++++ loader/windows/pe_synth.hpp | 60 ++ magic.mgc | Bin 0 -> 4752 bytes tests/CMakeLists.txt | 10 + tests/e2e/CMakeLists.txt | 212 +++++ tests/e2e/add_real.c | 1 + tests/e2e/extern_read.c | 15 + tests/e2e/hello_exec.c | 24 + tests/e2e/hello_printf.c | 11 + tests/e2e/host_libc_multi.c | 12 + tests/e2e/host_libc_pthread.c | 17 + tests/e2e/load_add.cpp | 90 ++ tests/e2e/load_extern_read.cpp | 54 ++ tests/e2e/load_hello_printf.cpp | 46 + tests/e2e/load_host_libc_multi.cpp | 39 + tests/e2e/load_host_libc_pthread.cpp | 40 + tests/e2e/load_multi_obj.cpp | 55 ++ tests/e2e/load_real_add.cpp | 49 + tests/e2e/load_static_counter.cpp | 56 ++ tests/e2e/load_sum_squares.cpp | 49 + tests/e2e/math_a.c | 10 + tests/e2e/math_b.c | 13 + tests/e2e/static_counter.c | 18 + tests/e2e/sum_squares.c | 6 + tests/e2e/validate_blobs.cpp | 84 ++ tests/format/CMakeLists.txt | 15 + tests/format/roundtrip.cpp | 50 + tests/fuzz/CMakeLists.txt | 33 + tests/fuzz/fuzz_coff_reader.cpp | 31 + tests/fuzz/fuzz_elf_reader.cpp | 32 + tests/fuzz/fuzz_macho_reader.cpp | 31 + tests/synth/CMakeLists.txt | 24 + tests/synth/elf_synth_test.cpp | 173 ++++ tests/synth/macho_synth_test.cpp | 157 +++ tests/synth/pe_synth_test.cpp | 129 +++ tools/gen_symlib_table.py | 163 ++++ tools/vlc.magic | 29 + voidlink/CMakeLists.txt | 26 + voidlink/builder.cpp | 257 +++++ voidlink/builder.hpp | 80 ++ voidlink/coff_reader.cpp | 318 +++++++ voidlink/coff_reader.hpp | 83 ++ voidlink/elf_reader.cpp | 265 ++++++ voidlink/elf_reader.hpp | 61 ++ voidlink/macho_reader.cpp | 324 +++++++ voidlink/macho_reader.hpp | 76 ++ voidlink/main.cpp | 1099 +++++++++++++++++++++ voidlink/merge.cpp | 143 +++ voidlink/merge.hpp | 26 + voidlink/reader.cpp | 177 ++++ voidlink/reader.hpp | 27 + voidlink/reloc_lowering.cpp | 850 +++++++++++++++++ voidlink/reloc_lowering.hpp | 37 + voidlink/symlib_table.cpp | 1323 ++++++++++++++++++++++++++ voidlink/symlib_table.hpp | 20 + voidlink/writer.cpp | 46 + voidlink/writer.hpp | 17 + voidloader/CMakeLists.txt | 7 + voidloader/main.cpp | 104 ++ 109 files changed, 14085 insertions(+) create mode 100644 .gitignore create mode 100644 .gitlab-ci.yml create mode 100644 CMakeLists.txt create mode 100644 Testing/Temporary/CTestCostData.txt create mode 100644 Testing/Temporary/LastTest.log create mode 100644 cmake/VoidLibCAutoVLC.cmake create mode 100644 cmake/VoidLibCConfig.cmake.in create mode 100644 cmake/toolchains/host-macos.cmake create mode 100644 cmake/toolchains/host-windows.cmake create mode 100644 cmake/toolchains/linux.cmake create mode 100644 cmake/toolchains/macos.cmake create mode 100644 cmake/toolchains/windows.cmake create mode 100644 cmake/zigcc/FindZig.cmake create mode 100644 cmake/zigcc/linux-musl.cmake create mode 100644 cmake/zigcc/macos.cmake create mode 100644 cmake/zigcc/windows-mingw.cmake create mode 100644 data/symlib_linux.txt create mode 100644 data/symlib_macos.txt create mode 100644 data/symlib_windows.txt create mode 100644 docs/format.md create mode 100644 format/reloc_ir.hpp create mode 100644 format/vlc_format.hpp create mode 100644 installer/linux/binfmt.d/vlc.conf create mode 100755 installer/linux/install.sh create mode 100644 installer/linux/magic/vlc.magic create mode 100755 installer/linux/register_binfmt.sh create mode 100755 installer/linux/uninstall.sh create mode 100644 installer/macos/install.sh create mode 100644 installer/macos/uninstall.sh create mode 100644 installer/windows/install.ps1 create mode 100644 installer/windows/uninstall.ps1 create mode 100644 libvoid/CMakeLists.txt create mode 100644 libvoid/api.cpp create mode 100644 libvoid/internal.h create mode 100644 loader/CMakeLists.txt create mode 100644 loader/common/CMakeLists.txt create mode 100644 loader/common/elf64.hpp create mode 100644 loader/common/elf_synth.cpp create mode 100644 loader/common/elf_synth.hpp create mode 100644 loader/linux/CMakeLists.txt create mode 100644 loader/linux/handoff.cpp create mode 100644 loader/linux/handoff.hpp create mode 100644 loader/macos/CMakeLists.txt create mode 100644 loader/macos/handoff.cpp create mode 100644 loader/macos/handoff.hpp create mode 100644 loader/macos/macho_synth.cpp create mode 100644 loader/macos/macho_synth.hpp create mode 100644 loader/windows/CMakeLists.txt create mode 100644 loader/windows/handoff.cpp create mode 100644 loader/windows/handoff.hpp create mode 100644 loader/windows/pe_synth.cpp create mode 100644 loader/windows/pe_synth.hpp create mode 100644 magic.mgc create mode 100644 tests/CMakeLists.txt create mode 100644 tests/e2e/CMakeLists.txt create mode 100644 tests/e2e/add_real.c create mode 100644 tests/e2e/extern_read.c create mode 100644 tests/e2e/hello_exec.c create mode 100644 tests/e2e/hello_printf.c create mode 100644 tests/e2e/host_libc_multi.c create mode 100644 tests/e2e/host_libc_pthread.c create mode 100644 tests/e2e/load_add.cpp create mode 100644 tests/e2e/load_extern_read.cpp create mode 100644 tests/e2e/load_hello_printf.cpp create mode 100644 tests/e2e/load_host_libc_multi.cpp create mode 100644 tests/e2e/load_host_libc_pthread.cpp create mode 100644 tests/e2e/load_multi_obj.cpp create mode 100644 tests/e2e/load_real_add.cpp create mode 100644 tests/e2e/load_static_counter.cpp create mode 100644 tests/e2e/load_sum_squares.cpp create mode 100644 tests/e2e/math_a.c create mode 100644 tests/e2e/math_b.c create mode 100644 tests/e2e/static_counter.c create mode 100644 tests/e2e/sum_squares.c create mode 100644 tests/e2e/validate_blobs.cpp create mode 100644 tests/format/CMakeLists.txt create mode 100644 tests/format/roundtrip.cpp create mode 100644 tests/fuzz/CMakeLists.txt create mode 100644 tests/fuzz/fuzz_coff_reader.cpp create mode 100644 tests/fuzz/fuzz_elf_reader.cpp create mode 100644 tests/fuzz/fuzz_macho_reader.cpp create mode 100644 tests/synth/CMakeLists.txt create mode 100644 tests/synth/elf_synth_test.cpp create mode 100644 tests/synth/macho_synth_test.cpp create mode 100644 tests/synth/pe_synth_test.cpp create mode 100755 tools/gen_symlib_table.py create mode 100644 tools/vlc.magic create mode 100644 voidlink/CMakeLists.txt create mode 100644 voidlink/builder.cpp create mode 100644 voidlink/builder.hpp create mode 100644 voidlink/coff_reader.cpp create mode 100644 voidlink/coff_reader.hpp create mode 100644 voidlink/elf_reader.cpp create mode 100644 voidlink/elf_reader.hpp create mode 100644 voidlink/macho_reader.cpp create mode 100644 voidlink/macho_reader.hpp create mode 100644 voidlink/main.cpp create mode 100644 voidlink/merge.cpp create mode 100644 voidlink/merge.hpp create mode 100644 voidlink/reader.cpp create mode 100644 voidlink/reader.hpp create mode 100644 voidlink/reloc_lowering.cpp create mode 100644 voidlink/reloc_lowering.hpp create mode 100644 voidlink/symlib_table.cpp create mode 100644 voidlink/symlib_table.hpp create mode 100644 voidlink/writer.cpp create mode 100644 voidlink/writer.hpp create mode 100644 voidloader/CMakeLists.txt create mode 100644 voidloader/main.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..378eac2 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +build diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..e5746a7 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,326 @@ +stages: + - validate + - build + - test + - package + - release + +variables: + DEBIAN_FRONTEND: noninteractive + PKG_CHANNEL: voidlibc + ZIG_VERSION: "0.13.0" + +# Heavy jobs (build, test, package) share this default. +# validate and release override before_script themselves. +default: + image: ubuntu:24.04 + before_script: + - apt-get update -qq + - apt-get install -y --no-install-recommends + clang-18 lld-18 cmake ninja-build python3 curl ca-certificates xz-utils zip + - ln -sf /usr/bin/clang-18 /usr/local/bin/clang + - ln -sf /usr/bin/clang++-18 /usr/local/bin/clang++ + - ln -sf /usr/bin/lld-18 /usr/local/bin/lld + - | + curl -sSL \ + "https://ziglang.org/download/${ZIG_VERSION}/zig-linux-x86_64-${ZIG_VERSION}.tar.xz" \ + | tar -xJ -C /opt/ + ln -sf "/opt/zig-linux-x86_64-${ZIG_VERSION}/zig" /usr/local/bin/zig + +# ============================================================================= +# validate +# ============================================================================= + +validate:symlib: + stage: validate + before_script: + - apt-get update -qq + - apt-get install -y --no-install-recommends python3 + script: + - python3 tools/gen_symlib_table.py --check + +# ============================================================================= +# build (Linux, full; artifact consumed by test and package:linux) +# ============================================================================= + +build:release: + stage: build + script: + - | + cmake -B build -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_C_COMPILER=clang \ + -DCMAKE_CXX_COMPILER=clang++ \ + -DVOIDLIBC_BUILD_VOIDLINK=ON \ + -DVOIDLIBC_BUILD_LOADER=ON \ + -DVOIDLIBC_BUILD_TESTS=ON + - cmake --build build + artifacts: + paths: + - build/ + expire_in: 2h + +# ============================================================================= +# test (parallel, Linux only — runtime validation requires Linux binfmt/dlopen) +# ============================================================================= + +test:unit: + stage: test + needs: [build:release] + script: + - ctest --test-dir build -L "format|synth" --output-on-failure -j "$(nproc)" + +test:e2e: + stage: test + needs: [build:release] + script: + - ctest --test-dir build -L e2e --output-on-failure -j "$(nproc)" + +# Fuzz smoke test: build the three reader harnesses and run each for 30 s. +# A crash here means the parser has undefined behaviour on malformed input. +# Runs independently of the main build artifact (own fresh build). +test:fuzz: + stage: test + needs: + - job: build:release + artifacts: false + script: + - | + cmake -B build-fuzz -G Ninja \ + -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_C_COMPILER=clang \ + -DCMAKE_CXX_COMPILER=clang++ \ + -DVOIDLIBC_BUILD_VOIDLINK=ON \ + -DVOIDLIBC_BUILD_LOADER=OFF \ + -DVOIDLIBC_BUILD_TESTS=ON \ + -DVOIDLIBC_BUILD_FUZZ=ON + - cmake --build build-fuzz + - | + for fuzzer in fuzz_elf_reader fuzz_coff_reader fuzz_macho_reader; do + echo "--- $fuzzer (30 s smoke run) ---" + build-fuzz/tests/fuzz/$fuzzer \ + -max_total_time=30 \ + -rss_limit_mb=512 \ + -print_final_stats=1 \ + 2>&1 | tail -8 + done + +# ============================================================================= +# package (one job per platform, all tags-only) +# ============================================================================= + +# ── Linux ───────────────────────────────────────────────────────────────────── +# Full install: voidlink + voidloader + libvoid.a + headers + CMake config. +# Uses DESTDIR staging so the absolute /etc/binfmt.d destination is safe. + +package:linux: + stage: package + needs: [build:release, test:unit, test:e2e] + rules: + - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+/ + script: + - STAGING="$(pwd)/staging-linux" + - ARTIFACT="voidlibc-${CI_COMMIT_TAG}-linux-x86_64.tar.gz" + - DESTDIR="$STAGING" cmake --install build --strip + - tar -czf "$ARTIFACT" -C "$STAGING" . + - | + URL="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic" + URL="${URL}/${PKG_CHANNEL}/${CI_COMMIT_TAG}/${ARTIFACT}" + curl --fail --silent --show-error \ + --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \ + --upload-file "$ARTIFACT" "$URL" + echo "LINUX_ARTIFACT_URL=${URL}" >> release.env + echo "LINUX_ARTIFACT_NAME=${ARTIFACT}" >> release.env + artifacts: + paths: ["voidlibc-*-linux-*.tar.gz"] + reports: + dotenv: release.env + expire_in: 30d + +# ── Windows ─────────────────────────────────────────────────────────────────── +# Full Windows package: voidlink.exe + voidloader.exe + libvoid.a + headers +# + CMake config + installer/, cross-compiled with zig targeting x86_64-windows-gnu. +# Statically linked so no mingw DLLs are required. + +package:windows: + stage: package + needs: + - job: build:release + artifacts: false # don't transfer the Linux build/ tree + - job: test:unit + artifacts: false + - job: test:e2e + artifacts: false + rules: + - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+/ + script: + # Create zig wrapper scripts for the cmake toolchain. + - | + printf '#!/bin/sh\nexec zig cc -target x86_64-windows-gnu "$@"\n' \ + > /usr/local/bin/zig-cc-win + printf '#!/bin/sh\nexec zig c++ -target x86_64-windows-gnu "$@"\n' \ + > /usr/local/bin/zig-cxx-win + chmod +x /usr/local/bin/zig-cc-win /usr/local/bin/zig-cxx-win + - | + cmake -B build-win -G Ninja \ + -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/host-windows.cmake \ + -DCMAKE_BUILD_TYPE=Release \ + -DVOIDLIBC_BUILD_VOIDLINK=ON \ + -DVOIDLIBC_BUILD_LOADER=ON \ + -DVOIDLIBC_BUILD_TESTS=OFF + - cmake --build build-win + - | + STAGING="$(pwd)/staging-win" + DESTDIR="$STAGING" cmake --install build-win --strip + # Linux-specific binfmt.d install rules do not fire for Windows targets, + # but guard explicitly in case. + rm -rf "$STAGING/etc" + # Add installer scripts under installer/ so the .ps1 finds bin/ via + # the package-layout path ($PSScriptRoot\..\bin\). + mkdir -p "$STAGING/installer" + cp installer/windows/install.ps1 "$STAGING/installer/" + cp installer/windows/uninstall.ps1 "$STAGING/installer/" + - ARTIFACT="voidlibc-${CI_COMMIT_TAG}-windows-x86_64.zip" + - zip -r "$ARTIFACT" staging-win/ + - | + URL="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic" + URL="${URL}/${PKG_CHANNEL}/${CI_COMMIT_TAG}/${ARTIFACT}" + curl --fail --silent --show-error \ + --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \ + --upload-file "$ARTIFACT" "$URL" + echo "WIN_ARTIFACT_URL=${URL}" >> release.env + echo "WIN_ARTIFACT_NAME=${ARTIFACT}" >> release.env + artifacts: + paths: ["voidlibc-*-windows-*.zip"] + reports: + dotenv: release.env + expire_in: 30d + +# ── macOS ───────────────────────────────────────────────────────────────────── +# Full macOS package: voidlink + voidloader + libvoid.a + headers + CMake config +# + installer/, cross-compiled with zig targeting x86_64-apple-macos12. +# zig 0.13 bundles macOS libc headers (no separate SDK required). + +package:macos: + stage: package + needs: + - job: build:release + artifacts: false + - job: test:unit + artifacts: false + - job: test:e2e + artifacts: false + rules: + - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+/ + script: + - | + printf '#!/bin/sh\nexec zig cc -target x86_64-macos12 "$@"\n' \ + > /usr/local/bin/zig-cc-mac + printf '#!/bin/sh\nexec zig c++ -target x86_64-macos12 "$@"\n' \ + > /usr/local/bin/zig-cxx-mac + chmod +x /usr/local/bin/zig-cc-mac /usr/local/bin/zig-cxx-mac + - | + cmake -B build-mac -G Ninja \ + -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/host-macos.cmake \ + -DCMAKE_BUILD_TYPE=Release \ + -DVOIDLIBC_BUILD_VOIDLINK=ON \ + -DVOIDLIBC_BUILD_LOADER=ON \ + -DVOIDLIBC_BUILD_TESTS=OFF + - cmake --build build-mac + - | + STAGING="$(pwd)/staging-mac" + DESTDIR="$STAGING" cmake --install build-mac --strip + rm -rf "$STAGING/etc" + # Add installer scripts so install.sh finds bin/ via the package-layout + # path (${SCRIPT_DIR}/../bin/). + mkdir -p "$STAGING/installer" + cp installer/macos/install.sh "$STAGING/installer/" + cp installer/macos/uninstall.sh "$STAGING/installer/" + - ARTIFACT="voidlibc-${CI_COMMIT_TAG}-macos-x86_64.tar.gz" + - tar -czf "$ARTIFACT" -C staging-mac . + - | + URL="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic" + URL="${URL}/${PKG_CHANNEL}/${CI_COMMIT_TAG}/${ARTIFACT}" + curl --fail --silent --show-error \ + --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \ + --upload-file "$ARTIFACT" "$URL" + echo "MAC_ARTIFACT_URL=${URL}" >> release.env + echo "MAC_ARTIFACT_NAME=${ARTIFACT}" >> release.env + artifacts: + paths: ["voidlibc-*-macos-*.tar.gz"] + reports: + dotenv: release.env + expire_in: 30d + +# ============================================================================= +# release (tags only — assembles GitLab Release from all three packages) +# ============================================================================= + +release: + stage: release + image: registry.gitlab.com/gitlab-org/release-cli:latest + needs: + - job: package:linux + artifacts: true # provides LINUX_ARTIFACT_URL / LINUX_ARTIFACT_NAME + - job: package:windows + artifacts: true # provides WIN_ARTIFACT_URL / WIN_ARTIFACT_NAME + - job: package:macos + artifacts: true # provides MAC_ARTIFACT_URL / MAC_ARTIFACT_NAME + rules: + - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+/ + before_script: [] # release-cli image has no apt + script: + - echo "Creating release ${CI_COMMIT_TAG}" + release: + name: "VoidLibC ${CI_COMMIT_TAG}" + tag_name: "${CI_COMMIT_TAG}" + description: | + ## VoidLibC ${CI_COMMIT_TAG} + + Universal x86-64 fat-binary format (`.vlc` / `.vls` / `.vle`) with host-libc delegation. + A single `.vlc` library bundles ELF, PE, and Mach-O blobs; voidloader selects the right + one at runtime and resolves symbols against the host libc automatically. + + ### Assets + + | File | Platform | Contents | + |------|----------|----------| + | `${LINUX_ARTIFACT_NAME}` | Linux x86-64 | voidlink, voidloader, libvoid.a, headers, CMake config, binfmt.d, installer/ | + | `${WIN_ARTIFACT_NAME}` | Windows x86-64 | voidlink.exe, voidloader.exe, libvoid.a, headers, CMake config, installer/ | + | `${MAC_ARTIFACT_NAME}` | macOS x86-64 | voidlink, voidloader, libvoid.a, headers, CMake config, installer/ | + + ### Install (Linux) + + ```sh + tar -xzf ${LINUX_ARTIFACT_NAME} + cd voidlibc-*-linux-x86_64 + sudo bash installer/linux/install.sh # copies binaries + registers binfmt_misc + ``` + + ### Install (Windows) + + ```powershell + Expand-Archive ${WIN_ARTIFACT_NAME} -DestinationPath voidlibc + cd voidlibc + powershell -ExecutionPolicy Bypass -File installer\install.ps1 + # Registers .vle file association and adds bin\ to user PATH + ``` + + ### Install (macOS) + + ```sh + tar -xzf ${MAC_ARTIFACT_NAME} + cd voidlibc-*-macos-x86_64 + bash installer/install.sh # copies voidlink + voidloader to /usr/local/bin + ``` + assets: + links: + - name: "${LINUX_ARTIFACT_NAME}" + url: "${LINUX_ARTIFACT_URL}" + link_type: package + - name: "${WIN_ARTIFACT_NAME}" + url: "${WIN_ARTIFACT_URL}" + link_type: package + - name: "${MAC_ARTIFACT_NAME}" + url: "${MAC_ARTIFACT_URL}" + link_type: package diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..8351b8d --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,127 @@ +cmake_minimum_required(VERSION 3.20) +project(VoidLibC + VERSION 0.0.1 + DESCRIPTION "Universal x86_64 library/executable format" + LANGUAGES CXX C +) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") +include(VoidLibCAutoVLC) + +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE) +endif() + +option(VOIDLIBC_BUILD_VOIDLINK "Build host-side voidlink toolchain" ON) +option(VOIDLIBC_BUILD_LOADER "Build voidloader + libvoid (target OS)" ON) +option(VOIDLIBC_BUILD_TESTS "Build tests" ON) +option(VOIDLIBC_BUILD_FUZZ "Build libFuzzer harnesses (requires clang -fsanitize=fuzzer)" OFF) + +add_compile_options( + -Wall -Wextra -Wpedantic + -Wno-missing-field-initializers +) + +# format/ is header-only and shared by host and target builds. +add_library(voidlibc_format INTERFACE) +target_include_directories(voidlibc_format INTERFACE + $ + $ +) +install(TARGETS voidlibc_format + EXPORT VoidLibCTargets +) +install(DIRECTORY format/ + DESTINATION include/format + FILES_MATCHING PATTERN "*.hpp" +) + +if(VOIDLIBC_BUILD_VOIDLINK) + add_subdirectory(voidlink) +endif() + +if(VOIDLIBC_BUILD_TESTS) + enable_testing() + add_subdirectory(tests) +endif() + +# Loader is a target-OS build (freestanding). Brought in only when explicitly enabled. +if(VOIDLIBC_BUILD_LOADER) + add_subdirectory(loader) + add_subdirectory(libvoid) + add_subdirectory(voidloader) +endif() + +# ============================================================================= +# CMake package config — consumers use: find_package(VoidLibC REQUIRED) +# ============================================================================= +include(CMakePackageConfigHelpers) + +configure_package_config_file( + cmake/VoidLibCConfig.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/VoidLibCConfig.cmake" + INSTALL_DESTINATION lib/cmake/VoidLibC +) +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/VoidLibCConfigVersion.cmake" + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion +) +install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/VoidLibCConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/VoidLibCConfigVersion.cmake" + DESTINATION lib/cmake/VoidLibC +) +install(FILES + cmake/VoidLibCAutoVLC.cmake + DESTINATION lib/cmake/VoidLibC +) +install(FILES + cmake/toolchains/linux.cmake + cmake/toolchains/windows.cmake + cmake/toolchains/macos.cmake + DESTINATION lib/cmake/VoidLibC/toolchains +) +install(EXPORT VoidLibCTargets + NAMESPACE VoidLibC:: + DESTINATION lib/cmake/VoidLibC +) + +# Install binfmt_misc config for systemd-binfmt.service (Linux only). +# The shell-based registration (write to /proc/sys/fs/binfmt_misc/register) +# is done by installer/linux/install.sh; CMake installs only the persistent +# config file that survives reboots. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOIDLIBC_BUILD_LOADER) + install( + FILES installer/linux/binfmt.d/vlc.conf + DESTINATION /etc/binfmt.d + ) + # Substitute the actual CMAKE_INSTALL_PREFIX into the installed config. + install(CODE " + set(_conf \"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/etc/binfmt.d/vlc.conf\") + if(EXISTS \"\${_conf}\") + file(READ \"\${_conf}\" _content) + string(REPLACE \"/usr/local/bin/voidloader\" + \"${CMAKE_INSTALL_PREFIX}/bin/voidloader\" + _content \"\${_content}\") + file(WRITE \"\${_conf}\" \"\${_content}\") + endif() + ") + # Install file(1) magic definition. + install( + FILES installer/linux/magic/vlc.magic + DESTINATION ${CMAKE_INSTALL_PREFIX}/share/file/magic + RENAME vlc + ) + install(CODE " + message(STATUS \"Run 'sudo systemctl restart systemd-binfmt' or\") + message(STATUS \" 'sudo installer/linux/register_binfmt.sh ${CMAKE_INSTALL_PREFIX}/bin/voidloader'\") + message(STATUS \"to activate .vle execution immediately.\") + message(STATUS \"Run 'sudo file -C -m ${CMAKE_INSTALL_PREFIX}/share/file/magic'\") + message(STATUS \"to compile the VoidLibC magic database for file(1).\") + ") +endif() diff --git a/Testing/Temporary/CTestCostData.txt b/Testing/Temporary/CTestCostData.txt new file mode 100644 index 0000000..ed97d53 --- /dev/null +++ b/Testing/Temporary/CTestCostData.txt @@ -0,0 +1 @@ +--- diff --git a/Testing/Temporary/LastTest.log b/Testing/Temporary/LastTest.log new file mode 100644 index 0000000..af07f2f --- /dev/null +++ b/Testing/Temporary/LastTest.log @@ -0,0 +1,3 @@ +Start testing: May 18 15:22 MSK +---------------------------------------------------------- +End testing: May 18 15:22 MSK diff --git a/cmake/VoidLibCAutoVLC.cmake b/cmake/VoidLibCAutoVLC.cmake new file mode 100644 index 0000000..e910425 --- /dev/null +++ b/cmake/VoidLibCAutoVLC.cmake @@ -0,0 +1,676 @@ +# VoidLibCAutoVLC.cmake +# +# Automatic fat-VLC generation for targets that link against 'void'. +# +# Usage in a CMakeLists.txt: +# +# include(VoidLibCAutoVLC) # in root, or done via add_subdirectory +# +# # Define the VLC source as a SHARED library, link void: +# add_library(mylib SHARED src.c) +# target_link_libraries(mylib PRIVATE void) +# set_target_properties(mylib PROPERTIES EXCLUDE_FROM_ALL TRUE) +# +# # For executable VLC (.vle), set the entry point before the hook fires: +# voidlibc_vlc_executable(mylib main) +# +# # Register the DEFER hook for this directory (call once per CMakeLists.txt): +# voidlibc_enable_auto_vlc() +# +# The hook fires at the end of the directory, scans all SHARED/STATIC targets +# that link 'void', and creates: +# /.vls or /.vle +# via zig cc (preferred) or clang cross-compilation for x86_64 Linux+Windows+macOS. +# Falls back to host compiler for Linux-only .vls when no cross-compiler is found. +# +# Compile options propagation: the hook reads COMPILE_OPTIONS and +# INCLUDE_DIRECTORIES from the target (filtering out generator expressions) +# and forwards them to every per-platform compile invocation. + +cmake_minimum_required(VERSION 3.19) # cmake_language(DEFER) + +# --------------------------------------------------------------------------- +# Internal: resolve the voidlink executable target. +# Works whether voidlink is a build-tree target or an installed IMPORTED target. +# Sets (name for generator expressions) and (DEPENDS list). +# --------------------------------------------------------------------------- +function(_voidlibc_resolve_voidlink tgt_var dep_var) + if(TARGET voidlink) + set(${tgt_var} "voidlink" PARENT_SCOPE) + set(${dep_var} "voidlink" PARENT_SCOPE) + elseif(TARGET VoidLibC::voidlink) + set(${tgt_var} "VoidLibC::voidlink" PARENT_SCOPE) + set(${dep_var} "VoidLibC::voidlink" PARENT_SCOPE) + else() + message(FATAL_ERROR + "VoidLibC auto-VLC: voidlink not found. " + "Either build from source or install VoidLibC.") + endif() +endfunction() + +# --------------------------------------------------------------------------- +# Internal: detect cross-compiler once, cache results. +# --------------------------------------------------------------------------- +function(_voidlibc_detect_cross) + if(DEFINED CACHE{_VOIDLIBC_CC_KIND}) + return() + endif() + + find_program(_VOIDLIBC_ZIG_EXE zig) + find_program(_VOIDLIBC_CLANG_EXE clang) + + if(_VOIDLIBC_ZIG_EXE) + set(_VOIDLIBC_CC_KIND "zig" CACHE INTERNAL "") + set(_VOIDLIBC_CC_BIN "${_VOIDLIBC_ZIG_EXE};cc" CACHE INTERNAL "") + set(_VOIDLIBC_CC_LINUX "x86_64-linux-musl" CACHE INTERNAL "") + set(_VOIDLIBC_CC_WINDOWS "x86_64-windows-gnu" CACHE INTERNAL "") + set(_VOIDLIBC_CC_MACOS "x86_64-macos-none" CACHE INTERNAL "") + message(STATUS "VoidLibC auto-VLC: using zig cc (${_VOIDLIBC_ZIG_EXE})") + elseif(_VOIDLIBC_CLANG_EXE) + set(_VOIDLIBC_CC_KIND "clang" CACHE INTERNAL "") + set(_VOIDLIBC_CC_BIN "${_VOIDLIBC_CLANG_EXE}" CACHE INTERNAL "") + set(_VOIDLIBC_CC_LINUX "x86_64-linux-gnu" CACHE INTERNAL "") + set(_VOIDLIBC_CC_WINDOWS "x86_64-pc-windows-msvc" CACHE INTERNAL "") + set(_VOIDLIBC_CC_MACOS "x86_64-apple-macos12" CACHE INTERNAL "") + message(STATUS "VoidLibC auto-VLC: using clang (${_VOIDLIBC_CLANG_EXE})") + else() + set(_VOIDLIBC_CC_KIND "host" CACHE INTERNAL "") + message(STATUS "VoidLibC auto-VLC: no cross-compiler found; producing Linux-only .vls") + endif() +endfunction() + +# --------------------------------------------------------------------------- +# Internal: filter a list, removing items that start with $< (generator exprs). +# Result written to in caller scope. +# --------------------------------------------------------------------------- +function(_voidlibc_filter_genex out_var) + set(_result "") + foreach(_item IN LISTS ARGN) + if(NOT "${_item}" MATCHES "^\\$<") + list(APPEND _result "${_item}") + endif() + endforeach() + set(${out_var} "${_result}" PARENT_SCOPE) +endfunction() + +# --------------------------------------------------------------------------- +# Internal: given a target and output dir, create all custom commands/targets +# that produce .vls or .vle. +# --------------------------------------------------------------------------- +function(_voidlibc_make_vlc _tgt _outdir) + _voidlibc_detect_cross() + + # Collect sources. + get_target_property(_srcs ${_tgt} SOURCES) + if(NOT _srcs) + return() + endif() + + # Platform filter: VOIDLIBC_VLC_PLATFORMS property lists which OS sections + # to include. Defaults to all three when a cross-compiler is available, + # or "linux" only when falling back to the host compiler. + get_target_property(_plat_prop ${_tgt} VOIDLIBC_VLC_PLATFORMS) + if(_plat_prop) + set(_platforms "${_plat_prop}") + elseif(_VOIDLIBC_CC_KIND STREQUAL "host") + set(_platforms "linux") + else() + set(_platforms "linux;windows;macos") + endif() + + # Determine output extension and entry flag. + get_target_property(_entry ${_tgt} VOIDLIBC_VLC_ENTRY) + if(_entry) + set(_ext ".vle") + set(_entry_args "--entry" "${_entry}") + else() + set(_ext ".vls") + set(_entry_args "") + endif() + + set(_out_vlc "${_outdir}/${_tgt}${_ext}") + + # Collect compile options and include dirs from the target (no genex). + get_target_property(_raw_opts ${_tgt} COMPILE_OPTIONS) + if(NOT _raw_opts) + set(_raw_opts "") + endif() + _voidlibc_filter_genex(_compile_opts ${_raw_opts}) + + get_target_property(_raw_incs ${_tgt} INCLUDE_DIRECTORIES) + if(NOT _raw_incs) + set(_raw_incs "") + endif() + _voidlibc_filter_genex(_raw_incs_clean ${_raw_incs}) + set(_inc_flags "") + foreach(_d IN LISTS _raw_incs_clean) + list(APPEND _inc_flags "-I${_d}") + endforeach() + + # Per-platform object lists. + set(_linux_objs "") + set(_windows_objs "") + set(_macos_objs "") + + foreach(_src IN LISTS _srcs) + # Make source path absolute. + get_filename_component(_src_abs "${_src}" ABSOLUTE + BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + get_filename_component(_src_base "${_src}" NAME_WE) + set(_stem "${_tgt}_${_src_base}") + + # Emit compile commands only for the requested platforms. + if("linux" IN_LIST _platforms) + set(_obj_linux "${_outdir}/${_stem}_linux.o") + if(_VOIDLIBC_CC_KIND STREQUAL "zig") + add_custom_command(OUTPUT "${_obj_linux}" + COMMAND ${_VOIDLIBC_CC_BIN} + -target ${_VOIDLIBC_CC_LINUX} + -O2 -fPIC ${_compile_opts} ${_inc_flags} + -c "${_src_abs}" -o "${_obj_linux}" + DEPENDS "${_src_abs}" + COMMENT "[VLC] zig cc → Linux musl: ${_src_base}.c" + VERBATIM + ) + elseif(_VOIDLIBC_CC_KIND STREQUAL "clang") + add_custom_command(OUTPUT "${_obj_linux}" + COMMAND ${_VOIDLIBC_CC_BIN} + --target=${_VOIDLIBC_CC_LINUX} + -O2 -fPIC ${_compile_opts} ${_inc_flags} + -c "${_src_abs}" -o "${_obj_linux}" + DEPENDS "${_src_abs}" + COMMENT "[VLC] clang → Linux: ${_src_base}.c" + VERBATIM + ) + else() + add_custom_command(OUTPUT "${_obj_linux}" + COMMAND ${CMAKE_C_COMPILER} + -O2 -fPIC ${_compile_opts} ${_inc_flags} + -c "${_src_abs}" -o "${_obj_linux}" + DEPENDS "${_src_abs}" + COMMENT "[VLC] host → Linux: ${_src_base}.c" + VERBATIM + ) + endif() + list(APPEND _linux_objs "${_obj_linux}") + endif() + + if("windows" IN_LIST _platforms AND NOT _VOIDLIBC_CC_KIND STREQUAL "host") + set(_obj_windows "${_outdir}/${_stem}_windows.obj") + if(_VOIDLIBC_CC_KIND STREQUAL "zig") + add_custom_command(OUTPUT "${_obj_windows}" + COMMAND ${_VOIDLIBC_CC_BIN} + -target ${_VOIDLIBC_CC_WINDOWS} + -O2 ${_compile_opts} ${_inc_flags} + -c "${_src_abs}" -o "${_obj_windows}" + DEPENDS "${_src_abs}" + COMMENT "[VLC] zig cc → Windows GNU: ${_src_base}.c" + VERBATIM + ) + else() + add_custom_command(OUTPUT "${_obj_windows}" + COMMAND ${_VOIDLIBC_CC_BIN} + --target=${_VOIDLIBC_CC_WINDOWS} + -O2 ${_compile_opts} ${_inc_flags} + -c "${_src_abs}" -o "${_obj_windows}" + DEPENDS "${_src_abs}" + COMMENT "[VLC] clang → Windows: ${_src_base}.c" + VERBATIM + ) + endif() + list(APPEND _windows_objs "${_obj_windows}") + endif() + + if("macos" IN_LIST _platforms AND NOT _VOIDLIBC_CC_KIND STREQUAL "host") + set(_obj_macos "${_outdir}/${_stem}_macos.o") + if(_VOIDLIBC_CC_KIND STREQUAL "zig") + add_custom_command(OUTPUT "${_obj_macos}" + COMMAND ${_VOIDLIBC_CC_BIN} + -target ${_VOIDLIBC_CC_MACOS} + -O2 -fPIC ${_compile_opts} ${_inc_flags} + -c "${_src_abs}" -o "${_obj_macos}" + DEPENDS "${_src_abs}" + COMMENT "[VLC] zig cc → macOS: ${_src_base}.c" + VERBATIM + ) + else() + add_custom_command(OUTPUT "${_obj_macos}" + COMMAND ${_VOIDLIBC_CC_BIN} + --target=${_VOIDLIBC_CC_MACOS} + -O2 -fPIC ${_compile_opts} ${_inc_flags} + -c "${_src_abs}" -o "${_obj_macos}" + DEPENDS "${_src_abs}" + COMMENT "[VLC] clang → macOS: ${_src_base}.c" + VERBATIM + ) + endif() + list(APPEND _macos_objs "${_obj_macos}") + endif() + endforeach() + + # Build the fuse/pack-elf command with only the active platform groups. + _voidlibc_resolve_voidlink(_vl_tgt _vl_dep) + set(_fuse_cmd $) + set(_fuse_deps ${_vl_dep}) + set(_fuse_platform_args "") + set(_fuse_comment_platforms "") + + if(_linux_objs) + list(APPEND _fuse_platform_args --linux ${_linux_objs}) + list(APPEND _fuse_deps ${_linux_objs}) + string(APPEND _fuse_comment_platforms "Linux") + endif() + if(_windows_objs) + list(APPEND _fuse_platform_args --windows ${_windows_objs}) + list(APPEND _fuse_deps ${_windows_objs}) + string(APPEND _fuse_comment_platforms "+Windows") + endif() + if(_macos_objs) + list(APPEND _fuse_platform_args --macos ${_macos_objs}) + list(APPEND _fuse_deps ${_macos_objs}) + string(APPEND _fuse_comment_platforms "+macOS") + endif() + + # Single platform → pack-elf; multiple → fuse. + list(LENGTH _platforms _nplat) + if(_nplat EQUAL 1 AND "linux" IN_LIST _platforms) + add_custom_command(OUTPUT "${_out_vlc}" + COMMAND $ + pack-elf --os linux + ${_linux_objs} + ${_entry_args} + -o "${_out_vlc}" + DEPENDS ${_fuse_deps} + COMMENT "[VLC] pack-elf → ${_tgt}${_ext} (${_fuse_comment_platforms})" + VERBATIM + ) + else() + add_custom_command(OUTPUT "${_out_vlc}" + COMMAND $ + fuse + ${_fuse_platform_args} + ${_entry_args} + -o "${_out_vlc}" + DEPENDS ${_fuse_deps} + COMMENT "[VLC] fuse → ${_tgt}${_ext} (${_fuse_comment_platforms})" + VERBATIM + ) + endif() + + add_custom_target(${_tgt}_vlc ALL DEPENDS "${_out_vlc}") +endfunction() + +# --------------------------------------------------------------------------- +# Internal: DEFER callback — scans the directory for VLC candidates. +# --------------------------------------------------------------------------- +function(_voidlibc_finalize_directory) + get_property(_targets + DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + PROPERTY BUILDSYSTEM_TARGETS + ) + foreach(_tgt IN LISTS _targets) + get_target_property(_type ${_tgt} TYPE) + # Only process library types; skip executables and interface targets. + if(NOT _type MATCHES "^(SHARED_LIBRARY|STATIC_LIBRARY|OBJECT_LIBRARY)$") + continue() + endif() + # Check for 'void' or 'VoidLibC::void' in LINK_LIBRARIES. + get_target_property(_libs ${_tgt} LINK_LIBRARIES) + if(NOT _libs) + continue() + endif() + if("void" IN_LIST _libs OR "VoidLibC::void" IN_LIST _libs) + _voidlibc_make_vlc(${_tgt} "${CMAKE_CURRENT_BINARY_DIR}") + endif() + endforeach() +endfunction() + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- + +# voidlibc_enable_auto_vlc() +# Call once per CMakeLists.txt that defines VLC-producing targets. +# Registers a DEFER hook that runs after all targets in this directory +# are defined and creates .vls / .vle for each one that +# links 'void'. +macro(voidlibc_enable_auto_vlc) + cmake_language(DEFER + DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + CALL _voidlibc_finalize_directory + ) +endmacro() + +# voidlibc_vlc_executable( ) +# Mark a SHARED library target to produce an executable .vle instead of +# a shared-library .vls. Must be called before voidlibc_enable_auto_vlc(). +macro(voidlibc_vlc_executable _tgt _entry) + set_target_properties(${_tgt} PROPERTIES VOIDLIBC_VLC_ENTRY "${_entry}") +endmacro() + +# --------------------------------------------------------------------------- +# High-level host-libc delegation API (Phase D) +# --------------------------------------------------------------------------- + +# _void_build_one_platform( +# +# +# ) +# +# Internal helper: compile each source for one platform and append objects to . +function(_void_build_one_platform _plat _cc_kind _cc_bin _triple + _srcs _stem_pfx _outdir + _compile_opts _inc_flags + _obj_list_var) + set(_objs "") + set(_ext ".o") + if(_plat STREQUAL "windows") + set(_ext ".obj") + endif() + + foreach(_src IN LISTS _srcs) + get_filename_component(_base "${_src}" NAME_WE) + set(_obj "${_outdir}/${_stem_pfx}_${_base}_${_plat}${_ext}") + + if(_cc_kind STREQUAL "zig") + set(_fPIC "") + if(NOT _plat STREQUAL "windows") + set(_fPIC "-fPIC") + endif() + add_custom_command(OUTPUT "${_obj}" + COMMAND ${_cc_bin} + -target ${_triple} + -O2 ${_fPIC} ${_compile_opts} ${_inc_flags} + -c "${_src}" -o "${_obj}" + DEPENDS "${_src}" + COMMENT "[VLC] zig cc → ${_plat}: ${_base}" + VERBATIM + ) + else() + set(_fPIC "") + if(NOT _plat STREQUAL "windows") + set(_fPIC "-fPIC") + endif() + add_custom_command(OUTPUT "${_obj}" + COMMAND ${_cc_bin} + --target=${_triple} + -O2 ${_fPIC} ${_compile_opts} ${_inc_flags} + -c "${_src}" -o "${_obj}" + DEPENDS "${_src}" + COMMENT "[VLC] clang → ${_plat}: ${_base}" + VERBATIM + ) + endif() + list(APPEND _objs "${_obj}") + endforeach() + + set(${_obj_list_var} "${_objs}" PARENT_SCOPE) +endfunction() + +# void_add_universal_library( +# SOURCES ... +# [TARGETS linux|windows|macos...] +# [LINUX_NEEDS ...] # DT_NEEDED entries for Linux section +# [WINDOWS_NEEDS ...] # import DLLs for Windows section +# [MACOS_NEEDS ...] # LC_LOAD_DYLIB entries for macOS section +# [LINUX_SYMLIBS ...] # --symlib overrides for Linux +# [WINDOWS_SYMLIBS ...] # --symlib overrides for Windows +# [MACOS_SYMLIBS ...] # --symlib overrides for macOS +# [STRICT_LIBS] # promote unresolved symbols to errors +# ) +# +# Cross-compiles SOURCES for each requested target OS and fuses them into +# /.vls via voidlink. +function(void_add_universal_library _tgt) + cmake_parse_arguments(_V "STRICT_LIBS" + "" + "SOURCES;TARGETS;LINUX_NEEDS;WINDOWS_NEEDS;MACOS_NEEDS;LINUX_SYMLIBS;WINDOWS_SYMLIBS;MACOS_SYMLIBS" + ${ARGN} + ) + + if(NOT _V_SOURCES) + message(FATAL_ERROR "void_add_universal_library(${_tgt}): SOURCES required") + endif() + + _voidlibc_detect_cross() + _voidlibc_resolve_voidlink(_vl_tgt _vl_dep) + + # Default platforms. + if(NOT _V_TARGETS) + if(_VOIDLIBC_CC_KIND STREQUAL "host") + set(_V_TARGETS "linux") + else() + set(_V_TARGETS "linux;windows;macos") + endif() + endif() + + # Absolute source paths. + set(_srcs_abs "") + foreach(_s IN LISTS _V_SOURCES) + get_filename_component(_sa "${_s}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + list(APPEND _srcs_abs "${_sa}") + endforeach() + + set(_outdir "${CMAKE_CURRENT_BINARY_DIR}") + set(_out_vls "${_outdir}/${_tgt}.vls") + + # Build per-platform object lists. + set(_linux_objs "") + set(_windows_objs "") + set(_macos_objs "") + + if("linux" IN_LIST _V_TARGETS) + _void_build_one_platform("linux" + "${_VOIDLIBC_CC_KIND}" "${_VOIDLIBC_CC_BIN}" + "${_VOIDLIBC_CC_LINUX}" + "${_srcs_abs}" "${_tgt}" "${_outdir}" "" "" + _linux_objs) + endif() + if("windows" IN_LIST _V_TARGETS AND NOT _VOIDLIBC_CC_KIND STREQUAL "host") + _void_build_one_platform("windows" + "${_VOIDLIBC_CC_KIND}" "${_VOIDLIBC_CC_BIN}" + "${_VOIDLIBC_CC_WINDOWS}" + "${_srcs_abs}" "${_tgt}" "${_outdir}" "" "" + _windows_objs) + endif() + if("macos" IN_LIST _V_TARGETS AND NOT _VOIDLIBC_CC_KIND STREQUAL "host") + _void_build_one_platform("macos" + "${_VOIDLIBC_CC_KIND}" "${_VOIDLIBC_CC_BIN}" + "${_VOIDLIBC_CC_MACOS}" + "${_srcs_abs}" "${_tgt}" "${_outdir}" "" "" + _macos_objs) + endif() + + # Build voidlink fuse command. + set(_fuse_args "") + set(_fuse_deps ${_vl_dep}) + set(_comment_plats "") + + set(_strict_arg "") + if(_V_STRICT_LIBS) + set(_strict_arg "--strict-libs") + endif() + + if(_linux_objs) + list(APPEND _fuse_args --linux ${_linux_objs}) + list(APPEND _fuse_deps ${_linux_objs}) + foreach(_n IN LISTS _V_LINUX_NEEDS) + list(APPEND _fuse_args --linux-need "${_n}") + endforeach() + foreach(_sl IN LISTS _V_LINUX_SYMLIBS) + list(APPEND _fuse_args --symlib "${_sl}") + endforeach() + string(APPEND _comment_plats "Linux") + endif() + if(_windows_objs) + list(APPEND _fuse_args --windows ${_windows_objs}) + list(APPEND _fuse_deps ${_windows_objs}) + foreach(_n IN LISTS _V_WINDOWS_NEEDS) + list(APPEND _fuse_args --windows-need "${_n}") + endforeach() + foreach(_sl IN LISTS _V_WINDOWS_SYMLIBS) + list(APPEND _fuse_args --symlib "${_sl}") + endforeach() + string(APPEND _comment_plats "+Windows") + endif() + if(_macos_objs) + list(APPEND _fuse_args --macos ${_macos_objs}) + list(APPEND _fuse_deps ${_macos_objs}) + foreach(_n IN LISTS _V_MACOS_NEEDS) + list(APPEND _fuse_args --macos-need "${_n}") + endforeach() + foreach(_sl IN LISTS _V_MACOS_SYMLIBS) + list(APPEND _fuse_args --symlib "${_sl}") + endforeach() + string(APPEND _comment_plats "+macOS") + endif() + + add_custom_command(OUTPUT "${_out_vls}" + COMMAND $ + fuse ${_fuse_args} ${_strict_arg} + -o "${_out_vls}" + DEPENDS ${_fuse_deps} + COMMENT "[VLC] fuse → ${_tgt}.vls (${_comment_plats})" + VERBATIM + ) + add_custom_target(${_tgt} ALL DEPENDS "${_out_vls}") +endfunction() + +# void_add_universal_executable( +# ENTRY +# SOURCES ... +# [same optional keyword args as void_add_universal_library] +# ) +# +# Like void_add_universal_library but produces .vle with an entry point. +function(void_add_universal_executable _tgt) + cmake_parse_arguments(_VE "STRICT_LIBS" + "ENTRY" + "SOURCES;TARGETS;LINUX_NEEDS;WINDOWS_NEEDS;MACOS_NEEDS;LINUX_SYMLIBS;WINDOWS_SYMLIBS;MACOS_SYMLIBS" + ${ARGN} + ) + + if(NOT _VE_ENTRY) + message(FATAL_ERROR "void_add_universal_executable(${_tgt}): ENTRY required") + endif() + if(NOT _VE_SOURCES) + message(FATAL_ERROR "void_add_universal_executable(${_tgt}): SOURCES required") + endif() + + _voidlibc_detect_cross() + _voidlibc_resolve_voidlink(_vl_tgt _vl_dep) + + if(NOT _VE_TARGETS) + if(_VOIDLIBC_CC_KIND STREQUAL "host") + set(_VE_TARGETS "linux") + else() + set(_VE_TARGETS "linux;windows;macos") + endif() + endif() + + set(_srcs_abs "") + foreach(_s IN LISTS _VE_SOURCES) + get_filename_component(_sa "${_s}" ABSOLUTE BASE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + list(APPEND _srcs_abs "${_sa}") + endforeach() + + set(_outdir "${CMAKE_CURRENT_BINARY_DIR}") + set(_out_vle "${_outdir}/${_tgt}.vle") + + set(_linux_objs "") + set(_windows_objs "") + set(_macos_objs "") + + if("linux" IN_LIST _VE_TARGETS) + _void_build_one_platform("linux" + "${_VOIDLIBC_CC_KIND}" "${_VOIDLIBC_CC_BIN}" + "${_VOIDLIBC_CC_LINUX}" + "${_srcs_abs}" "${_tgt}" "${_outdir}" "" "" + _linux_objs) + endif() + if("windows" IN_LIST _VE_TARGETS AND NOT _VOIDLIBC_CC_KIND STREQUAL "host") + _void_build_one_platform("windows" + "${_VOIDLIBC_CC_KIND}" "${_VOIDLIBC_CC_BIN}" + "${_VOIDLIBC_CC_WINDOWS}" + "${_srcs_abs}" "${_tgt}" "${_outdir}" "" "" + _windows_objs) + endif() + if("macos" IN_LIST _VE_TARGETS AND NOT _VOIDLIBC_CC_KIND STREQUAL "host") + _void_build_one_platform("macos" + "${_VOIDLIBC_CC_KIND}" "${_VOIDLIBC_CC_BIN}" + "${_VOIDLIBC_CC_MACOS}" + "${_srcs_abs}" "${_tgt}" "${_outdir}" "" "" + _macos_objs) + endif() + + set(_fuse_args "--entry" "${_VE_ENTRY}") + set(_fuse_deps ${_vl_dep}) + set(_comment_plats "") + set(_strict_arg "") + if(_VE_STRICT_LIBS) + set(_strict_arg "--strict-libs") + endif() + + if(_linux_objs) + list(APPEND _fuse_args --linux ${_linux_objs}) + list(APPEND _fuse_deps ${_linux_objs}) + foreach(_n IN LISTS _VE_LINUX_NEEDS) + list(APPEND _fuse_args --linux-need "${_n}") + endforeach() + foreach(_sl IN LISTS _VE_LINUX_SYMLIBS) + list(APPEND _fuse_args --symlib "${_sl}") + endforeach() + string(APPEND _comment_plats "Linux") + endif() + if(_windows_objs) + list(APPEND _fuse_args --windows ${_windows_objs}) + list(APPEND _fuse_deps ${_windows_objs}) + foreach(_n IN LISTS _VE_WINDOWS_NEEDS) + list(APPEND _fuse_args --windows-need "${_n}") + endforeach() + foreach(_sl IN LISTS _VE_WINDOWS_SYMLIBS) + list(APPEND _fuse_args --symlib "${_sl}") + endforeach() + string(APPEND _comment_plats "+Windows") + endif() + if(_macos_objs) + list(APPEND _fuse_args --macos ${_macos_objs}) + list(APPEND _fuse_deps ${_macos_objs}) + foreach(_n IN LISTS _VE_MACOS_NEEDS) + list(APPEND _fuse_args --macos-need "${_n}") + endforeach() + foreach(_sl IN LISTS _VE_MACOS_SYMLIBS) + list(APPEND _fuse_args --symlib "${_sl}") + endforeach() + string(APPEND _comment_plats "+macOS") + endif() + + add_custom_command(OUTPUT "${_out_vle}" + COMMAND $ + fuse ${_fuse_args} ${_strict_arg} + -o "${_out_vle}" + DEPENDS ${_fuse_deps} + COMMENT "[VLC] fuse → ${_tgt}.vle (${_comment_plats})" + VERBATIM + ) + add_custom_target(${_tgt} ALL DEPENDS "${_out_vle}") +endfunction() + +# void_symbol_library( ) +# Append per-symbol host library overrides to the _VOID_{LINUX,WINDOWS,MACOS}_SYMLIBS +# lists in the caller's scope. Pass these lists to void_add_universal_library via +# LINUX_SYMLIBS / WINDOWS_SYMLIBS / MACOS_SYMLIBS. +# +# Example: +# void_symbol_library(my_platform_func +# myplatlib.so myplatlib.dll myplatlib.dylib) +# void_add_universal_library(mylib SOURCES foo.c +# LINUX_SYMLIBS ${_VOID_LINUX_SYMLIBS} +# WINDOWS_SYMLIBS ${_VOID_WINDOWS_SYMLIBS} +# MACOS_SYMLIBS ${_VOID_MACOS_SYMLIBS} +# ) +macro(void_symbol_library _sym _linux_lib _win_lib _macos_lib) + list(APPEND _VOID_LINUX_SYMLIBS "${_sym}=${_linux_lib}") + list(APPEND _VOID_WINDOWS_SYMLIBS "${_sym}=${_win_lib}") + list(APPEND _VOID_MACOS_SYMLIBS "${_sym}=${_macos_lib}") +endmacro() diff --git a/cmake/VoidLibCConfig.cmake.in b/cmake/VoidLibCConfig.cmake.in new file mode 100644 index 0000000..5ae3cf1 --- /dev/null +++ b/cmake/VoidLibCConfig.cmake.in @@ -0,0 +1,11 @@ +@PACKAGE_INIT@ + +# Bring in the auto-VLC hook so consumers can call: +# voidlibc_enable_auto_vlc() +# voidlibc_vlc_executable( ) +include("${CMAKE_CURRENT_LIST_DIR}/VoidLibCAutoVLC.cmake") + +# Import VoidLibC::void, VoidLibC::voidlink, and their internal dependencies. +include("${CMAKE_CURRENT_LIST_DIR}/VoidLibCTargets.cmake") + +check_required_components(VoidLibC) diff --git a/cmake/toolchains/host-macos.cmake b/cmake/toolchains/host-macos.cmake new file mode 100644 index 0000000..5ad6383 --- /dev/null +++ b/cmake/toolchains/host-macos.cmake @@ -0,0 +1,21 @@ +# Cross-compile host tools (voidlink) for x86_64-apple-macos12 using zig cc. +# Used by the CI release pipeline; NOT for target-blob cross-compilation. +# +# zig 0.13 bundles macOS libc headers so no separate SDK is required. +# Usage: +# cmake -B build-mac -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/host-macos.cmake + +set(CMAKE_SYSTEM_NAME Darwin) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +# zig cc/c++ wrappers must be on PATH before invoking cmake. +# The pipeline creates /usr/local/bin/zig-cc-mac and zig-cxx-mac. +set(CMAKE_C_COMPILER zig-cc-mac CACHE FILEPATH "") +set(CMAKE_CXX_COMPILER zig-cxx-mac CACHE FILEPATH "") + +# Skip try_compile executable run — we can't execute macOS binaries on the Linux runner. +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY CACHE STRING "") + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/cmake/toolchains/host-windows.cmake b/cmake/toolchains/host-windows.cmake new file mode 100644 index 0000000..61358fb --- /dev/null +++ b/cmake/toolchains/host-windows.cmake @@ -0,0 +1,24 @@ +# Cross-compile host tools (voidlink) for x86_64-windows-gnu using zig cc. +# Used by the CI release pipeline; NOT for target-blob cross-compilation. +# +# Produces a statically linked .exe that has no mingw DLL dependencies. +# Usage: +# cmake -B build-win -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/host-windows.cmake + +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR AMD64) + +# zig cc/c++ wrappers must be on PATH before invoking cmake. +# The pipeline creates /usr/local/bin/zig-cc-win and zig-cxx-win. +set(CMAKE_C_COMPILER zig-cc-win CACHE FILEPATH "") +set(CMAKE_CXX_COMPILER zig-cxx-win CACHE FILEPATH "") + +# Static link so the .exe is self-contained (no mingw DLLs needed). +set(CMAKE_EXE_LINKER_FLAGS_INIT "-static") + +# Skip try_compile executable run — we can't execute Windows binaries on the Linux runner. +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY CACHE STRING "") + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/cmake/toolchains/linux.cmake b/cmake/toolchains/linux.cmake new file mode 100644 index 0000000..2b04391 --- /dev/null +++ b/cmake/toolchains/linux.cmake @@ -0,0 +1,29 @@ +# Toolchain: clang targeting x86_64-linux-gnu (host glibc delegation) +# Produces a PIC object file suitable for voidlink to pack into a .vlc section. +# +# Usage (from a consumer CMakeLists.txt driven by void_add_universal_library): +# cmake -B build-linux -DCMAKE_TOOLCHAIN_FILE=/cmake/toolchains/linux.cmake +# +# The resulting .o files are packed by voidlink; undefined symbols are resolved +# against the host process's glibc/libpthread/libm at dlopen time via DT_NEEDED. + +set(CMAKE_SYSTEM_NAME Linux) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +find_program(_CLANG_EXE NAMES clang clang-18 clang-17 clang-16 REQUIRED) + +set(CMAKE_C_COMPILER "${_CLANG_EXE}" CACHE FILEPATH "") +set(CMAKE_CXX_COMPILER "${_CLANG_EXE}" CACHE FILEPATH "") + +# -fPIC: required for DSO code; -c: produce .o, not linked binary. +# -target: explicit x86_64-linux-gnu to avoid accidentally targeting musl. +set(CMAKE_C_FLAGS_INIT "-target x86_64-unknown-linux-gnu -fPIC") +set(CMAKE_CXX_FLAGS_INIT "-target x86_64-unknown-linux-gnu -fPIC") + +# Object-only build: no linking step. +set(CMAKE_EXE_LINKER_FLAGS_INIT "") +set(CMAKE_SHARED_LINKER_FLAGS_INIT "") + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/cmake/toolchains/macos.cmake b/cmake/toolchains/macos.cmake new file mode 100644 index 0000000..a3f1450 --- /dev/null +++ b/cmake/toolchains/macos.cmake @@ -0,0 +1,26 @@ +# Toolchain: clang targeting x86_64-apple-macos12 (libSystem delegation) +# Produces a Mach-O object file suitable for voidlink to pack into a .vlc section. +# +# Usage (from a consumer CMakeLists.txt driven by void_add_universal_library): +# cmake -B build-macos -DCMAKE_TOOLCHAIN_FILE=/cmake/toolchains/macos.cmake +# +# The resulting .o files are packed by voidlink; undefined symbols are resolved +# against the host process's /usr/lib/libSystem.B.dylib via LC_LOAD_DYLIB. + +set(CMAKE_SYSTEM_NAME Darwin) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +find_program(_CLANG_EXE NAMES clang clang-18 clang-17 clang-16 REQUIRED) + +set(CMAKE_C_COMPILER "${_CLANG_EXE}" CACHE FILEPATH "") +set(CMAKE_CXX_COMPILER "${_CLANG_EXE}" CACHE FILEPATH "") + +set(CMAKE_C_FLAGS_INIT "-target x86_64-apple-macos12 -O2") +set(CMAKE_CXX_FLAGS_INIT "-target x86_64-apple-macos12 -O2") + +set(CMAKE_EXE_LINKER_FLAGS_INIT "") +set(CMAKE_SHARED_LINKER_FLAGS_INIT "") + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/cmake/toolchains/windows.cmake b/cmake/toolchains/windows.cmake new file mode 100644 index 0000000..4aed7a8 --- /dev/null +++ b/cmake/toolchains/windows.cmake @@ -0,0 +1,30 @@ +# Toolchain: clang targeting x86_64-pc-windows-msvc (UCRT, MSVC ABI) +# Produces a COFF object file suitable for voidlink to pack into a .vlc section. +# +# Usage (from a consumer CMakeLists.txt driven by void_add_universal_library): +# cmake -B build-windows -DCMAKE_TOOLCHAIN_FILE=/cmake/toolchains/windows.cmake +# +# The resulting .obj files are packed by voidlink; undefined symbols are resolved +# against the host process's ucrtbase.dll / KERNEL32.DLL etc. via IMAGE_IMPORT_DESCRIPTOR. +# +# Note: MSVC-ABI cross-compilation requires clang + Windows SDK headers or +# MinGW-w64 headers. If headers are unavailable, use --symlib overrides on +# any non-UCRT imports. + +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR AMD64) + +find_program(_CLANG_EXE NAMES clang clang-18 clang-17 clang-16 REQUIRED) + +set(CMAKE_C_COMPILER "${_CLANG_EXE}" CACHE FILEPATH "") +set(CMAKE_CXX_COMPILER "${_CLANG_EXE}" CACHE FILEPATH "") + +set(CMAKE_C_FLAGS_INIT "-target x86_64-pc-windows-msvc -O2") +set(CMAKE_CXX_FLAGS_INIT "-target x86_64-pc-windows-msvc -O2") + +set(CMAKE_EXE_LINKER_FLAGS_INIT "") +set(CMAKE_SHARED_LINKER_FLAGS_INIT "") + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/cmake/zigcc/FindZig.cmake b/cmake/zigcc/FindZig.cmake new file mode 100644 index 0000000..de5d0ff --- /dev/null +++ b/cmake/zigcc/FindZig.cmake @@ -0,0 +1,30 @@ +# FindZig.cmake +# Locates the zig compiler and exposes: +# Zig_FOUND — TRUE if zig was found +# Zig_EXECUTABLE — full path to the zig binary +# Zig_VERSION — version string (e.g. "0.13.0") +# +# Minimum required version can be checked via find_package(Zig 0.13 REQUIRED). + +find_program(Zig_EXECUTABLE + NAMES zig + DOC "Zig compiler" +) + +if(Zig_EXECUTABLE) + execute_process( + COMMAND "${Zig_EXECUTABLE}" version + OUTPUT_VARIABLE Zig_VERSION + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Zig + REQUIRED_VARS Zig_EXECUTABLE + VERSION_VAR Zig_VERSION + FAIL_MESSAGE "zig compiler not found. Install zig >= 0.13 from https://ziglang.org/download/" +) + +mark_as_advanced(Zig_EXECUTABLE) diff --git a/cmake/zigcc/linux-musl.cmake b/cmake/zigcc/linux-musl.cmake new file mode 100644 index 0000000..b5a83a0 --- /dev/null +++ b/cmake/zigcc/linux-musl.cmake @@ -0,0 +1,25 @@ +# Toolchain: zig cc targeting x86_64-linux-musl (static musl libc) +# Use this file to produce a statically-linked Linux binary with no glibc dep: +# +# cmake -B build-linux -DCMAKE_TOOLCHAIN_FILE=cmake/zigcc/linux-musl.cmake +# +# The resulting binary runs on any x86_64 Linux without any shared library +# dependencies beyond the kernel ABI. + +set(CMAKE_SYSTEM_NAME Linux) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +find_program(_ZIG_EXE zig REQUIRED) + +set(CMAKE_C_COMPILER "${_ZIG_EXE}" CACHE FILEPATH "") +set(CMAKE_CXX_COMPILER "${_ZIG_EXE}" CACHE FILEPATH "") +set(CMAKE_C_COMPILER_ARG1 "cc;-target;x86_64-linux-musl" CACHE STRING "") +set(CMAKE_CXX_COMPILER_ARG1 "c++;-target;x86_64-linux-musl" CACHE STRING "") + +# Produce fully-static binaries (no dynamic linking at all). +set(CMAKE_EXE_LINKER_FLAGS_INIT "-static") +set(CMAKE_SHARED_LINKER_FLAGS_INIT "-static") + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/cmake/zigcc/macos.cmake b/cmake/zigcc/macos.cmake new file mode 100644 index 0000000..ac5fd8f --- /dev/null +++ b/cmake/zigcc/macos.cmake @@ -0,0 +1,24 @@ +# Toolchain: zig cc targeting x86_64-macos-none +# Use this file to cross-compile a macOS binary from Linux: +# +# cmake -B build-macos -DCMAKE_TOOLCHAIN_FILE=cmake/zigcc/macos.cmake +# +# zig bundles macOS libc headers so no Xcode SDK is required on the build host. +# The resulting binary requires macOS 12+ (Monterey) on the target machine. + +set(CMAKE_SYSTEM_NAME Darwin) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +find_program(_ZIG_EXE zig REQUIRED) + +set(CMAKE_C_COMPILER "${_ZIG_EXE}" CACHE FILEPATH "") +set(CMAKE_CXX_COMPILER "${_ZIG_EXE}" CACHE FILEPATH "") +set(CMAKE_C_COMPILER_ARG1 "cc;-target;x86_64-macos-none" CACHE STRING "") +set(CMAKE_CXX_COMPILER_ARG1 "c++;-target;x86_64-macos-none" CACHE STRING "") + +# Dylib suffix on macOS. +set(CMAKE_SHARED_LIBRARY_SUFFIX ".dylib") + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/cmake/zigcc/windows-mingw.cmake b/cmake/zigcc/windows-mingw.cmake new file mode 100644 index 0000000..deb4b56 --- /dev/null +++ b/cmake/zigcc/windows-mingw.cmake @@ -0,0 +1,30 @@ +# Toolchain: zig cc targeting x86_64-windows-gnu (MinGW/GNU ABI) +# Use this file to cross-compile a Windows executable from Linux: +# +# cmake -B build-windows -DCMAKE_TOOLCHAIN_FILE=cmake/zigcc/windows-mingw.cmake +# +# zig bundles all MinGW headers/libs so no separate SDK is required. + +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +find_program(_ZIG_EXE zig REQUIRED) + +set(CMAKE_C_COMPILER "${_ZIG_EXE}" CACHE FILEPATH "") +set(CMAKE_CXX_COMPILER "${_ZIG_EXE}" CACHE FILEPATH "") +set(CMAKE_C_COMPILER_ARG1 "cc;-target;x86_64-windows-gnu" CACHE STRING "") +set(CMAKE_CXX_COMPILER_ARG1 "c++;-target;x86_64-windows-gnu" CACHE STRING "") + +set(CMAKE_RC_COMPILER "${_ZIG_EXE}" CACHE FILEPATH "") +set(CMAKE_RC_COMPILER_ARG1 "rc" CACHE STRING "") + +# Produce fully-static binaries (bundle libgcc + libstdc++ from zig's mingw). +set(CMAKE_EXE_LINKER_FLAGS_INIT "-static") +set(CMAKE_SHARED_LINKER_FLAGS_INIT "-static") + +# .exe suffix +set(CMAKE_EXECUTABLE_SUFFIX ".exe") + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/data/symlib_linux.txt b/data/symlib_linux.txt new file mode 100644 index 0000000..63602a3 --- /dev/null +++ b/data/symlib_linux.txt @@ -0,0 +1,487 @@ +# Linux symbol → import library table. +# Format: +# Keep sorted alphabetically by symbol (first field). +# Used by voidlink/symlib_table.cpp (do not edit that file; edit here and regenerate). + +# ── stdlib ───────────────────────────────────────────────────────────────────── +__assert_fail libc.so.6 +__cxa_atexit libc.so.6 +__cxa_finalize libc.so.6 +__cxa_pure_virtual libc.so.6 +__cxa_throw libc.so.6 +__errno_location libc.so.6 +__stack_chk_fail libc.so.6 +_exit libc.so.6 +abort libc.so.6 +abs libc.so.6 +aligned_alloc libc.so.6 +atexit libc.so.6 +atof libc.so.6 +atoi libc.so.6 +atol libc.so.6 +atoll libc.so.6 +bsearch libc.so.6 +calloc libc.so.6 +div libc.so.6 +exit libc.so.6 +free libc.so.6 +getenv libc.so.6 +labs libc.so.6 +ldiv libc.so.6 +llabs libc.so.6 +lldiv libc.so.6 +malloc libc.so.6 +memalign libc.so.6 +on_exit libc.so.6 +posix_memalign libc.so.6 +putenv libc.so.6 +qsort libc.so.6 +rand libc.so.6 +rand_r libc.so.6 +realloc libc.so.6 +setenv libc.so.6 +srand libc.so.6 +strtod libc.so.6 +strtof libc.so.6 +strtol libc.so.6 +strtold libc.so.6 +strtoll libc.so.6 +strtoul libc.so.6 +strtoull libc.so.6 +system libc.so.6 +unsetenv libc.so.6 + +# ── string ───────────────────────────────────────────────────────────────────── +memchr libc.so.6 +memcmp libc.so.6 +memcpy libc.so.6 +memmove libc.so.6 +memset libc.so.6 +strcat libc.so.6 +strchr libc.so.6 +strcmp libc.so.6 +strcoll libc.so.6 +strcpy libc.so.6 +strcspn libc.so.6 +strdup libc.so.6 +strerror libc.so.6 +strerror_r libc.so.6 +strlen libc.so.6 +strncat libc.so.6 +strncmp libc.so.6 +strncpy libc.so.6 +strndup libc.so.6 +strnlen libc.so.6 +strpbrk libc.so.6 +strrchr libc.so.6 +strspn libc.so.6 +strstr libc.so.6 +strtok libc.so.6 +strtok_r libc.so.6 +strxfrm libc.so.6 +wcscat libc.so.6 +wcscmp libc.so.6 +wcscpy libc.so.6 +wcslen libc.so.6 +wmemcpy libc.so.6 + +# ── stdio ────────────────────────────────────────────────────────────────────── +asprintf libc.so.6 +clearerr libc.so.6 +dprintf libc.so.6 +fclose libc.so.6 +fdopen libc.so.6 +feof libc.so.6 +ferror libc.so.6 +fflush libc.so.6 +fgetc libc.so.6 +fgetpos libc.so.6 +fgets libc.so.6 +fileno libc.so.6 +fopen libc.so.6 +fprintf libc.so.6 +fputc libc.so.6 +fputs libc.so.6 +fread libc.so.6 +freopen libc.so.6 +fscanf libc.so.6 +fseek libc.so.6 +fseeko libc.so.6 +fsetpos libc.so.6 +ftell libc.so.6 +ftello libc.so.6 +fwrite libc.so.6 +getc libc.so.6 +getchar libc.so.6 +getline libc.so.6 +pclose libc.so.6 +perror libc.so.6 +popen libc.so.6 +printf libc.so.6 +putc libc.so.6 +putchar libc.so.6 +puts libc.so.6 +rewind libc.so.6 +scanf libc.so.6 +setbuf libc.so.6 +setbuffer libc.so.6 +setvbuf libc.so.6 +snprintf libc.so.6 +sprintf libc.so.6 +sscanf libc.so.6 +tmpfile libc.so.6 +tmpnam libc.so.6 +ungetc libc.so.6 +vasprintf libc.so.6 +vdprintf libc.so.6 +vfprintf libc.so.6 +vfscanf libc.so.6 +vprintf libc.so.6 +vscanf libc.so.6 +vsnprintf libc.so.6 +vsprintf libc.so.6 +vsscanf libc.so.6 + +# ── math (libm.so.6) ──────────────────────────────────────────────────────────── +acos libm.so.6 +acosf libm.so.6 +acosh libm.so.6 +acoshf libm.so.6 +asin libm.so.6 +asinf libm.so.6 +asinh libm.so.6 +asinhf libm.so.6 +atan libm.so.6 +atan2 libm.so.6 +atan2f libm.so.6 +atanf libm.so.6 +atanh libm.so.6 +atanhf libm.so.6 +cbrt libm.so.6 +cbrtf libm.so.6 +ceil libm.so.6 +ceilf libm.so.6 +copysign libm.so.6 +copysignf libm.so.6 +cos libm.so.6 +cosf libm.so.6 +cosh libm.so.6 +coshf libm.so.6 +erf libm.so.6 +erfc libm.so.6 +erfcf libm.so.6 +erff libm.so.6 +exp libm.so.6 +exp2 libm.so.6 +exp2f libm.so.6 +expf libm.so.6 +expm1 libm.so.6 +expm1f libm.so.6 +fabs libm.so.6 +fabsf libm.so.6 +fdim libm.so.6 +fdimf libm.so.6 +floor libm.so.6 +floorf libm.so.6 +fma libm.so.6 +fmaf libm.so.6 +fmax libm.so.6 +fmaxf libm.so.6 +fmin libm.so.6 +fminf libm.so.6 +fmod libm.so.6 +fmodf libm.so.6 +frexp libm.so.6 +frexpf libm.so.6 +hypot libm.so.6 +hypotf libm.so.6 +ilogb libm.so.6 +ilogbf libm.so.6 +ldexp libm.so.6 +ldexpf libm.so.6 +lgamma libm.so.6 +lgammaf libm.so.6 +log libm.so.6 +log10 libm.so.6 +log10f libm.so.6 +log1p libm.so.6 +log1pf libm.so.6 +log2 libm.so.6 +log2f libm.so.6 +logb libm.so.6 +logbf libm.so.6 +logf libm.so.6 +modf libm.so.6 +modff libm.so.6 +nan libm.so.6 +nanf libm.so.6 +nearbyint libm.so.6 +nearbyintf libm.so.6 +nextafter libm.so.6 +nextafterf libm.so.6 +pow libm.so.6 +powf libm.so.6 +remainder libm.so.6 +remainderf libm.so.6 +remquo libm.so.6 +remquof libm.so.6 +rint libm.so.6 +rintf libm.so.6 +round libm.so.6 +roundf libm.so.6 +scalbn libm.so.6 +scalbnf libm.so.6 +sin libm.so.6 +sinf libm.so.6 +sinh libm.so.6 +sinhf libm.so.6 +sqrt libm.so.6 +sqrtf libm.so.6 +tan libm.so.6 +tanf libm.so.6 +tanh libm.so.6 +tanhf libm.so.6 +tgamma libm.so.6 +tgammaf libm.so.6 +trunc libm.so.6 +truncf libm.so.6 + +# ── POSIX / unix ─────────────────────────────────────────────────────────────── +access libc.so.6 +chdir libc.so.6 +chmod libc.so.6 +chown libc.so.6 +close libc.so.6 +closedir libc.so.6 +clock libc.so.6 +clock_getres libc.so.6 +clock_gettime libc.so.6 +clock_nanosleep libc.so.6 +confstr libc.so.6 +creat libc.so.6 +difftime libc.so.6 +dup libc.so.6 +dup2 libc.so.6 +dup3 libc.so.6 +epoll_create libc.so.6 +epoll_create1 libc.so.6 +epoll_ctl libc.so.6 +epoll_pwait libc.so.6 +epoll_wait libc.so.6 +execl libc.so.6 +execle libc.so.6 +execlp libc.so.6 +execv libc.so.6 +execve libc.so.6 +execvp libc.so.6 +fchdir libc.so.6 +fchmod libc.so.6 +fchown libc.so.6 +fcntl libc.so.6 +fdatasync libc.so.6 +fork libc.so.6 +fstat libc.so.6 +fsync libc.so.6 +ftruncate libc.so.6 +futimens libc.so.6 +getcwd libc.so.6 +getegid libc.so.6 +geteuid libc.so.6 +getgid libc.so.6 +getgroups libc.so.6 +gethostname libc.so.6 +getpid libc.so.6 +getppid libc.so.6 +gettimeofday libc.so.6 +getuid libc.so.6 +gmtime libc.so.6 +gmtime_r libc.so.6 +ioctl libc.so.6 +kill libc.so.6 +lchown libc.so.6 +link libc.so.6 +localtime libc.so.6 +localtime_r libc.so.6 +lseek libc.so.6 +lstat libc.so.6 +mkdir libc.so.6 +mkdtemp libc.so.6 +mkstemp libc.so.6 +mktime libc.so.6 +mmap libc.so.6 +mprotect libc.so.6 +munmap libc.so.6 +nanosleep libc.so.6 +open libc.so.6 +opendir libc.so.6 +pathconf libc.so.6 +pipe libc.so.6 +pipe2 libc.so.6 +poll libc.so.6 +pread libc.so.6 +pwrite libc.so.6 +raise libc.so.6 +read libc.so.6 +readdir libc.so.6 +readlink libc.so.6 +rename libc.so.6 +rmdir libc.so.6 +select libc.so.6 +setgid libc.so.6 +setpgid libc.so.6 +setsid libc.so.6 +setuid libc.so.6 +sigaction libc.so.6 +sigaddset libc.so.6 +sigdelset libc.so.6 +sigemptyset libc.so.6 +sigfillset libc.so.6 +signal libc.so.6 +sigpending libc.so.6 +sigprocmask libc.so.6 +sigsuspend libc.so.6 +sleep libc.so.6 +stat libc.so.6 +strftime libc.so.6 +strptime libc.so.6 +symlink libc.so.6 +sysconf libc.so.6 +time libc.so.6 +truncate libc.so.6 +umask libc.so.6 +uname libc.so.6 +unlink libc.so.6 +usleep libc.so.6 +utimes libc.so.6 +wait libc.so.6 +waitpid libc.so.6 +write libc.so.6 + +# ── network ──────────────────────────────────────────────────────────────────── +accept libc.so.6 +bind libc.so.6 +connect libc.so.6 +freeaddrinfo libc.so.6 +getaddrinfo libc.so.6 +gethostbyname libc.so.6 +getnameinfo libc.so.6 +getpeername libc.so.6 +getsockname libc.so.6 +getsockopt libc.so.6 +htonl libc.so.6 +htons libc.so.6 +inet_addr libc.so.6 +inet_ntoa libc.so.6 +inet_ntop libc.so.6 +inet_pton libc.so.6 +listen libc.so.6 +ntohl libc.so.6 +ntohs libc.so.6 +recv libc.so.6 +recvfrom libc.so.6 +recvmsg libc.so.6 +send libc.so.6 +sendmsg libc.so.6 +sendto libc.so.6 +setsockopt libc.so.6 +shutdown libc.so.6 +socket libc.so.6 +socketpair libc.so.6 + +# ── pthread / semaphore (libc.so.6 on glibc 2.34+) ─────────────────────────── +pthread_attr_destroy libc.so.6 +pthread_attr_init libc.so.6 +pthread_attr_setdetachstate libc.so.6 +pthread_attr_setschedparam libc.so.6 +pthread_attr_setstacksize libc.so.6 +pthread_barrier_destroy libc.so.6 +pthread_barrier_init libc.so.6 +pthread_barrier_wait libc.so.6 +pthread_cancel libc.so.6 +pthread_cond_broadcast libc.so.6 +pthread_cond_destroy libc.so.6 +pthread_cond_init libc.so.6 +pthread_cond_signal libc.so.6 +pthread_cond_timedwait libc.so.6 +pthread_cond_wait libc.so.6 +pthread_create libc.so.6 +pthread_detach libc.so.6 +pthread_equal libc.so.6 +pthread_exit libc.so.6 +pthread_getspecific libc.so.6 +pthread_join libc.so.6 +pthread_key_create libc.so.6 +pthread_key_delete libc.so.6 +pthread_mutex_destroy libc.so.6 +pthread_mutex_init libc.so.6 +pthread_mutex_lock libc.so.6 +pthread_mutex_timedlock libc.so.6 +pthread_mutex_trylock libc.so.6 +pthread_mutex_unlock libc.so.6 +pthread_once libc.so.6 +pthread_rwlock_destroy libc.so.6 +pthread_rwlock_init libc.so.6 +pthread_rwlock_rdlock libc.so.6 +pthread_rwlock_timedrdlock libc.so.6 +pthread_rwlock_timedwrlock libc.so.6 +pthread_rwlock_tryrdlock libc.so.6 +pthread_rwlock_trywrlock libc.so.6 +pthread_rwlock_unlock libc.so.6 +pthread_rwlock_wrlock libc.so.6 +pthread_self libc.so.6 +pthread_setspecific libc.so.6 +pthread_sigmask libc.so.6 +pthread_spin_destroy libc.so.6 +pthread_spin_init libc.so.6 +pthread_spin_lock libc.so.6 +pthread_spin_trylock libc.so.6 +pthread_spin_unlock libc.so.6 +pthread_testcancel libc.so.6 +sem_close libc.so.6 +sem_destroy libc.so.6 +sem_getvalue libc.so.6 +sem_init libc.so.6 +sem_open libc.so.6 +sem_post libc.so.6 +sem_timedwait libc.so.6 +sem_trywait libc.so.6 +sem_unlink libc.so.6 +sem_wait libc.so.6 + +# ── dl (libc.so.6 on glibc 2.34+) ───────────────────────────────────────────── +dladdr libc.so.6 +dlclose libc.so.6 +dlerror libc.so.6 +dlinfo libc.so.6 +dlopen libc.so.6 +dlsym libc.so.6 + +# ── shm / mqueue / timer (libc.so.6 on glibc 2.34+) ────────────────────────── +mq_close libc.so.6 +mq_open libc.so.6 +mq_receive libc.so.6 +mq_send libc.so.6 +mq_timedreceive libc.so.6 +mq_timedsend libc.so.6 +shm_open libc.so.6 +shm_unlink libc.so.6 +timer_create libc.so.6 +timer_delete libc.so.6 +timer_gettime libc.so.6 +timer_settime libc.so.6 + +# ── ctype ────────────────────────────────────────────────────────────────────── +isalnum libc.so.6 +isalpha libc.so.6 +isblank libc.so.6 +iscntrl libc.so.6 +isdigit libc.so.6 +isgraph libc.so.6 +islower libc.so.6 +isprint libc.so.6 +ispunct libc.so.6 +isspace libc.so.6 +isupper libc.so.6 +isxdigit libc.so.6 +tolower libc.so.6 +toupper libc.so.6 diff --git a/data/symlib_macos.txt b/data/symlib_macos.txt new file mode 100644 index 0000000..6b068ce --- /dev/null +++ b/data/symlib_macos.txt @@ -0,0 +1,359 @@ +# macOS symbol → import dylib table. +# Format: +# Keep sorted alphabetically by symbol (first field). +# On macOS nearly everything is in libSystem.B.dylib (which re-exports +# libsystem_c, libsystem_pthread, libsystem_m, libdyld, etc.). + +# ── libSystem.B.dylib — essentially everything ───────────────────────────────── +CFArrayCreate /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +CFArrayGetCount /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +CFArrayGetValueAtIndex /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +CFDataCreate /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +CFRelease /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +CFRetain /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +CFStringCreateWithCString /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +CFStringGetCString /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +CFStringGetLength /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation +__assert_rtn /usr/lib/libSystem.B.dylib +__cxa_atexit /usr/lib/libSystem.B.dylib +__cxa_finalize /usr/lib/libSystem.B.dylib +__cxa_pure_virtual /usr/lib/libSystem.B.dylib +__cxa_throw /usr/lib/libSystem.B.dylib +__stack_chk_fail /usr/lib/libSystem.B.dylib +_exit /usr/lib/libSystem.B.dylib +abort /usr/lib/libSystem.B.dylib +abs /usr/lib/libSystem.B.dylib +accept /usr/lib/libSystem.B.dylib +acos /usr/lib/libSystem.B.dylib +acosf /usr/lib/libSystem.B.dylib +acosh /usr/lib/libSystem.B.dylib +acoshf /usr/lib/libSystem.B.dylib +aligned_alloc /usr/lib/libSystem.B.dylib +asin /usr/lib/libSystem.B.dylib +asinf /usr/lib/libSystem.B.dylib +asinh /usr/lib/libSystem.B.dylib +asinhf /usr/lib/libSystem.B.dylib +asprintf /usr/lib/libSystem.B.dylib +atan /usr/lib/libSystem.B.dylib +atan2 /usr/lib/libSystem.B.dylib +atan2f /usr/lib/libSystem.B.dylib +atanf /usr/lib/libSystem.B.dylib +atanh /usr/lib/libSystem.B.dylib +atanhf /usr/lib/libSystem.B.dylib +atof /usr/lib/libSystem.B.dylib +atoi /usr/lib/libSystem.B.dylib +atol /usr/lib/libSystem.B.dylib +atoll /usr/lib/libSystem.B.dylib +bind /usr/lib/libSystem.B.dylib +bsearch /usr/lib/libSystem.B.dylib +calloc /usr/lib/libSystem.B.dylib +cbrt /usr/lib/libSystem.B.dylib +cbrtf /usr/lib/libSystem.B.dylib +ceil /usr/lib/libSystem.B.dylib +ceilf /usr/lib/libSystem.B.dylib +chdir /usr/lib/libSystem.B.dylib +chmod /usr/lib/libSystem.B.dylib +chown /usr/lib/libSystem.B.dylib +clearerr /usr/lib/libSystem.B.dylib +clock /usr/lib/libSystem.B.dylib +clock_getres /usr/lib/libSystem.B.dylib +clock_gettime /usr/lib/libSystem.B.dylib +close /usr/lib/libSystem.B.dylib +closedir /usr/lib/libSystem.B.dylib +connect /usr/lib/libSystem.B.dylib +copysign /usr/lib/libSystem.B.dylib +copysignf /usr/lib/libSystem.B.dylib +cos /usr/lib/libSystem.B.dylib +cosf /usr/lib/libSystem.B.dylib +cosh /usr/lib/libSystem.B.dylib +coshf /usr/lib/libSystem.B.dylib +div /usr/lib/libSystem.B.dylib +dladdr /usr/lib/libSystem.B.dylib +dlclose /usr/lib/libSystem.B.dylib +dlerror /usr/lib/libSystem.B.dylib +dlopen /usr/lib/libSystem.B.dylib +dlsym /usr/lib/libSystem.B.dylib +dup /usr/lib/libSystem.B.dylib +dup2 /usr/lib/libSystem.B.dylib +exit /usr/lib/libSystem.B.dylib +exp /usr/lib/libSystem.B.dylib +exp2 /usr/lib/libSystem.B.dylib +exp2f /usr/lib/libSystem.B.dylib +expf /usr/lib/libSystem.B.dylib +expm1 /usr/lib/libSystem.B.dylib +expm1f /usr/lib/libSystem.B.dylib +fabs /usr/lib/libSystem.B.dylib +fabsf /usr/lib/libSystem.B.dylib +fchdir /usr/lib/libSystem.B.dylib +fchmod /usr/lib/libSystem.B.dylib +fclose /usr/lib/libSystem.B.dylib +fcntl /usr/lib/libSystem.B.dylib +fdatasync /usr/lib/libSystem.B.dylib +fdopen /usr/lib/libSystem.B.dylib +feof /usr/lib/libSystem.B.dylib +ferror /usr/lib/libSystem.B.dylib +fflush /usr/lib/libSystem.B.dylib +fgetc /usr/lib/libSystem.B.dylib +fgets /usr/lib/libSystem.B.dylib +fileno /usr/lib/libSystem.B.dylib +floor /usr/lib/libSystem.B.dylib +floorf /usr/lib/libSystem.B.dylib +fma /usr/lib/libSystem.B.dylib +fmaf /usr/lib/libSystem.B.dylib +fmax /usr/lib/libSystem.B.dylib +fmaxf /usr/lib/libSystem.B.dylib +fmin /usr/lib/libSystem.B.dylib +fminf /usr/lib/libSystem.B.dylib +fmod /usr/lib/libSystem.B.dylib +fmodf /usr/lib/libSystem.B.dylib +fopen /usr/lib/libSystem.B.dylib +fork /usr/lib/libSystem.B.dylib +fprintf /usr/lib/libSystem.B.dylib +fputs /usr/lib/libSystem.B.dylib +fread /usr/lib/libSystem.B.dylib +free /usr/lib/libSystem.B.dylib +freeaddrinfo /usr/lib/libSystem.B.dylib +freopen /usr/lib/libSystem.B.dylib +frexp /usr/lib/libSystem.B.dylib +frexpf /usr/lib/libSystem.B.dylib +fseek /usr/lib/libSystem.B.dylib +fstat /usr/lib/libSystem.B.dylib +fsync /usr/lib/libSystem.B.dylib +ftruncate /usr/lib/libSystem.B.dylib +fwrite /usr/lib/libSystem.B.dylib +getaddrinfo /usr/lib/libSystem.B.dylib +getc /usr/lib/libSystem.B.dylib +getchar /usr/lib/libSystem.B.dylib +getcwd /usr/lib/libSystem.B.dylib +getenv /usr/lib/libSystem.B.dylib +getgid /usr/lib/libSystem.B.dylib +gethostbyname /usr/lib/libSystem.B.dylib +gethostname /usr/lib/libSystem.B.dylib +getnameinfo /usr/lib/libSystem.B.dylib +getpeername /usr/lib/libSystem.B.dylib +getpid /usr/lib/libSystem.B.dylib +getppid /usr/lib/libSystem.B.dylib +getsockname /usr/lib/libSystem.B.dylib +getsockopt /usr/lib/libSystem.B.dylib +gettimeofday /usr/lib/libSystem.B.dylib +getuid /usr/lib/libSystem.B.dylib +gmtime /usr/lib/libSystem.B.dylib +gmtime_r /usr/lib/libSystem.B.dylib +htonl /usr/lib/libSystem.B.dylib +htons /usr/lib/libSystem.B.dylib +hypot /usr/lib/libSystem.B.dylib +hypotf /usr/lib/libSystem.B.dylib +inet_addr /usr/lib/libSystem.B.dylib +inet_ntoa /usr/lib/libSystem.B.dylib +inet_ntop /usr/lib/libSystem.B.dylib +inet_pton /usr/lib/libSystem.B.dylib +ioctl /usr/lib/libSystem.B.dylib +isalnum /usr/lib/libSystem.B.dylib +isalpha /usr/lib/libSystem.B.dylib +isblank /usr/lib/libSystem.B.dylib +iscntrl /usr/lib/libSystem.B.dylib +isdigit /usr/lib/libSystem.B.dylib +isgraph /usr/lib/libSystem.B.dylib +islower /usr/lib/libSystem.B.dylib +isprint /usr/lib/libSystem.B.dylib +ispunct /usr/lib/libSystem.B.dylib +isspace /usr/lib/libSystem.B.dylib +isupper /usr/lib/libSystem.B.dylib +isxdigit /usr/lib/libSystem.B.dylib +kill /usr/lib/libSystem.B.dylib +labs /usr/lib/libSystem.B.dylib +ldexp /usr/lib/libSystem.B.dylib +ldexpf /usr/lib/libSystem.B.dylib +ldiv /usr/lib/libSystem.B.dylib +lgamma /usr/lib/libSystem.B.dylib +lgammaf /usr/lib/libSystem.B.dylib +link /usr/lib/libSystem.B.dylib +listen /usr/lib/libSystem.B.dylib +llabs /usr/lib/libSystem.B.dylib +lldiv /usr/lib/libSystem.B.dylib +localtime /usr/lib/libSystem.B.dylib +localtime_r /usr/lib/libSystem.B.dylib +log /usr/lib/libSystem.B.dylib +log10 /usr/lib/libSystem.B.dylib +log10f /usr/lib/libSystem.B.dylib +log2 /usr/lib/libSystem.B.dylib +log2f /usr/lib/libSystem.B.dylib +logf /usr/lib/libSystem.B.dylib +lseek /usr/lib/libSystem.B.dylib +lstat /usr/lib/libSystem.B.dylib +malloc /usr/lib/libSystem.B.dylib +memchr /usr/lib/libSystem.B.dylib +memcmp /usr/lib/libSystem.B.dylib +memcpy /usr/lib/libSystem.B.dylib +memmove /usr/lib/libSystem.B.dylib +memset /usr/lib/libSystem.B.dylib +mkdir /usr/lib/libSystem.B.dylib +mkdtemp /usr/lib/libSystem.B.dylib +mkstemp /usr/lib/libSystem.B.dylib +mktime /usr/lib/libSystem.B.dylib +mmap /usr/lib/libSystem.B.dylib +modf /usr/lib/libSystem.B.dylib +modff /usr/lib/libSystem.B.dylib +mprotect /usr/lib/libSystem.B.dylib +munmap /usr/lib/libSystem.B.dylib +nanosleep /usr/lib/libSystem.B.dylib +nan /usr/lib/libSystem.B.dylib +nanf /usr/lib/libSystem.B.dylib +nearbyint /usr/lib/libSystem.B.dylib +nearbyintf /usr/lib/libSystem.B.dylib +nextafter /usr/lib/libSystem.B.dylib +nextafterf /usr/lib/libSystem.B.dylib +ntohl /usr/lib/libSystem.B.dylib +ntohs /usr/lib/libSystem.B.dylib +open /usr/lib/libSystem.B.dylib +opendir /usr/lib/libSystem.B.dylib +perror /usr/lib/libSystem.B.dylib +pipe /usr/lib/libSystem.B.dylib +poll /usr/lib/libSystem.B.dylib +posix_memalign /usr/lib/libSystem.B.dylib +pow /usr/lib/libSystem.B.dylib +powf /usr/lib/libSystem.B.dylib +printf /usr/lib/libSystem.B.dylib +pthread_attr_destroy /usr/lib/libSystem.B.dylib +pthread_attr_init /usr/lib/libSystem.B.dylib +pthread_attr_setdetachstate /usr/lib/libSystem.B.dylib +pthread_attr_setstacksize /usr/lib/libSystem.B.dylib +pthread_barrier_destroy /usr/lib/libSystem.B.dylib +pthread_barrier_init /usr/lib/libSystem.B.dylib +pthread_barrier_wait /usr/lib/libSystem.B.dylib +pthread_cancel /usr/lib/libSystem.B.dylib +pthread_cond_broadcast /usr/lib/libSystem.B.dylib +pthread_cond_destroy /usr/lib/libSystem.B.dylib +pthread_cond_init /usr/lib/libSystem.B.dylib +pthread_cond_signal /usr/lib/libSystem.B.dylib +pthread_cond_timedwait /usr/lib/libSystem.B.dylib +pthread_cond_wait /usr/lib/libSystem.B.dylib +pthread_create /usr/lib/libSystem.B.dylib +pthread_detach /usr/lib/libSystem.B.dylib +pthread_exit /usr/lib/libSystem.B.dylib +pthread_getspecific /usr/lib/libSystem.B.dylib +pthread_join /usr/lib/libSystem.B.dylib +pthread_key_create /usr/lib/libSystem.B.dylib +pthread_key_delete /usr/lib/libSystem.B.dylib +pthread_mutex_destroy /usr/lib/libSystem.B.dylib +pthread_mutex_init /usr/lib/libSystem.B.dylib +pthread_mutex_lock /usr/lib/libSystem.B.dylib +pthread_mutex_trylock /usr/lib/libSystem.B.dylib +pthread_mutex_unlock /usr/lib/libSystem.B.dylib +pthread_once /usr/lib/libSystem.B.dylib +pthread_rwlock_destroy /usr/lib/libSystem.B.dylib +pthread_rwlock_init /usr/lib/libSystem.B.dylib +pthread_rwlock_rdlock /usr/lib/libSystem.B.dylib +pthread_rwlock_unlock /usr/lib/libSystem.B.dylib +pthread_rwlock_wrlock /usr/lib/libSystem.B.dylib +pthread_self /usr/lib/libSystem.B.dylib +pthread_setspecific /usr/lib/libSystem.B.dylib +pthread_sigmask /usr/lib/libSystem.B.dylib +putchar /usr/lib/libSystem.B.dylib +puts /usr/lib/libSystem.B.dylib +qsort /usr/lib/libSystem.B.dylib +raise /usr/lib/libSystem.B.dylib +rand /usr/lib/libSystem.B.dylib +read /usr/lib/libSystem.B.dylib +readdir /usr/lib/libSystem.B.dylib +readlink /usr/lib/libSystem.B.dylib +realloc /usr/lib/libSystem.B.dylib +recv /usr/lib/libSystem.B.dylib +recvfrom /usr/lib/libSystem.B.dylib +remainder /usr/lib/libSystem.B.dylib +remainderf /usr/lib/libSystem.B.dylib +rename /usr/lib/libSystem.B.dylib +rint /usr/lib/libSystem.B.dylib +rintf /usr/lib/libSystem.B.dylib +rmdir /usr/lib/libSystem.B.dylib +round /usr/lib/libSystem.B.dylib +roundf /usr/lib/libSystem.B.dylib +scalbn /usr/lib/libSystem.B.dylib +scalbnf /usr/lib/libSystem.B.dylib +select /usr/lib/libSystem.B.dylib +sem_close /usr/lib/libSystem.B.dylib +sem_destroy /usr/lib/libSystem.B.dylib +sem_init /usr/lib/libSystem.B.dylib +sem_open /usr/lib/libSystem.B.dylib +sem_post /usr/lib/libSystem.B.dylib +sem_timedwait /usr/lib/libSystem.B.dylib +sem_trywait /usr/lib/libSystem.B.dylib +sem_unlink /usr/lib/libSystem.B.dylib +sem_wait /usr/lib/libSystem.B.dylib +send /usr/lib/libSystem.B.dylib +sendto /usr/lib/libSystem.B.dylib +setenv /usr/lib/libSystem.B.dylib +setsockopt /usr/lib/libSystem.B.dylib +shutdown /usr/lib/libSystem.B.dylib +sigaction /usr/lib/libSystem.B.dylib +sigemptyset /usr/lib/libSystem.B.dylib +sigfillset /usr/lib/libSystem.B.dylib +signal /usr/lib/libSystem.B.dylib +sin /usr/lib/libSystem.B.dylib +sinf /usr/lib/libSystem.B.dylib +sinh /usr/lib/libSystem.B.dylib +sinhf /usr/lib/libSystem.B.dylib +sleep /usr/lib/libSystem.B.dylib +snprintf /usr/lib/libSystem.B.dylib +socket /usr/lib/libSystem.B.dylib +socketpair /usr/lib/libSystem.B.dylib +sprintf /usr/lib/libSystem.B.dylib +sqrt /usr/lib/libSystem.B.dylib +sqrtf /usr/lib/libSystem.B.dylib +srand /usr/lib/libSystem.B.dylib +sscanf /usr/lib/libSystem.B.dylib +stat /usr/lib/libSystem.B.dylib +strcat /usr/lib/libSystem.B.dylib +strchr /usr/lib/libSystem.B.dylib +strcmp /usr/lib/libSystem.B.dylib +strcpy /usr/lib/libSystem.B.dylib +strcspn /usr/lib/libSystem.B.dylib +strdup /usr/lib/libSystem.B.dylib +strerror /usr/lib/libSystem.B.dylib +strftime /usr/lib/libSystem.B.dylib +strlen /usr/lib/libSystem.B.dylib +strncat /usr/lib/libSystem.B.dylib +strncmp /usr/lib/libSystem.B.dylib +strncpy /usr/lib/libSystem.B.dylib +strndup /usr/lib/libSystem.B.dylib +strnlen /usr/lib/libSystem.B.dylib +strpbrk /usr/lib/libSystem.B.dylib +strrchr /usr/lib/libSystem.B.dylib +strspn /usr/lib/libSystem.B.dylib +strstr /usr/lib/libSystem.B.dylib +strtod /usr/lib/libSystem.B.dylib +strtof /usr/lib/libSystem.B.dylib +strtok /usr/lib/libSystem.B.dylib +strtok_r /usr/lib/libSystem.B.dylib +strtol /usr/lib/libSystem.B.dylib +strtoll /usr/lib/libSystem.B.dylib +strtoul /usr/lib/libSystem.B.dylib +strtoull /usr/lib/libSystem.B.dylib +symlink /usr/lib/libSystem.B.dylib +sysconf /usr/lib/libSystem.B.dylib +tan /usr/lib/libSystem.B.dylib +tanf /usr/lib/libSystem.B.dylib +tanh /usr/lib/libSystem.B.dylib +tanhf /usr/lib/libSystem.B.dylib +tgamma /usr/lib/libSystem.B.dylib +tgammaf /usr/lib/libSystem.B.dylib +time /usr/lib/libSystem.B.dylib +tolower /usr/lib/libSystem.B.dylib +toupper /usr/lib/libSystem.B.dylib +truncate /usr/lib/libSystem.B.dylib +trunc /usr/lib/libSystem.B.dylib +truncf /usr/lib/libSystem.B.dylib +umask /usr/lib/libSystem.B.dylib +uname /usr/lib/libSystem.B.dylib +unlink /usr/lib/libSystem.B.dylib +unsetenv /usr/lib/libSystem.B.dylib +usleep /usr/lib/libSystem.B.dylib +vasprintf /usr/lib/libSystem.B.dylib +vfprintf /usr/lib/libSystem.B.dylib +vprintf /usr/lib/libSystem.B.dylib +vsnprintf /usr/lib/libSystem.B.dylib +vsprintf /usr/lib/libSystem.B.dylib +wait /usr/lib/libSystem.B.dylib +waitpid /usr/lib/libSystem.B.dylib +wcslen /usr/lib/libSystem.B.dylib +write /usr/lib/libSystem.B.dylib diff --git a/data/symlib_windows.txt b/data/symlib_windows.txt new file mode 100644 index 0000000..24bf6a2 --- /dev/null +++ b/data/symlib_windows.txt @@ -0,0 +1,458 @@ +# Windows symbol → import DLL table. +# Format: +# Canonical DLL names are ALL-CAPS as Windows resolves them case-insensitively. +# Keep sorted alphabetically by symbol (first field). + +# ── UCRT (ucrtbase.dll) — standard C library ─────────────────────────────────── +_access ucrtbase.dll +_chdir ucrtbase.dll +_close ucrtbase.dll +_dup ucrtbase.dll +_dup2 ucrtbase.dll +_exit ucrtbase.dll +_fileno ucrtbase.dll +_fstat64 ucrtbase.dll +_getcwd ucrtbase.dll +_getpid ucrtbase.dll +_isnan ucrtbase.dll +_lseeki64 ucrtbase.dll +_mkdir ucrtbase.dll +_mktemp ucrtbase.dll +_open ucrtbase.dll +_pclose ucrtbase.dll +_popen ucrtbase.dll +_read ucrtbase.dll +_rmdir ucrtbase.dll +_stat64 ucrtbase.dll +_strdup ucrtbase.dll +_stricmp ucrtbase.dll +_strnicmp ucrtbase.dll +_write ucrtbase.dll +abort ucrtbase.dll +abs ucrtbase.dll +acos ucrtbase.dll +acosf ucrtbase.dll +aligned_free ucrtbase.dll +aligned_malloc ucrtbase.dll +asin ucrtbase.dll +asinf ucrtbase.dll +atan ucrtbase.dll +atan2 ucrtbase.dll +atan2f ucrtbase.dll +atanf ucrtbase.dll +atof ucrtbase.dll +atoi ucrtbase.dll +atol ucrtbase.dll +atoll ucrtbase.dll +bsearch ucrtbase.dll +bsearch_s ucrtbase.dll +calloc ucrtbase.dll +cbrt ucrtbase.dll +cbrtf ucrtbase.dll +ceil ucrtbase.dll +ceilf ucrtbase.dll +clearerr ucrtbase.dll +cos ucrtbase.dll +cosf ucrtbase.dll +cosh ucrtbase.dll +coshf ucrtbase.dll +div ucrtbase.dll +exit ucrtbase.dll +exp ucrtbase.dll +exp2 ucrtbase.dll +exp2f ucrtbase.dll +expf ucrtbase.dll +fabs ucrtbase.dll +fabsf ucrtbase.dll +fclose ucrtbase.dll +fdim ucrtbase.dll +feof ucrtbase.dll +ferror ucrtbase.dll +fflush ucrtbase.dll +fgetc ucrtbase.dll +fgetpos ucrtbase.dll +fgets ucrtbase.dll +floor ucrtbase.dll +floorf ucrtbase.dll +fma ucrtbase.dll +fmax ucrtbase.dll +fmin ucrtbase.dll +fmod ucrtbase.dll +fmodf ucrtbase.dll +fopen ucrtbase.dll +fprintf ucrtbase.dll +fputc ucrtbase.dll +fputs ucrtbase.dll +fread ucrtbase.dll +free ucrtbase.dll +freopen ucrtbase.dll +fscanf ucrtbase.dll +fseek ucrtbase.dll +fsetpos ucrtbase.dll +ftell ucrtbase.dll +fwrite ucrtbase.dll +getc ucrtbase.dll +getchar ucrtbase.dll +getenv ucrtbase.dll +hypot ucrtbase.dll +hypotf ucrtbase.dll +isalnum ucrtbase.dll +isalpha ucrtbase.dll +isblank ucrtbase.dll +iscntrl ucrtbase.dll +isdigit ucrtbase.dll +isgraph ucrtbase.dll +islower ucrtbase.dll +isprint ucrtbase.dll +ispunct ucrtbase.dll +isspace ucrtbase.dll +isupper ucrtbase.dll +isxdigit ucrtbase.dll +labs ucrtbase.dll +ldiv ucrtbase.dll +ldexp ucrtbase.dll +llabs ucrtbase.dll +lldiv ucrtbase.dll +log ucrtbase.dll +log10 ucrtbase.dll +log10f ucrtbase.dll +log2 ucrtbase.dll +log2f ucrtbase.dll +logf ucrtbase.dll +malloc ucrtbase.dll +memchr ucrtbase.dll +memcmp ucrtbase.dll +memcpy ucrtbase.dll +memmove ucrtbase.dll +memset ucrtbase.dll +modf ucrtbase.dll +modff ucrtbase.dll +nearbyint ucrtbase.dll +nearbyintf ucrtbase.dll +perror ucrtbase.dll +pow ucrtbase.dll +powf ucrtbase.dll +printf ucrtbase.dll +putc ucrtbase.dll +putchar ucrtbase.dll +puts ucrtbase.dll +qsort ucrtbase.dll +qsort_s ucrtbase.dll +rand ucrtbase.dll +realloc ucrtbase.dll +remainder ucrtbase.dll +rewind ucrtbase.dll +rint ucrtbase.dll +rintf ucrtbase.dll +round ucrtbase.dll +roundf ucrtbase.dll +scanf ucrtbase.dll +setenv ucrtbase.dll +sin ucrtbase.dll +sinf ucrtbase.dll +sinh ucrtbase.dll +sinhf ucrtbase.dll +snprintf ucrtbase.dll +sprintf ucrtbase.dll +sqrt ucrtbase.dll +sqrtf ucrtbase.dll +srand ucrtbase.dll +sscanf ucrtbase.dll +strcat ucrtbase.dll +strchr ucrtbase.dll +strcmp ucrtbase.dll +strcpy ucrtbase.dll +strcspn ucrtbase.dll +strerror ucrtbase.dll +strlen ucrtbase.dll +strncat ucrtbase.dll +strncmp ucrtbase.dll +strncpy ucrtbase.dll +strnlen ucrtbase.dll +strpbrk ucrtbase.dll +strrchr ucrtbase.dll +strspn ucrtbase.dll +strstr ucrtbase.dll +strtod ucrtbase.dll +strtof ucrtbase.dll +strtok ucrtbase.dll +strtok_s ucrtbase.dll +strtol ucrtbase.dll +strtoll ucrtbase.dll +strtoul ucrtbase.dll +strtoull ucrtbase.dll +tan ucrtbase.dll +tanf ucrtbase.dll +tanh ucrtbase.dll +tanhf ucrtbase.dll +time ucrtbase.dll +tmpfile ucrtbase.dll +tmpnam ucrtbase.dll +tolower ucrtbase.dll +toupper ucrtbase.dll +trunc ucrtbase.dll +truncf ucrtbase.dll +ungetc ucrtbase.dll +vfprintf ucrtbase.dll +vprintf ucrtbase.dll +vsnprintf ucrtbase.dll +vsprintf ucrtbase.dll +wcscat ucrtbase.dll +wcscmp ucrtbase.dll +wcscpy ucrtbase.dll +wcslen ucrtbase.dll + +# ── KERNEL32.DLL — core Win32 ────────────────────────────────────────────────── +CloseHandle KERNEL32.DLL +CreateDirectoryA KERNEL32.DLL +CreateDirectoryW KERNEL32.DLL +CreateEventA KERNEL32.DLL +CreateEventW KERNEL32.DLL +CreateFileA KERNEL32.DLL +CreateFileW KERNEL32.DLL +CreateMutexA KERNEL32.DLL +CreateMutexW KERNEL32.DLL +CreateProcessA KERNEL32.DLL +CreateProcessW KERNEL32.DLL +CreateSemaphoreA KERNEL32.DLL +CreateSemaphoreW KERNEL32.DLL +CreateThread KERNEL32.DLL +DeleteCriticalSection KERNEL32.DLL +DeleteFileA KERNEL32.DLL +DeleteFileW KERNEL32.DLL +DeviceIoControl KERNEL32.DLL +EnterCriticalSection KERNEL32.DLL +ExitProcess KERNEL32.DLL +ExitThread KERNEL32.DLL +FindClose KERNEL32.DLL +FindFirstFileA KERNEL32.DLL +FindFirstFileW KERNEL32.DLL +FindNextFileA KERNEL32.DLL +FindNextFileW KERNEL32.DLL +FlushFileBuffers KERNEL32.DLL +FormatMessageA KERNEL32.DLL +FormatMessageW KERNEL32.DLL +FreeLibrary KERNEL32.DLL +GetCommandLineA KERNEL32.DLL +GetCommandLineW KERNEL32.DLL +GetConsoleMode KERNEL32.DLL +GetCurrentDirectoryA KERNEL32.DLL +GetCurrentDirectoryW KERNEL32.DLL +GetCurrentProcess KERNEL32.DLL +GetCurrentProcessId KERNEL32.DLL +GetCurrentThread KERNEL32.DLL +GetCurrentThreadId KERNEL32.DLL +GetEnvironmentVariableA KERNEL32.DLL +GetEnvironmentVariableW KERNEL32.DLL +GetFileAttributesA KERNEL32.DLL +GetFileAttributesW KERNEL32.DLL +GetFileSizeEx KERNEL32.DLL +GetFileType KERNEL32.DLL +GetLastError KERNEL32.DLL +GetModuleFileNameA KERNEL32.DLL +GetModuleFileNameW KERNEL32.DLL +GetModuleHandleA KERNEL32.DLL +GetModuleHandleW KERNEL32.DLL +GetProcAddress KERNEL32.DLL +GetProcessHeap KERNEL32.DLL +GetStdHandle KERNEL32.DLL +GetSystemInfo KERNEL32.DLL +GetSystemTime KERNEL32.DLL +GetSystemTimeAsFileTime KERNEL32.DLL +GetTempPathA KERNEL32.DLL +GetTempPathW KERNEL32.DLL +GetThreadContext KERNEL32.DLL +GetTickCount KERNEL32.DLL +GetTickCount64 KERNEL32.DLL +GlobalAlloc KERNEL32.DLL +GlobalFree KERNEL32.DLL +HeapAlloc KERNEL32.DLL +HeapCreate KERNEL32.DLL +HeapDestroy KERNEL32.DLL +HeapFree KERNEL32.DLL +HeapReAlloc KERNEL32.DLL +HeapSize KERNEL32.DLL +InitializeCriticalSection KERNEL32.DLL +InitializeCriticalSectionAndSpinCount KERNEL32.DLL +InitializeConditionVariable KERNEL32.DLL +LeaveCriticalSection KERNEL32.DLL +LoadLibraryA KERNEL32.DLL +LoadLibraryW KERNEL32.DLL +LoadLibraryExA KERNEL32.DLL +LoadLibraryExW KERNEL32.DLL +LocalAlloc KERNEL32.DLL +LocalFree KERNEL32.DLL +MapViewOfFile KERNEL32.DLL +MapViewOfFileEx KERNEL32.DLL +MoveFileA KERNEL32.DLL +MoveFileW KERNEL32.DLL +MoveFileExA KERNEL32.DLL +MoveFileExW KERNEL32.DLL +MultiByteToWideChar KERNEL32.DLL +OpenEventA KERNEL32.DLL +OpenEventW KERNEL32.DLL +OpenFileMappingA KERNEL32.DLL +OpenFileMappingW KERNEL32.DLL +OpenMutexA KERNEL32.DLL +OpenMutexW KERNEL32.DLL +OpenProcess KERNEL32.DLL +OpenSemaphoreA KERNEL32.DLL +OpenSemaphoreW KERNEL32.DLL +OpenThread KERNEL32.DLL +QueryPerformanceCounter KERNEL32.DLL +QueryPerformanceFrequency KERNEL32.DLL +ReadFile KERNEL32.DLL +ReleaseMutex KERNEL32.DLL +ReleaseSemaphore KERNEL32.DLL +RemoveDirectoryA KERNEL32.DLL +RemoveDirectoryW KERNEL32.DLL +ResetEvent KERNEL32.DLL +ResumeThread KERNEL32.DLL +SetCurrentDirectoryA KERNEL32.DLL +SetCurrentDirectoryW KERNEL32.DLL +SetEndOfFile KERNEL32.DLL +SetEnvironmentVariableA KERNEL32.DLL +SetEnvironmentVariableW KERNEL32.DLL +SetEvent KERNEL32.DLL +SetFileAttributesA KERNEL32.DLL +SetFileAttributesW KERNEL32.DLL +SetFilePointerEx KERNEL32.DLL +SetLastError KERNEL32.DLL +SetThreadPriority KERNEL32.DLL +SetUnhandledExceptionFilter KERNEL32.DLL +Sleep KERNEL32.DLL +SleepConditionVariableCS KERNEL32.DLL +SleepEx KERNEL32.DLL +SuspendThread KERNEL32.DLL +TerminateProcess KERNEL32.DLL +TerminateThread KERNEL32.DLL +TlsAlloc KERNEL32.DLL +TlsFree KERNEL32.DLL +TlsGetValue KERNEL32.DLL +TlsSetValue KERNEL32.DLL +TryEnterCriticalSection KERNEL32.DLL +UnmapViewOfFile KERNEL32.DLL +VirtualAlloc KERNEL32.DLL +VirtualAllocEx KERNEL32.DLL +VirtualFree KERNEL32.DLL +VirtualFreeEx KERNEL32.DLL +VirtualProtect KERNEL32.DLL +VirtualProtectEx KERNEL32.DLL +VirtualQuery KERNEL32.DLL +WaitForMultipleObjects KERNEL32.DLL +WaitForMultipleObjectsEx KERNEL32.DLL +WaitForSingleObject KERNEL32.DLL +WaitForSingleObjectEx KERNEL32.DLL +WakeAllConditionVariable KERNEL32.DLL +WakeConditionVariable KERNEL32.DLL +WideCharToMultiByte KERNEL32.DLL +WriteFile KERNEL32.DLL +WriteProcessMemory KERNEL32.DLL + +# ── USER32.DLL — GUI ─────────────────────────────────────────────────────────── +CreateWindowExA USER32.DLL +CreateWindowExW USER32.DLL +DefWindowProcA USER32.DLL +DefWindowProcW USER32.DLL +DestroyWindow USER32.DLL +DispatchMessageA USER32.DLL +DispatchMessageW USER32.DLL +GetClientRect USER32.DLL +GetMessageA USER32.DLL +GetMessageW USER32.DLL +InvalidateRect USER32.DLL +LoadCursorA USER32.DLL +LoadCursorW USER32.DLL +MessageBoxA USER32.DLL +MessageBoxW USER32.DLL +PeekMessageA USER32.DLL +PeekMessageW USER32.DLL +PostMessageA USER32.DLL +PostMessageW USER32.DLL +PostQuitMessage USER32.DLL +RegisterClassA USER32.DLL +RegisterClassExA USER32.DLL +RegisterClassExW USER32.DLL +RegisterClassW USER32.DLL +SendMessageA USER32.DLL +SendMessageW USER32.DLL +SetWindowPos USER32.DLL +SetWindowTextA USER32.DLL +SetWindowTextW USER32.DLL +ShowWindow USER32.DLL +TranslateMessage USER32.DLL +UpdateWindow USER32.DLL + +# ── ADVAPI32.DLL — registry / security ──────────────────────────────────────── +AdjustTokenPrivileges ADVAPI32.DLL +ConvertSidToStringSidA ADVAPI32.DLL +ConvertSidToStringSidW ADVAPI32.DLL +ConvertStringSidToSidA ADVAPI32.DLL +ConvertStringSidToSidW ADVAPI32.DLL +GetTokenInformation ADVAPI32.DLL +GetUserNameA ADVAPI32.DLL +GetUserNameW ADVAPI32.DLL +InitializeSecurityDescriptor ADVAPI32.DLL +LookupAccountNameA ADVAPI32.DLL +LookupAccountNameW ADVAPI32.DLL +LookupPrivilegeValueA ADVAPI32.DLL +LookupPrivilegeValueW ADVAPI32.DLL +OpenProcessToken ADVAPI32.DLL +OpenThreadToken ADVAPI32.DLL +RegCloseKey ADVAPI32.DLL +RegCreateKeyExA ADVAPI32.DLL +RegCreateKeyExW ADVAPI32.DLL +RegDeleteKeyA ADVAPI32.DLL +RegDeleteKeyW ADVAPI32.DLL +RegDeleteValueA ADVAPI32.DLL +RegDeleteValueW ADVAPI32.DLL +RegEnumKeyExA ADVAPI32.DLL +RegEnumKeyExW ADVAPI32.DLL +RegEnumValueA ADVAPI32.DLL +RegEnumValueW ADVAPI32.DLL +RegOpenKeyExA ADVAPI32.DLL +RegOpenKeyExW ADVAPI32.DLL +RegQueryValueExA ADVAPI32.DLL +RegQueryValueExW ADVAPI32.DLL +RegSetValueExA ADVAPI32.DLL +RegSetValueExW ADVAPI32.DLL + +# ── WS2_32.DLL — Winsock ────────────────────────────────────────────────────── +WSACleanup WS2_32.DLL +WSACloseEvent WS2_32.DLL +WSACreateEvent WS2_32.DLL +WSAGetLastError WS2_32.DLL +WSAPoll WS2_32.DLL +WSARecv WS2_32.DLL +WSASend WS2_32.DLL +WSASetLastError WS2_32.DLL +WSAStartup WS2_32.DLL +accept WS2_32.DLL +bind WS2_32.DLL +closesocket WS2_32.DLL +connect WS2_32.DLL +freeaddrinfo WS2_32.DLL +getaddrinfo WS2_32.DLL +gethostbyname WS2_32.DLL +gethostname WS2_32.DLL +getnameinfo WS2_32.DLL +getpeername WS2_32.DLL +getsockname WS2_32.DLL +getsockopt WS2_32.DLL +htonl WS2_32.DLL +htons WS2_32.DLL +inet_addr WS2_32.DLL +inet_ntoa WS2_32.DLL +inet_ntop WS2_32.DLL +inet_pton WS2_32.DLL +listen WS2_32.DLL +ntohl WS2_32.DLL +ntohs WS2_32.DLL +recv WS2_32.DLL +recvfrom WS2_32.DLL +select WS2_32.DLL +send WS2_32.DLL +sendto WS2_32.DLL +setsockopt WS2_32.DLL +shutdown WS2_32.DLL +socket WS2_32.DLL diff --git a/docs/format.md b/docs/format.md new file mode 100644 index 0000000..e6b077f --- /dev/null +++ b/docs/format.md @@ -0,0 +1,204 @@ +# `.vlc` container format — v0.1 (draft) + +Status: **M1–M3 complete** (Linux ELF + Windows PE synthesis, fat-VLC fuse, dlopen interposition). macOS Mach-O synthesis in progress (M4). + +All integers are **little-endian**. All offsets are **byte offsets from the start of the file**. The on-disk layout is `#pragma pack(push, 1)` — no implicit padding. `format/vlc_format.hpp` is the source of truth; this document explains intent. + +--- + +## File extensions + +VoidLibC uses three file extensions based on the container's `ContainerFlags`: + +| Extension | Name | Flag | Description | +|-----------|------------------|----------------------------|-------------| +| `.vle` | Executable | `Executable` (0x04) | Has a defined entry point. Run via `voidloader` or binfmt. | +| `.vls` | Shared library | *(none of the below)* | Loadable at runtime via `dlopen()` (interposed by `libvoid.a`). | +| `.vla` | Static archive | `StaticLibrary` (0x10) | For build-time linking via `voidlink`. Not loadable at runtime. | + +`voidlink` automatically appends the correct extension when `-o` is specified without one. The extension is a convention for humans and file managers; tools identify VoidLibC files by the `VLC\0` magic bytes, not by extension. + +--- + +## `file(1)` integration + +A magic definition (`installer/linux/magic/vlc.magic`) is provided for the `file` command. After installation (the installer copies it to `/usr/share/file/magic/` and recompiles the database), `file` recognizes VoidLibC files: + +``` +$ file hello.vle +hello.vle: VoidLibC binary, v0.1, executable (.vle), x86_64 +$ file lib.vls +lib.vls: VoidLibC binary, v0.1, x86_64, dynamic imports +``` + +--- + +## Consumer API + +Consumers use standard ``. Linking against `VoidLibC::void` (a static archive) interposes `dlopen` so that any path whose first four bytes are `VLC\0` is handled by VoidLibC's synthesis path; all other paths fall through to the OS's real `dlopen`. + +```c +#include + +void* h = dlopen("mylib.vls", RTLD_NOW); // transparently loaded by libvoid.a +int (*fn)(int, int) = dlsym(h, "add"); +printf("%d\n", fn(1, 2)); +dlclose(h); +``` + +`dlsym`, `dlclose`, and `dlerror` are **not** interposed — the handle returned is a native OS handle, so the native implementations work directly. + +For executable containers (`.vle`), invoke via `voidloader`: + +```sh +voidloader hello.vle arg1 arg2 +# or, if binfmt_misc is registered on Linux: +./hello.vle arg1 arg2 +``` + +--- + +## Shipping a fat VLC (CMake integration) + +Link against `VoidLibC::void` and call `voidlibc_enable_auto_vlc()` at the end of your `CMakeLists.txt`. The DEFER hook cross-compiles your sources for Linux (musl), Windows (MinGW), and macOS, then fuses them into a single fat container automatically. + +```cmake +find_package(VoidLibC REQUIRED) + +add_library(mylib SHARED src.c) +target_link_libraries(mylib PRIVATE VoidLibC::void) +set_target_properties(mylib PROPERTIES EXCLUDE_FROM_ALL TRUE) + +# Optional: mark as executable (.vle) instead of library (.vls) +# voidlibc_vlc_executable(mylib main) + +# Optional: restrict to Linux only (e.g., when using extern global vars) +# set_target_properties(mylib PROPERTIES VOIDLIBC_VLC_PLATFORMS "linux") + +voidlibc_enable_auto_vlc() # call once per CMakeLists.txt +``` + +After `cmake --build`, `/mylib.vls` is a fat container with Linux + Windows + macOS sections. Requires `zig` on `PATH` (preferred) or `clang` with cross-compilation support. + +--- + +## File outline + +``` ++-------------------------------+ 0 +| FileHeader | fixed 84 bytes ++-------------------------------+ section_dir_off +| SectionEntry[section_count] | 64 bytes each ++-------------------------------+ +| SymbolTableHeader | +| SymbolEntry[...] | 36 bytes each +| name pool (UTF-8) | ++-------------------------------+ +| RelocChunk + RelocEntry[] | see reloc-ir.md ++-------------------------------+ +| raw machine code (PIC) | ++-------------------------------+ +| DWARF / PDB / DWARF blob | ++-------------------------------+ +| ImportsHeader + ... | (M1) ++-------------------------------+ +| ExportsHeader + ... | (M1) ++-------------------------------+ file_size +``` + +The directory + tables describe *where* things are; producers can lay regions out in any order as long as offsets are consistent and `file_size` matches the on-disk total. + +--- + +## FileHeader (84 bytes) + +| Field | Type | Notes | +|-------------------|----------|-------| +| `magic` | `u32` | `0x00434C56` = bytes `V L C \0`. Reject anything else. | +| `version_major` | `u16` | Breaking changes bump this. Readers must reject unknown majors. | +| `version_minor` | `u16` | Additive changes bump this. Readers may accept higher minors of a known major. | +| `flags` | `u32` | Bitfield. See `ContainerFlags` in the header. | +| `arch` | `u16` | `1` = x86_64. MVP rejects everything else. | +| `reserved` | `u16` | Must be `0`. | +| `section_count` | `u32` | Number of `SectionEntry`s following `section_dir_off`. | +| `section_dir_off` | `u64` | Byte offset of the section directory. | +| `symtab_off` | `u64` | Byte offset of `SymbolTableHeader`. | +| `symtab_size` | `u64` | Total bytes of the symbol-table region (header + entries + name pool). | +| `imports_off` | `u64` | (M1) | +| `imports_size` | `u64` | (M1) | +| `exports_off` | `u64` | (M1) | +| `exports_size` | `u64` | (M1) | +| `file_size` | `u64` | Total bytes of the file. Must equal the actual on-disk length. | + +For an empty container, all `*_off` may equal `sizeof(FileHeader)` with corresponding sizes `0`. This is what `voidlink create-empty` produces. + +--- + +## SectionEntry (64 bytes) + +One per (target OS) at MVP — typically 3 (Linux, Windows, macOS). Each entry describes a per-OS native code region plus the portable relocation IR that patches it. + +| Field | Type | Notes | +|----------------|----------|-------| +| `target_os` | `u16` | `1` Linux, `2` Windows, `3` macOS. | +| `reserved0` | `u16` | `0`. | +| `reserved1` | `u32` | `0`. | +| `code_off` | `u64` | Offset of the raw code blob. | +| `code_size` | `u64` | Code blob byte length. | +| `reloc_off` | `u64` | Offset of the `RelocChunk` for this section. | +| `reloc_size` | `u64` | RelocChunk byte length. | +| `debug_off` | `u64` | `0` if no debug info. | +| `debug_size` | `u64` | `0` if no debug info. | +| `entry_offset` | `u64` | For executables: offset of the entry point within `code`. `0` for libraries with no entry. | + +Sections **must be position-independent** (PIC / `-fPIC`). The synthesis core relies on no absolute addresses being baked into `code`. + +--- + +## SymbolTableHeader + SymbolEntry (36 bytes each) + +A flat region: `SymbolTableHeader` + `SymbolEntry[entry_count]` + a UTF-8 name pool of size `name_pool_size`. Symbol references elsewhere are by `u32` index into this entry array. + +Each symbol carries **three optional name views** into the pool: +- `name` — canonical (typically C linkage or unmangled) name. +- `itanium_name` — Itanium C++ mangled form (Linux/macOS). `name_off=0` means absent. +- `msvc_name` — MSVC C++ mangled form (Windows). `name_off=0` means absent. + +When the synthesis core re-exports a C++ symbol, it picks the mangled form matching the running OS. C symbols use `name` for all three OSes. + +`SymbolKind`: `Undefined`/`Function`/`Object`/`TLS`. `SymbolFlags`: bitfield with `Exported`, `Weak`, `Hidden`. + +--- + +## RelocChunk + +8-byte header followed by an array of `RelocEntry`. See `format/reloc_ir.hpp` and (forthcoming) `docs/reloc-ir.md` for opcode semantics. + +`RelocChunk.target_os` must match the owning `SectionEntry.target_os` — redundant but lets readers validate. + +--- + +## Version policy + +- **v0.x** is *unstable*. The format may break between minors during pre-alpha. +- **v1.0** will lock the on-disk layout. After that: + - Major bump = breaking change. Old readers reject the file. + - Minor bump = additive change. Old readers may parse it, ignoring unknown bits in `flags`. +- New `RelocOp` opcodes are an additive change (minor bump). Readers encountering unknown opcodes must fail closed, not silently skip. + +--- + +## Validation checklist for readers + +A conforming reader **must** check, in order: +1. File length ≥ `sizeof(FileHeader)`. +2. `magic == 0x00434C56`. +3. `version_major` is supported. +4. `arch == X86_64`. +5. `file_size` equals the on-disk length. +6. All `*_off + *_size` are within `file_size`. +7. `section_dir_off + section_count * sizeof(SectionEntry)` is within `file_size`. +8. Each `SectionEntry`'s `code_off + code_size`, `reloc_off + reloc_size`, `debug_off + debug_size` are within `file_size`. +9. `RelocChunk.target_os` matches its owning `SectionEntry.target_os`. + +Readers must treat any failure as a hard error — never best-effort parse a malformed `.vlc`. diff --git a/format/reloc_ir.hpp b/format/reloc_ir.hpp new file mode 100644 index 0000000..51d9d00 --- /dev/null +++ b/format/reloc_ir.hpp @@ -0,0 +1,66 @@ +#pragma once + +#include + +namespace voidlibc::format { + +// Portable relocation IR. The synthesis core in loader/common/ lowers +// these to native relocation entries (ELF R_X86_64_*, PE +// IMAGE_REL_AMD64_*, Mach-O X86_64_RELOC_*) per target OS. voidlink +// raises native relocs from input .o files into this IR. +// +// Semantics use these conventions: +// base = run-time base address of the loaded code section +// P = base + dst_offset (place of the relocation) +// S = run-time address of symbol[sym_id] +// A = signed addend +// G = run-time address of the GOT slot for symbol[sym_id] +// L = run-time address of the PLT entry for symbol[sym_id] +// +// Operands are uniform: { dst_offset, sym_id, addend }. Opcodes that +// don't reference a symbol use sym_id = kNoSymbol. + +enum class RelocOp : std::uint16_t { + // Direct fills + Abs64 = 1, // *(u64*)P = S + A + Abs32 = 2, // *(u32*)P = (u32)(S + A); overflow not checked at MVP + Abs32Signed = 3, // *(i32*)P = (i32)(S + A); overflow checked + + // PC-relative + PC32 = 10, // *(i32*)P = (S + A) - P (R_X86_64_PC32 / IMAGE_REL_AMD64_REL32 / X86_64_RELOC_SIGNED) + PC32_1 = 11, // PC32 with -1 bias (REL32_1) + PC32_2 = 12, // PC32 with -2 bias + PC32_4 = 13, // PC32 with -4 bias + PC32_5 = 14, // PC32 with -5 bias (call/jmp imm32 forms) + + // GOT / PLT + GotPC32 = 20, // *(i32*)P = (G + A) - P (R_X86_64_GOTPCREL) + GotPC32X = 21, // GOTPCREL relaxable form (R_X86_64_GOTPCRELX) + GotPC32XRex = 22, // REX-form relaxable (R_X86_64_REX_GOTPCRELX) + PLT32 = 30, // *(i32*)P = (L + A) - P (R_X86_64_PLT32) + + // TLS — placeholders, each OS uses a different scheme (TLSGD, TLSLD, + // GOTTPOFF on ELF; SECREL on PE/TLS; TLVP on Mach-O). Lowering is + // future work; encoding the operation portably for now. + TlsLE = 40, // local-exec TLS offset + TlsIE = 41, // initial-exec TLS offset (via GOT) + TlsGD = 42, // general-dynamic TLS descriptor + TlsLD = 43, // local-dynamic TLS descriptor +}; + +inline constexpr std::uint32_t kNoSymbol = 0xFFFFFFFFu; + +#pragma pack(push, 1) +struct RelocEntry { + RelocOp op; + std::uint16_t reserved; // = 0 + std::uint32_t dst_offset; // byte offset within the section's code + std::uint32_t sym_id; // index into the symbol table, or kNoSymbol + std::int32_t addend; +}; +#pragma pack(pop) + +static_assert(sizeof(RelocEntry) == 16, + "RelocEntry on-disk size must be stable"); + +} // namespace voidlibc::format diff --git a/format/vlc_format.hpp b/format/vlc_format.hpp new file mode 100644 index 0000000..59a7713 --- /dev/null +++ b/format/vlc_format.hpp @@ -0,0 +1,162 @@ +#pragma once + +#include + +namespace voidlibc::format { + +inline constexpr std::uint32_t kMagic = 0x00434C56u; // 'V','L','C','\0' LE +inline constexpr std::uint16_t kVersionMajor = 0; +inline constexpr std::uint16_t kVersionMinor = 1; + +enum class TargetOS : std::uint16_t { + Unknown = 0, + Linux = 1, + Windows = 2, + MacOS = 3, +}; + +enum class TargetArch : std::uint16_t { + Unknown = 0, + X86_64 = 1, +}; + +enum class ContainerFlags : std::uint32_t { + None = 0, + HasDebug = 1u << 0, + HasCppExports = 1u << 1, + Executable = 1u << 2, + HasDynamicImports = 1u << 3, + StaticLibrary = 1u << 4, +}; + +inline constexpr const char* kExtExecutable = ".vle"; +inline constexpr const char* kExtShared = ".vls"; +inline constexpr const char* kExtStatic = ".vla"; + +inline constexpr bool flag_set(std::uint32_t flags, ContainerFlags f) { + return (flags & static_cast(f)) != 0; +} + +inline const char* infer_extension(std::uint32_t flags) { + if (flag_set(flags, ContainerFlags::Executable)) return kExtExecutable; + if (flag_set(flags, ContainerFlags::StaticLibrary)) return kExtStatic; + return kExtShared; +} + +// All on-disk integers are little-endian. Host is x86_64 in MVP, so +// no byte-swapping helpers are wired up yet — add when a big-endian +// host is in scope. + +#pragma pack(push, 1) + +struct FileHeader { + std::uint32_t magic; // = kMagic + std::uint16_t version_major; // = kVersionMajor + std::uint16_t version_minor; // = kVersionMinor + std::uint32_t flags; // ContainerFlags bitfield + TargetArch arch; // = X86_64 in MVP + std::uint16_t reserved; // = 0 + std::uint32_t section_count; + std::uint64_t section_dir_off; // file offset of SectionEntry[section_count] + std::uint64_t symtab_off; // file offset of SymbolTableHeader + std::uint64_t symtab_size; // bytes + std::uint64_t imports_off; // file offset of ImportsHeader + std::uint64_t imports_size; // bytes + std::uint64_t exports_off; // file offset of ExportsHeader + std::uint64_t exports_size; // bytes + std::uint64_t file_size; // total .vlc size; sanity check +}; + +static_assert(sizeof(FileHeader) == 84, + "FileHeader on-disk size must be stable"); + +// One per (target_os) at MVP. Each section holds raw native code + a +// portable relocation IR blob describing how to patch it on load. +// How the section's code_off/code_size blob is stored. +enum class SectionKind : std::uint16_t { + // Raw PIC code + portable reloc IR (reloc_off/reloc_size). + // Requires load-time synthesis before handing to the OS loader. + RawCode = 0, + // Pre-synthesized native OS object (ELF ET_DYN / PE DLL / Mach-O dylib). + // reloc_off/reloc_size = 0; loader passes the blob directly to the OS. + NativeBlob = 1, +}; + +struct SectionEntry { + TargetOS target_os; + SectionKind kind; // RawCode or NativeBlob + std::uint32_t reserved1; // = 0 + std::uint64_t code_off; + std::uint64_t code_size; + std::uint64_t reloc_off; // file offset of RelocChunk (0 if NativeBlob) + std::uint64_t reloc_size; // bytes (0 if NativeBlob) + std::uint64_t data_off; // file offset of writable data blob; 0 if absent + std::uint64_t data_size; // bytes of writable data blob; 0 if absent + std::uint64_t entry_offset; // offset within code for executable entry; 0 for pure libraries +}; + +static_assert(sizeof(SectionEntry) == 64, + "SectionEntry on-disk size must be stable"); + +// Symbol table is a flat blob: header + array of SymbolEntry + a name +// pool. Names are stored as offset+length into the pool; UTF-8. +struct SymbolTableHeader { + std::uint32_t entry_count; + std::uint32_t name_pool_size; + // SymbolEntry entries[entry_count]; + // char name_pool[name_pool_size]; +}; + +enum class SymbolKind : std::uint8_t { + Undefined = 0, + Function = 1, + Object = 2, + TLS = 3, +}; + +enum class SymbolFlags : std::uint8_t { + None = 0, + Exported = 1u << 0, + Weak = 1u << 1, + Hidden = 1u << 2, + DataSection = 1u << 3, // symbol lives in the writable data blob, not the code blob +}; + +// `section_index` is the index into the .vlc section directory of the +// section that owns this symbol; 0xFFFF (`kSymUndefined`) marks an +// import. `value` is the byte offset of the symbol's definition within +// its section's code blob (meaningless if undefined). +inline constexpr std::uint16_t kSymUndefined = 0xFFFF; + +struct SymbolEntry { + std::uint32_t name_off; // offset into name_pool of canonical (C) name + std::uint32_t name_len; + std::uint32_t itanium_name_off; // 0 if not C++ Itanium-mangled + std::uint32_t itanium_name_len; + std::uint32_t msvc_name_off; // 0 if not C++ MSVC-mangled + std::uint32_t msvc_name_len; + std::uint64_t value; // byte offset within the owning section + std::uint64_t size; // 0 for code symbols of unknown extent + std::uint16_t section_index; // index into section dir; kSymUndefined = import + SymbolKind kind; + std::uint8_t flags; + std::uint32_t reserved; // = 0 +}; + +static_assert(sizeof(SymbolEntry) == 48, + "SymbolEntry on-disk size must be stable"); + +// Per-section relocation IR blob. Lives at SectionEntry::reloc_off. +struct RelocChunk { + TargetOS target_os; // matches owning section + std::uint16_t reserved0; // = 0 + std::uint32_t entry_count; + // RelocEntry entries[entry_count]; (see reloc_ir.hpp) +}; + +static_assert(sizeof(RelocChunk) == 8, + "RelocChunk on-disk size must be stable"); + +#pragma pack(pop) + +} // namespace voidlibc::format diff --git a/installer/linux/binfmt.d/vlc.conf b/installer/linux/binfmt.d/vlc.conf new file mode 100644 index 0000000..cb57a36 --- /dev/null +++ b/installer/linux/binfmt.d/vlc.conf @@ -0,0 +1,14 @@ +# VoidLibC executable format (.vle) +# Registered with systemd-binfmt.service (reads /etc/binfmt.d/*.conf on boot). +# +# File extensions used by VoidLibC: +# .vle executable (run via voidloader, triggered by this binfmt rule) +# .vls shared library (loaded via voidlib_load / dlopen, not executed directly) +# .vla static archive (linked at build time via voidlink, not executed directly) +# +# Format: :name:type:offset:magic:mask:interpreter:flags +# M = magic-based detection (not extension-based) +# offset 0, magic = "VLC\0" (4 bytes: 0x56 0x4C 0x43 0x00) +# voidloader verifies the Executable flag in the container header; +# shared libraries and static archives are rejected. +:vlc:M:0:VLC\x00::/usr/local/bin/voidloader: diff --git a/installer/linux/install.sh b/installer/linux/install.sh new file mode 100755 index 0000000..e6801e4 --- /dev/null +++ b/installer/linux/install.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# VoidLibC Linux installer. +# Installs voidlink + voidloader, then registers the .vle binfmt_misc entry. +# Must be run as root (or with sudo). + +set -euo pipefail + +INSTALL_BIN="${INSTALL_BIN:-/usr/local/bin}" +BINFMT_CONF_DIR="${BINFMT_CONF_DIR:-/etc/binfmt.d}" +MAGIC_DIR="${MAGIC_DIR:-/usr/share/file/magic}" +BINFMT_PROC="/proc/sys/fs/binfmt_misc" +BINFMT_ENTRY_NAME="vlc" + +# --- Resolve build artifacts --- +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BUILD_DIR="${BUILD_DIR:-${SCRIPT_DIR}/../../build}" + +VOIDLOADER="${BUILD_DIR}/voidloader/voidloader" +VOIDLINK="${BUILD_DIR}/voidlink/voidlink" + +if [[ ! -f "$VOIDLOADER" ]]; then + echo "error: voidloader not found at $VOIDLOADER" >&2 + echo " Set BUILD_DIR to your cmake build directory." >&2 + exit 1 +fi +if [[ ! -f "$VOIDLINK" ]]; then + echo "error: voidlink not found at $VOIDLINK" >&2 + echo " Set BUILD_DIR to your cmake build directory." >&2 + exit 1 +fi + +# --- Install binaries --- +echo "Installing voidlink → ${INSTALL_BIN}/voidlink" +install -Dm755 "$VOIDLINK" "${INSTALL_BIN}/voidlink" +echo "Installing voidloader → ${INSTALL_BIN}/voidloader" +install -Dm755 "$VOIDLOADER" "${INSTALL_BIN}/voidloader" + +# --- Register binfmt_misc --- +# 1. Persistent (systemd-binfmt.service reads /etc/binfmt.d on boot). +if [[ -d "$BINFMT_CONF_DIR" ]]; then + echo "Installing binfmt.d config → ${BINFMT_CONF_DIR}/vlc.conf" + install -Dm644 "${SCRIPT_DIR}/binfmt.d/vlc.conf" \ + "${BINFMT_CONF_DIR}/vlc.conf" + # Substitute actual interpreter path in case it differs from the default. + sed -i "s|/usr/local/bin/voidloader|${INSTALL_BIN}/voidloader|g" \ + "${BINFMT_CONF_DIR}/vlc.conf" +fi + +# 2. Immediate (without needing a reboot or systemctl restart). +if [[ -d "$BINFMT_PROC" ]]; then + # Remove stale entry if present (ignore errors if not registered yet). + if [[ -f "${BINFMT_PROC}/${BINFMT_ENTRY_NAME}" ]]; then + echo "Removing stale binfmt_misc entry '${BINFMT_ENTRY_NAME}'" + echo -1 > "${BINFMT_PROC}/${BINFMT_ENTRY_NAME}" 2>/dev/null || true + fi + + echo "Registering binfmt_misc entry '${BINFMT_ENTRY_NAME}'" + # Magic: V=0x56 L=0x4C C=0x43 \0=0x00 — null escaped as \x00. + printf ':vlc:M:0:VLC\x00::%s:\n' "${INSTALL_BIN}/voidloader" \ + > "${BINFMT_PROC}/register" + echo " binfmt_misc: .vlc files will now execute via voidloader" +else + echo "warning: ${BINFMT_PROC} not mounted; binfmt_misc not active." >&2 + echo " Run: mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc" >&2 + echo " Then re-run this installer, or reboot after installing the binfmt.d config." >&2 +fi + +# --- Install file(1) magic database entry --- +if [[ -d "$MAGIC_DIR" ]]; then + echo "Installing file(1) magic definition → ${MAGIC_DIR}/vlc" + install -Dm644 "${SCRIPT_DIR}/magic/vlc.magic" "${MAGIC_DIR}/vlc" + # Recompile the system magic database so `file` picks it up. + # file -C -m DIR reads all magic sources from DIR and writes magic.mgc + # into the current working directory. We need to cd to the parent so + # the compiled database lands next to the magic/ directory where file(1) + # expects it. + if command -v file &>/dev/null; then + MAGIC_PARENT="$(dirname "$MAGIC_DIR")" + MAGIC_BASE="$(basename "$MAGIC_DIR")" + echo "Recompiling magic database in ${MAGIC_PARENT}..." + if ( cd "$MAGIC_PARENT" && file -C -m "$MAGIC_BASE" ) 2>/dev/null; then + echo " file(1) now recognizes VoidLibC files" + else + echo " warning: magic database recompile failed" >&2 + echo " Try manually: cd ${MAGIC_PARENT} && sudo file -C -m ${MAGIC_BASE}" >&2 + fi + fi +else + echo "warning: ${MAGIC_DIR} not found; file(1) magic not installed." >&2 + echo " Install file(1) and re-run, or copy tools/vlc.magic manually." >&2 + echo " System-wide: sudo cp tools/vlc.magic ${MAGIC_DIR}/vlc" >&2 + echo " cd $(dirname '${MAGIC_DIR}') && sudo file -C -m $(basename '${MAGIC_DIR}')" >&2 +fi + +echo "" +echo "VoidLibC installed successfully." +echo " voidlink: ${INSTALL_BIN}/voidlink" +echo " voidloader: ${INSTALL_BIN}/voidloader" +echo "" +echo "Test: chmod +x hello.vle && ./hello.vle" +echo " voidlink dump hello.vls" diff --git a/installer/linux/magic/vlc.magic b/installer/linux/magic/vlc.magic new file mode 100644 index 0000000..8d9e138 --- /dev/null +++ b/installer/linux/magic/vlc.magic @@ -0,0 +1,29 @@ +# magic(5) entry for VoidLibC container files. +# +# File extensions: +# .vle executable (bit 2 = Executable) +# .vls shared library (default when neither executable nor static) +# .vla static archive (bit 4 = StaticLibrary) +# +# Offset layout (FileHeader, packed, LE): +# 0 u32 magic = 0x00434C56 +# 4 u16 version_major +# 6 u16 version_minor +# 8 u32 flags (bit 0=HasDebug, bit 1=HasCppExports, bit 2=Executable, +# bit 3=HasDynamicImports, bit 4=StaticLibrary) +# 12 u16 arch (1 = x86_64) +# +# Quick test: file -m vlc.magic +# System-wide: sudo cp vlc.magic /usr/share/file/magic/vlc +# cd /usr/share/file && sudo file -C -m magic + +0 lelong 0x00434C56 VoidLibC container +>4 leshort x \b v%d +>6 leshort x \b.%d +>12 leshort 1 \b, x86_64 +>8 lelong &0x04 \b, executable +>8 lelong ^0x04 \b, shared library +>8 lelong &0x10 \b, static archive +>8 lelong &0x08 \b, dynamically linked +>8 lelong ^0x08 \b, statically linked +>8 lelong &0x01 \b, with debug diff --git a/installer/linux/register_binfmt.sh b/installer/linux/register_binfmt.sh new file mode 100755 index 0000000..63781d8 --- /dev/null +++ b/installer/linux/register_binfmt.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Register the .vlc binfmt_misc entry for an already-installed voidloader. +# Use this after a source build instead of running the full installer. +# Requires root (or write access to /proc/sys/fs/binfmt_misc/register). +# +# Usage: sudo ./register_binfmt.sh [/path/to/voidloader] + +set -euo pipefail + +VOIDLOADER="${1:-/usr/local/bin/voidloader}" +BINFMT_PROC="/proc/sys/fs/binfmt_misc" +BINFMT_ENTRY_NAME="vlc" + +if [[ ! -x "$VOIDLOADER" ]]; then + echo "error: voidloader not found or not executable: $VOIDLOADER" >&2 + echo " Build it first (cmake --build build) or pass its path as an argument." >&2 + exit 1 +fi + +if [[ ! -d "$BINFMT_PROC" ]]; then + echo "error: ${BINFMT_PROC} not found — is binfmt_misc mounted?" >&2 + echo " Try: sudo mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc" >&2 + exit 1 +fi + +# Remove stale entry (ignore if not registered). +if [[ -f "${BINFMT_PROC}/${BINFMT_ENTRY_NAME}" ]]; then + echo "Removing stale binfmt_misc entry '${BINFMT_ENTRY_NAME}'" + echo -1 > "${BINFMT_PROC}/${BINFMT_ENTRY_NAME}" +fi + +# Register: magic is V=0x56 L=0x4C C=0x43 \0=0x00. +printf ':vlc:M:0:VLC\x00::%s:\n' "$VOIDLOADER" > "${BINFMT_PROC}/register" + +echo "Registered: .vlc files → ${VOIDLOADER}" +echo " Note: this registration is lost on reboot." +echo " For persistence: copy installer/linux/binfmt.d/vlc.conf to /etc/binfmt.d/" +echo " and run: sudo systemctl restart systemd-binfmt" diff --git a/installer/linux/uninstall.sh b/installer/linux/uninstall.sh new file mode 100755 index 0000000..dc6eb85 --- /dev/null +++ b/installer/linux/uninstall.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# VoidLibC Linux uninstaller. +# Reverses install.sh: removes binaries and deregisters binfmt_misc. +# Must be run as root (or with sudo). + +set -euo pipefail + +INSTALL_BIN="${INSTALL_BIN:-/usr/local/bin}" +BINFMT_CONF_DIR="${BINFMT_CONF_DIR:-/etc/binfmt.d}" +MAGIC_DIR="${MAGIC_DIR:-/usr/share/file/magic}" +BINFMT_PROC="/proc/sys/fs/binfmt_misc" +BINFMT_ENTRY_NAME="vlc" + +# --- Deregister binfmt_misc --- +if [[ -f "${BINFMT_PROC}/${BINFMT_ENTRY_NAME}" ]]; then + echo "Deregistering binfmt_misc entry '${BINFMT_ENTRY_NAME}'" + echo -1 > "${BINFMT_PROC}/${BINFMT_ENTRY_NAME}" +else + echo "(binfmt_misc entry '${BINFMT_ENTRY_NAME}' not active — skipping)" +fi + +# --- Remove binfmt.d config --- +if [[ -f "${BINFMT_CONF_DIR}/vlc.conf" ]]; then + echo "Removing ${BINFMT_CONF_DIR}/vlc.conf" + rm -f "${BINFMT_CONF_DIR}/vlc.conf" +fi + +# --- Remove binaries --- +for f in "${INSTALL_BIN}/voidlink" "${INSTALL_BIN}/voidloader"; do + if [[ -f "$f" ]]; then + echo "Removing $f" + rm -f "$f" + fi +done + +# --- Remove file(1) magic entry --- +if [[ -f "${MAGIC_DIR}/vlc" ]]; then + echo "Removing ${MAGIC_DIR}/vlc" + rm -f "${MAGIC_DIR}/vlc" + if command -v file &>/dev/null; then + echo "Recompiling magic database..." + file -C -m "$MAGIC_DIR" 2>/dev/null || true + fi +fi + +echo "" +echo "VoidLibC uninstalled." diff --git a/installer/macos/install.sh b/installer/macos/install.sh new file mode 100644 index 0000000..de0d417 --- /dev/null +++ b/installer/macos/install.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# VoidLibC macOS installer. +# Installs voidlink + voidloader to INSTALL_BIN (default: /usr/local/bin). +# Does not require root if INSTALL_BIN is user-writable (e.g. Homebrew prefix). +# +# .vle files are not auto-executed via binfmt_misc on macOS; invoke via: +# voidloader file.vle [args...] +# or register a file association via Finder/Launch Services separately. + +set -euo pipefail + +INSTALL_BIN="${INSTALL_BIN:-/usr/local/bin}" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Release package layout: binaries live in ../bin/ relative to installer/. +# Development layout: binaries live in BUILD_DIR (set via env or default). +if [[ -f "${SCRIPT_DIR}/../bin/voidlink" ]]; then + VOIDLINK="${SCRIPT_DIR}/../bin/voidlink" + VOIDLOADER="${SCRIPT_DIR}/../bin/voidloader" +else + BUILD_DIR="${BUILD_DIR:-${SCRIPT_DIR}/../../build}" + VOIDLINK="${BUILD_DIR}/voidlink/voidlink" + VOIDLOADER="${BUILD_DIR}/voidloader/voidloader" +fi + +for f in "$VOIDLINK" "$VOIDLOADER"; do + if [[ ! -f "$f" ]]; then + echo "error: $(basename "$f") not found at $f" >&2 + echo " If running from a release package, make sure you extracted" >&2 + echo " the archive before running this script." >&2 + echo " For development builds, set BUILD_DIR to your cmake directory." >&2 + exit 1 + fi +done + +mkdir -p "${INSTALL_BIN}" + +echo "Installing voidlink → ${INSTALL_BIN}/voidlink" +install -m755 "$VOIDLINK" "${INSTALL_BIN}/voidlink" +echo "Installing voidloader → ${INSTALL_BIN}/voidloader" +install -m755 "$VOIDLOADER" "${INSTALL_BIN}/voidloader" + +# Verify the binaries are in PATH. +if ! command -v voidlink &>/dev/null || ! command -v voidloader &>/dev/null; then + echo "" + echo "note: ${INSTALL_BIN} is not in your PATH." + echo " Add the following to your shell profile:" + echo " export PATH=\"${INSTALL_BIN}:\$PATH\"" +fi + +echo "" +echo "VoidLibC installed successfully." +echo " voidlink: ${INSTALL_BIN}/voidlink" +echo " voidloader: ${INSTALL_BIN}/voidloader" +echo "" +echo "Run .vle files: voidloader hello.vle" +echo "Inspect .vls: voidlink dump hello.vls" diff --git a/installer/macos/uninstall.sh b/installer/macos/uninstall.sh new file mode 100644 index 0000000..725b30c --- /dev/null +++ b/installer/macos/uninstall.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# VoidLibC macOS uninstaller. Reverses install.sh. + +set -euo pipefail + +INSTALL_BIN="${INSTALL_BIN:-/usr/local/bin}" + +for f in "${INSTALL_BIN}/voidlink" "${INSTALL_BIN}/voidloader"; do + if [[ -f "$f" ]]; then + echo "Removing $f" + rm -f "$f" + else + echo "(not found: $f — skipping)" + fi +done + +echo "" +echo "VoidLibC uninstalled." diff --git a/installer/windows/install.ps1 b/installer/windows/install.ps1 new file mode 100644 index 0000000..d7bba3e --- /dev/null +++ b/installer/windows/install.ps1 @@ -0,0 +1,87 @@ +# VoidLibC Windows installer (PowerShell). +# Copies voidlink.exe + voidloader.exe to %LOCALAPPDATA%\VoidLibC\bin and +# optionally registers .vle files to open with voidloader via the registry. +# +# Usage from a release package (recommended): +# powershell -ExecutionPolicy Bypass -File installer\install.ps1 +# +# Usage from a dev build: +# powershell -ExecutionPolicy Bypass -File installer\windows\install.ps1 -BuildDir .\build +# +# Optional parameters: +# -BuildDir path cmake build directory (ignored when running from a release package) +# -InstallDir path Install directory (default: %LOCALAPPDATA%\VoidLibC\bin) +# -RegisterVle Register .vle file association (default: $true) + +param( + [string]$BuildDir = "", + [string]$InstallDir = "$env:LOCALAPPDATA\VoidLibC\bin", + [bool]$RegisterVle = $true +) + +$ErrorActionPreference = "Stop" + +# Release package layout: binaries live in ..\bin\ relative to installer\. +# Development layout: binaries live in BuildDir\voidlink\ etc. +$PackageBin = Join-Path $PSScriptRoot ".." "bin" +if (Test-Path (Join-Path $PackageBin "voidlink.exe")) { + $VoidLink = Join-Path $PackageBin "voidlink.exe" + $VoidLoader = Join-Path $PackageBin "voidloader.exe" +} else { + if (-not $BuildDir) { $BuildDir = Join-Path $PSScriptRoot ".." ".." "build" } + $VoidLink = Join-Path $BuildDir "voidlink" "voidlink.exe" + $VoidLoader = Join-Path $BuildDir "voidloader" "voidloader.exe" +} + +foreach ($f in @($VoidLink, $VoidLoader)) { + if (-not (Test-Path $f)) { + Write-Error ( + "Not found: $f`n" + + "If running from a release package, ensure you extracted the archive first.`n" + + "For dev builds, pass -BuildDir to your cmake build directory." + ) + exit 1 + } +} + +New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null + +Write-Host "Installing voidlink.exe -> $InstallDir" +Copy-Item -Force $VoidLink (Join-Path $InstallDir "voidlink.exe") +Write-Host "Installing voidloader.exe -> $InstallDir" +Copy-Item -Force $VoidLoader (Join-Path $InstallDir "voidloader.exe") + +# Add to user PATH if not already present. +$userPath = [Environment]::GetEnvironmentVariable("PATH", "User") ?? "" +if ($userPath -notlike "*$InstallDir*") { + [Environment]::SetEnvironmentVariable( + "PATH", "$InstallDir;$userPath", "User") + Write-Host "Added $InstallDir to user PATH." + Write-Host "(Restart your terminal or log off/on for PATH to take effect.)" +} + +# Register .vle file association in HKCU (no admin required). +if ($RegisterVle) { + $vloaderPath = Join-Path $InstallDir "voidloader.exe" + + # ProgID + $progId = "VoidLibC.VLE.1" + New-Item -Force -Path "HKCU:\Software\Classes\$progId" | + Set-ItemProperty -Name "(Default)" -Value "VoidLibC Executable" + New-Item -Force -Path "HKCU:\Software\Classes\$progId\shell\open\command" | + Set-ItemProperty -Name "(Default)" -Value "`"$vloaderPath`" `"%1`" %*" + + # .vle extension + New-Item -Force -Path "HKCU:\Software\Classes\.vle" | + Set-ItemProperty -Name "(Default)" -Value $progId + + Write-Host "Registered .vle -> voidloader.exe via HKCU\Software\Classes" +} + +Write-Host "" +Write-Host "VoidLibC installed successfully." +Write-Host " voidlink: $(Join-Path $InstallDir 'voidlink.exe')" +Write-Host " voidloader: $(Join-Path $InstallDir 'voidloader.exe')" +Write-Host "" +Write-Host "Run .vle files: double-click in Explorer, or: voidloader hello.vle" +Write-Host "Inspect .vls: voidlink dump hello.vls" diff --git a/installer/windows/uninstall.ps1 b/installer/windows/uninstall.ps1 new file mode 100644 index 0000000..d69465e --- /dev/null +++ b/installer/windows/uninstall.ps1 @@ -0,0 +1,37 @@ +# VoidLibC Windows uninstaller. Reverses install.ps1. + +param( + [string]$InstallDir = "$env:LOCALAPPDATA\VoidLibC\bin" +) + +$ErrorActionPreference = "Stop" + +foreach ($exe in @("voidlink.exe", "voidloader.exe")) { + $f = Join-Path $InstallDir $exe + if (Test-Path $f) { + Write-Host "Removing $f" + Remove-Item -Force $f + } else { + Write-Host "(not found: $f — skipping)" + } +} + +# Remove .vle file association. +foreach ($key in @("HKCU:\Software\Classes\.vle", + "HKCU:\Software\Classes\VoidLibC.VLE.1")) { + if (Test-Path $key) { + Write-Host "Removing registry key $key" + Remove-Item -Recurse -Force $key + } +} + +# Remove from user PATH. +$userPath = [Environment]::GetEnvironmentVariable("PATH", "User") ?? "" +$newPath = ($userPath -split ";" | Where-Object { $_ -ne $InstallDir }) -join ";" +if ($newPath -ne $userPath) { + [Environment]::SetEnvironmentVariable("PATH", $newPath, "User") + Write-Host "Removed $InstallDir from user PATH." +} + +Write-Host "" +Write-Host "VoidLibC uninstalled." diff --git a/libvoid/CMakeLists.txt b/libvoid/CMakeLists.txt new file mode 100644 index 0000000..7ef728b --- /dev/null +++ b/libvoid/CMakeLists.txt @@ -0,0 +1,24 @@ +add_library(void STATIC + api.cpp +) +target_include_directories(void + PUBLIC + $ + $ + $ +) +# The loader static archives must also be linked by consumers because a static +# library does not bundle its own dependencies. +target_link_libraries(void PUBLIC + voidlibc_loader_common + $<$:$,voidlibc_loader_macos,voidlibc_loader_linux>> + ${CMAKE_DL_LIBS} +) +if(WIN32) + target_link_libraries(void PUBLIC voidlibc_loader_windows) +endif() + +install(TARGETS void + EXPORT VoidLibCTargets + ARCHIVE DESTINATION lib +) diff --git a/libvoid/api.cpp b/libvoid/api.cpp new file mode 100644 index 0000000..aa231d2 --- /dev/null +++ b/libvoid/api.cpp @@ -0,0 +1,464 @@ +#include "internal.h" + +#include "format/reloc_ir.hpp" +#include "format/vlc_format.hpp" + +#if defined(__linux__) +# include "loader/common/elf_synth.hpp" +# include "loader/linux/handoff.hpp" +# include +#elif defined(__APPLE__) +# include "loader/macos/macho_synth.hpp" +# include "loader/macos/handoff.hpp" +# include +#elif defined(_WIN32) +# include "loader/windows/pe_synth.hpp" +# include "loader/windows/handoff.hpp" +# include +#else +# error "libvoid: unsupported platform" +#endif + +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace voidlibc::format; + +thread_local std::string g_last_error; + +void set_error(std::string msg) { + g_last_error = std::move(msg); +} + +#if defined(__linux__) +constexpr TargetOS kHostOS = TargetOS::Linux; +#elif defined(__APPLE__) +constexpr TargetOS kHostOS = TargetOS::MacOS; +#elif defined(_WIN32) +constexpr TargetOS kHostOS = TargetOS::Windows; +#endif + +bool read_all(const char* path, std::vector& out) { + std::ifstream in(path, std::ios::binary | std::ios::ate); + if (!in) { + set_error(std::string("cannot open: ") + path); + return false; + } + const auto size = static_cast(in.tellg()); + in.seekg(0, std::ios::beg); + out.resize(static_cast(size)); + in.read(reinterpret_cast(out.data()), size); + if (!in) { + set_error("short read"); + return false; + } + return true; +} + +struct ParsedVlc { + FileHeader hdr; + std::vector sections; + std::vector symbols; + std::vector name_pool; + std::vector> section_relocs; +}; + +bool parse_vlc(const std::vector& data, ParsedVlc& p) { + if (data.size() < sizeof(FileHeader)) { + set_error(".vlc too small for header"); + return false; + } + std::memcpy(&p.hdr, data.data(), sizeof(FileHeader)); + if (p.hdr.magic != kMagic) { + set_error("bad magic; not a .vlc"); + return false; + } + if (p.hdr.version_major != kVersionMajor) { + set_error("unsupported version"); + return false; + } + if (p.hdr.arch != TargetArch::X86_64) { + set_error("unsupported architecture"); + return false; + } + if (p.hdr.file_size != data.size()) { + set_error("header file_size disagrees with on-disk size"); + return false; + } + + const std::uint64_t sd_end = + p.hdr.section_dir_off + + static_cast(p.hdr.section_count) * sizeof(SectionEntry); + if (sd_end > data.size()) { + set_error("section directory truncated"); + return false; + } + p.sections.resize(p.hdr.section_count); + if (p.hdr.section_count > 0) { + std::memcpy(p.sections.data(), + data.data() + p.hdr.section_dir_off, + p.sections.size() * sizeof(SectionEntry)); + } + + if (p.hdr.symtab_size > 0) { + if (p.hdr.symtab_off + p.hdr.symtab_size > data.size()) { + set_error("symtab truncated"); + return false; + } + SymbolTableHeader sth{}; + if (p.hdr.symtab_size < sizeof(sth)) { + set_error("symtab smaller than its header"); + return false; + } + std::memcpy(&sth, data.data() + p.hdr.symtab_off, sizeof(sth)); + const std::uint64_t entries_off = p.hdr.symtab_off + sizeof(sth); + const std::uint64_t entries_size = + static_cast(sth.entry_count) * sizeof(SymbolEntry); + const std::uint64_t pool_off = entries_off + entries_size; + const std::uint64_t pool_size = sth.name_pool_size; + if (entries_off + entries_size + pool_size + > p.hdr.symtab_off + p.hdr.symtab_size) { + set_error("symtab fields exceed symtab_size"); + return false; + } + p.symbols.resize(sth.entry_count); + if (sth.entry_count > 0) { + std::memcpy(p.symbols.data(), + data.data() + entries_off, + entries_size); + } + p.name_pool.assign( + reinterpret_cast(data.data() + pool_off), + reinterpret_cast(data.data() + pool_off + pool_size)); + } + + p.section_relocs.resize(p.sections.size()); + for (std::size_t si = 0; si < p.sections.size(); ++si) { + const auto& sec = p.sections[si]; + if (sec.reloc_size == 0) continue; + if (sec.reloc_off + sec.reloc_size > data.size()) { + set_error("reloc chunk truncated"); + return false; + } + if (sec.reloc_size < sizeof(RelocChunk)) { + set_error("reloc chunk smaller than its header"); + return false; + } + RelocChunk rc{}; + std::memcpy(&rc, data.data() + sec.reloc_off, sizeof(rc)); + const std::uint64_t entries_off = sec.reloc_off + sizeof(rc); + const std::uint64_t entries_size = + static_cast(rc.entry_count) * sizeof(RelocEntry); + if (entries_off + entries_size > sec.reloc_off + sec.reloc_size) { + set_error("reloc entries exceed chunk size"); + return false; + } + p.section_relocs[si].resize(rc.entry_count); + if (rc.entry_count > 0) { + std::memcpy(p.section_relocs[si].data(), + data.data() + entries_off, + entries_size); + } + } + return true; +} + +const SectionEntry* find_section(const ParsedVlc& p, TargetOS os) { + for (const auto& s : p.sections) { + if (s.target_os == os) return &s; + } + return nullptr; +} + +std::string name_from_pool(const ParsedVlc& p, + std::uint32_t off, + std::uint32_t len) { + if (len == 0 || off + len > p.name_pool.size()) return {}; + return std::string(p.name_pool.data() + off, len); +} + +} // namespace + +namespace voidlibc::detail { + +void* load_vlc(const char* path, bool allow_exec) { + g_last_error.clear(); + if (!path) { set_error("null path"); return nullptr; } + + std::vector bytes; + if (!read_all(path, bytes)) return nullptr; + + ParsedVlc p{}; + if (!parse_vlc(bytes, p)) return nullptr; + + const bool is_exec = flag_set(p.hdr.flags, ContainerFlags::Executable); + const bool is_stat = flag_set(p.hdr.flags, ContainerFlags::StaticLibrary); + if (is_stat) { + set_error(std::string(path) + + ": this is a static archive (.vla), not loadable at runtime — " + "link with voidlink instead"); + return nullptr; + } + if (is_exec && !allow_exec) { + set_error(std::string(path) + + ": this is an executable .vlc, not a shared library — " + "use voidloader to run it"); + return nullptr; + } + + const SectionEntry* sec = find_section(p, kHostOS); + if (!sec) { + set_error("no matching OS section in .vlc"); + return nullptr; + } + if (sec->code_off + sec->code_size > bytes.size()) { + set_error("code section truncated"); + return nullptr; + } + + if (sec->kind == SectionKind::NativeBlob) { +#if defined(__linux__) + std::vector blob(bytes.data() + sec->code_off, + bytes.data() + sec->code_off + sec->code_size); + const auto loaded = voidlibc::loader::linux_handoff::dlopen_buffer(blob); + if (!loaded.ok) { set_error(loaded.error); return nullptr; } + return loaded.dl_handle; +#elif defined(__APPLE__) + std::vector blob(bytes.data() + sec->code_off, + bytes.data() + sec->code_off + sec->code_size); + const auto loaded = voidlibc::loader::macos_handoff::dlopen_buffer(blob); + if (!loaded.ok) { set_error(loaded.error); return nullptr; } + return loaded.dl_handle; +#elif defined(_WIN32) + std::vector blob(bytes.data() + sec->code_off, + bytes.data() + sec->code_off + sec->code_size); + const auto loaded = voidlibc::loader::windows_handoff::load_pe_buffer(blob); + if (!loaded.ok) { set_error(loaded.error); return nullptr; } + return loaded.handle; +#endif + } + + const auto vlc_sec_index = static_cast(sec - p.sections.data()); + + struct SymInfo { + std::string name; + std::uint64_t value = 0; + std::uint64_t size = 0; + std::uint32_t sym_id = 0; + bool exported = false; + bool is_data = false; + bool is_func = false; + bool weak = false; + bool defined = false; + bool imported = false; + }; + std::vector sym_infos; + sym_infos.reserve(p.symbols.size()); + + for (std::uint32_t i = 0; i < p.symbols.size(); ++i) { + const auto& sym = p.symbols[i]; + SymInfo s{}; + s.name = name_from_pool(p, sym.name_off, sym.name_len); + s.sym_id = i; + s.value = sym.value; + s.size = sym.size; + s.exported = (sym.flags & static_cast(SymbolFlags::Exported)) != 0; + s.is_data = (sym.flags & static_cast(SymbolFlags::DataSection)) != 0; + s.weak = (sym.flags & static_cast(SymbolFlags::Weak)) != 0; + s.is_func = sym.kind == SymbolKind::Function; + s.defined = sym.section_index != kSymUndefined && sym.section_index == vlc_sec_index; + s.imported = sym.section_index == kSymUndefined; + if (s.name.empty() && !s.defined && !s.imported) continue; + sym_infos.push_back(std::move(s)); + } + + std::vector relocs; + if (!p.section_relocs[vlc_sec_index].empty()) + relocs = p.section_relocs[vlc_sec_index]; + +#if defined(__linux__) + { + voidlibc::loader::ElfSynthInput input{}; + input.code.assign(bytes.data() + sec->code_off, + bytes.data() + sec->code_off + sec->code_size); + if (sec->data_size > 0) { + if (sec->data_off + sec->data_size > bytes.size()) { + set_error("data blob truncated"); return nullptr; + } + input.data_blob.assign(bytes.data() + sec->data_off, + bytes.data() + sec->data_off + sec->data_size); + } + input.relocs = relocs; + for (const auto& s : sym_infos) { + if (s.exported && s.defined && !s.is_data) { + voidlibc::loader::ExportedSymbol e{}; + e.name = s.name; e.code_offset = s.value; e.size = s.size; + e.is_function = s.is_func; e.weak = s.weak; + input.exports.push_back(std::move(e)); + } + if (s.defined && !s.is_data) { + voidlibc::loader::InternalSymbol is{}; + is.sym_id = s.sym_id; is.code_offset = s.value; is.name = s.name; + input.internal_symbols.push_back(std::move(is)); + } + if (s.defined && s.is_data) { + voidlibc::loader::DataSymbol ds{}; + ds.sym_id = s.sym_id; ds.data_offset = s.value; ds.name = s.name; + input.data_symbols.push_back(std::move(ds)); + } + if (s.imported && !s.name.empty()) { + voidlibc::loader::ImportedSymbol im{}; + im.sym_id = s.sym_id; im.name = s.name; + input.imports.push_back(std::move(im)); + } + } + if (input.exports.empty()) { set_error("no exported symbols"); return nullptr; } + const auto synth = voidlibc::loader::synthesize_elf(input); + if (!synth.ok) { set_error(synth.error); return nullptr; } + const auto loaded = voidlibc::loader::linux_handoff::dlopen_buffer(synth.bytes); + if (!loaded.ok) { set_error(loaded.error); return nullptr; } + return loaded.dl_handle; + } +#elif defined(__APPLE__) + { + voidlibc::loader::macos::MachoSynthInput input{}; + input.code.assign(bytes.data() + sec->code_off, + bytes.data() + sec->code_off + sec->code_size); + if (sec->data_size > 0) { + if (sec->data_off + sec->data_size > bytes.size()) { + set_error("data blob truncated"); return nullptr; + } + input.data_blob.assign(bytes.data() + sec->data_off, + bytes.data() + sec->data_off + sec->data_size); + } + input.relocs = relocs; + for (const auto& s : sym_infos) { + if (s.exported && s.defined && !s.is_data) { + voidlibc::loader::macos::MachoExportedSymbol e{}; + e.name = s.name; e.code_offset = s.value; e.size = s.size; + e.is_function = s.is_func; e.weak = s.weak; + input.exports.push_back(std::move(e)); + } + if (s.defined && !s.is_data) { + voidlibc::loader::macos::MachoInternalSymbol is{}; + is.sym_id = s.sym_id; is.code_offset = s.value; is.name = s.name; + input.internal_symbols.push_back(std::move(is)); + } + if (s.defined && s.is_data) { + voidlibc::loader::macos::MachoDataSymbol ds{}; + ds.sym_id = s.sym_id; ds.data_offset = s.value; ds.name = s.name; + input.data_symbols.push_back(std::move(ds)); + } + if (s.imported && !s.name.empty()) { + voidlibc::loader::macos::MachoImportedSymbol im{}; + im.sym_id = s.sym_id; im.name = s.name; + input.imports.push_back(std::move(im)); + } + } + if (input.exports.empty()) { set_error("no exported symbols"); return nullptr; } + const auto synth = voidlibc::loader::macos::synthesize_macho(input); + if (!synth.ok) { set_error(synth.error); return nullptr; } + const auto loaded = voidlibc::loader::macos_handoff::dlopen_buffer(synth.bytes); + if (!loaded.ok) { set_error(loaded.error); return nullptr; } + return loaded.dl_handle; + } +#elif defined(_WIN32) + voidlibc::loader::windows::PeSynthInput input{}; + input.code.assign(bytes.data() + sec->code_off, + bytes.data() + sec->code_off + sec->code_size); + if (sec->data_size > 0) { + if (sec->data_off + sec->data_size > bytes.size()) { + set_error("data blob truncated"); return nullptr; + } + input.data_blob.assign(bytes.data() + sec->data_off, + bytes.data() + sec->data_off + sec->data_size); + } + input.relocs = relocs; + input.dll_name = std::filesystem::path(path).filename().string(); + for (const auto& s : sym_infos) { + if (s.exported && s.defined && !s.is_data) { + voidlibc::loader::windows::WinExportedSymbol e{}; + e.name = s.name; e.code_offset = s.value; e.size = s.size; + e.is_function = s.is_func; + input.exports.push_back(std::move(e)); + } + if (s.defined && !s.is_data) { + voidlibc::loader::windows::WinInternalSymbol is{}; + is.sym_id = s.sym_id; is.code_offset = s.value; is.name = s.name; + input.internal_symbols.push_back(std::move(is)); + } + if (s.defined && s.is_data) { + voidlibc::loader::windows::WinDataSymbol ds{}; + ds.sym_id = s.sym_id; ds.data_offset = s.value; ds.name = s.name; + input.data_symbols.push_back(std::move(ds)); + } + if (s.imported && !s.name.empty()) { + voidlibc::loader::windows::WinImportedSymbol im{}; + im.sym_id = s.sym_id; im.name = s.name; + input.imports.push_back(std::move(im)); + } + } + if (input.exports.empty()) { set_error("no exported symbols"); return nullptr; } + const auto synth = voidlibc::loader::windows::synthesize_pe(input); + if (!synth.ok) { set_error(synth.error); return nullptr; } + const auto loaded = voidlibc::loader::windows_handoff::load_pe_buffer(synth.bytes); + if (!loaded.ok) { set_error(loaded.error); return nullptr; } + return loaded.handle; +#endif +} + +} // namespace voidlibc::detail + +// --------------------------------------------------------------------------- +// dlopen / dlerror interposers (Linux/macOS only; Windows uses LoadLibrary) +// --------------------------------------------------------------------------- +#if defined(__linux__) || defined(__APPLE__) + +static constexpr std::uint8_t kVlcMagic[4] = { + static_cast('V'), + static_cast('L'), + static_cast('C'), + static_cast('\0') +}; + +static bool sniff_vlc(const char* path) { + std::FILE* f = std::fopen(path, "rb"); + if (!f) return false; + std::uint8_t hdr[4] = {}; + const bool got = std::fread(hdr, 1, 4, f) == 4; + std::fclose(f); + return got && std::memcmp(hdr, kVlcMagic, 4) == 0; +} + +extern "C" void* dlopen(const char* path, int flags) { + using real_t = void* (*)(const char*, int); + static real_t real = reinterpret_cast(::dlsym(RTLD_NEXT, "dlopen")); + + if (!path || !sniff_vlc(path)) + return real(path, flags); + + return voidlibc::detail::load_vlc(path, /*allow_exec=*/false); +} + +extern "C" char* dlerror() { + using real_t = char* (*)(); + static real_t real = reinterpret_cast(::dlsym(RTLD_NEXT, "dlerror")); + + if (!g_last_error.empty()) { + // Mimic POSIX dlerror: return message then clear, so next call returns NULL. + static thread_local char buf[1024]; + std::strncpy(buf, g_last_error.c_str(), sizeof(buf) - 1); + buf[sizeof(buf) - 1] = '\0'; + g_last_error.clear(); + return buf; + } + return real(); +} + +#endif // __linux__ || __APPLE__ diff --git a/libvoid/internal.h b/libvoid/internal.h new file mode 100644 index 0000000..9bedcae --- /dev/null +++ b/libvoid/internal.h @@ -0,0 +1,10 @@ +#pragma once + +namespace voidlibc::detail { + +// Load a .vlc file and return a native OS handle (dlopen handle on Linux/macOS, +// HMODULE on Windows). Returns nullptr on failure; call dlerror() for the reason. +// allow_exec=true is required to load .vle executables (voidloader only). +void* load_vlc(const char* path, bool allow_exec); + +} // namespace voidlibc::detail diff --git a/loader/CMakeLists.txt b/loader/CMakeLists.txt new file mode 100644 index 0000000..0846602 --- /dev/null +++ b/loader/CMakeLists.txt @@ -0,0 +1,4 @@ +add_subdirectory(common) +add_subdirectory(linux) +add_subdirectory(windows) +add_subdirectory(macos) diff --git a/loader/common/CMakeLists.txt b/loader/common/CMakeLists.txt new file mode 100644 index 0000000..0ffa30a --- /dev/null +++ b/loader/common/CMakeLists.txt @@ -0,0 +1,14 @@ +add_library(voidlibc_loader_common STATIC + elf_synth.cpp +) +target_include_directories(voidlibc_loader_common PUBLIC + $ + $ + $ +) +target_link_libraries(voidlibc_loader_common PUBLIC voidlibc_format) +set_target_properties(voidlibc_loader_common PROPERTIES POSITION_INDEPENDENT_CODE ON) +install(TARGETS voidlibc_loader_common + EXPORT VoidLibCTargets + ARCHIVE DESTINATION lib +) diff --git a/loader/common/elf64.hpp b/loader/common/elf64.hpp new file mode 100644 index 0000000..0a208a8 --- /dev/null +++ b/loader/common/elf64.hpp @@ -0,0 +1,216 @@ +#pragma once + +// Minimal x86_64 ELF64 definitions, in-tree to avoid noise. +// Only the subset we synthesize is here. + +#include + +namespace voidlibc::loader { + +inline constexpr std::uint8_t kElfMag0 = 0x7F; +inline constexpr std::uint8_t kElfMag1 = 'E'; +inline constexpr std::uint8_t kElfMag2 = 'L'; +inline constexpr std::uint8_t kElfMag3 = 'F'; + +inline constexpr std::uint8_t kElfClass64 = 2; +inline constexpr std::uint8_t kElfData2LSB = 1; +inline constexpr std::uint8_t kElfVersionCurrent = 1; +inline constexpr std::uint8_t kElfOsAbiSysV = 0; + +inline constexpr std::uint16_t kEtRel = 1; +inline constexpr std::uint16_t kEtDyn = 3; +inline constexpr std::uint16_t kEmX86_64 = 62; +inline constexpr std::uint32_t kEvCurrent = 1; + +// Section header types +inline constexpr std::uint32_t kShtNull = 0; +inline constexpr std::uint32_t kShtProgbits = 1; +inline constexpr std::uint32_t kShtSymtab = 2; +inline constexpr std::uint32_t kShtStrtab = 3; +inline constexpr std::uint32_t kShtRela = 4; +inline constexpr std::uint32_t kShtNobits = 8; +inline constexpr std::uint32_t kShtRel = 9; +inline constexpr std::uint32_t kShtGnuVerdef = 0x6FFFFFFDu; // .gnu.version_d +inline constexpr std::uint32_t kShtGnuVerneed = 0x6FFFFFFEu; // .gnu.version_r +inline constexpr std::uint32_t kShtGnuVersym = 0x6FFFFFFFu; // .gnu.version + +// Section header flags +inline constexpr std::uint64_t kShfWrite = 0x1; +inline constexpr std::uint64_t kShfAlloc = 0x2; +inline constexpr std::uint64_t kShfExecinstr = 0x4; + +// x86_64 relocation types (subset) +inline constexpr std::uint32_t kRX86_64_None = 0; +inline constexpr std::uint32_t kRX86_64_64 = 1; +inline constexpr std::uint32_t kRX86_64_PC32 = 2; +inline constexpr std::uint32_t kRX86_64_GOT32 = 3; +inline constexpr std::uint32_t kRX86_64_PLT32 = 4; +inline constexpr std::uint32_t kRX86_64_GOTPCREL = 9; +inline constexpr std::uint32_t kRX86_64_32 = 10; +inline constexpr std::uint32_t kRX86_64_32S = 11; +inline constexpr std::uint32_t kRX86_64_GOTPCRELX = 41; +inline constexpr std::uint32_t kRX86_64_REX_GOTPCRELX = 42; + +inline constexpr std::uint32_t r_sym(std::uint64_t info) { return static_cast(info >> 32); } +inline constexpr std::uint32_t r_type(std::uint64_t info) { return static_cast(info & 0xFFFFFFFFu); } + +// Phdr p_type +inline constexpr std::uint32_t kPtLoad = 1; +inline constexpr std::uint32_t kPtDynamic = 2; +inline constexpr std::uint32_t kPtPhdr = 6; +inline constexpr std::uint32_t kPtGnuStack = 0x6474E551; // GNU non-exec stack marker + +// Phdr p_flags +inline constexpr std::uint32_t kPfX = 1; +inline constexpr std::uint32_t kPfW = 2; +inline constexpr std::uint32_t kPfR = 4; + +// Sym st_info bind/type +inline constexpr std::uint8_t kStbLocal = 0; +inline constexpr std::uint8_t kStbGlobal = 1; +inline constexpr std::uint8_t kStbWeak = 2; +inline constexpr std::uint8_t kSttNotype = 0; +inline constexpr std::uint8_t kSttObject = 1; +inline constexpr std::uint8_t kSttFunc = 2; + +inline constexpr std::uint8_t st_info(std::uint8_t bind, std::uint8_t type) { + return static_cast((bind << 4) | (type & 0xF)); +} + +inline constexpr std::uint16_t kShnUndef = 0; +inline constexpr std::uint16_t kShnAbs = 0xFFF1; + +// x86_64 dynamic relocation types +inline constexpr std::uint32_t kRX86_64_GlobDat = 6; +inline constexpr std::uint32_t kRX86_64_JumpSlot = 7; +inline constexpr std::uint32_t kRX86_64_Relative = 8; + +// Dynamic tags +inline constexpr std::int64_t kDtNull = 0; +inline constexpr std::int64_t kDtNeeded = 1; +inline constexpr std::int64_t kDtPltRelSz = 2; +inline constexpr std::int64_t kDtPltGot = 3; +inline constexpr std::int64_t kDtHash = 4; +inline constexpr std::int64_t kDtStrtab = 5; +inline constexpr std::int64_t kDtSymtab = 6; +inline constexpr std::int64_t kDtRela = 7; // also used as DT_PLTREL value +inline constexpr std::int64_t kDtRelaSz = 8; +inline constexpr std::int64_t kDtRelaEnt = 9; +inline constexpr std::int64_t kDtStrsz = 10; +inline constexpr std::int64_t kDtSyment = 11; +inline constexpr std::int64_t kDtSoname = 14; +inline constexpr std::int64_t kDtPltRel = 20; // DT_PLTREL (type of PLT relocs) +inline constexpr std::int64_t kDtJmpRel = 23; // DT_JMPREL (vaddr of .rela.plt) +inline constexpr std::int64_t kDtFlags = 30; +inline constexpr std::int64_t kDtFlags1 = 0x6FFFFFFB; +inline constexpr std::int64_t kDtVersym = 0x6FFFFFF0; +inline constexpr std::int64_t kDtVerneed = 0x6FFFFFFE; +inline constexpr std::int64_t kDtVerneedNum = 0x6FFFFFFF; +inline constexpr std::int64_t kDfBindNow = 0x8; +inline constexpr std::int64_t kDf1Now = 0x1; + +#pragma pack(push, 1) + +struct Ehdr { + std::uint8_t e_ident[16]; + std::uint16_t e_type; + std::uint16_t e_machine; + std::uint32_t e_version; + std::uint64_t e_entry; + std::uint64_t e_phoff; + std::uint64_t e_shoff; + std::uint32_t e_flags; + std::uint16_t e_ehsize; + std::uint16_t e_phentsize; + std::uint16_t e_phnum; + std::uint16_t e_shentsize; + std::uint16_t e_shnum; + std::uint16_t e_shstrndx; +}; +static_assert(sizeof(Ehdr) == 64); + +struct Phdr { + std::uint32_t p_type; + std::uint32_t p_flags; + std::uint64_t p_offset; + std::uint64_t p_vaddr; + std::uint64_t p_paddr; + std::uint64_t p_filesz; + std::uint64_t p_memsz; + std::uint64_t p_align; +}; +static_assert(sizeof(Phdr) == 56); + +struct Shdr { + std::uint32_t sh_name; + std::uint32_t sh_type; + std::uint64_t sh_flags; + std::uint64_t sh_addr; + std::uint64_t sh_offset; + std::uint64_t sh_size; + std::uint32_t sh_link; + std::uint32_t sh_info; + std::uint64_t sh_addralign; + std::uint64_t sh_entsize; +}; +static_assert(sizeof(Shdr) == 64); + +struct Sym { + std::uint32_t st_name; + std::uint8_t st_info; + std::uint8_t st_other; + std::uint16_t st_shndx; + std::uint64_t st_value; + std::uint64_t st_size; +}; +static_assert(sizeof(Sym) == 24); + +inline constexpr std::uint8_t st_bind(std::uint8_t info) { return info >> 4; } +inline constexpr std::uint8_t st_type(std::uint8_t info) { return info & 0xF; } + +struct Rela { + std::uint64_t r_offset; + std::uint64_t r_info; + std::int64_t r_addend; +}; +static_assert(sizeof(Rela) == 24); + +struct Dyn { + std::int64_t d_tag; + std::uint64_t d_val; // unioned with d_ptr in real ELF; same size +}; +static_assert(sizeof(Dyn) == 16); + +struct Verneed { + std::uint16_t vn_version; // = 1 + std::uint16_t vn_cnt; // number of Vernaux entries + std::uint32_t vn_file; // strtab offset to library name + std::uint32_t vn_aux; // byte offset from this Verneed to first Vernaux + std::uint32_t vn_next; // byte offset to next Verneed (0 = last) +}; +static_assert(sizeof(Verneed) == 16); + +struct Vernaux { + std::uint32_t vna_hash; // ELF hash of version name + std::uint16_t vna_flags; // 0 or VER_FLG_WEAK + std::uint16_t vna_other; // version index (assigned locally) + std::uint32_t vna_name; // strtab offset to version name + std::uint32_t vna_next; // byte offset to next Vernaux (0 = last) +}; +static_assert(sizeof(Vernaux) == 16); + +#pragma pack(pop) + +// SysV ELF hash, per the ELF gABI. +inline std::uint32_t elf_hash(const char* name) { + std::uint32_t h = 0; + while (*name) { + h = (h << 4) + static_cast(*name++); + const std::uint32_t g = h & 0xF0000000u; + if (g) h ^= g >> 24; + h &= ~g; + } + return h; +} + +} // namespace voidlibc::loader diff --git a/loader/common/elf_synth.cpp b/loader/common/elf_synth.cpp new file mode 100644 index 0000000..ba88c26 --- /dev/null +++ b/loader/common/elf_synth.cpp @@ -0,0 +1,816 @@ +#include "elf_synth.hpp" + +#include "elf64.hpp" +#include "format/reloc_ir.hpp" + +#include +#include +#include +#include + +namespace voidlibc::loader { + +namespace { + +constexpr std::uint64_t kPageSize = 0x1000; + +constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) { + return (v + (a - 1)) & ~(a - 1); +} + +// Lay out as five segments: +// PT_LOAD R @ 0x0000 — Ehdr + Phdrs + .dynsym + .dynstr + .hash + [.rela.dyn] + [.rela.plt] +// PT_LOAD RX @ 0x1000 — [PLT stubs] + code +// PT_LOAD RW @ next page — [data blob] + [.got] + [.got.plt] + .dynamic +// PT_DYNAMIC — overlays the RW PT_LOAD +// PT_GNU_STACK — zero-size; tells the loader the stack is RW (not RWX) +constexpr std::uint16_t kPhdrCount = 5; + +void write32le(std::vector& buf, std::uint64_t off, std::int32_t v) { + std::uint32_t u; + std::memcpy(&u, &v, 4); + buf[off + 0] = static_cast(u); + buf[off + 1] = static_cast(u >> 8); + buf[off + 2] = static_cast(u >> 16); + buf[off + 3] = static_cast(u >> 24); +} + +// Apply all portable reloc IR entries to the combined buffer. +// +// combined = [PLT stubs (plt_size bytes)] [.text + .rodata (code blob)] +// sym_id_to_got_vaddr = sym_id → run-time vaddr of its .got slot (external GOTPCREL only) +bool apply_relocs_combined( + std::vector& combined, + const std::vector& relocs, + const std::vector& internal_syms, + const std::vector& data_syms, + const std::unordered_map& import_to_plt, + const std::unordered_map& sym_id_to_got_vaddr, + std::uint64_t plt_size, + std::uint64_t code_vaddr, + std::uint64_t data_vaddr, + std::string& error) { + using namespace voidlibc::format; + + std::unordered_map sym_offset; + sym_offset.reserve(internal_syms.size()); + for (const auto& s : internal_syms) + sym_offset.emplace(s.sym_id, s.code_offset); + + std::unordered_map data_sym_offset; + data_sym_offset.reserve(data_syms.size()); + for (const auto& s : data_syms) + data_sym_offset.emplace(s.sym_id, s.data_offset); + + auto patch32 = [&](std::uint64_t combined_off, std::int64_t v) -> bool { + if (combined_off + 4 > combined.size()) { + std::ostringstream os; + os << "reloc patch at 0x" << std::hex << combined_off + << " out of range (combined size 0x" << combined.size() << ")"; + error = os.str(); + return false; + } + write32le(combined, combined_off, static_cast(v)); + return true; + }; + + for (const auto& r : relocs) { + const std::uint64_t combined_off = plt_size + r.dst_offset; + + switch (r.op) { + case RelocOp::PC32: + case RelocOp::PC32_1: case RelocOp::PC32_2: + case RelocOp::PC32_4: case RelocOp::PC32_5: { + std::int64_t bias = 0; + if (r.op == RelocOp::PC32_1) bias = -1; + else if (r.op == RelocOp::PC32_2) bias = -2; + else if (r.op == RelocOp::PC32_4) bias = -4; + else if (r.op == RelocOp::PC32_5) bias = -5; + + // Try code blob first. + auto it = sym_offset.find(r.sym_id); + if (it != sym_offset.end()) { + const std::uint64_t target_combined = plt_size + it->second; + const std::int64_t disp = + static_cast(target_combined) + - static_cast(combined_off) + + r.addend + bias; + if (!patch32(combined_off, disp)) return false; + break; + } + // Try data blob (cross-segment, vaddr-based). + auto dit = data_sym_offset.find(r.sym_id); + if (dit != data_sym_offset.end()) { + const std::int64_t disp = + static_cast(data_vaddr + dit->second) + - static_cast(code_vaddr + combined_off) + + r.addend + bias; + if (!patch32(combined_off, disp)) return false; + break; + } + { + std::ostringstream os; + os << "PC32 reloc at 0x" << std::hex << r.dst_offset + << " references unknown sym_id " << std::dec << r.sym_id; + error = os.str(); + return false; + } + } + case RelocOp::PLT32: { + // Cross-object merge: if the sym is now defined internally, + // treat as a direct PC32 call (no PLT stub needed). + auto sit = sym_offset.find(r.sym_id); + if (sit != sym_offset.end()) { + const std::uint64_t target = plt_size + sit->second; + const std::int64_t disp = + static_cast(target) + - static_cast(combined_off) + + r.addend; + if (!patch32(combined_off, disp)) return false; + break; + } + // External symbol — route through PLT stub. + auto it = import_to_plt.find(r.sym_id); + if (it == import_to_plt.end()) { + std::ostringstream os; + os << "PLT32 reloc at 0x" << std::hex << r.dst_offset + << " references unknown import sym_id " << std::dec << r.sym_id; + error = os.str(); + return false; + } + const std::uint64_t plt_stub = static_cast(it->second + 1) * 16; + const std::int64_t disp = + static_cast(plt_stub) + + r.addend + - static_cast(combined_off); + if (!patch32(combined_off, disp)) return false; + break; + } + case RelocOp::GotPC32: + case RelocOp::GotPC32X: + case RelocOp::GotPC32XRex: { + // Check for internal sym — relax if possible. + const bool relaxable = + (r.op == RelocOp::GotPC32X || r.op == RelocOp::GotPC32XRex); + + auto it_code = sym_offset.find(r.sym_id); + auto it_data = data_sym_offset.find(r.sym_id); + const bool is_internal = + (it_code != sym_offset.end() || it_data != data_sym_offset.end()); + + if (is_internal && relaxable) { + // Relax movq sym@GOTPCREL(%rip), %reg → leaq sym(%rip), %reg + // Instruction layout: [REX] opcode(0x8B) ModRM disp32 + // ^-1 ^combined_off + // Opcode is at combined_off-2; ModRM is at combined_off-1. + if (combined_off < 3 || combined[combined_off - 2] != 0x8B) { + std::ostringstream os; + os << "GotPC32(X)Xrex relaxation at 0x" << std::hex << r.dst_offset + << ": expected 0x8B opcode at -2, got 0x" + << static_cast(combined[combined_off - 2]); + error = os.str(); + return false; + } + combined[combined_off - 2] = 0x8D; // MOV → LEA + + std::int64_t disp; + if (it_code != sym_offset.end()) { + const std::uint64_t target = plt_size + it_code->second; + disp = static_cast(target) + - static_cast(combined_off) + + r.addend; + } else { + disp = static_cast(data_vaddr + it_data->second) + - static_cast(code_vaddr + combined_off) + + r.addend; + } + if (!patch32(combined_off, disp)) return false; + break; + } + + // External sym — use the pre-allocated .got slot. + auto git = sym_id_to_got_vaddr.find(r.sym_id); + if (git == sym_id_to_got_vaddr.end()) { + std::ostringstream os; + os << "GOTPCREL reloc at 0x" << std::hex << r.dst_offset + << " sym_id " << std::dec << r.sym_id + << " has no GOT slot (internal sym must use relaxable form)"; + error = os.str(); + return false; + } + const std::int64_t disp = + static_cast(git->second) + - static_cast(code_vaddr + combined_off) + + r.addend; + if (!patch32(combined_off, disp)) return false; + break; + } + case RelocOp::Abs64: + error = "Abs64 reloc not yet supported (needs R_X86_64_RELATIVE)"; + return false; + case RelocOp::Abs32: + case RelocOp::Abs32Signed: + error = "Abs32 reloc not yet supported"; + return false; + case RelocOp::TlsLE: case RelocOp::TlsIE: + case RelocOp::TlsGD: case RelocOp::TlsLD: + error = "TLS reloc not yet supported"; + return false; + } + } + return true; +} + +// Emit PLT[0] (bootstrap) and PLT[1..nimports] into combined[0..plt_size). +void fill_plt_stubs(std::vector& combined, + std::uint64_t code_vaddr, + std::uint64_t gotplt_vaddr, + std::size_t nimports) { + if (nimports == 0) return; + + // PLT[0]: bootstrap — pushq *GOT[1](%rip) ; jmpq *GOT[2](%rip) ; nop + { + const std::uint64_t plt0_vaddr = code_vaddr; + combined[0] = 0xff; combined[1] = 0x35; + const std::int32_t d1 = static_cast( + (gotplt_vaddr + 8) - (plt0_vaddr + 6)); + write32le(combined, 2, d1); + combined[6] = 0xff; combined[7] = 0x25; + const std::int32_t d2 = static_cast( + (gotplt_vaddr + 16) - (plt0_vaddr + 12)); + write32le(combined, 8, d2); + combined[12] = 0x0f; combined[13] = 0x1f; + combined[14] = 0x40; combined[15] = 0x00; + } + + // PLT[i+1]: per-import stub + for (std::size_t i = 0; i < nimports; ++i) { + const std::uint64_t stub_off = static_cast(1 + i) * 16; + const std::uint64_t stub_vaddr = code_vaddr + stub_off; + combined[stub_off + 0] = 0xff; + combined[stub_off + 1] = 0x25; + const std::int32_t dg = static_cast( + (gotplt_vaddr + (3 + i) * 8) - (stub_vaddr + 6)); + write32le(combined, stub_off + 2, dg); + combined[stub_off + 6] = 0x68; + write32le(combined, stub_off + 7, + static_cast(static_cast(i))); + combined[stub_off + 11] = 0xe9; + const std::int32_t dp = static_cast( + static_cast(code_vaddr) + - static_cast(stub_vaddr + 16)); + write32le(combined, stub_off + 12, dp); + } +} + +} // anonymous namespace + +ElfSynthOutput synthesize_elf(const ElfSynthInput& input) { + ElfSynthOutput out{}; + + if (input.code.empty()) { + out.ok = false; + out.error = "elf_synth: code is empty"; + return out; + } + + // --- Classify imports: PLT (function calls) vs GOT data (extern variables) --- + // A sym_id referenced via PLT32 gets a PLT stub. + // A sym_id referenced via GotPC32* and not internal gets a .got slot + GLOB_DAT. + // + // Build quick lookup sets for internal and data symbols. + std::unordered_set internal_sym_ids; + for (const auto& s : input.internal_symbols) internal_sym_ids.insert(s.sym_id); + std::unordered_set data_sym_ids; + for (const auto& s : input.data_symbols) data_sym_ids.insert(s.sym_id); + + // PLT-needed imports (referenced via PLT32 reloc). + std::unordered_map import_to_plt; + // GOT-data imports (external sym referenced via GotPC32*; slot index within .got). + std::unordered_map got_data_import_to_slot; + { + std::uint32_t plt_idx = 0; + std::uint32_t got_slot = 0; + using format::RelocOp; + for (const auto& r : input.relocs) { + if (r.op == RelocOp::PLT32) { + // Skip syms that are internally defined (cross-object resolution). + if (!internal_sym_ids.count(r.sym_id) && + !data_sym_ids.count(r.sym_id) && + !import_to_plt.count(r.sym_id)) + import_to_plt.emplace(r.sym_id, plt_idx++); + } else if (r.op == RelocOp::GotPC32 || + r.op == RelocOp::GotPC32X || + r.op == RelocOp::GotPC32XRex) { + // Only external (non-internal, non-data) syms need GOT slots. + if (!internal_sym_ids.count(r.sym_id) && + !data_sym_ids.count(r.sym_id) && + !got_data_import_to_slot.count(r.sym_id)) { + got_data_import_to_slot.emplace(r.sym_id, got_slot++); + } + } + } + } + const std::size_t nimports = import_to_plt.size(); // PLT stubs + const std::uint32_t ngot_data = static_cast(got_data_import_to_slot.size()); + + // --- Build combined buffer: [PLT stubs][.text + .rodata] --- + const std::uint64_t plt_size = nimports > 0 + ? static_cast(1 + nimports) * 16 + : 0; + std::vector combined(plt_size + input.code.size(), 0); + std::memcpy(combined.data() + plt_size, input.code.data(), input.code.size()); + + // --- Compute key vaddrs before reloc patching --- + // RX segment: code_vaddr = kPageSize + // RW segment: starts at next page after RX + const std::uint64_t data_blob_size = input.data_blob.size(); + const std::uint64_t rw_start_prelim = + align_up(kPageSize + plt_size + input.code.size(), kPageSize); + const std::uint64_t data_vaddr = rw_start_prelim; // data blob is first in RW + + // .got (GLOB_DAT slots) comes after data blob (8-byte aligned). + const std::uint64_t got_data_vaddr_prelim = + align_up(rw_start_prelim + data_blob_size, 8); + + // Build sym_id → GOT slot vaddr map for apply_relocs_combined. + std::unordered_map sym_id_to_got_vaddr; + for (const auto& [sym_id, slot_idx] : got_data_import_to_slot) + sym_id_to_got_vaddr.emplace(sym_id, got_data_vaddr_prelim + slot_idx * 8); + + // --- Apply relocs --- + if (!input.relocs.empty()) { + std::string reloc_err; + if (!apply_relocs_combined(combined, input.relocs, + input.internal_symbols, input.data_symbols, + import_to_plt, + sym_id_to_got_vaddr, + plt_size, + kPageSize, // code_vaddr + data_vaddr, + reloc_err)) { + out.ok = false; + out.error = "elf_synth: " + reloc_err; + return out; + } + } + + // --- Build .dynstr --- + std::vector dynstr; + dynstr.push_back('\0'); + + std::vector export_name_offs; + export_name_offs.reserve(input.exports.size()); + for (const auto& e : input.exports) { + export_name_offs.push_back(static_cast(dynstr.size())); + dynstr.insert(dynstr.end(), e.name.begin(), e.name.end()); + dynstr.push_back('\0'); + } + + // All imports (PLT + GOT data) get dynstr entries. + std::vector import_name_offs; + import_name_offs.reserve(input.imports.size()); + for (const auto& im : input.imports) { + import_name_offs.push_back(static_cast(dynstr.size())); + dynstr.insert(dynstr.end(), im.name.begin(), im.name.end()); + dynstr.push_back('\0'); + } + + // DT_NEEDED entries: one per distinct import library. + // When input.needed_libs is set explicitly (--need), use that verbatim. + // Otherwise derive from import.library fields; fall back to libc.so.6 if + // we have imports but no per-import library information. + std::vector needed_name_offs; + { + std::vector libs; + if (!input.needed_libs.empty()) { + libs = input.needed_libs; + } else { + // Collect unique libraries in insertion order. + std::vector seen_order; + std::unordered_map seen; + for (const auto& im : input.imports) { + const std::string& lib = im.library.empty() ? std::string{"libc.so.6"} : im.library; + if (seen.emplace(lib, true).second) + seen_order.push_back(lib); + } + libs = std::move(seen_order); + if (libs.empty() && !input.imports.empty()) + libs.push_back("libc.so.6"); + } + for (const auto& lib : libs) { + needed_name_offs.push_back(static_cast(dynstr.size())); + dynstr.insert(dynstr.end(), lib.begin(), lib.end()); + dynstr.push_back('\0'); + } + } + + std::uint32_t soname_off = 0; + if (!input.soname.empty()) { + soname_off = static_cast(dynstr.size()); + dynstr.insert(dynstr.end(), input.soname.begin(), input.soname.end()); + dynstr.push_back('\0'); + } + + // Build sym_id → .dynsym index map for all imports (needed for GLOB_DAT r_info). + const std::size_t nexports = input.exports.size(); + const std::size_t nall_imports = input.imports.size(); + std::unordered_map sym_id_to_dynsym; + for (std::size_t i = 0; i < nall_imports; ++i) + sym_id_to_dynsym[input.imports[i].sym_id] = + static_cast(1 + nexports + i); + + // --- Build GNU symbol versioning tables (Phase C) --- + // Assign local version indices starting at 2 for unique (library, version_name) pairs. + // Index 0 = VER_NDX_LOCAL, 1 = VER_NDX_GLOBAL (unversioned), 2+ = requirements. + struct VerEntry { + std::string library; + std::string version_name; + std::uint32_t hash = 0; + std::uint16_t flags = 0; + std::uint16_t index = 0; // assigned version index + }; + std::vector ver_entries; // unique versioned requirements, in order + // per-import version index (parallel to input.imports); 1 if unversioned + std::vector import_ver_idx(nall_imports, 1); + const bool needs_versioning = [&] { + for (const auto& im : input.imports) + if (!im.version_name.empty()) return true; + return false; + }(); + if (needs_versioning) { + std::uint16_t next_idx = 2; + std::unordered_map ver_key_to_idx; + for (std::size_t i = 0; i < nall_imports; ++i) { + const auto& im = input.imports[i]; + if (im.version_name.empty()) continue; + const std::string key = im.library + '\0' + im.version_name; + auto [it, inserted] = ver_key_to_idx.emplace(key, next_idx); + if (inserted) { + VerEntry ve; + ve.library = im.library.empty() ? "libc.so.6" : im.library; + ve.version_name = im.version_name; + ve.hash = im.version_hash; + ve.flags = im.version_flags; + ve.index = next_idx++; + ver_entries.push_back(std::move(ve)); + } + import_ver_idx[i] = it->second; + } + } + + // Build .gnu.version bytes: one uint16_t per dynsym entry. + // [0]=local(0), [1..nexports]=global(1), [nexports+1..]=per-import index. + std::vector gnu_version_bytes; + // Build .gnu.version_r bytes: grouped by library. + std::vector gnu_verneed_bytes; + std::uint32_t n_verneed = 0; // number of Verneed records (for DT_VERNEEDNUM) + + if (needs_versioning) { + const std::uint64_t ndynsym_val = 1u + nexports + nall_imports; + gnu_version_bytes.resize(ndynsym_val * 2, 0); + // [0] stays 0 (VER_NDX_LOCAL for null sym); exports get 1 (VER_NDX_GLOBAL). + for (std::uint64_t i = 0; i < nexports; ++i) { + std::uint16_t vi = 1; + std::memcpy(gnu_version_bytes.data() + (1 + i) * 2, &vi, 2); + } + for (std::size_t i = 0; i < nall_imports; ++i) { + std::uint16_t vi = import_ver_idx[i]; + std::memcpy(gnu_version_bytes.data() + (1 + nexports + i) * 2, &vi, 2); + } + // Align to 8 bytes. + while (gnu_version_bytes.size() % 8) gnu_version_bytes.push_back(0); + + // Build .gnu.version_r: group VerEntries by library. + // Use the dynstr already being built. We need to add library + version names + // to dynstr now, so we interleave the strtab build here. + // Collect unique (library) groups preserving insertion order. + std::vector vn_libs_order; + std::unordered_map> vn_lib_to_entries; + for (std::size_t i = 0; i < ver_entries.size(); ++i) { + auto [it, inserted] = vn_lib_to_entries.emplace(ver_entries[i].library, + std::vector{}); + if (inserted) vn_libs_order.push_back(ver_entries[i].library); + it->second.push_back(i); + } + n_verneed = static_cast(vn_libs_order.size()); + + // Pre-compute strtab offsets for all strings we'll add. + // Note: dynstr is still being built so these come after DT_NEEDED/soname entries. + struct VnStrings { std::uint32_t lib_off; std::vector ver_offs; }; + std::vector vn_strs; + for (const auto& lib : vn_libs_order) { + VnStrings vs; + vs.lib_off = static_cast(dynstr.size()); + dynstr.insert(dynstr.end(), lib.begin(), lib.end()); dynstr.push_back('\0'); + for (std::size_t ei : vn_lib_to_entries[lib]) { + vs.ver_offs.push_back(static_cast(dynstr.size())); + const std::string& vn = ver_entries[ei].version_name; + dynstr.insert(dynstr.end(), vn.begin(), vn.end()); dynstr.push_back('\0'); + } + vn_strs.push_back(std::move(vs)); + } + + // Now build the raw Verneed + Vernaux binary blob. + for (std::size_t li = 0; li < vn_libs_order.size(); ++li) { + const auto& lib = vn_libs_order[li]; + const auto& idxs = vn_lib_to_entries[lib]; + const auto& vstrs = vn_strs[li]; + const bool last_lib = (li + 1 == vn_libs_order.size()); + + Verneed vn{}; + vn.vn_version = 1; + vn.vn_cnt = static_cast(idxs.size()); + vn.vn_file = vstrs.lib_off; + vn.vn_aux = sizeof(Verneed); + vn.vn_next = last_lib ? 0u + : static_cast(sizeof(Verneed) + idxs.size() * sizeof(Vernaux)); + + const std::size_t vn_off = gnu_verneed_bytes.size(); + gnu_verneed_bytes.resize(vn_off + sizeof(Verneed), 0); + std::memcpy(gnu_verneed_bytes.data() + vn_off, &vn, sizeof(vn)); + + for (std::size_t ai = 0; ai < idxs.size(); ++ai) { + const auto& ve = ver_entries[idxs[ai]]; + const bool last_aux = (ai + 1 == idxs.size()); + Vernaux va{}; + va.vna_hash = ve.hash; + va.vna_flags = ve.flags; + va.vna_other = ve.index; + va.vna_name = vstrs.ver_offs[ai]; + va.vna_next = last_aux ? 0u : static_cast(sizeof(Vernaux)); + const std::size_t va_off = gnu_verneed_bytes.size(); + gnu_verneed_bytes.resize(va_off + sizeof(Vernaux), 0); + std::memcpy(gnu_verneed_bytes.data() + va_off, &va, sizeof(va)); + } + } + while (gnu_verneed_bytes.size() % 8) gnu_verneed_bytes.push_back(0); + } + + // --- Plan segment 0 (RO) layout --- + const std::uint64_t phdr_off = sizeof(Ehdr); + const std::uint64_t phdr_size = static_cast(kPhdrCount) * sizeof(Phdr); + + const std::uint64_t ndynsym = 1u + nexports + nall_imports; + const std::uint64_t dynsym_off = phdr_off + phdr_size; + const std::uint64_t dynsym_size = ndynsym * sizeof(Sym); + + const std::uint64_t dynstr_off = dynsym_off + dynsym_size; + const std::uint64_t dynstr_size = dynstr.size(); + + const std::uint32_t nbuckets = 1; + const std::uint32_t nchain = static_cast(ndynsym); + const std::uint64_t hash_off = align_up(dynstr_off + dynstr_size, 8); + const std::uint64_t hash_size = (2u + nbuckets + nchain) * sizeof(std::uint32_t); + + // .rela.dyn — R_X86_64_GLOB_DAT for each external GOTPCREL import. + const std::uint64_t reladyn_off = align_up(hash_off + hash_size, 8); + const std::uint64_t reladyn_size = ngot_data * sizeof(Rela); + + const std::uint64_t relaplt_off = align_up(reladyn_off + reladyn_size, 8); + const std::uint64_t relaplt_size = nimports * sizeof(Rela); + + // .gnu.version (SHT_GNU_versym) — only emitted when needs_versioning. + const std::uint64_t gnuver_off = align_up(relaplt_off + relaplt_size, 2); + const std::uint64_t gnuver_size = gnu_version_bytes.size(); + // .gnu.version_r (SHT_GNU_verneed) + const std::uint64_t gnuvnr_off = align_up(gnuver_off + gnuver_size, 8); + const std::uint64_t gnuvnr_size = gnu_verneed_bytes.size(); + + const std::uint64_t seg0_filesz = gnuvnr_off + gnuvnr_size; + if (seg0_filesz > kPageSize) { + out.ok = false; + out.error = "elf_synth: RO segment exceeds one page; " + "split layout not yet supported"; + return out; + } + + // --- Plan segment 1 (RX) layout --- + const std::uint64_t code_off = kPageSize; + const std::uint64_t code_size = combined.size(); + const std::uint64_t code_vaddr = kPageSize; + + // --- Plan segment 2 (RW) layout: [data blob] [.got] [.got.plt] [.dynamic] --- + const std::uint64_t rw_start = align_up(code_off + code_size, kPageSize); + const std::uint64_t data_off = rw_start; + const std::uint64_t got_data_off = align_up(data_off + data_blob_size, 8); + const std::uint64_t got_data_size = ngot_data * sizeof(std::uint64_t); + const std::uint64_t gotplt_off = align_up(got_data_off + got_data_size, 8); + const std::uint64_t gotplt_size = nimports > 0 + ? (3u + nimports) * sizeof(std::uint64_t) + : 0; + const std::uint64_t dyn_off = align_up(gotplt_off + gotplt_size, 8); + const std::uint64_t gotplt_vaddr = gotplt_off; // file_offset == vaddr + + // Verify consistency: got_data_off must equal got_data_vaddr_prelim. + // (Both compute align_up(rw_start + data_blob_size, 8).) + + // Fill PLT stubs now that we know gotplt_vaddr. + fill_plt_stubs(combined, code_vaddr, gotplt_vaddr, nimports); + + // --- Build .dynamic --- + std::vector dyn; + auto add_dyn = [&](std::int64_t tag, std::uint64_t val) { + dyn.push_back(Dyn{tag, val}); + }; + add_dyn(kDtHash, hash_off); + add_dyn(kDtStrtab, dynstr_off); + add_dyn(kDtSymtab, dynsym_off); + add_dyn(kDtStrsz, dynstr_size); + add_dyn(kDtSyment, sizeof(Sym)); + if (soname_off) add_dyn(kDtSoname, soname_off); + for (std::uint32_t off : needed_name_offs) + add_dyn(kDtNeeded, off); + if (ngot_data > 0) { + add_dyn(kDtRela, reladyn_off); + add_dyn(kDtRelaSz, reladyn_size); + add_dyn(kDtRelaEnt, sizeof(Rela)); + } + if (nimports > 0) { + add_dyn(kDtPltGot, gotplt_vaddr); + add_dyn(kDtPltRelSz, relaplt_size); + add_dyn(kDtPltRel, static_cast(kDtRela)); + add_dyn(kDtJmpRel, relaplt_off); + } + if (needs_versioning) { + add_dyn(kDtVersym, gnuver_off); + add_dyn(kDtVerneed, gnuvnr_off); + add_dyn(kDtVerneedNum, static_cast(n_verneed)); + } + add_dyn(kDtFlags, static_cast(kDfBindNow)); + add_dyn(kDtFlags1, static_cast(kDf1Now)); + add_dyn(kDtNull, 0); + + const std::uint64_t dyn_size = dyn.size() * sizeof(Dyn); + const std::uint64_t file_size = dyn_off + dyn_size; + + // --- Emit file --- + out.bytes.assign(file_size, 0); + auto write_at = [&](std::uint64_t off, const void* src, std::uint64_t n) { + std::memcpy(out.bytes.data() + off, src, n); + }; + + // Ehdr + Ehdr eh{}; + eh.e_ident[0] = kElfMag0; eh.e_ident[1] = kElfMag1; + eh.e_ident[2] = kElfMag2; eh.e_ident[3] = kElfMag3; + eh.e_ident[4] = kElfClass64; + eh.e_ident[5] = kElfData2LSB; + eh.e_ident[6] = kElfVersionCurrent; + eh.e_ident[7] = kElfOsAbiSysV; + eh.e_type = kEtDyn; + eh.e_machine = kEmX86_64; + eh.e_version = kEvCurrent; + eh.e_entry = 0; + eh.e_phoff = phdr_off; + eh.e_shoff = 0; + eh.e_flags = 0; + eh.e_ehsize = sizeof(Ehdr); + eh.e_phentsize = sizeof(Phdr); + eh.e_phnum = kPhdrCount; + eh.e_shentsize = 0; + eh.e_shnum = 0; + eh.e_shstrndx = 0; + write_at(0, &eh, sizeof(eh)); + + // Phdrs + Phdr phdrs[kPhdrCount] = {}; + phdrs[0].p_type = kPtLoad; phdrs[0].p_flags = kPfR; + phdrs[0].p_offset = 0; phdrs[0].p_vaddr = 0; phdrs[0].p_paddr = 0; + phdrs[0].p_filesz = seg0_filesz; phdrs[0].p_memsz = seg0_filesz; + phdrs[0].p_align = kPageSize; + + phdrs[1].p_type = kPtLoad; phdrs[1].p_flags = kPfR | kPfX; + phdrs[1].p_offset = code_off; phdrs[1].p_vaddr = code_vaddr; phdrs[1].p_paddr = code_vaddr; + phdrs[1].p_filesz = code_size; phdrs[1].p_memsz = code_size; + phdrs[1].p_align = kPageSize; + + phdrs[2].p_type = kPtLoad; phdrs[2].p_flags = kPfR | kPfW; + phdrs[2].p_offset = rw_start; phdrs[2].p_vaddr = rw_start; phdrs[2].p_paddr = rw_start; + phdrs[2].p_filesz = dyn_off + dyn_size - rw_start; + phdrs[2].p_memsz = phdrs[2].p_filesz; + phdrs[2].p_align = kPageSize; + + phdrs[3].p_type = kPtDynamic; phdrs[3].p_flags = kPfR | kPfW; + phdrs[3].p_offset = dyn_off; phdrs[3].p_vaddr = dyn_off; phdrs[3].p_paddr = dyn_off; + phdrs[3].p_filesz = dyn_size; phdrs[3].p_memsz = dyn_size; + phdrs[3].p_align = 8; + + phdrs[4].p_type = kPtGnuStack; phdrs[4].p_flags = kPfR | kPfW; + phdrs[4].p_align = 16; + + write_at(phdr_off, phdrs, sizeof(phdrs)); + + // .dynsym: [0]=undef, [1..nexports]=exports, [nexports+1..]=all imports + { + std::vector syms(ndynsym); + syms[0] = Sym{}; + for (std::size_t i = 0; i < nexports; ++i) { + const auto& e = input.exports[i]; + Sym s{}; + s.st_name = export_name_offs[i]; + s.st_info = st_info(e.weak ? kStbWeak : kStbGlobal, + e.is_function ? kSttFunc : kSttObject); + s.st_shndx = 1; + s.st_value = code_vaddr + plt_size + e.code_offset; + s.st_size = e.size; + syms[i + 1] = s; + } + for (std::size_t i = 0; i < nall_imports; ++i) { + Sym s{}; + s.st_name = import_name_offs[i]; + s.st_info = st_info(kStbGlobal, kSttObject); // may be func or obj; RTLD doesn't care + s.st_shndx = kShnUndef; + s.st_value = 0; + s.st_size = 0; + syms[nexports + 1 + i] = s; + } + write_at(dynsym_off, syms.data(), dynsym_size); + } + + // .dynstr + write_at(dynstr_off, dynstr.data(), dynstr_size); + + // .hash — single-bucket chain through all exported symbols + { + std::vector hash_tab(2 + nbuckets + nchain, 0); + hash_tab[0] = nbuckets; + hash_tab[1] = nchain; + if (nexports > 0) { + hash_tab[2] = 1; + for (std::uint32_t i = 1; i + 1 < static_cast(nexports + 1); ++i) + hash_tab[2 + nbuckets + i] = i + 1; + } + write_at(hash_off, hash_tab.data(), hash_size); + } + + // .rela.dyn — R_X86_64_GLOB_DAT for each external GOTPCREL import + if (ngot_data > 0) { + std::vector rela_dyn; + rela_dyn.reserve(ngot_data); + for (const auto& [sym_id, slot_idx] : got_data_import_to_slot) { + const std::uint64_t got_slot_vaddr = got_data_off + slot_idx * 8; + const auto dsym_it = sym_id_to_dynsym.find(sym_id); + if (dsym_it == sym_id_to_dynsym.end()) { + out.ok = false; + out.error = "elf_synth: GOT import sym_id not in .dynsym"; + return out; + } + Rela r{}; + r.r_offset = got_slot_vaddr; + r.r_info = (static_cast(dsym_it->second) << 32) | kRX86_64_GlobDat; + r.r_addend = 0; + rela_dyn.push_back(r); + } + write_at(reladyn_off, rela_dyn.data(), reladyn_size); + } + + // .gnu.version + .gnu.version_r (emitted only when needs_versioning) + if (needs_versioning) { + if (!gnu_version_bytes.empty()) + write_at(gnuver_off, gnu_version_bytes.data(), gnu_version_bytes.size()); + if (!gnu_verneed_bytes.empty()) + write_at(gnuvnr_off, gnu_verneed_bytes.data(), gnu_verneed_bytes.size()); + } + + // .rela.plt — R_X86_64_JUMP_SLOT for each PLT import + if (nimports > 0) { + // Build ordered list of PLT imports (import_to_plt maps sym_id → index). + std::vector plt_syms(nimports); + for (const auto& im : input.imports) { + auto it = import_to_plt.find(im.sym_id); + if (it != import_to_plt.end()) + plt_syms[it->second] = &im; + } + std::vector rela_plt(nimports); + for (std::size_t i = 0; i < nimports; ++i) { + const std::uint64_t got_slot = gotplt_vaddr + (3 + i) * sizeof(std::uint64_t); + const std::uint64_t dsym_idx = sym_id_to_dynsym.at(plt_syms[i]->sym_id); + rela_plt[i].r_offset = got_slot; + rela_plt[i].r_info = (dsym_idx << 32) | kRX86_64_JumpSlot; + rela_plt[i].r_addend = 0; + } + write_at(relaplt_off, rela_plt.data(), relaplt_size); + } + + // Code (PLT stubs + patched .text + .rodata) + write_at(code_off, combined.data(), code_size); + + // Data blob (.data + .bss zeros) + if (!input.data_blob.empty()) + write_at(data_off, input.data_blob.data(), data_blob_size); + + // .got (GLOB_DAT slots) — zeroed (RTLD fills with GLOB_DAT at load time) + // out.bytes is already zero-initialised, nothing to write. + + // .got.plt — zeroed; RTLD fills with JUMP_SLOT targets (DF_BIND_NOW / RTLD_NOW). + // out.bytes is already zero-initialised. + + // .dynamic + write_at(dyn_off, dyn.data(), dyn_size); + + out.code_vaddr = code_vaddr + plt_size; + return out; +} + +} // namespace voidlibc::loader diff --git a/loader/common/elf_synth.hpp b/loader/common/elf_synth.hpp new file mode 100644 index 0000000..53bde23 --- /dev/null +++ b/loader/common/elf_synth.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include "format/reloc_ir.hpp" + +#include +#include +#include + +namespace voidlibc::loader { + +struct ExportedSymbol { + std::string name; // C-name (null-terminated when written) + std::uint64_t code_offset; // offset into the code blob + std::uint64_t size; // 0 if unknown + bool is_function = true; + bool weak = false; +}; + +// For Slice 1B the synthesizer needs to resolve internal relocations +// at synthesis time (PC-relative). Each `InternalSymbol` is a defined +// symbol referenced by a relocation, identified by `sym_id` matching +// the relocation's sym_id, and located at `code_offset` within the +// code blob. +struct InternalSymbol { + std::uint32_t sym_id = 0; + std::uint64_t code_offset = 0; + std::string name; // for error messages +}; + +// External (undefined) symbol resolved by the native linker via .rela.plt. +struct ImportedSymbol { + std::uint32_t sym_id = 0; + std::string name; + std::string library; // DT_NEEDED soname that provides this symbol; "" → default libc + // GNU symbol version requirement forwarded from input .o (SHT_GNU_verneed). + // Empty version_name → emit VER_NDX_GLOBAL (1) in .gnu.version; no .gnu.version_r entry. + std::string version_name; + std::uint32_t version_hash = 0; + std::uint16_t version_flags = 0; +}; + +// Writable symbol in the data blob (mapped in the RW segment). +// PC32 relocs from .text to data symbols are patched using vaddr arithmetic. +struct DataSymbol { + std::uint32_t sym_id = 0; + std::uint64_t data_offset = 0; // byte offset within data_blob + std::string name; +}; + +struct ElfSynthInput { + std::vector code; + std::vector exports; + std::vector relocs; + std::vector internal_symbols; + std::vector imports; + std::vector data_blob; // .data + .bss (RW) + std::vector data_symbols; + std::string soname; + // Explicit DT_NEEDED entries for the synthesized ELF's .dynamic section. + // Empty = no host dependencies (statically linked VLC, ldd shows "statically linked"). + // Set via voidlink --need at pack time. + std::vector needed_libs; +}; + +struct ElfSynthOutput { + std::vector bytes; // synthesized in-memory ELF64 DSO + std::uint64_t code_vaddr = 0; // base vaddr where code is mapped + std::string error; // empty on success + bool ok = true; +}; + +// Produce a valid in-memory ELF64 DSO (ET_DYN, EM_X86_64) that dlopen +// will accept. Single contiguous .text + .dynsym/.dynstr/.hash/.dynamic. +// No relocations, imports, or section headers — enough for M1 export. +ElfSynthOutput synthesize_elf(const ElfSynthInput& input); + +} // namespace voidlibc::loader diff --git a/loader/linux/CMakeLists.txt b/loader/linux/CMakeLists.txt new file mode 100644 index 0000000..127be3a --- /dev/null +++ b/loader/linux/CMakeLists.txt @@ -0,0 +1,13 @@ +# Placeholder; the Linux handoff source is added in the next task. +add_library(voidlibc_loader_linux STATIC + handoff.cpp +) +target_link_libraries(voidlibc_loader_linux + PUBLIC voidlibc_loader_common + PRIVATE ${CMAKE_DL_LIBS} +) +set_target_properties(voidlibc_loader_linux PROPERTIES POSITION_INDEPENDENT_CODE ON) +install(TARGETS voidlibc_loader_linux + EXPORT VoidLibCTargets + ARCHIVE DESTINATION lib +) diff --git a/loader/linux/handoff.cpp b/loader/linux/handoff.cpp new file mode 100644 index 0000000..c1790d0 --- /dev/null +++ b/loader/linux/handoff.cpp @@ -0,0 +1,136 @@ +#include "handoff.hpp" + +#ifdef __linux__ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace voidlibc::loader::linux_handoff { + +namespace { + +int memfd_create_sys(const char* name, unsigned int flags) { + // glibc has memfd_create() but only in recent versions; go via + // syscall to keep this independent of host libc feature levels. + return static_cast(::syscall(SYS_memfd_create, name, flags)); +} + +bool write_all(int fd, const std::uint8_t* p, std::size_t n) { + while (n > 0) { + const auto w = ::write(fd, p, n); + if (w < 0) { + if (errno == EINTR) continue; + return false; + } + if (w == 0) return false; + p += static_cast(w); + n -= static_cast(w); + } + return true; +} + +std::string errno_msg(const char* where) { + char buf[256]; + std::snprintf(buf, sizeof(buf), "%s: %s", where, std::strerror(errno)); + return std::string(buf); +} + +} // namespace + +LoadResult dlopen_buffer(const std::vector& elf_bytes, + const char* debug_name) { + LoadResult r{}; + + int fd = memfd_create_sys(debug_name ? debug_name : "voidlibc.elf", 0); + bool used_tmpfile = false; + char tmpl[] = "/tmp/voidlibc.elf.XXXXXX"; + if (fd < 0) { + // Fallback: O_TMPFILE on /tmp (kernel < 3.17 won't have memfd). + fd = ::open("/tmp", + O_TMPFILE | O_RDWR | O_EXCL, + S_IRUSR | S_IWUSR | S_IXUSR); + if (fd < 0) { + // Final fallback: a named temp file we manually unlink. + fd = ::mkstemp(tmpl); + if (fd < 0) { + r.error = errno_msg("memfd/tmpfile open"); + return r; + } + used_tmpfile = true; + } + } + + if (!write_all(fd, elf_bytes.data(), elf_bytes.size())) { + r.error = errno_msg("write elf bytes"); + ::close(fd); + if (used_tmpfile) ::unlink(tmpl); + return r; + } + + // dlopen via /proc/self/fd/N — this works for memfds and unnamed + // O_TMPFILE files. + char path[64]; + std::snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + + // Use RTLD_NEXT to bypass the libvoid dlopen interposer (which shadows + // dlopen in the consumer binary) and call the real OS dlopen directly. + using real_dlopen_t = void* (*)(const char*, int); + static real_dlopen_t real_dlopen = + reinterpret_cast(::dlsym(RTLD_NEXT, "dlopen")); + + // RTLD_NOW catches resolution failures at load time; cleaner errors + // than RTLD_LAZY where a missing symbol surfaces on first call. + void* h = real_dlopen(path, RTLD_NOW); + if (!h) { + const char* dl = ::dlerror(); + r.error = std::string("dlopen: ") + (dl ? dl : "unknown"); + ::close(fd); + if (used_tmpfile) ::unlink(tmpl); + return r; + } + + // Once dlopen has mapped the segments, we can close the fd. The + // mappings remain valid until dlclose. Same for O_TMPFILE (and the + // mkstemp fallback, where we already-unlinked-via-fd-only-open). + ::close(fd); + if (used_tmpfile) ::unlink(tmpl); + + r.dl_handle = h; + r.ok = true; + return r; +} + +void* sym(void* handle, const char* name) { + if (!handle || !name) return nullptr; + return ::dlsym(handle, name); +} + +int close_(void* handle) { + if (!handle) return 0; + return ::dlclose(handle); +} + +} // namespace voidlibc::loader::linux_handoff + +#else // stub for non-Linux builds so the target compiles on all platforms + +namespace voidlibc::loader::linux_handoff { + +LoadResult dlopen_buffer(const std::vector&, const char*) { + return {{}, "linux_handoff not available on this platform", false}; +} +void* sym(void*, const char*) { return nullptr; } +int close_(void*) { return 0; } + +} // namespace voidlibc::loader::linux_handoff + +#endif // __linux__ diff --git a/loader/linux/handoff.hpp b/loader/linux/handoff.hpp new file mode 100644 index 0000000..93875d2 --- /dev/null +++ b/loader/linux/handoff.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include +#include +#include + +namespace voidlibc::loader::linux_handoff { + +struct LoadResult { + void* dl_handle = nullptr; // opaque handle from dlopen + std::string error; // empty on success + bool ok = false; +}; + +// Take a synthesized ELF DSO buffer, place it in a memfd (or fallback +// temp file), and dlopen it. Returns the raw dlopen handle. Callers +// own it and must dlclose() it. +LoadResult dlopen_buffer(const std::vector& elf_bytes, + const char* debug_name = "voidlibc.elf"); + +// Thin wrappers so the caller never includes . +void* sym(void* handle, const char* name); +int close_(void* handle); + +} // namespace voidlibc::loader::linux_handoff diff --git a/loader/macos/CMakeLists.txt b/loader/macos/CMakeLists.txt new file mode 100644 index 0000000..af7cb40 --- /dev/null +++ b/loader/macos/CMakeLists.txt @@ -0,0 +1,15 @@ +add_library(voidlibc_loader_macos STATIC + macho_synth.cpp + handoff.cpp +) +target_link_libraries(voidlibc_loader_macos + PUBLIC voidlibc_loader_common +) +if(APPLE) + target_link_libraries(voidlibc_loader_macos PRIVATE ${CMAKE_DL_LIBS}) +endif() +set_target_properties(voidlibc_loader_macos PROPERTIES POSITION_INDEPENDENT_CODE ON) +install(TARGETS voidlibc_loader_macos + EXPORT VoidLibCTargets + ARCHIVE DESTINATION lib +) diff --git a/loader/macos/handoff.cpp b/loader/macos/handoff.cpp new file mode 100644 index 0000000..b852cfb --- /dev/null +++ b/loader/macos/handoff.cpp @@ -0,0 +1,76 @@ +#include "handoff.hpp" + +#ifdef __APPLE__ + +#include +#include +#include +#include +#include + +namespace voidlibc::loader::macos_handoff { + +LoadResult dlopen_buffer(const std::vector& blob) { + LoadResult res{}; + + // Write blob to a temp file, dlopen it, then unlink. + // macOS dyld requires a path — no memfd_create equivalent. + char tmp[256]; + const char* tmpdir = ::getenv("TMPDIR"); + if (!tmpdir || !*tmpdir) tmpdir = "/tmp"; + std::snprintf(tmp, sizeof(tmp), "%s/voidlib.%d.XXXXXX.dylib", tmpdir, static_cast(::getpid())); + + const int fd = ::mkstemps(tmp, 6 /* len(".dylib") */); + if (fd < 0) { res.error = std::string("mkstemps: ") + std::strerror(errno); return res; } + + const std::uint8_t* p = blob.data(); + std::size_t remaining = blob.size(); + while (remaining > 0) { + const ssize_t n = ::write(fd, p, remaining); + if (n <= 0) { + ::close(fd); ::unlink(tmp); + res.error = std::string("write: ") + std::strerror(errno); return res; + } + p += n; remaining -= static_cast(n); + } + ::close(fd); + + // chmod +x so dyld will map it as executable + ::chmod(tmp, 0755); + + void* handle = ::dlopen(tmp, RTLD_NOW | RTLD_LOCAL); + ::unlink(tmp); + if (!handle) { + res.error = ::dlerror() ? ::dlerror() : "dlopen failed"; + return res; + } + res.dl_handle = handle; + res.ok = true; + return res; +} + +void* sym(void* handle, const char* name) { + if (!handle || !name) return nullptr; + return ::dlsym(handle, name); +} + +int close_(void* handle) { + if (!handle) return 0; + return ::dlclose(handle); +} + +} // namespace voidlibc::loader::macos_handoff + +#else // stub compilation so non-macOS hosts can include this TU + +namespace voidlibc::loader::macos_handoff { + +LoadResult dlopen_buffer(const std::vector&) { + return {{}, "macos_handoff not available on this platform", false}; +} +void* sym(void*, const char*) { return nullptr; } +int close_(void*) { return 0; } + +} // namespace voidlibc::loader::macos_handoff + +#endif // __APPLE__ diff --git a/loader/macos/handoff.hpp b/loader/macos/handoff.hpp new file mode 100644 index 0000000..3ffb8e5 --- /dev/null +++ b/loader/macos/handoff.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include +#include +#include + +namespace voidlibc::loader::macos_handoff { + +struct LoadResult { + void* dl_handle = nullptr; + std::string error; + bool ok = false; +}; + +// Write `blob` to a per-process temp file under $TMPDIR and call dlopen on it. +// The temp file is unlinked after dlopen succeeds (the mapping keeps the data alive). +// Returns a native dlopen handle on success. +LoadResult dlopen_buffer(const std::vector& blob); + +void* sym(void* handle, const char* name); +int close_(void* handle); + +} // namespace voidlibc::loader::macos_handoff diff --git a/loader/macos/macho_synth.cpp b/loader/macos/macho_synth.cpp new file mode 100644 index 0000000..2c8002c --- /dev/null +++ b/loader/macos/macho_synth.cpp @@ -0,0 +1,677 @@ +#include "macho_synth.hpp" + +#include +#include +#include +#include + +namespace voidlibc::loader::macos { + +namespace { + +// ── On-disk structs (x86_64 LE host = no byte-swap needed) ───────────────── + +constexpr std::uint32_t kMhMagic64 = 0xFEEDFACFu; +constexpr std::int32_t kCpuTypeX86_64 = 0x01000007; +constexpr std::int32_t kCpuSubX86All = 3; +constexpr std::uint32_t kMhDylib = 6; +// DYLDLINK | TWOLEVEL | NO_REEXPORTED_DYLIBS +constexpr std::uint32_t kMhFlags = 0x00100084u; + +constexpr std::uint32_t kLcSegment64 = 0x19u; +constexpr std::uint32_t kLcDyldInfoOnly = 0x80000022u; +constexpr std::uint32_t kLcSymtab = 0x02u; +constexpr std::uint32_t kLcDysymtab = 0x0bu; +constexpr std::uint32_t kLcIdDylib = 0x0du; +constexpr std::uint32_t kLcLoadDylib = 0x0cu; +constexpr std::uint32_t kLcVersionMinMacOS = 0x24u; + +constexpr std::int32_t kVmProtR = 0x1; +constexpr std::int32_t kVmProtW = 0x2; +constexpr std::int32_t kVmProtX = 0x4; + +constexpr std::uint32_t kSAttrPureInstr = 0x80000000u; +constexpr std::uint32_t kSAttrSomeInstr = 0x00000400u; +constexpr std::uint32_t kSSymbolStubs = 0x00000008u; +constexpr std::uint32_t kSNonLazySymPtrs = 0x00000006u; + +constexpr std::uint8_t kNExt = 0x01u; +constexpr std::uint8_t kNSect = 0x0eu; +constexpr std::uint8_t kNUndf = 0x00u; + +constexpr std::uint8_t kBindOpDone = 0x00u; +constexpr std::uint8_t kBindOpSetDylibOrdinalImm = 0x10u; +constexpr std::uint8_t kBindOpSetSymbolFlags = 0x40u; +constexpr std::uint8_t kBindOpSetTypeImm = 0x50u; +constexpr std::uint8_t kBindOpSetSegAndOff = 0x70u; +constexpr std::uint8_t kBindOpDoBind = 0x90u; +constexpr std::uint8_t kBindTypePointer = 1u; + +constexpr std::uint64_t kPageSize = 0x1000u; + +#pragma pack(push, 1) + +struct MachHeader64 { + std::uint32_t magic, cputype_u, cpusubtype_u, filetype; + std::uint32_t ncmds, sizeofcmds, flags, reserved; +}; +static_assert(sizeof(MachHeader64) == 32); + +struct SegCmd64 { + std::uint32_t cmd, cmdsize; + char segname[16]; + std::uint64_t vmaddr, vmsize, fileoff, filesize; + std::int32_t maxprot, initprot; + std::uint32_t nsects, flags; +}; +static_assert(sizeof(SegCmd64) == 72); // segment_command_64 is 72 bytes (not 64) + +struct Sec64 { + char sectname[16], segname[16]; + std::uint64_t addr, size; + std::uint32_t offset, align, reloff, nreloc, flags, reserved1, reserved2, reserved3; +}; +static_assert(sizeof(Sec64) == 80); + +struct DyldInfoCmd { + std::uint32_t cmd, cmdsize; + std::uint32_t rebase_off, rebase_size; + std::uint32_t bind_off, bind_size; + std::uint32_t weak_bind_off, weak_bind_size; + std::uint32_t lazy_bind_off, lazy_bind_size; + std::uint32_t export_off, export_size; +}; +static_assert(sizeof(DyldInfoCmd) == 48); + +struct SymtabCmd { std::uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; }; +static_assert(sizeof(SymtabCmd) == 24); + +struct DysymtabCmd { + std::uint32_t cmd, cmdsize; + std::uint32_t ilocalsym, nlocalsym, iextdefsym, nextdefsym, iundefsym, nundefsym; + std::uint32_t tocoff, ntoc, modtaboff, nmodtab, extrefsymoff, nextrefsyms; + std::uint32_t indirectsymoff, nindirectsyms, extreloff, nextrel, locreloff, nlocrel; +}; +static_assert(sizeof(DysymtabCmd) == 80); + +struct NList64 { + std::uint32_t n_strx; std::uint8_t n_type, n_sect; std::uint16_t n_desc; + std::uint64_t n_value; +}; +static_assert(sizeof(NList64) == 16); + +struct VersionMinCmd { + std::uint32_t cmd, cmdsize, version, sdk; +}; +static_assert(sizeof(VersionMinCmd) == 16); + +#pragma pack(pop) + +// ── Helpers ───────────────────────────────────────────────────────────────── + +static constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) { + return (v + (a-1)) & ~(a-1); +} + +static void push_uleb(std::vector& b, std::uint64_t v) { + do { + std::uint8_t byte = v & 0x7f; + v >>= 7; + if (v) byte |= 0x80; + b.push_back(byte); + } while (v); +} + +// Fixed 2-byte ULEB128 (covers 0..16383, enough for any trie offset in MVP). +static void push_uleb2(std::vector& b, std::uint64_t v) { + b.push_back(static_cast((v & 0x7f) | 0x80)); + b.push_back(static_cast((v >> 7) & 0x7f)); +} + +static void write32le(std::vector& buf, std::uint64_t off, std::int32_t v) { + std::uint32_t u; std::memcpy(&u, &v, 4); + buf[off+0] = u & 0xff; buf[off+1] = (u >> 8) & 0xff; + buf[off+2] = (u >> 16) & 0xff; buf[off+3] = (u >> 24) & 0xff; +} + +static void set_name(char (&out)[16], const char* src) { + std::memset(out, 0, 16); + std::strncpy(out, src, 16); +} + +// Flat export trie: root → one leaf per symbol (full symbol name as edge label). +// `sym_vmaddr` = symbol vmaddr from image base (= text_sect_vmaddr + code_offset). +static std::vector build_export_trie( + const std::vector& exports, + std::uint64_t text_sect_vmaddr) { + if (exports.empty()) return {0, 0}; + + struct Leaf { std::string name; std::vector bytes; }; + std::vector leaves; + for (const auto& e : exports) { + Leaf lf; lf.name = e.name; + std::vector td; + push_uleb(td, 0); // flags = regular + push_uleb(td, text_sect_vmaddr + e.code_offset); // vmaddr from image base + push_uleb(lf.bytes, td.size()); // terminal_size + lf.bytes.insert(lf.bytes.end(), td.begin(), td.end()); + lf.bytes.push_back(0); // num_children + leaves.push_back(std::move(lf)); + } + + // Root node size with 2-byte fixed ULEBs for child offsets: + // 1 (terminal_size=0) + 1 (num_children) + Σ(name.size()+1+2) per child + std::size_t root_sz = 2; + for (const auto& lf : leaves) root_sz += lf.name.size() + 1 + 2; + + std::vector leaf_offs; + std::size_t cursor = root_sz; + for (const auto& lf : leaves) { leaf_offs.push_back(cursor); cursor += lf.bytes.size(); } + + std::vector trie; + trie.push_back(0); // not terminal + trie.push_back(static_cast(exports.size())); // num_children + for (std::size_t i = 0; i < exports.size(); ++i) { + const auto& lf = leaves[i]; + trie.insert(trie.end(), lf.name.begin(), lf.name.end()); + trie.push_back(0); + push_uleb2(trie, leaf_offs[i]); + } + for (const auto& lf : leaves) + trie.insert(trie.end(), lf.bytes.begin(), lf.bytes.end()); + + while (trie.size() % 8) trie.push_back(0); + return trie; +} + +// Non-lazy bind opcodes. Each import gets one slot in __nl_symbol_ptr. +// Slots [0..nstubs-1] = function call stubs; slots [nstubs..] = GOT data. +// lib_ordinals: dylib install name → 1-based LC_LOAD_DYLIB ordinal. +static std::vector build_bind_opcodes( + const std::vector& ordered_imports, + const std::unordered_map& lib_ordinals, + std::uint32_t data_seg_idx, + std::uint64_t nl_sym_off_in_data_seg) { + if (ordered_imports.empty()) return {kBindOpDone}; + static constexpr const char* kDefaultLib = "/usr/lib/libSystem.B.dylib"; + std::vector buf; + for (std::size_t i = 0; i < ordered_imports.size(); ++i) { + if (!ordered_imports[i]) continue; + const auto& im = *ordered_imports[i]; + const std::string& lib = im.library.empty() ? kDefaultLib : im.library; + auto oit = lib_ordinals.find(lib); + const int ordinal = (oit != lib_ordinals.end()) ? oit->second : 1; + buf.push_back(kBindOpSetDylibOrdinalImm | static_cast(ordinal & 0xf)); + buf.push_back(kBindOpSetSymbolFlags | 0); + buf.insert(buf.end(), im.name.begin(), im.name.end()); + buf.push_back(0); + buf.push_back(kBindOpSetTypeImm | kBindTypePointer); + buf.push_back(kBindOpSetSegAndOff | (data_seg_idx & 0xf)); + push_uleb(buf, nl_sym_off_in_data_seg + i * 8); + buf.push_back(kBindOpDoBind); + } + buf.push_back(kBindOpDone); + while (buf.size() % 8) buf.push_back(0); + return buf; +} + +} // anonymous namespace + +MachoSynthOutput synthesize_macho(const MachoSynthInput& input) { + MachoSynthOutput out{}; + if (input.code.empty()) { + out.ok = false; out.error = "macho_synth: code is empty"; return out; + } + + // ── Classify imports ──────────────────────────────────────────────────── + std::unordered_set internal_ids, data_ids; + for (const auto& s : input.internal_symbols) internal_ids.insert(s.sym_id); + for (const auto& s : input.data_symbols) data_ids.insert(s.sym_id); + + // PLT32 → stub; GotPC32* (external) → nl_symbol_ptr GOT slot + std::unordered_map imp_to_stub, imp_to_got; + { + std::uint32_t si = 0, gi = 0; + using format::RelocOp; + for (const auto& r : input.relocs) { + if (r.op == RelocOp::PLT32 && + !internal_ids.count(r.sym_id) && !data_ids.count(r.sym_id) && + !imp_to_stub.count(r.sym_id)) + imp_to_stub[r.sym_id] = si++; + else if ((r.op == RelocOp::GotPC32 || r.op == RelocOp::GotPC32X || + r.op == RelocOp::GotPC32XRex) && + !internal_ids.count(r.sym_id) && !data_ids.count(r.sym_id) && + !imp_to_got.count(r.sym_id)) + imp_to_got[r.sym_id] = gi++; + } + } + const auto nstubs = static_cast(imp_to_stub.size()); + const auto ngot = static_cast(imp_to_got.size()); + const auto n_nlsym = nstubs + ngot; + + // ── Load command sizes ────────────────────────────────────────────────── + const std::uint32_t ntext_sects = (nstubs > 0) ? 2u : 1u; + const bool has_data_blob = !input.data_blob.empty(); + const bool has_nlsym = (n_nlsym > 0); + const bool has_data_seg = has_data_blob || has_nlsym; + const auto ndata_sects = static_cast( + (has_data_blob ? 1u : 0u) + (has_nlsym ? 1u : 0u)); + + const std::string dylib_name = input.soname.empty() + ? "/usr/local/lib/libvoid_module.dylib" : input.soname; + const std::uint32_t iddylib_sz = static_cast( + align_up(8u + 16u + dylib_name.size() + 1u, 4u)); + + std::vector needed_libs; + if (!input.needed_libs.empty()) { + needed_libs = input.needed_libs; + } else if (nstubs > 0 || ngot > 0) { + // Collect unique libraries in insertion order from per-import library fields. + std::unordered_map seen; + for (const auto& im : input.imports) { + const std::string& lib = im.library.empty() + ? "/usr/lib/libSystem.B.dylib" : im.library; + if (seen.emplace(lib, true).second) + needed_libs.push_back(lib); + } + if (needed_libs.empty()) + needed_libs.push_back("/usr/lib/libSystem.B.dylib"); + } + + // 1-based ordinal map (ordinal 1 = first LC_LOAD_DYLIB). + std::unordered_map lib_ordinal; + for (std::size_t i = 0; i < needed_libs.size(); ++i) + lib_ordinal[needed_libs[i]] = static_cast(i + 1); + + std::vector loaddylib_szs; + for (const auto& lib : needed_libs) + loaddylib_szs.push_back(static_cast( + align_up(8u + 16u + lib.size() + 1u, 4u))); + + std::uint32_t total_lc_sz = 0; + total_lc_sz += sizeof(SegCmd64) + ntext_sects * sizeof(Sec64); // __TEXT + if (has_data_seg) + total_lc_sz += sizeof(SegCmd64) + ndata_sects * sizeof(Sec64); // __DATA + total_lc_sz += sizeof(SegCmd64); // __LINKEDIT + total_lc_sz += sizeof(DyldInfoCmd); + total_lc_sz += sizeof(SymtabCmd); + total_lc_sz += sizeof(DysymtabCmd); + total_lc_sz += iddylib_sz; + for (std::uint32_t sz : loaddylib_szs) total_lc_sz += sz; + total_lc_sz += sizeof(VersionMinCmd); + + const std::uint64_t hdr_lc_sz = sizeof(MachHeader64) + total_lc_sz; + + // ── Vmaddr layout ──────────────────────────────────────────────────────── + // __TEXT: vmaddr=0, fileoff=0; vmaddr == fileoff throughout. + const std::uint64_t text_sect_va = align_up(hdr_lc_sz, 16); + const std::uint64_t text_sect_sz = input.code.size(); + const std::uint64_t stubs_va = align_up(text_sect_va + text_sect_sz, 2); + const std::uint64_t stubs_sz = nstubs * 6; + const std::uint64_t text_seg_end = stubs_va + stubs_sz; + + const std::uint64_t data_seg_va = align_up(text_seg_end, kPageSize); + const std::uint64_t data_sect_va = data_seg_va; + const std::uint64_t data_sect_sz = input.data_blob.size(); + const std::uint64_t nlsym_va = align_up(data_sect_va + data_sect_sz, 8); + const std::uint64_t nlsym_sz = n_nlsym * 8; + const std::uint64_t data_seg_end = nlsym_va + nlsym_sz; + + const std::uint64_t linkedit_va = has_data_seg + ? align_up(data_seg_end, kPageSize) + : align_up(text_seg_end, kPageSize); + + // ── Build LINKEDIT content ─────────────────────────────────────────────── + + // Bind imports: stubs first [0..nstubs-1], then GOT data [nstubs..nstubs+ngot-1]. + std::vector stub_order(nstubs, nullptr); + std::vector got_order(ngot, nullptr); + for (const auto& im : input.imports) { + auto sit = imp_to_stub.find(im.sym_id); + if (sit != imp_to_stub.end()) stub_order[sit->second] = &im; + auto git = imp_to_got.find(im.sym_id); + if (git != imp_to_got.end()) got_order[git->second] = &im; + } + std::vector bind_order; + bind_order.insert(bind_order.end(), stub_order.begin(), stub_order.end()); + bind_order.insert(bind_order.end(), got_order.begin(), got_order.end()); + + const std::uint32_t data_seg_idx = has_data_seg ? 1u : 0u; // 0-based + const std::uint64_t nlsym_off_in_data = nlsym_va - data_seg_va; + auto bind_bytes = build_bind_opcodes(bind_order, lib_ordinal, data_seg_idx, nlsym_off_in_data); + + auto export_trie = build_export_trie(input.exports, text_sect_va); + + // Symbol table: extdef (exports) then undef (imports). + std::vector strtab; strtab.push_back(0); + std::vector nlist; + + const std::uint32_t iextdefsym = 0; + for (const auto& e : input.exports) { + NList64 n{}; + n.n_strx = static_cast(strtab.size()); + strtab.insert(strtab.end(), e.name.begin(), e.name.end()); strtab.push_back(0); + n.n_type = kNExt | kNSect; + n.n_sect = 1; // 1-based: __text is section 1 + n.n_value = text_sect_va + e.code_offset; + nlist.push_back(n); + } + const std::uint32_t iundefsym = static_cast(nlist.size()); + for (const auto& im : input.imports) { + NList64 n{}; + n.n_strx = static_cast(strtab.size()); + strtab.insert(strtab.end(), im.name.begin(), im.name.end()); strtab.push_back(0); + n.n_type = kNExt | kNUndf; + n.n_sect = 0; // NO_SECT + nlist.push_back(n); + } + while (strtab.size() % 4) strtab.push_back(0); + + // LINKEDIT offsets + std::uint64_t li = linkedit_va; + const std::uint64_t bind_off = li; li += bind_bytes.size(); + const std::uint64_t exp_off = li; li += export_trie.size(); + li = align_up(li, 8); + const std::uint64_t sym_off = li; li += nlist.size() * sizeof(NList64); + li = align_up(li, 4); + const std::uint64_t str_off = li; li += strtab.size(); + const std::uint64_t linkedit_filesz = li - linkedit_va; + + // ── Apply reloc IR to code blob ───────────────────────────────────────── + std::vector code_buf(input.code); + + // Build stub bytes (6-byte JMP stubs → nl_symbol_ptr slots). + // Each stub: FF 25 (jmpq *slot(%rip)) + // Stubs use slots [0..nstubs-1] in nl_symbol_ptr. + std::vector stub_buf(stubs_sz, 0); + for (std::uint32_t i = 0; i < nstubs; ++i) { + const std::uint64_t stub_va = stubs_va + i * 6; + const std::uint64_t slot_va = nlsym_va + i * 8; + const std::int32_t disp = static_cast( + static_cast(slot_va) - static_cast(stub_va + 6)); + stub_buf[i*6 + 0] = 0xff; stub_buf[i*6 + 1] = 0x25; + std::uint32_t u; std::memcpy(&u, &disp, 4); + stub_buf[i*6 + 2] = u & 0xff; stub_buf[i*6 + 3] = (u >> 8) & 0xff; + stub_buf[i*6 + 4] = (u >> 16) & 0xff; stub_buf[i*6 + 5] = (u >> 24) & 0xff; + } + + // vmaddr maps + std::unordered_map sym_va, dat_va; + for (const auto& s : input.internal_symbols) sym_va[s.sym_id] = text_sect_va + s.code_offset; + for (const auto& s : input.data_symbols) dat_va[s.sym_id] = data_sect_va + s.data_offset; + + using format::RelocOp; + for (const auto& r : input.relocs) { + const std::uint64_t coff = r.dst_offset; + if (coff + 4 > code_buf.size()) { + out.ok = false; + std::ostringstream os; + os << "macho_synth: reloc at 0x" << std::hex << coff << " out of range"; + out.error = os.str(); return out; + } + const std::uint64_t site_va = text_sect_va + coff; + std::int64_t disp = 0; bool patched = false; + + switch (r.op) { + case RelocOp::PC32: + case RelocOp::PC32_1: case RelocOp::PC32_2: + case RelocOp::PC32_4: case RelocOp::PC32_5: { + std::int64_t bias = 0; + if (r.op == RelocOp::PC32_1) bias = -1; + else if (r.op == RelocOp::PC32_2) bias = -2; + else if (r.op == RelocOp::PC32_4) bias = -4; + else if (r.op == RelocOp::PC32_5) bias = -5; + auto ic = sym_va.find(r.sym_id); + if (ic != sym_va.end()) { + disp = static_cast(ic->second) + - static_cast(site_va + 4) + r.addend + bias; + patched = true; break; + } + auto id = dat_va.find(r.sym_id); + if (id != dat_va.end()) { + disp = static_cast(id->second) + - static_cast(site_va + 4) + r.addend + bias; + patched = true; break; + } + out.ok = false; + { std::ostringstream os; + os << "PC32: sym_id " << r.sym_id << " not found"; out.error = os.str(); } + return out; + } + case RelocOp::PLT32: { + auto ic = sym_va.find(r.sym_id); + if (ic != sym_va.end()) { + disp = static_cast(ic->second) + - static_cast(site_va + 4) + r.addend; + patched = true; break; + } + auto sit = imp_to_stub.find(r.sym_id); + if (sit != imp_to_stub.end()) { + const std::uint64_t sv = stubs_va + sit->second * 6; + disp = static_cast(sv) + - static_cast(site_va + 4) + r.addend; + patched = true; break; + } + out.ok = false; + { std::ostringstream os; + os << "PLT32: sym_id " << r.sym_id << " not found"; out.error = os.str(); } + return out; + } + case RelocOp::GotPC32: + case RelocOp::GotPC32X: + case RelocOp::GotPC32XRex: { + const bool relax = r.op == RelocOp::GotPC32X || r.op == RelocOp::GotPC32XRex; + auto ic = sym_va.find(r.sym_id); + auto id = dat_va.find(r.sym_id); + if ((ic != sym_va.end() || id != dat_va.end()) && relax) { + if (coff < 2 || code_buf[coff-1] != 0x8b) { + out.ok = false; out.error = "GOTPCREL relax: expected MOV"; return out; + } + code_buf[coff-1] = 0x8d; + std::uint64_t tv = (ic != sym_va.end()) ? ic->second : id->second; + disp = static_cast(tv) + - static_cast(site_va + 4) + r.addend; + patched = true; break; + } + auto git = imp_to_got.find(r.sym_id); + if (git != imp_to_got.end()) { + const std::uint64_t sv = nlsym_va + (nstubs + git->second) * 8; + disp = static_cast(sv) + - static_cast(site_va + 4) + r.addend; + patched = true; break; + } + out.ok = false; + { std::ostringstream os; + os << "GOTPCREL: sym_id " << r.sym_id << " not found"; out.error = os.str(); } + return out; + } + case RelocOp::Abs64: case RelocOp::Abs32: case RelocOp::Abs32Signed: + out.ok = false; out.error = "Abs reloc not yet supported in macho_synth"; return out; + case RelocOp::TlsLE: case RelocOp::TlsIE: case RelocOp::TlsGD: case RelocOp::TlsLD: + out.ok = false; out.error = "TLS not yet supported in macho_synth"; return out; + } + + if (patched) write32le(code_buf, coff, static_cast(disp)); + } + + // ── Emit file ──────────────────────────────────────────────────────────── + const std::uint64_t file_sz = li; + out.bytes.assign(file_sz, 0); + + auto write_at = [&](std::uint64_t off, const void* src, std::uint64_t n) { + std::memcpy(out.bytes.data() + off, src, n); + }; + + // -- Mach header -- + std::uint32_t ncmds = 0; + ncmds++; if (has_data_seg) ncmds++; ncmds++; // segments + ncmds += 4; // DyldInfo, Symtab, Dysymtab, VersionMin + ncmds++; // ID_DYLIB + ncmds += static_cast(needed_libs.size()); + + MachHeader64 mh{}; + mh.magic = kMhMagic64; + mh.cputype_u = static_cast(kCpuTypeX86_64); + mh.cpusubtype_u = static_cast(kCpuSubX86All); + mh.filetype = kMhDylib; + mh.ncmds = ncmds; + mh.sizeofcmds = total_lc_sz; + mh.flags = kMhFlags; + write_at(0, &mh, sizeof(mh)); + + std::uint64_t lc = sizeof(MachHeader64); + auto emit = [&](const void* p, std::uint32_t n) { write_at(lc, p, n); lc += n; }; + + // __TEXT segment + { + const std::uint32_t text_cmd_sz = sizeof(SegCmd64) + ntext_sects * sizeof(Sec64); + SegCmd64 seg{}; + seg.cmd = kLcSegment64; seg.cmdsize = text_cmd_sz; + set_name(seg.segname, "__TEXT"); + seg.vmsize = seg.filesize = align_up(text_seg_end, kPageSize); + seg.maxprot = kVmProtR | kVmProtX; seg.initprot = kVmProtR | kVmProtX; + seg.nsects = ntext_sects; + emit(&seg, sizeof(seg)); + + Sec64 ts{}; + set_name(ts.sectname, "__text"); set_name(ts.segname, "__TEXT"); + ts.addr = text_sect_va; ts.size = text_sect_sz; + ts.offset = static_cast(text_sect_va); + ts.align = 4; // 2^4 = 16 + ts.flags = kSAttrPureInstr | kSAttrSomeInstr; + emit(&ts, sizeof(ts)); + + if (nstubs > 0) { + Sec64 ss{}; + set_name(ss.sectname, "__stubs"); set_name(ss.segname, "__TEXT"); + ss.addr = stubs_va; ss.size = stubs_sz; + ss.offset = static_cast(stubs_va); + ss.align = 1; // 2^1 = 2 + ss.flags = kSSymbolStubs | kSAttrSomeInstr | kSAttrPureInstr; + ss.reserved2 = 6; // stub entry size + emit(&ss, sizeof(ss)); + } + } + + // __DATA segment + if (has_data_seg) { + const std::uint32_t data_cmd_sz = sizeof(SegCmd64) + ndata_sects * sizeof(Sec64); + SegCmd64 seg{}; + seg.cmd = kLcSegment64; seg.cmdsize = data_cmd_sz; + set_name(seg.segname, "__DATA"); + seg.vmaddr = seg.fileoff = data_seg_va; + seg.vmsize = seg.filesize = align_up(data_seg_end - data_seg_va, kPageSize); + seg.maxprot = kVmProtR | kVmProtW; seg.initprot = kVmProtR | kVmProtW; + seg.nsects = ndata_sects; + emit(&seg, sizeof(seg)); + + if (has_data_blob) { + Sec64 ds{}; + set_name(ds.sectname, "__data"); set_name(ds.segname, "__DATA"); + ds.addr = data_sect_va; ds.size = data_sect_sz; + ds.offset = static_cast(data_sect_va); + ds.align = 3; + emit(&ds, sizeof(ds)); + } + if (has_nlsym) { + Sec64 ns{}; + set_name(ns.sectname, "__nl_symbol_ptr"); set_name(ns.segname, "__DATA"); + ns.addr = nlsym_va; ns.size = nlsym_sz; + ns.offset = static_cast(nlsym_va); + ns.align = 3; + ns.flags = kSNonLazySymPtrs; + emit(&ns, sizeof(ns)); + } + } + + // __LINKEDIT segment + { + SegCmd64 seg{}; + seg.cmd = kLcSegment64; seg.cmdsize = sizeof(SegCmd64); + set_name(seg.segname, "__LINKEDIT"); + seg.vmaddr = seg.fileoff = linkedit_va; + seg.vmsize = seg.filesize = align_up(linkedit_filesz, kPageSize); + seg.maxprot = kVmProtR; seg.initprot = kVmProtR; + emit(&seg, sizeof(seg)); + } + + // LC_DYLD_INFO_ONLY + { + DyldInfoCmd dc{}; + dc.cmd = kLcDyldInfoOnly; dc.cmdsize = sizeof(dc); + dc.bind_off = static_cast(bind_off); + dc.bind_size = static_cast(bind_bytes.size()); + dc.export_off = static_cast(exp_off); + dc.export_size = static_cast(export_trie.size()); + emit(&dc, sizeof(dc)); + } + + // LC_SYMTAB + { + SymtabCmd sc{}; + sc.cmd = kLcSymtab; sc.cmdsize = sizeof(sc); + sc.symoff = static_cast(sym_off); + sc.nsyms = static_cast(nlist.size()); + sc.stroff = static_cast(str_off); + sc.strsize = static_cast(strtab.size()); + emit(&sc, sizeof(sc)); + } + + // LC_DYSYMTAB + { + DysymtabCmd dc{}; + dc.cmd = kLcDysymtab; dc.cmdsize = sizeof(dc); + dc.iextdefsym = iextdefsym; + dc.nextdefsym = iundefsym - iextdefsym; + dc.iundefsym = iundefsym; + dc.nundefsym = static_cast(nlist.size()) - iundefsym; + emit(&dc, sizeof(dc)); + } + + // LC_ID_DYLIB + { + std::vector lc_buf(iddylib_sz, 0); + auto* u = reinterpret_cast(lc_buf.data()); + u[0] = kLcIdDylib; u[1] = iddylib_sz; + u[2] = 8u + 16u; // name offset from cmd start + u[3] = 0; u[4] = 0x00010000u; u[5] = 0x00010000u; + std::memcpy(lc_buf.data() + 8 + 16, dylib_name.c_str(), dylib_name.size()); + emit(lc_buf.data(), iddylib_sz); + } + + // LC_LOAD_DYLIB entries + for (std::size_t i = 0; i < needed_libs.size(); ++i) { + const std::uint32_t sz = loaddylib_szs[i]; + std::vector lc_buf(sz, 0); + auto* u = reinterpret_cast(lc_buf.data()); + u[0] = kLcLoadDylib; u[1] = sz; + u[2] = 8u + 16u; u[3] = 0; u[4] = 0x00010000u; u[5] = 0x00010000u; + std::memcpy(lc_buf.data() + 8 + 16, needed_libs[i].c_str(), needed_libs[i].size()); + emit(lc_buf.data(), sz); + } + + // LC_VERSION_MIN_MACOSX + { + VersionMinCmd vc{}; + vc.cmd = kLcVersionMinMacOS; vc.cmdsize = sizeof(vc); + vc.version = 0x000c0000u; // 12.0.0 + vc.sdk = 0x000c0000u; + emit(&vc, sizeof(vc)); + } + + // -- Section data -- + write_at(text_sect_va, code_buf.data(), code_buf.size()); + if (stubs_sz > 0) write_at(stubs_va, stub_buf.data(), stub_buf.size()); + if (has_data_blob) write_at(data_sect_va, input.data_blob.data(), input.data_blob.size()); + // __nl_symbol_ptr: zeroed — dyld fills via bind opcodes + + // -- LINKEDIT data -- + if (!bind_bytes.empty()) write_at(bind_off, bind_bytes.data(), bind_bytes.size()); + write_at(exp_off, export_trie.data(), export_trie.size()); + if (!nlist.empty()) write_at(sym_off, nlist.data(), nlist.size() * sizeof(NList64)); + write_at(str_off, strtab.data(), strtab.size()); + + return out; +} + +} // namespace voidlibc::loader::macos diff --git a/loader/macos/macho_synth.hpp b/loader/macos/macho_synth.hpp new file mode 100644 index 0000000..eb4f239 --- /dev/null +++ b/loader/macos/macho_synth.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include "format/reloc_ir.hpp" + +#include +#include +#include + +namespace voidlibc::loader::macos { + +struct MachoExportedSymbol { + std::string name; + std::uint64_t code_offset = 0; + std::uint64_t size = 0; + bool is_function = true; + bool weak = false; +}; + +struct MachoImportedSymbol { + std::uint32_t sym_id = 0; + std::string name; + std::string library; // dylib install name; "" → /usr/lib/libSystem.B.dylib +}; + +struct MachoInternalSymbol { + std::uint32_t sym_id = 0; + std::uint64_t code_offset = 0; + std::string name; +}; + +struct MachoDataSymbol { + std::uint32_t sym_id = 0; + std::uint64_t data_offset = 0; + std::string name; +}; + +struct MachoSynthInput { + std::vector code; + std::vector exports; + std::vector relocs; + std::vector internal_symbols; + std::vector imports; + std::vector data_blob; + std::vector data_symbols; + std::string soname; + // Explicit LC_LOAD_DYLIB entries. Empty + imports present → defaults to + // /usr/lib/libSystem.B.dylib. Empty + no imports → static (no NEEDED). + std::vector needed_libs; +}; + +struct MachoSynthOutput { + std::vector bytes; + std::string error; + bool ok = true; +}; + +// Produce a minimal Mach-O64 dylib (MH_DYLIB, x86_64) that dlopen will accept. +// Layout: __TEXT (header+LCs+code+stubs) / __DATA (data+nl_symbol_ptr) / __LINKEDIT. +// Non-lazy binding via LC_DYLD_INFO_ONLY bind opcodes; no lazy stubs. +MachoSynthOutput synthesize_macho(const MachoSynthInput& input); + +} // namespace voidlibc::loader::macos diff --git a/loader/windows/CMakeLists.txt b/loader/windows/CMakeLists.txt new file mode 100644 index 0000000..a15eeed --- /dev/null +++ b/loader/windows/CMakeLists.txt @@ -0,0 +1,10 @@ +add_library(voidlibc_loader_windows STATIC + pe_synth.cpp + handoff.cpp +) +target_include_directories(voidlibc_loader_windows PUBLIC + ${CMAKE_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/.. +) +target_link_libraries(voidlibc_loader_windows PUBLIC voidlibc_format) +set_target_properties(voidlibc_loader_windows PROPERTIES POSITION_INDEPENDENT_CODE ON) diff --git a/loader/windows/handoff.cpp b/loader/windows/handoff.cpp new file mode 100644 index 0000000..42eaaca --- /dev/null +++ b/loader/windows/handoff.cpp @@ -0,0 +1,73 @@ +#include "handoff.hpp" + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#else +// Stub for non-Windows builds (so the file compiles everywhere). +#include +#endif + +namespace voidlibc::loader::windows_handoff { + +LoadResult load_pe_buffer(const std::vector& bytes) { +#ifdef _WIN32 + // Write bytes to a temp file, load it, then delete the file. + char tmp_path[MAX_PATH]; + char tmp_dir[MAX_PATH]; + GetTempPathA(MAX_PATH, tmp_dir); + GetTempFileNameA(tmp_dir, "vlc", 0, tmp_path); + + // Write PE bytes. + HANDLE fh = CreateFileA(tmp_path, GENERIC_WRITE, 0, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (fh == INVALID_HANDLE_VALUE) { + return {nullptr, "CreateFile failed for temp PE", false}; + } + DWORD written = 0; + BOOL ok = WriteFile(fh, bytes.data(), + static_cast(bytes.size()), &written, nullptr); + CloseHandle(fh); + if (!ok || written != bytes.size()) { + DeleteFileA(tmp_path); + return {nullptr, "WriteFile failed for temp PE", false}; + } + + // Load the DLL. + HMODULE mod = LoadLibraryExA(tmp_path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); + DeleteFileA(tmp_path); // safe to delete once mapped + + if (!mod) { + char msg[256]; + std::snprintf(msg, sizeof(msg), + "LoadLibraryEx failed (error %lu)", GetLastError()); + return {nullptr, msg, false}; + } + return {static_cast(mod), {}, true}; +#else + (void)bytes; + return {nullptr, "load_pe_buffer: not implemented on non-Windows", false}; +#endif +} + +void* get_proc(void* handle, const char* name) { +#ifdef _WIN32 + return reinterpret_cast( + GetProcAddress(static_cast(handle), name)); +#else + (void)handle; (void)name; + return nullptr; +#endif +} + +void unload(void* handle) { +#ifdef _WIN32 + FreeLibrary(static_cast(handle)); +#else + (void)handle; +#endif +} + +} // namespace voidlibc::loader::windows_handoff diff --git a/loader/windows/handoff.hpp b/loader/windows/handoff.hpp new file mode 100644 index 0000000..70caed0 --- /dev/null +++ b/loader/windows/handoff.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +namespace voidlibc::loader::windows_handoff { + +struct LoadResult { + void* handle = nullptr; // opaque OS handle (HMODULE on Windows) + std::string error; + bool ok = true; +}; + +// Write `bytes` to a temp file and load it via LoadLibraryEx (Windows) / +// dlopen from a temp file (stub for non-Windows builds so the code compiles +// everywhere). The temp file is deleted once the DLL is loaded. +LoadResult load_pe_buffer(const std::vector& bytes); + +// Resolve a symbol from a handle returned by load_pe_buffer. +void* get_proc(void* handle, const char* name); + +// Unload a handle returned by load_pe_buffer. +void unload(void* handle); + +} // namespace voidlibc::loader::windows_handoff diff --git a/loader/windows/pe_synth.cpp b/loader/windows/pe_synth.cpp new file mode 100644 index 0000000..70c4aba --- /dev/null +++ b/loader/windows/pe_synth.cpp @@ -0,0 +1,571 @@ +// Minimal PE64 DLL synthesizer. +// +// Layout produced (all RVAs relative to image base 0x10000000): +// +// File offset 0x000 : DOS stub + PE signature +// File offset 0x040 : PE signature "PE\0\0" +// File offset 0x044 : IMAGE_FILE_HEADER (20 bytes) +// File offset 0x058 : IMAGE_OPTIONAL_HEADER64 (240 bytes) +// File offset 0x148 : Section table (N × 40 bytes) +// File offset 0x200 : .text raw data (code + thunk stubs, file-aligned 0x200) +// File offset ... : .rdata raw data (export dir, import dir, IAT, names) +// File offset ... : .data raw data (data blob — writable; omitted if empty) +// +// Virtual layout (section-aligned 0x1000): +// VA 0x1000 : .text (RX) +// VA ... : .rdata (R) +// VA ... : .data (RW, omitted if empty) +// +// Import thunks (JMP QWORD PTR [IAT_entry+rip]) live at the START of .text +// (index 0..nimports-1, 6 bytes each, padded to 16-byte stride). +// Code blob follows at offset = nimports * 16. + +#include "pe_synth.hpp" + +#include +#include +#include + +namespace voidlibc::loader::windows { + +namespace { + +using format::RelocOp; + +constexpr std::uint16_t kMachineAmd64 = 0x8664; +constexpr std::uint16_t kCharDll = 0x2000; +constexpr std::uint16_t kCharExecutable= 0x0002; +constexpr std::uint16_t kCharLargeAddr = 0x0020; +constexpr std::uint16_t kMagicPE64 = 0x020B; +constexpr std::uint32_t kFileAlign = 0x200; +constexpr std::uint32_t kSecAlign = 0x1000; +constexpr std::uint64_t kImageBase = 0x10000000ULL; + +constexpr std::uint32_t align_up(std::uint32_t v, std::uint32_t a) { + return (v + a - 1) & ~(a - 1); +} + +// Write helpers (little-endian). +static void w16(std::vector& v, std::uint32_t off, std::uint16_t x) { + v[off] = static_cast(x); + v[off+1] = static_cast(x >> 8); +} +static void w32(std::vector& v, std::uint32_t off, std::uint32_t x) { + v[off] = static_cast(x); + v[off+1] = static_cast(x >> 8); + v[off+2] = static_cast(x >> 16); + v[off+3] = static_cast(x >> 24); +} +static void w64(std::vector& v, std::uint32_t off, std::uint64_t x) { + w32(v, off, static_cast(x)); + w32(v, off+4, static_cast(x >> 32)); +} +struct SectionDesc { + char name[9] = {}; // up to 8 chars + NUL + std::uint32_t rva = 0; + std::uint32_t vsize = 0; // virtual size + std::uint32_t foff = 0; // file offset of raw data + std::uint32_t fsize = 0; // raw data size (file-aligned) + std::uint32_t chars = 0; // IMAGE_SCN_* flags +}; + +void write_section_header(std::vector& out, + std::uint32_t at, + const SectionDesc& s) { + // Pad name to 8 chars. + std::memcpy(out.data() + at, s.name, 8); + w32(out, at + 8, s.vsize); + w32(out, at + 12, s.rva); + w32(out, at + 20, s.fsize); // SizeOfRawData + w32(out, at + 16, s.foff); // PointerToRawData + w32(out, at + 24, 0); // PointerToRelocations + w32(out, at + 28, 0); // PointerToLinenumbers + w16(out, at + 32, 0); // NumberOfRelocations + w16(out, at + 34, 0); // NumberOfLinenumbers + w32(out, at + 36, s.chars); +} + +} // namespace + +PeSynthOutput synthesize_pe(const PeSynthInput& input) { + PeSynthOutput out; + + const std::uint32_t nimports = static_cast(input.imports.size()); + const std::uint32_t nexports = static_cast(input.exports.size()); + + // Each import gets a 6-byte thunk (JMP [rip+X]) padded to 16 bytes. + const std::uint32_t thunk_stride = 16; + const std::uint32_t thunks_size = nimports * thunk_stride; + + // --- Build .text content: [thunks][code blob] --- + std::vector text_raw(thunks_size + input.code.size(), 0); + std::memcpy(text_raw.data() + thunks_size, input.code.data(), input.code.size()); + + // sym_id → import index (0-based) for PLT-like thunks. + std::unordered_map import_to_thunk; + { + std::uint32_t idx = 0; + for (const auto& imp : input.imports) + import_to_thunk.emplace(imp.sym_id, idx++); + } + + // sym_id → code offset (within code blob, relative to code blob start). + std::unordered_map sym_code_offset; + for (const auto& s : input.internal_symbols) + sym_code_offset.emplace(s.sym_id, s.code_offset); + + // sym_id → data blob offset. + std::unordered_map sym_data_offset; + for (const auto& s : input.data_symbols) + sym_data_offset.emplace(s.sym_id, s.data_offset); + + // --- Section layout planning --- + // .text: VA 0x1000, RX + // .rdata: VA immediately after .text (section-aligned), R + // .data: VA immediately after .rdata (section-aligned), RW (omitted if empty) + const std::uint32_t text_rva = kSecAlign; // 0x1000 + const std::uint32_t text_vsz = static_cast(text_raw.size()); + const std::uint32_t rdata_rva = align_up(text_rva + text_vsz, kSecAlign); + + // --- Build .rdata: export table, import descriptors, IAT, name strings --- + // We'll assemble it as a flat buffer, keeping track of RVAs. + std::vector rdata; + auto rdata_rva_of = [&](std::uint32_t rdata_off) { + return rdata_rva + rdata_off; + }; + + // Partition imports by DLL (stable insertion order preserves import_to_thunk order). + // Each group has: its DLL name + the set of imports from that DLL. + struct DllGroup { + std::string dll_name; + std::vector import_indices; // indices into input.imports + }; + std::vector dll_groups; + std::unordered_map dll_index; + { + const std::string default_dll = input.dll_name.empty() ? "ucrtbase.dll" : input.dll_name; + for (std::uint32_t i = 0; i < nimports; ++i) { + const std::string& dll = input.imports[i].library.empty() + ? default_dll : input.imports[i].library; + auto [it, inserted] = dll_index.emplace(dll, dll_groups.size()); + if (inserted) dll_groups.push_back({dll, {}}); + dll_groups[it->second].import_indices.push_back(i); + } + } + const std::uint32_t ndlls = static_cast(dll_groups.size()); + + // IAT layout: [grp0_entries][grp0_null] [grp1_entries][grp1_null] ... + // Total = (nimports + ndlls) * 8 bytes. + const std::uint32_t iat_off = 0; + const std::uint32_t iat_size = (nimports + ndlls) * 8; + rdata.resize(iat_size, 0); + + // INT: same layout as IAT, placed after IAT. + const std::uint32_t int_off = iat_size; + const std::uint32_t int_size = (nimports + ndlls) * 8; + rdata.resize(rdata.size() + int_size, 0); + + // Compute per-import global slot index (position in the flat IAT). + // import_to_thunk already maps sym_id → original index; we need + // sym_id → IAT-slot-for-thunk. + std::vector import_iat_slot(nimports); // index → IAT slot + { + std::uint32_t slot = 0; + for (const auto& g : dll_groups) { + for (std::uint32_t idx : g.import_indices) + import_iat_slot[idx] = slot++; + ++slot; // null terminator slot + } + } + // Rebuild import_to_thunk using IAT slot (thunk #i JMPs through IAT[import_iat_slot[i]]). + // The existing import_to_thunk maps sym_id → import_index (0-based insertion order). + // We need sym_id → IAT_slot for the .rdata reloc in thunk patching below. + std::unordered_map sym_to_iat_slot; + for (std::uint32_t i = 0; i < nimports; ++i) + sym_to_iat_slot[input.imports[i].sym_id] = import_iat_slot[i]; + + // Hint+name table (IMAGE_IMPORT_BY_NAME records). + std::vector import_name_rvas(nimports); + for (std::uint32_t i = 0; i < nimports; ++i) { + const std::uint32_t name_off = static_cast(rdata.size()); + rdata.push_back(0); rdata.push_back(0); // hint = 0 + const auto& name = input.imports[i].name; + rdata.insert(rdata.end(), name.begin(), name.end()); + rdata.push_back(0); + if (rdata.size() & 1) rdata.push_back(0); + import_name_rvas[i] = rdata_rva_of(name_off); + } + + // Fill IAT and INT entries per group. + { + std::uint32_t slot = 0; + for (const auto& g : dll_groups) { + for (std::uint32_t idx : g.import_indices) { + w64(rdata, iat_off + slot * 8, import_name_rvas[idx]); + w64(rdata, int_off + slot * 8, import_name_rvas[idx]); + ++slot; + } + ++slot; // null terminator already zero + } + } + + // Import descriptor table: one IMAGE_IMPORT_DESCRIPTOR (20 bytes) per DLL + null. + // DLL names first (so we know their RVAs). + std::vector dll_name_rvas(ndlls); + for (std::uint32_t d = 0; d < ndlls; ++d) { + const std::uint32_t off = static_cast(rdata.size()); + rdata.insert(rdata.end(), dll_groups[d].dll_name.begin(), dll_groups[d].dll_name.end()); + rdata.push_back(0); + if (rdata.size() & 1) rdata.push_back(0); + dll_name_rvas[d] = rdata_rva_of(off); + } + + const std::uint32_t imp_desc_off = static_cast(rdata.size()); + // (ndlls + 1) descriptors (last = null terminator). + rdata.resize(rdata.size() + (ndlls + 1) * 20, 0); + { + std::uint32_t slot = 0; + for (std::uint32_t d = 0; d < ndlls; ++d) { + const std::uint32_t at = imp_desc_off + d * 20; + const std::uint32_t grp_iat_rva = rdata_rva_of(iat_off + slot * 8); + const std::uint32_t grp_int_rva = rdata_rva_of(int_off + slot * 8); + w32(rdata, at + 0, grp_int_rva); // OriginalFirstThunk (INT) + w32(rdata, at + 4, 0); // TimeDateStamp + w32(rdata, at + 8, 0); // ForwarderChain + w32(rdata, at + 12, dll_name_rvas[d]); // Name + w32(rdata, at + 16, grp_iat_rva); // FirstThunk (IAT) + slot += static_cast(dll_groups[d].import_indices.size()) + 1; // +1 null + } + // Last descriptor = null (already zero). + } + + // Export directory (IMAGE_EXPORT_DIRECTORY, 40 bytes). + const std::uint32_t exp_fn_rvas_off = static_cast(rdata.size()); + rdata.resize(rdata.size() + nexports * 4, 0); // function RVA array + + const std::uint32_t exp_name_rvas_off = static_cast(rdata.size()); + rdata.resize(rdata.size() + nexports * 4, 0); // name RVA array + + const std::uint32_t exp_ordinals_off = static_cast(rdata.size()); + rdata.resize(rdata.size() + nexports * 2, 0); // ordinal array + + // Export name strings. + std::vector exp_name_rva(nexports); + for (std::uint32_t i = 0; i < nexports; ++i) { + exp_name_rva[i] = rdata_rva_of(static_cast(rdata.size())); + const auto& nm = input.exports[i].name; + rdata.insert(rdata.end(), nm.begin(), nm.end()); + rdata.push_back(0); + } + if (rdata.size() & 1) rdata.push_back(0); + + // Export DLL name string. + const std::uint32_t exp_dll_name_off = static_cast(rdata.size()); + rdata.insert(rdata.end(), input.dll_name.begin(), input.dll_name.end()); + rdata.push_back(0); + + // IMAGE_EXPORT_DIRECTORY. + const std::uint32_t exp_dir_off = static_cast(rdata.size()); + rdata.resize(rdata.size() + 40, 0); + + const std::uint32_t rdata_vsz = static_cast(rdata.size()); + const std::uint32_t data_rva = align_up(rdata_rva + rdata_vsz, kSecAlign); + + // --- Determine section count --- + const bool has_data = !input.data_blob.empty(); + const int nsec = has_data ? 3 : 2; + + // --- Headers --- + // File layout: headers (0x200 file-aligned), .text, .rdata, [.data] + const std::uint32_t hdrs_size = align_up( + 0x148 + static_cast(nsec) * 40, kFileAlign); + + const std::uint32_t text_foff = hdrs_size; + const std::uint32_t text_fsz = align_up(text_vsz, kFileAlign); + const std::uint32_t rdata_foff = text_foff + text_fsz; + const std::uint32_t rdata_fsz = align_up(rdata_vsz, kFileAlign); + const std::uint32_t data_foff = rdata_foff + rdata_fsz; + const std::uint32_t data_vsz = static_cast(input.data_blob.size()); + const std::uint32_t data_fsz = has_data ? align_up(data_vsz, kFileAlign) : 0; + + const std::uint32_t image_size = has_data + ? align_up(data_rva + data_vsz, kSecAlign) + : align_up(rdata_rva + rdata_vsz, kSecAlign); + + const std::uint32_t total_file = data_foff + data_fsz; + out.bytes.assign(total_file, 0); + auto& img = out.bytes; + + // DOS header. + img[0] = 'M'; img[1] = 'Z'; + w32(img, 0x3C, 0x40); // e_lfanew + + // PE signature. + img[0x40] = 'P'; img[0x41] = 'E'; + + // COFF File Header at 0x44. + const std::uint32_t fhdr = 0x44; + w16(img, fhdr + 0, kMachineAmd64); + w16(img, fhdr + 2, static_cast(nsec)); + w32(img, fhdr + 4, 0); // TimeDateStamp + w32(img, fhdr + 8, 0); // PointerToSymbolTable + w32(img, fhdr + 12, 0); // NumberOfSymbols + w16(img, fhdr + 16, 240); // SizeOfOptionalHeader + w16(img, fhdr + 18, kCharExecutable | kCharDll | kCharLargeAddr); + + // Optional Header at 0x58. + const std::uint32_t ohdr = 0x58; + w16(img, ohdr + 0, kMagicPE64); + img[ohdr + 2] = 14; img[ohdr + 3] = 0; // MajorLinkerVersion, MinorLinkerVersion + w32(img, ohdr + 4, text_fsz); // SizeOfCode + w32(img, ohdr + 8, rdata_fsz + data_fsz); // SizeOfInitializedData + w32(img, ohdr + 12, 0); // SizeOfUninitializedData + w32(img, ohdr + 16, 0); // AddressOfEntryPoint (DLL: 0 is fine) + w32(img, ohdr + 20, text_rva); // BaseOfCode + w64(img, ohdr + 24, kImageBase); // ImageBase + w32(img, ohdr + 32, kSecAlign); // SectionAlignment + w32(img, ohdr + 36, kFileAlign); // FileAlignment + w16(img, ohdr + 40, 6); w16(img, ohdr + 42, 0); // OS version 6.0 + w16(img, ohdr + 44, 0); w16(img, ohdr + 46, 0); // Image version + w16(img, ohdr + 48, 6); w16(img, ohdr + 50, 0); // Subsystem version 6.0 + w32(img, ohdr + 52, 0); // Win32VersionValue + w32(img, ohdr + 56, image_size); // SizeOfImage + w32(img, ohdr + 60, hdrs_size); // SizeOfHeaders + w32(img, ohdr + 64, 0); // CheckSum + w16(img, ohdr + 68, 3); // Subsystem = WINDOWS_CUI + w16(img, ohdr + 70, 0x8160); // DllCharacteristics (ASLR, NX, ...) + w64(img, ohdr + 72, 0x100000); // SizeOfStackReserve + w64(img, ohdr + 80, 0x1000); // SizeOfStackCommit + w64(img, ohdr + 88, 0x100000); // SizeOfHeapReserve + w64(img, ohdr + 96, 0x1000); // SizeOfHeapCommit + w32(img, ohdr + 104, 0); // LoaderFlags + w32(img, ohdr + 108, 16); // NumberOfRvaAndSizes + + // Data directories (at ohdr+112, 8 bytes each: RVA + Size). + const std::uint32_t dd = ohdr + 112; + // [0] Export directory. + w32(img, dd + 0, rdata_rva_of(exp_dir_off)); + w32(img, dd + 4, 40); + // [1] Import directory. + if (nimports > 0) { + w32(img, dd + 8, rdata_rva_of(imp_desc_off)); + w32(img, dd + 12, (ndlls + 1) * 20); + // [12] IAT. + w32(img, dd + 96, rdata_rva_of(iat_off)); + w32(img, dd + 100, iat_size); + } + + // Section headers. + const std::uint32_t shdrs = 0x148; + { + SectionDesc s; + std::memcpy(s.name, ".text\0\0\0", 8); + s.rva = text_rva; s.vsize = text_vsz; + s.foff = text_foff; s.fsize = text_fsz; + s.chars = 0x60000020; // CNT_CODE | MEM_EXECUTE | MEM_READ + write_section_header(img, shdrs, s); + } + { + SectionDesc s; + std::memcpy(s.name, ".rdata\0\0", 8); + s.rva = rdata_rva; s.vsize = rdata_vsz; + s.foff = rdata_foff; s.fsize = rdata_fsz; + s.chars = 0x40000040; // CNT_INITIALIZED_DATA | MEM_READ + write_section_header(img, shdrs + 40, s); + } + if (has_data) { + SectionDesc s; + std::memcpy(s.name, ".data\0\0\0", 8); + s.rva = data_rva; s.vsize = data_vsz; + s.foff = data_foff; s.fsize = data_fsz; + s.chars = 0xC0000040; // CNT_INITIALIZED_DATA | MEM_READ | MEM_WRITE + write_section_header(img, shdrs + 80, s); + } + + // --- Apply relocations into text_raw --- + // code_vaddr = kImageBase + text_rva + thunks_size (start of code blob) + // data_vaddr = kImageBase + data_rva + // iat_vaddr = kImageBase + rdata_rva + iat_off + const std::uint64_t code_vaddr = kImageBase + text_rva + thunks_size; + const std::uint64_t data_vaddr = kImageBase + data_rva; + const std::uint64_t iat_vaddr = kImageBase + rdata_rva + iat_off; + + std::string reloc_error; + for (const auto& r : input.relocs) { + // dst_offset is within the code blob; in text_raw it is at thunks_size + r.dst_offset. + const std::uint32_t raw_off = thunks_size + r.dst_offset; + // Virtual address of the patch site. + const std::uint64_t P = kImageBase + text_rva + raw_off; + + auto patch32 = [&](std::int64_t v) -> bool { + if (raw_off + 4 > static_cast(text_raw.size())) { + reloc_error = "reloc patch out of range"; + return false; + } + const std::int32_t v32 = static_cast(v); + std::memcpy(text_raw.data() + raw_off, &v32, 4); + return true; + }; + auto patch64 = [&](std::int64_t v) -> bool { + if (raw_off + 8 > static_cast(text_raw.size())) { + reloc_error = "reloc64 patch out of range"; + return false; + } + std::memcpy(text_raw.data() + raw_off, &v, 8); + return true; + }; + + // Helper: find symbol's runtime virtual address. + auto sym_va = [&](std::uint32_t sym_id, std::int64_t addend, + std::uint64_t& va_out) -> bool { + if (auto it = sym_code_offset.find(sym_id); it != sym_code_offset.end()) { + va_out = code_vaddr + it->second + static_cast(addend); + return true; + } + if (auto it = sym_data_offset.find(sym_id); it != sym_data_offset.end()) { + va_out = data_vaddr + it->second + static_cast(addend); + return true; + } + reloc_error = "sym_id not found for reloc"; + return false; + }; + + switch (r.op) { + case RelocOp::PC32: case RelocOp::PC32_1: case RelocOp::PC32_2: + case RelocOp::PC32_4: case RelocOp::PC32_5: { + std::int64_t bias = 0; + if (r.op == RelocOp::PC32_1) bias = -1; + else if (r.op == RelocOp::PC32_2) bias = -2; + else if (r.op == RelocOp::PC32_4) bias = -4; + else if (r.op == RelocOp::PC32_5) bias = -5; + + // Check for thunk call (PLT-like through IAT). + if (auto it = import_to_thunk.find(r.sym_id); + it != import_to_thunk.end()) { + const std::uint64_t thunk_va = + kImageBase + text_rva + it->second * thunk_stride; + const std::int64_t disp = static_cast(thunk_va) + - static_cast(P) + r.addend + bias; + if (!patch32(disp)) goto done; + break; + } + // Internal sym or data sym. + { + std::uint64_t sym_va_val = 0; + if (auto it = sym_code_offset.find(r.sym_id); + it != sym_code_offset.end()) { + sym_va_val = code_vaddr + it->second; + } else if (auto it = sym_data_offset.find(r.sym_id); + it != sym_data_offset.end()) { + sym_va_val = data_vaddr + it->second; + } else { + reloc_error = "PC32: unknown sym_id"; + goto done; + } + const std::int64_t disp = static_cast(sym_va_val) + - static_cast(P) + r.addend + bias; + if (!patch32(disp)) goto done; + } + break; + } + case RelocOp::PLT32: { + // Route through import thunk if external, otherwise treat as PC32. + if (auto it = import_to_thunk.find(r.sym_id); + it != import_to_thunk.end()) { + const std::uint64_t thunk_va = + kImageBase + text_rva + it->second * thunk_stride; + const std::int64_t disp = static_cast(thunk_va) + - static_cast(P) + r.addend; + if (!patch32(disp)) goto done; + break; + } + if (auto it = sym_code_offset.find(r.sym_id); + it != sym_code_offset.end()) { + const std::int64_t disp = static_cast( + code_vaddr + it->second) - static_cast(P) + r.addend; + if (!patch32(disp)) goto done; + break; + } + reloc_error = "PLT32: unknown sym_id"; + goto done; + } + case RelocOp::Abs64: { + std::uint64_t va = 0; + if (!sym_va(r.sym_id, r.addend, va)) goto done; + if (!patch64(static_cast(va))) goto done; + break; + } + case RelocOp::Abs32: case RelocOp::Abs32Signed: { + std::uint64_t va = 0; + if (!sym_va(r.sym_id, r.addend, va)) goto done; + if (!patch32(static_cast(va))) goto done; + break; + } + default: + // Skip GOT/TLS opcodes — not expected in freestanding COFF objects. + break; + } + } +done: + if (!reloc_error.empty()) { + out.ok = false; + out.error = "pe_synth reloc: " + reloc_error; + return out; + } + + // --- Fill import thunk stubs: JMP QWORD PTR [RIP + disp32] --- + // Each stub is at text_rva + i * thunk_stride in the image. + // The IAT entry is at rdata_rva + iat_off + import_iat_slot[i] * 8 + // (the IAT is partitioned per DLL with null terminators, so i != slot). + for (std::uint32_t i = 0; i < nimports; ++i) { + const std::uint32_t stub_off = i * thunk_stride; + const std::uint64_t stub_va = kImageBase + text_rva + stub_off; + const std::uint64_t iat_entry_va = iat_vaddr + import_iat_slot[i] * 8; + // JMP QWORD PTR [RIP + disp]: FF 25 + // RIP at time of dispatch = stub_va + 6. + const std::int64_t disp = static_cast(iat_entry_va) + - static_cast(stub_va + 6); + text_raw[stub_off + 0] = 0xFF; + text_raw[stub_off + 1] = 0x25; + std::int32_t disp32 = static_cast(disp); + std::memcpy(text_raw.data() + stub_off + 2, &disp32, 4); + // bytes 6-15: NOP padding + std::fill(text_raw.begin() + stub_off + 6, + text_raw.begin() + stub_off + thunk_stride, + static_cast(0x90)); + } + + // --- Fill export directory --- + for (std::uint32_t i = 0; i < nexports; ++i) { + // Function RVA = thunks_size + code_offset. + const std::uint32_t fn_rva = + text_rva + thunks_size + + static_cast(input.exports[i].code_offset); + w32(rdata, exp_fn_rvas_off + i * 4, fn_rva); + w32(rdata, exp_name_rvas_off + i * 4, exp_name_rva[i]); + w16(rdata, exp_ordinals_off + i * 2, static_cast(i)); + } + { + const std::uint32_t at = exp_dir_off; + w32(rdata, at + 0, 0); // Characteristics + w32(rdata, at + 4, 0); // TimeDateStamp + w16(rdata, at + 8, 0); w16(rdata, at + 10, 0); // Version + w32(rdata, at + 12, rdata_rva_of(exp_dll_name_off)); // Name + w32(rdata, at + 16, 1); // Base (ordinal base) + w32(rdata, at + 20, nexports); // NumberOfFunctions + w32(rdata, at + 24, nexports); // NumberOfNames + w32(rdata, at + 28, rdata_rva_of(exp_fn_rvas_off)); // AddressOfFunctions + w32(rdata, at + 32, rdata_rva_of(exp_name_rvas_off));// AddressOfNames + w32(rdata, at + 36, rdata_rva_of(exp_ordinals_off)); // AddressOfNameOrdinals + } + + // --- Copy sections into final image --- + std::memcpy(img.data() + text_foff, text_raw.data(), text_raw.size()); + std::memcpy(img.data() + rdata_foff, rdata.data(), rdata.size()); + if (has_data) + std::memcpy(img.data() + data_foff, input.data_blob.data(), input.data_blob.size()); + + return out; +} + +} // namespace voidlibc::loader::windows diff --git a/loader/windows/pe_synth.hpp b/loader/windows/pe_synth.hpp new file mode 100644 index 0000000..89a816e --- /dev/null +++ b/loader/windows/pe_synth.hpp @@ -0,0 +1,60 @@ +#pragma once + +#include "format/reloc_ir.hpp" + +#include +#include +#include + +namespace voidlibc::loader::windows { + +struct WinExportedSymbol { + std::string name; + std::uint64_t code_offset; + std::uint64_t size; + bool is_function = true; +}; + +struct WinImportedSymbol { + std::uint32_t sym_id = 0; + std::string name; + std::string library; // DLL name (e.g. "KERNEL32.DLL"); "" → default ucrtbase.dll +}; + +struct WinInternalSymbol { + std::uint32_t sym_id = 0; + std::uint64_t code_offset = 0; + std::string name; +}; + +struct WinDataSymbol { + std::uint32_t sym_id = 0; + std::uint64_t data_offset = 0; + std::string name; +}; + +struct PeSynthInput { + std::vector code; // [.text] + [.rdata] blob + std::vector exports; + std::vector relocs; + std::vector internal_symbols; + std::vector imports; + std::vector data_blob; // [.data] + [.bss] + std::vector data_symbols; + std::string dll_name; // suggested file name +}; + +struct PeSynthOutput { + std::vector bytes; // complete PE image bytes + std::string error; + bool ok = true; +}; + +// Produce a minimal PE64 DLL image (IMAGE_FILE_DLL, Machine=0x8664) that +// LoadLibraryEx will accept on Windows x64. Exports all symbols in +// input.exports; resolves imported symbols via an IAT pointing into a +// synthetic ".voidlib" import descriptor (the voidlib shim resolves these +// at load time against the calling process's symbol space). +PeSynthOutput synthesize_pe(const PeSynthInput& input); + +} // namespace voidlibc::loader::windows diff --git a/magic.mgc b/magic.mgc new file mode 100644 index 0000000000000000000000000000000000000000..0d66960457cdab77280e47b1251fa84092aff6bb GIT binary patch literal 4752 zcmeH}&uhXk6vrco$mYSrbU)PbE_y1ShV0_Wt7nfJX%g13S|LW){@MEv)?$ip(sN&+ z4TOG43-3cdyfoA9>+b_&>@J_}@P7v&M_jY}f1riGa_qL7GLk%Z2Q9Zc+<-VFmg__r z5)5yO4q1n#uDiO9YUB+aV{o2Jk8sFQu&t^Js@U?dRHE?ep(H9+* zDPjQW`|5M`Mp4_xnuV{0`+xNv;1dEZ&q%aXYYaf8N}MbYV^wQmPm2}4K5l$HBUXA} z$A}vxA=aVcCPQeAj8*;hf_7qvGDQsFXt~t_xDk;)H@?TJd`*y;@{B}FwZ;Hsmhin6 wJdU%x$&zo?==);Tc{oKz=zU%KtJQUpQq^BG.vls|vle +# ============================================================================= + +# --- e2e_load_add: hand-crafted VLC built in-process via builder API --- +# (Not auto-hook driven; builds the VLC itself at runtime.) +add_executable(e2e_load_add load_add.cpp) +target_include_directories(e2e_load_add PRIVATE + ${CMAKE_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/voidlink +) +target_sources(e2e_load_add PRIVATE + ${CMAKE_SOURCE_DIR}/voidlink/builder.cpp + ${CMAKE_SOURCE_DIR}/voidlink/writer.cpp +) +target_link_libraries(e2e_load_add PRIVATE void) +add_test(NAME e2e_load_add COMMAND e2e_load_add) +set_tests_properties(e2e_load_add PROPERTIES LABELS "e2e") + +# --- e2e_load_real_add --- +add_executable(e2e_load_real_add load_real_add.cpp) +target_link_libraries(e2e_load_real_add PRIVATE void) +target_compile_definitions(e2e_load_real_add PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/add_real.vls" +) +add_test(NAME e2e_load_real_add COMMAND e2e_load_real_add) +set_tests_properties(e2e_load_real_add PROPERTIES LABELS "e2e") + +# --- e2e_load_sum_squares --- +add_executable(e2e_load_sum_squares load_sum_squares.cpp) +target_link_libraries(e2e_load_sum_squares PRIVATE void) +target_compile_definitions(e2e_load_sum_squares PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/sum_squares.vls" +) +add_test(NAME e2e_load_sum_squares COMMAND e2e_load_sum_squares) +set_tests_properties(e2e_load_sum_squares PROPERTIES LABELS "e2e") + +# --- e2e_load_hello_printf --- +add_executable(e2e_load_hello_printf load_hello_printf.cpp) +target_link_libraries(e2e_load_hello_printf PRIVATE void) +target_compile_definitions(e2e_load_hello_printf PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/hello_printf.vls" +) +add_test(NAME e2e_load_hello_printf COMMAND e2e_load_hello_printf) +set_tests_properties(e2e_load_hello_printf PROPERTIES LABELS "e2e") + +# --- e2e_load_static_counter --- +add_executable(e2e_load_static_counter load_static_counter.cpp) +target_link_libraries(e2e_load_static_counter PRIVATE void) +target_compile_definitions(e2e_load_static_counter PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/static_counter.vls" +) +add_test(NAME e2e_load_static_counter COMMAND e2e_load_static_counter) +set_tests_properties(e2e_load_static_counter PROPERTIES LABELS "e2e") + +# --- e2e_load_extern_read --- +add_executable(e2e_load_extern_read load_extern_read.cpp) +target_link_libraries(e2e_load_extern_read PRIVATE void) +target_compile_definitions(e2e_load_extern_read PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/extern_read.vls" +) +# The dlopen'd DSO resolves `the_answer` from this executable's symbol table. +target_link_options(e2e_load_extern_read PRIVATE -Wl,--export-dynamic) +add_test(NAME e2e_load_extern_read COMMAND e2e_load_extern_read) +set_tests_properties(e2e_load_extern_read PROPERTIES LABELS "e2e") + +# --- e2e_load_multi_obj --- +add_executable(e2e_load_multi_obj load_multi_obj.cpp) +target_link_libraries(e2e_load_multi_obj PRIVATE void) +target_compile_definitions(e2e_load_multi_obj PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/math_combined.vls" +) +add_test(NAME e2e_load_multi_obj COMMAND e2e_load_multi_obj) +set_tests_properties(e2e_load_multi_obj PROPERTIES LABELS "e2e") + +# --- e2e_exec_mode: voidloader runs hello_exec.vle --- +add_test(NAME e2e_exec_mode + COMMAND $ + ${CMAKE_CURRENT_BINARY_DIR}/hello_exec.vle + hello_arg +) +set_tests_properties(e2e_exec_mode PROPERTIES LABELS "e2e") + +# --- e2e_host_libc_pthread --- +add_executable(e2e_load_host_libc_pthread load_host_libc_pthread.cpp) +target_link_libraries(e2e_load_host_libc_pthread PRIVATE void) +target_compile_definitions(e2e_load_host_libc_pthread PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/host_libc_pthread.vls" +) +add_test(NAME e2e_host_libc_pthread COMMAND e2e_load_host_libc_pthread) +set_tests_properties(e2e_host_libc_pthread PROPERTIES LABELS "e2e;host-libc") + +# --- e2e_host_libc_multi --- +add_executable(e2e_load_host_libc_multi load_host_libc_multi.cpp) +target_link_libraries(e2e_load_host_libc_multi PRIVATE void) +target_compile_definitions(e2e_load_host_libc_multi PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/host_libc_multi.vls" +) +add_test(NAME e2e_host_libc_multi COMMAND e2e_load_host_libc_multi) +set_tests_properties(e2e_host_libc_multi PROPERTIES LABELS "e2e;host-libc") + +# ============================================================================= +# fuse smoke test — verifies the fuse-produced fat VLC loads correctly. +# The auto-hook already uses `voidlink fuse` to build add_real.vls with all 3 +# platform sections, so this test exercises that output directly. +# ============================================================================= +add_executable(e2e_load_fuse load_real_add.cpp) +target_link_libraries(e2e_load_fuse PRIVATE void) +target_compile_definitions(e2e_load_fuse PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/add_real.vls" +) +add_test(NAME e2e_fuse COMMAND e2e_load_fuse) +set_tests_properties(e2e_fuse PROPERTIES LABELS "e2e;fuse") + +# ============================================================================= +# Fat VLC test — same add_real.vls artifact, labeled for CI filtering. +# Confirms the Linux section of the multi-OS container loads and executes. +# ============================================================================= +add_executable(e2e_load_fat_vlc load_real_add.cpp) +target_link_libraries(e2e_load_fat_vlc PRIVATE void) +target_compile_definitions(e2e_load_fat_vlc PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/add_real.vls" +) +add_test(NAME e2e_fat_vlc COMMAND e2e_load_fat_vlc) +set_tests_properties(e2e_fat_vlc PROPERTIES LABELS "e2e;fat-vlc;cross-platform") + +# ============================================================================= +# blob validation test — checks ELF/PE/Mach-O magic bytes in a fat .vls +# without executing cross-platform code; runs on any Linux host. +# ============================================================================= +add_executable(e2e_blob_validate validate_blobs.cpp) +target_link_libraries(e2e_blob_validate PRIVATE voidlibc_format) +target_include_directories(e2e_blob_validate PRIVATE ${CMAKE_SOURCE_DIR}) +target_compile_definitions(e2e_blob_validate PRIVATE + VOIDLIBC_TEST_VLC_PATH="${CMAKE_CURRENT_BINARY_DIR}/add_real.vls" +) +add_test(NAME e2e_blob_validate COMMAND e2e_blob_validate) +set_tests_properties(e2e_blob_validate PROPERTIES + LABELS "e2e;cross-platform" + DEPENDS add_real_vlc +) + +# ============================================================================= +# Register the auto-VLC DEFER hook for this directory. +# All SHARED library targets above that link 'void' will get .vls/.vle built. +# ============================================================================= +voidlibc_enable_auto_vlc() diff --git a/tests/e2e/add_real.c b/tests/e2e/add_real.c new file mode 100644 index 0000000..1f76448 --- /dev/null +++ b/tests/e2e/add_real.c @@ -0,0 +1 @@ +int add(int a, int b) { return a + b; } diff --git a/tests/e2e/extern_read.c b/tests/e2e/extern_read.c new file mode 100644 index 0000000..cc2e580 --- /dev/null +++ b/tests/e2e/extern_read.c @@ -0,0 +1,15 @@ +// Accesses an extern global variable via R_X86_64_REX_GOTPCRELX. +// Tests that the GOT data slot + R_X86_64_GLOB_DAT flow works: +// the synthesized ELF declares the symbol as SHN_UNDEF in .dynsym, +// emits a GLOB_DAT reloc in .rela.dyn, and RTLD resolves it from +// the caller's global symbol table. + +extern int the_answer; + +int get_the_answer(void) { + return the_answer; +} + +int double_the_answer(void) { + return the_answer * 2; +} diff --git a/tests/e2e/hello_exec.c b/tests/e2e/hello_exec.c new file mode 100644 index 0000000..3966f12 --- /dev/null +++ b/tests/e2e/hello_exec.c @@ -0,0 +1,24 @@ +// Exec-mode test: a complete program with main() and printf. +// Compiled to a .vlc and run via voidloader; tests that: +// - main() is exported and callable +// - printf works via PLT → host libc +// - argc/argv are forwarded correctly (argv[0] = .vlc path) + +#include +#include + +int main(int argc, char** argv) { + // argv[0] is the .vlc path; expect at least one extra arg. + if (argc < 2) { + fprintf(stderr, "FAIL: expected at least one argument\n"); + return 1; + } + // Check argv[1] is what we passed from the test. + if (strcmp(argv[1], "hello_arg") != 0) { + fprintf(stderr, "FAIL: argv[1] = '%s', expected 'hello_arg'\n", argv[1]); + return 1; + } + printf("PASS: exec mode — argc=%d argv[0]=%s argv[1]=%s\n", + argc, argv[0], argv[1]); + return 0; +} diff --git a/tests/e2e/hello_printf.c b/tests/e2e/hello_printf.c new file mode 100644 index 0000000..b1b8d47 --- /dev/null +++ b/tests/e2e/hello_printf.c @@ -0,0 +1,11 @@ +#include + +int hello(void) { + printf("hello from vlc: %d\n", 42); + return 42; +} + +int main(void) { + hello(); + return 0; +} diff --git a/tests/e2e/host_libc_multi.c b/tests/e2e/host_libc_multi.c new file mode 100644 index 0000000..29c439f --- /dev/null +++ b/tests/e2e/host_libc_multi.c @@ -0,0 +1,12 @@ +#include +#include + +// Combines a libc.so.6 symbol (strlen) and a libm.so.6 symbol (sqrt). +// Returns 0 on success (verifies both imported symbols resolve correctly). +int multi_libc_test(void) { + const char* msg = "hello"; + size_t n = strlen(msg); // libc.so.6 + double s = sqrt((double)n); // libm.so.6 + // sqrt(5) ≈ 2.236; check it's in a reasonable range. + return (s > 2.0 && s < 3.0) ? 0 : 1; +} diff --git a/tests/e2e/host_libc_pthread.c b/tests/e2e/host_libc_pthread.c new file mode 100644 index 0000000..d6a901c --- /dev/null +++ b/tests/e2e/host_libc_pthread.c @@ -0,0 +1,17 @@ +#include +#include + +static void* worker(void* arg) { + return (void*)((intptr_t)arg * 2); +} + +// Returns (input * 2) computed inside a spawned pthread. +int pthread_double(int x) { + pthread_t tid; + if (pthread_create(&tid, NULL, worker, (void*)(intptr_t)x) != 0) + return -1; + void* ret = NULL; + if (pthread_join(tid, &ret) != 0) + return -2; + return (int)(intptr_t)ret; +} diff --git a/tests/e2e/load_add.cpp b/tests/e2e/load_add.cpp new file mode 100644 index 0000000..c7d43d4 --- /dev/null +++ b/tests/e2e/load_add.cpp @@ -0,0 +1,90 @@ +// E2E: build a one-section .vlc containing the x86_64 bytes for +// +// int add(int a, int b) { return a + b; } +// +// then dlopen it (triggering the libvoid interposer), dlsym("add"), call, assert. +// +// Machine code (System V AMD64 ABI: arg1=EDI, arg2=ESI, return=EAX): +// mov eax, edi ; 89 f8 +// add eax, esi ; 01 f0 +// ret ; c3 + +#include "builder.hpp" +#include "format/vlc_format.hpp" + +#include +#include +#include +#include + +namespace fs = std::filesystem; +using namespace voidlibc::format; +using namespace voidlibc::voidlink; + +namespace { + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int run() { + const fs::path tmp = fs::temp_directory_path() / "voidlibc_add.vls"; + fs::remove(tmp); + + // 1. Build the .vlc. + { + ContainerBuilder b; + + SymbolSpec add_sym{}; + add_sym.name = "add"; + add_sym.kind = SymbolKind::Function; + add_sym.value = 0; + add_sym.size = 5; + add_sym.section_index = 0; + add_sym.exported = true; + b.add_symbol(std::move(add_sym)); + + SectionSpec sec{}; + sec.target_os = TargetOS::Linux; + sec.code = {0x89, 0xf8, 0x01, 0xf0, 0xc3}; + sec.entry_offset = 0; + b.add_section(std::move(sec)); + + const auto w = b.write(tmp); + REQUIRE(w.ok); + } + + // 2. Load via dlopen — the libvoid interposer detects VLC magic and + // synthesizes an ELF DSO transparently. + void* h = ::dlopen(tmp.c_str(), RTLD_NOW); + REQUIRE(h != nullptr); + + // 3. Resolve add. + using add_fn_t = int (*)(int, int); + auto* add = reinterpret_cast(::dlsym(h, "add")); + REQUIRE(add != nullptr); + + // 4. Call it. + const int result = add(7, 35); + if (result != 42) { + std::fprintf(stderr, "FAIL: add(7, 35) = %d (expected 42)\n", result); + std::exit(1); + } + + // 5. Close. + REQUIRE(::dlclose(h) == 0); + fs::remove(tmp); + + std::printf("PASS: e2e_load_add — add(7, 35) = %d\n", result); + return 0; +} + +} // namespace + +int main() { return run(); } diff --git a/tests/e2e/load_extern_read.cpp b/tests/e2e/load_extern_read.cpp new file mode 100644 index 0000000..2938b02 --- /dev/null +++ b/tests/e2e/load_extern_read.cpp @@ -0,0 +1,54 @@ +// E2E: extern global variable access via GOTPCREL / GLOB_DAT. +// extern_read.c references `the_answer` (an extern int defined here in the +// test executable). The synthesized ELF must emit a .rela.dyn GLOB_DAT entry +// so that RTLD resolves `the_answer` from the executable's global symbol table. + +#include +#include +#include + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +// Defined here; exported to the process's global symbol table so the +// dlopen'd synthesized ELF can resolve `the_answer` via GLOB_DAT. +extern "C" int the_answer = 42; + +namespace { + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int run() { + void* h = ::dlopen(VOIDLIBC_TEST_VLC_PATH, RTLD_NOW); + REQUIRE(h != nullptr); + + using int_fn = int (*)(); + auto* get = reinterpret_cast(::dlsym(h, "get_the_answer")); + auto* dbl = reinterpret_cast(::dlsym(h, "double_the_answer")); + REQUIRE(get != nullptr); + REQUIRE(dbl != nullptr); + + REQUIRE(get() == 42); + REQUIRE(dbl() == 84); + + the_answer = 7; + REQUIRE(get() == 7); + REQUIRE(dbl() == 14); + + REQUIRE(::dlclose(h) == 0); + std::printf("PASS: e2e_load_extern_read — GOTPCREL / GLOB_DAT extern global works\n"); + return 0; +} + +} // namespace + +int main() { return run(); } diff --git a/tests/e2e/load_hello_printf.cpp b/tests/e2e/load_hello_printf.cpp new file mode 100644 index 0000000..3c419dd --- /dev/null +++ b/tests/e2e/load_hello_printf.cpp @@ -0,0 +1,46 @@ +// E2E: external-call demo. hello_printf.c calls printf (libc) — +// an external symbol resolved via a synthesized PLT stub at load time. + +#include +#include +#include + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +namespace { + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int run() { + void* h = ::dlopen(VOIDLIBC_TEST_VLC_PATH, RTLD_NOW); + REQUIRE(h != nullptr); + + using fn_t = int (*)(); + auto* hello = reinterpret_cast(::dlsym(h, "hello")); + REQUIRE(hello != nullptr); + + const int result = hello(); + if (result != 42) { + std::fprintf(stderr, "FAIL: hello() = %d (expected 42)\n", result); + std::exit(1); + } + + REQUIRE(::dlclose(h) == 0); + std::printf("PASS: e2e_load_hello_printf — PLT stub resolved, " + "hello() = %d\n", result); + return 0; +} + +} // namespace + +int main() { return run(); } diff --git a/tests/e2e/load_host_libc_multi.cpp b/tests/e2e/load_host_libc_multi.cpp new file mode 100644 index 0000000..174f979 --- /dev/null +++ b/tests/e2e/load_host_libc_multi.cpp @@ -0,0 +1,39 @@ +// E2E: host-libc delegation — symbols from both libc.so.6 (strlen) and libm.so.6 (sqrt). +// Verifies that multi-DT_NEEDED ELF synthesis resolves symbols across two libraries. + +#include +#include +#include + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int main() { + void* h = ::dlopen(VOIDLIBC_TEST_VLC_PATH, RTLD_NOW); + REQUIRE(h != nullptr); + + using fn_t = int (*)(); + auto* fn = reinterpret_cast(::dlsym(h, "multi_libc_test")); + REQUIRE(fn != nullptr); + + const int result = fn(); + if (result != 0) { + std::fprintf(stderr, "FAIL: multi_libc_test() = %d (expected 0)\n", result); + std::exit(1); + } + + REQUIRE(::dlclose(h) == 0); + std::printf("PASS: e2e_host_libc_multi — strlen(libc) + sqrt(libm) resolved\n"); + return 0; +} diff --git a/tests/e2e/load_host_libc_pthread.cpp b/tests/e2e/load_host_libc_pthread.cpp new file mode 100644 index 0000000..2fc46b4 --- /dev/null +++ b/tests/e2e/load_host_libc_pthread.cpp @@ -0,0 +1,40 @@ +// E2E: host-libc delegation — pthread_create/join resolved from libpthread.so.0 +// (or libc.so.6 on modern glibc where pthread is merged). + +#include +#include +#include + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int main() { + void* h = ::dlopen(VOIDLIBC_TEST_VLC_PATH, RTLD_NOW); + REQUIRE(h != nullptr); + + using fn_t = int (*)(int); + auto* fn = reinterpret_cast(::dlsym(h, "pthread_double")); + REQUIRE(fn != nullptr); + + const int result = fn(21); + if (result != 42) { + std::fprintf(stderr, "FAIL: pthread_double(21) = %d (expected 42)\n", result); + std::exit(1); + } + + REQUIRE(::dlclose(h) == 0); + std::printf("PASS: e2e_host_libc_pthread — pthread_create/join resolved, " + "pthread_double(21) = %d\n", result); + return 0; +} diff --git a/tests/e2e/load_multi_obj.cpp b/tests/e2e/load_multi_obj.cpp new file mode 100644 index 0000000..a7684e0 --- /dev/null +++ b/tests/e2e/load_multi_obj.cpp @@ -0,0 +1,55 @@ +// E2E: multi-object merge. math_a.o (add, square) and math_b.o +// (add_and_double, sum_of_squares — calling into math_a) are merged into a +// single .vlc. Tests that cross-object PLT32 relocs are resolved as direct +// PC32 calls (no PLT stub for internally-defined symbols). + +#include +#include +#include + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +namespace { + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int run() { + void* h = ::dlopen(VOIDLIBC_TEST_VLC_PATH, RTLD_NOW); + REQUIRE(h != nullptr); + + using int2_fn = int (*)(int, int); + using int1_fn = int (*)(int); + + auto* add = reinterpret_cast(::dlsym(h, "add")); + auto* square = reinterpret_cast(::dlsym(h, "square")); + auto* add_and_double = reinterpret_cast(::dlsym(h, "add_and_double")); + auto* sum_of_squares = reinterpret_cast(::dlsym(h, "sum_of_squares")); + + REQUIRE(add != nullptr); + REQUIRE(square != nullptr); + REQUIRE(add_and_double != nullptr); + REQUIRE(sum_of_squares != nullptr); + + REQUIRE(add(3, 4) == 7); + REQUIRE(square(5) == 25); + REQUIRE(add_and_double(3, 4) == 14); // (3+4)*2 + REQUIRE(sum_of_squares(3, 4) == 25); // 9+16 + + REQUIRE(::dlclose(h) == 0); + std::printf("PASS: e2e_load_multi_obj — multi-object merge + cross-object call\n"); + return 0; +} + +} // namespace + +int main() { return run(); } diff --git a/tests/e2e/load_real_add.cpp b/tests/e2e/load_real_add.cpp new file mode 100644 index 0000000..6178b72 --- /dev/null +++ b/tests/e2e/load_real_add.cpp @@ -0,0 +1,49 @@ +// E2E: stock-toolchain pipeline. +// +// CMake compiles add_real.c with -fPIC -c, invokes voidlink pack-elf to +// produce add_real.vls, then this test loads it via dlopen (which hits the +// libvoid interposer) and confirms add(7, 35) == 42. + +#include +#include +#include + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +namespace { + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int run() { + void* h = ::dlopen(VOIDLIBC_TEST_VLC_PATH, RTLD_NOW); + REQUIRE(h != nullptr); + + using add_fn_t = int (*)(int, int); + auto* add = reinterpret_cast(::dlsym(h, "add")); + REQUIRE(add != nullptr); + + const int result = add(7, 35); + if (result != 42) { + std::fprintf(stderr, "FAIL: add(7, 35) = %d (expected 42)\n", result); + std::exit(1); + } + + REQUIRE(::dlclose(h) == 0); + std::printf("PASS: e2e_load_real_add — stock toolchain → .vls → libvoid → %d\n", + result); + return 0; +} + +} // namespace + +int main() { return run(); } diff --git a/tests/e2e/load_static_counter.cpp b/tests/e2e/load_static_counter.cpp new file mode 100644 index 0000000..3755f27 --- /dev/null +++ b/tests/e2e/load_static_counter.cpp @@ -0,0 +1,56 @@ +// E2E: global-data demo. static_counter.c uses a BSS global (call_count) +// and an initialised .data global (step). PC32 relocs from .text to both +// sections are patched at synthesis time using vaddr arithmetic. + +#include +#include +#include + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +namespace { + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int run() { + void* h = ::dlopen(VOIDLIBC_TEST_VLC_PATH, RTLD_NOW); + REQUIRE(h != nullptr); + + using void_fn = void (*)(); + using int_fn = int (*)(); + + auto* reset = reinterpret_cast(::dlsym(h, "counter_reset")); + auto* step_up = reinterpret_cast (::dlsym(h, "counter_step_up")); + auto* get = reinterpret_cast (::dlsym(h, "counter_get")); + REQUIRE(reset != nullptr); + REQUIRE(step_up != nullptr); + REQUIRE(get != nullptr); + + REQUIRE(get() == 0); + REQUIRE(step_up() == 1); + REQUIRE(step_up() == 2); + REQUIRE(step_up() == 3); + REQUIRE(get() == 3); + + reset(); + REQUIRE(get() == 0); + REQUIRE(step_up() == 1); + + REQUIRE(::dlclose(h) == 0); + std::printf("PASS: e2e_load_static_counter — BSS/data globals work\n"); + return 0; +} + +} // namespace + +int main() { return run(); } diff --git a/tests/e2e/load_sum_squares.cpp b/tests/e2e/load_sum_squares.cpp new file mode 100644 index 0000000..0cf121a --- /dev/null +++ b/tests/e2e/load_sum_squares.cpp @@ -0,0 +1,49 @@ +// E2E: internal-call demo. sum_squares.c has two functions where +// sum_squares calls square (marked noinline). gcc emits a PC32/PLT32 +// reloc on the call; voidlink lowers it to portable RelocOp::PC32 and +// the synthesizer patches it in-place at load time. + +#include +#include +#include + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +namespace { + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + const char* le = ::dlerror(); \ + if (le) std::fprintf(stderr, " dlerror: %s\n", le); \ + std::exit(1); \ + } \ +} while (0) + +int run() { + void* h = ::dlopen(VOIDLIBC_TEST_VLC_PATH, RTLD_NOW); + REQUIRE(h != nullptr); + + using fn_t = int (*)(int, int); + auto* sum_squares = reinterpret_cast(::dlsym(h, "sum_squares")); + REQUIRE(sum_squares != nullptr); + + const int result = sum_squares(3, 4); // 9 + 16 = 25 + if (result != 25) { + std::fprintf(stderr, "FAIL: sum_squares(3, 4) = %d (expected 25)\n", + result); + std::exit(1); + } + + REQUIRE(::dlclose(h) == 0); + std::printf("PASS: e2e_load_sum_squares — internal reloc patched, " + "sum_squares(3, 4) = %d\n", result); + return 0; +} + +} // namespace + +int main() { return run(); } diff --git a/tests/e2e/math_a.c b/tests/e2e/math_a.c new file mode 100644 index 0000000..916403c --- /dev/null +++ b/tests/e2e/math_a.c @@ -0,0 +1,10 @@ +// Object A: provides add() and square(). +// Compiled separately to test multi-object merge. + +int add(int a, int b) { + return a + b; +} + +int square(int x) { + return x * x; +} diff --git a/tests/e2e/math_b.c b/tests/e2e/math_b.c new file mode 100644 index 0000000..4920359 --- /dev/null +++ b/tests/e2e/math_b.c @@ -0,0 +1,13 @@ +// Object B: calls add() and square() defined in math_a.c. +// Tests cross-object PLT32 → PC32 resolution in the merger. + +extern int add(int, int); +extern int square(int); + +int add_and_double(int a, int b) { + return add(a, b) * 2; +} + +int sum_of_squares(int a, int b) { + return add(square(a), square(b)); +} diff --git a/tests/e2e/static_counter.c b/tests/e2e/static_counter.c new file mode 100644 index 0000000..2355f15 --- /dev/null +++ b/tests/e2e/static_counter.c @@ -0,0 +1,18 @@ +// Stateful library using BSS (zero-init global) and .data (init global). +// Exercises PC32 relocs from .text to .bss/.data across segments. + +static int call_count = 0; // BSS: zero-initialized +static int step = 1; // .data: initialized to 1 + +void counter_reset(void) { + call_count = 0; +} + +int counter_step_up(void) { + call_count += step; + return call_count; +} + +int counter_get(void) { + return call_count; +} diff --git a/tests/e2e/sum_squares.c b/tests/e2e/sum_squares.c new file mode 100644 index 0000000..22de770 --- /dev/null +++ b/tests/e2e/sum_squares.c @@ -0,0 +1,6 @@ +__attribute__((noinline)) +int square(int x) { return x * x; } + +int sum_squares(int a, int b) { + return square(a) + square(b); +} diff --git a/tests/e2e/validate_blobs.cpp b/tests/e2e/validate_blobs.cpp new file mode 100644 index 0000000..f61c3b0 --- /dev/null +++ b/tests/e2e/validate_blobs.cpp @@ -0,0 +1,84 @@ +// E2E: structural blob validation — confirms the Windows (MZ) and macOS +// (Mach-O 64-bit) sections inside a fat .vls have correct magic bytes. +// This runs on Linux and validates cross-platform blobs without executing them. + +#include +#include +#include +#include +#include +#include + +#include "format/vlc_format.hpp" + +#ifndef VOIDLIBC_TEST_VLC_PATH +#error "VOIDLIBC_TEST_VLC_PATH must be set by CMake" +#endif + +using namespace voidlibc::format; + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + std::exit(1); \ + } \ +} while (0) + +static std::vector read_section_bytes( + std::ifstream& f, const SectionEntry& sec) { + f.seekg(static_cast(sec.code_off)); + std::vector buf(static_cast(sec.code_size)); + f.read(reinterpret_cast(buf.data()), + static_cast(buf.size())); + return buf; +} + +int main() { + std::ifstream f(VOIDLIBC_TEST_VLC_PATH, std::ios::binary); + REQUIRE(f.is_open()); + + FileHeader hdr{}; + f.read(reinterpret_cast(&hdr), sizeof(hdr)); + REQUIRE(f.good()); + REQUIRE(hdr.magic == kMagic); + REQUIRE(hdr.section_count >= 3); // must have linux + windows + macos + + f.seekg(static_cast(hdr.section_dir_off)); + std::vector sects(hdr.section_count); + f.read(reinterpret_cast(sects.data()), + static_cast(hdr.section_count * sizeof(SectionEntry))); + REQUIRE(f.good()); + + bool saw_linux = false, saw_windows = false, saw_macos = false; + + for (const auto& sec : sects) { + REQUIRE(sec.kind == SectionKind::NativeBlob); + REQUIRE(sec.code_size >= 4); + auto bytes = read_section_bytes(f, sec); + REQUIRE(bytes.size() >= 4); + + if (sec.target_os == TargetOS::Linux) { + // ELF magic: \x7F E L F + REQUIRE(bytes[0] == 0x7F && bytes[1] == 'E' && + bytes[2] == 'L' && bytes[3] == 'F'); + saw_linux = true; + } else if (sec.target_os == TargetOS::Windows) { + // PE: MZ header + REQUIRE(bytes[0] == 'M' && bytes[1] == 'Z'); + saw_windows = true; + } else if (sec.target_os == TargetOS::MacOS) { + // Mach-O 64-bit LE: 0xCFFAEDFE + REQUIRE(bytes[0] == 0xCF && bytes[1] == 0xFA && + bytes[2] == 0xED && bytes[3] == 0xFE); + saw_macos = true; + } + } + + REQUIRE(saw_linux); + REQUIRE(saw_windows); + REQUIRE(saw_macos); + + std::printf("PASS: e2e_blob_validate — ELF/PE/Mach-O magic bytes all correct\n"); + return 0; +} diff --git a/tests/format/CMakeLists.txt b/tests/format/CMakeLists.txt new file mode 100644 index 0000000..6802344 --- /dev/null +++ b/tests/format/CMakeLists.txt @@ -0,0 +1,15 @@ +add_executable(test_format_roundtrip roundtrip.cpp) +target_link_libraries(test_format_roundtrip PRIVATE voidlibc_format) +target_include_directories(test_format_roundtrip + PRIVATE + ${CMAKE_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/voidlink +) +# Pick up writer/reader sources directly — these are small and tests are +# the only consumer outside the voidlink binary. +target_sources(test_format_roundtrip PRIVATE + ${CMAKE_SOURCE_DIR}/voidlink/writer.cpp + ${CMAKE_SOURCE_DIR}/voidlink/reader.cpp +) +add_test(NAME format_roundtrip COMMAND test_format_roundtrip) +set_tests_properties(format_roundtrip PROPERTIES LABELS "format;unit") diff --git a/tests/format/roundtrip.cpp b/tests/format/roundtrip.cpp new file mode 100644 index 0000000..0d0c43a --- /dev/null +++ b/tests/format/roundtrip.cpp @@ -0,0 +1,50 @@ +#include "format/vlc_format.hpp" +#include "reader.hpp" +#include "writer.hpp" + +#include +#include +#include + +namespace fs = std::filesystem; +using namespace voidlibc::format; +using namespace voidlibc::voidlink; + +namespace { + +#define EXPECT(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL: %s (line %d)\n", #cond, \ + __LINE__); \ + std::exit(1); \ + } \ +} while (0) + +int run() { + const fs::path tmp = fs::temp_directory_path() / "voidlibc_roundtrip.vlc"; + fs::remove(tmp); + + { + const auto w = write_empty(tmp); + EXPECT(w.ok); + } + { + const auto r = read_container(tmp); + const auto* container = std::get_if(&r); + EXPECT(container != nullptr); + EXPECT(container->header.magic == kMagic); + EXPECT(container->header.version_major == kVersionMajor); + EXPECT(container->header.version_minor == kVersionMinor); + EXPECT(container->header.arch == TargetArch::X86_64); + EXPECT(container->header.section_count == 0); + EXPECT(container->header.file_size == sizeof(FileHeader)); + EXPECT(container->actual_file_size == sizeof(FileHeader)); + } + fs::remove(tmp); + std::printf("PASS: format_roundtrip\n"); + return 0; +} + +} // namespace + +int main() { return run(); } diff --git a/tests/fuzz/CMakeLists.txt b/tests/fuzz/CMakeLists.txt new file mode 100644 index 0000000..1e2f879 --- /dev/null +++ b/tests/fuzz/CMakeLists.txt @@ -0,0 +1,33 @@ +# libFuzzer harnesses for VoidLibC format readers. +# Requires clang with -fsanitize=fuzzer,address support. +# Enable with: cmake -DVOIDLIBC_BUILD_FUZZ=ON ... +# +# Each fuzzer reads arbitrary bytes from stdin (via LLVMFuzzerTestOneInput), +# writes them to a memfd, and calls the corresponding parser. A crash means +# the parser has undefined behaviour on malformed input. +# +# Typical usage: +# mkdir corpus && ./fuzz_elf_reader corpus/ -max_total_time=3600 +# ./fuzz_elf_reader -rss_limit_mb=512 corpus/ crashes/ + +set(FUZZ_FLAGS -fsanitize=fuzzer,address -g -O1) + +# Reader sources live in voidlink/; elf_reader also needs loader/common/elf64.hpp. +set(ELF_READER_SRC ${CMAKE_SOURCE_DIR}/voidlink/elf_reader.cpp) +set(COFF_READER_SRC ${CMAKE_SOURCE_DIR}/voidlink/coff_reader.cpp) +set(MACHO_READER_SRC ${CMAKE_SOURCE_DIR}/voidlink/macho_reader.cpp) + +function(add_fuzz_target name src) + add_executable(${name} ${name}.cpp ${src}) + target_include_directories(${name} PRIVATE + ${CMAKE_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/voidlink + ) + target_compile_options(${name} PRIVATE ${FUZZ_FLAGS}) + target_link_options(${name} PRIVATE ${FUZZ_FLAGS}) + # No install rule — fuzz binaries are for local developer / CI use only. +endfunction() + +add_fuzz_target(fuzz_elf_reader ${ELF_READER_SRC}) +add_fuzz_target(fuzz_coff_reader ${COFF_READER_SRC}) +add_fuzz_target(fuzz_macho_reader ${MACHO_READER_SRC}) diff --git a/tests/fuzz/fuzz_coff_reader.cpp b/tests/fuzz/fuzz_coff_reader.cpp new file mode 100644 index 0000000..eb58764 --- /dev/null +++ b/tests/fuzz/fuzz_coff_reader.cpp @@ -0,0 +1,31 @@ +// libFuzzer harness for the COFF object file reader. +// Build with: cmake -DVOIDLIBC_BUILD_FUZZ=ON ... +// Run: ./fuzz_coff_reader [-max_total_time=60] [corpus_dir] + +#include "voidlink/coff_reader.hpp" + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) { + const int fd = static_cast(::syscall(SYS_memfd_create, "fuzz_coff", 0)); + if (fd < 0) return 0; + + const std::uint8_t* p = data; + std::size_t rem = size; + while (rem > 0) { + const ssize_t n = ::write(fd, p, rem); + if (n <= 0) break; + p += static_cast(n); + rem -= static_cast(n); + } + + char path[64]; + std::snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + (void)voidlibc::voidlink::coff::parse_coff_object(path); + + ::close(fd); + return 0; +} diff --git a/tests/fuzz/fuzz_elf_reader.cpp b/tests/fuzz/fuzz_elf_reader.cpp new file mode 100644 index 0000000..827cde9 --- /dev/null +++ b/tests/fuzz/fuzz_elf_reader.cpp @@ -0,0 +1,32 @@ +// libFuzzer harness for the ELF object file reader. +// Build with: cmake -DVOIDLIBC_BUILD_FUZZ=ON ... +// Run: ./fuzz_elf_reader [-max_total_time=60] [corpus_dir] + +#include "voidlink/elf_reader.hpp" + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) { + // Use memfd so no real file I/O hits disk. + const int fd = static_cast(::syscall(SYS_memfd_create, "fuzz_elf", 0)); + if (fd < 0) return 0; + + const std::uint8_t* p = data; + std::size_t rem = size; + while (rem > 0) { + const ssize_t n = ::write(fd, p, rem); + if (n <= 0) break; + p += static_cast(n); + rem -= static_cast(n); + } + + char path[64]; + std::snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + (void)voidlibc::voidlink::elf::parse_elf64_object(path); + + ::close(fd); + return 0; +} diff --git a/tests/fuzz/fuzz_macho_reader.cpp b/tests/fuzz/fuzz_macho_reader.cpp new file mode 100644 index 0000000..4af14ca --- /dev/null +++ b/tests/fuzz/fuzz_macho_reader.cpp @@ -0,0 +1,31 @@ +// libFuzzer harness for the Mach-O object file reader. +// Build with: cmake -DVOIDLIBC_BUILD_FUZZ=ON ... +// Run: ./fuzz_macho_reader [-max_total_time=60] [corpus_dir] + +#include "voidlink/macho_reader.hpp" + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) { + const int fd = static_cast(::syscall(SYS_memfd_create, "fuzz_macho", 0)); + if (fd < 0) return 0; + + const std::uint8_t* p = data; + std::size_t rem = size; + while (rem > 0) { + const ssize_t n = ::write(fd, p, rem); + if (n <= 0) break; + p += static_cast(n); + rem -= static_cast(n); + } + + char path[64]; + std::snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + (void)voidlibc::voidlink::macho::parse_macho_object(path); + + ::close(fd); + return 0; +} diff --git a/tests/synth/CMakeLists.txt b/tests/synth/CMakeLists.txt new file mode 100644 index 0000000..385135e --- /dev/null +++ b/tests/synth/CMakeLists.txt @@ -0,0 +1,24 @@ +# Synthesizer unit tests — verify ELF/PE/Mach-O output structure without +# executing the synthesized blobs. These link the synthesizer static libraries +# directly; they don't need the full loader runtime. + +# ── ELF synth tests ────────────────────────────────────────────────────────── +add_executable(test_elf_synth elf_synth_test.cpp) +target_link_libraries(test_elf_synth PRIVATE voidlibc_loader_common) +target_include_directories(test_elf_synth PRIVATE ${CMAKE_SOURCE_DIR}) +add_test(NAME synth_elf COMMAND test_elf_synth) +set_tests_properties(synth_elf PROPERTIES LABELS "synth;unit") + +# ── PE synth tests ─────────────────────────────────────────────────────────── +add_executable(test_pe_synth pe_synth_test.cpp) +target_link_libraries(test_pe_synth PRIVATE voidlibc_loader_windows) +target_include_directories(test_pe_synth PRIVATE ${CMAKE_SOURCE_DIR}) +add_test(NAME synth_pe COMMAND test_pe_synth) +set_tests_properties(synth_pe PROPERTIES LABELS "synth;unit") + +# ── Mach-O synth tests ─────────────────────────────────────────────────────── +add_executable(test_macho_synth macho_synth_test.cpp) +target_link_libraries(test_macho_synth PRIVATE voidlibc_loader_macos) +target_include_directories(test_macho_synth PRIVATE ${CMAKE_SOURCE_DIR}) +add_test(NAME synth_macho COMMAND test_macho_synth) +set_tests_properties(synth_macho PROPERTIES LABELS "synth;unit") diff --git a/tests/synth/elf_synth_test.cpp b/tests/synth/elf_synth_test.cpp new file mode 100644 index 0000000..6c2359d --- /dev/null +++ b/tests/synth/elf_synth_test.cpp @@ -0,0 +1,173 @@ +// Unit tests for synthesize_elf() — verifies the structural correctness of +// the ELF64 DSO bytes without executing them. + +#include "loader/common/elf_synth.hpp" +#include "loader/common/elf64.hpp" + +#include +#include +#include +#include + +using namespace voidlibc::loader; + +// ── Helpers ───────────────────────────────────────────────────────────────── + +template +static T read_at(const std::vector& b, std::size_t off) { + T val{}; + if (off + sizeof(T) <= b.size()) std::memcpy(&val, b.data() + off, sizeof(T)); + return val; +} + +static int count_dyn_tag(const std::vector& b, std::int64_t tag) { + const Ehdr hdr = read_at(b, 0); + int count = 0; + for (int pi = 0; pi < hdr.e_phnum; ++pi) { + const Phdr ph = read_at(b, hdr.e_phoff + static_cast(pi) * sizeof(Phdr)); + if (ph.p_type != kPtDynamic) continue; + for (std::size_t off = ph.p_offset; off + sizeof(Dyn) <= ph.p_offset + ph.p_filesz; off += sizeof(Dyn)) { + const Dyn dyn = read_at(b, off); + if (dyn.d_tag == kDtNull) break; + if (dyn.d_tag == tag) ++count; + } + break; + } + return count; +} + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL [%s]: %s (line %d)\n", \ + test_name, #cond, __LINE__); \ + ++failures; \ + } \ +} while (0) + +// ── Tests ──────────────────────────────────────────────────────────────────── + +static int test_basic_magic_and_type(const char* test_name) { + int failures = 0; + ElfSynthInput in{}; + in.code = {0x90}; // nop + ExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + in.exports.push_back(e); + + const auto out = synthesize_elf(in); + REQUIRE(out.ok); + REQUIRE(out.bytes.size() >= sizeof(Ehdr)); + + const Ehdr hdr = read_at(out.bytes, 0); + REQUIRE(hdr.e_ident[0] == kElfMag0); + REQUIRE(hdr.e_ident[1] == kElfMag1); + REQUIRE(hdr.e_ident[2] == kElfMag2); + REQUIRE(hdr.e_ident[3] == kElfMag3); + REQUIRE(hdr.e_type == kEtDyn); + REQUIRE(hdr.e_machine == kEmX86_64); + return failures; +} + +static int test_multi_needed_two_libs(const char* test_name) { + int failures = 0; + ElfSynthInput in{}; + in.code = {0x90}; + ExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + in.exports.push_back(e); + + ImportedSymbol im1{}; im1.sym_id = 0; im1.name = "printf"; im1.library = "libc.so.6"; + ImportedSymbol im2{}; im2.sym_id = 1; im2.name = "sqrt"; im2.library = "libm.so.6"; + in.imports.push_back(im1); + in.imports.push_back(im2); + + const auto out = synthesize_elf(in); + REQUIRE(out.ok); + REQUIRE(count_dyn_tag(out.bytes, kDtNeeded) == 2); + return failures; +} + +static int test_no_needed_when_no_imports(const char* test_name) { + int failures = 0; + ElfSynthInput in{}; + in.code = {0x90}; + ExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + in.exports.push_back(e); + // No imports → no DT_NEEDED + + const auto out = synthesize_elf(in); + REQUIRE(out.ok); + REQUIRE(count_dyn_tag(out.bytes, kDtNeeded) == 0); + return failures; +} + +static int test_versioned_import_emits_verneed(const char* test_name) { + int failures = 0; + ElfSynthInput in{}; + in.code = {0x90}; + ExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + in.exports.push_back(e); + + ImportedSymbol im{}; + im.sym_id = 0; + im.name = "memcpy"; + im.library = "libc.so.6"; + im.version_name = "GLIBC_2.14"; + im.version_hash = elf_hash("GLIBC_2.14"); + im.version_flags = 0; + in.imports.push_back(im); + + const auto out = synthesize_elf(in); + REQUIRE(out.ok); + REQUIRE(count_dyn_tag(out.bytes, kDtVerneed) == 1); + REQUIRE(count_dyn_tag(out.bytes, kDtVerneedNum) == 1); + REQUIRE(count_dyn_tag(out.bytes, kDtVersym) == 1); + return failures; +} + +static int test_unversioned_import_no_verneed(const char* test_name) { + int failures = 0; + ElfSynthInput in{}; + in.code = {0x90}; + ExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + in.exports.push_back(e); + + ImportedSymbol im{}; + im.sym_id = 0; + im.name = "strlen"; + im.library = "libc.so.6"; + // version_name intentionally empty + in.imports.push_back(im); + + const auto out = synthesize_elf(in); + REQUIRE(out.ok); + REQUIRE(count_dyn_tag(out.bytes, kDtVerneed) == 0); + REQUIRE(count_dyn_tag(out.bytes, kDtVersym) == 0); + return failures; +} + +// ── main ───────────────────────────────────────────────────────────────────── + +struct Test { const char* name; int (*fn)(const char*); }; + +static const Test kTests[] = { + {"elf_basic_magic_and_type", test_basic_magic_and_type}, + {"elf_multi_needed_two_libs", test_multi_needed_two_libs}, + {"elf_no_needed_when_no_imports", test_no_needed_when_no_imports}, + {"elf_versioned_import_emits_verneed",test_versioned_import_emits_verneed}, + {"elf_unversioned_import_no_verneed", test_unversioned_import_no_verneed}, +}; + +int main() { + int total_failures = 0; + for (const auto& t : kTests) { + const int f = t.fn(t.name); + total_failures += f; + std::printf("%s: %s\n", f == 0 ? "PASS" : "FAIL", t.name); + } + if (total_failures > 0) { + std::fprintf(stderr, "%d assertion(s) failed\n", total_failures); + return 1; + } + std::printf("All %zu ELF synth tests passed\n", + sizeof(kTests) / sizeof(kTests[0])); + return 0; +} diff --git a/tests/synth/macho_synth_test.cpp b/tests/synth/macho_synth_test.cpp new file mode 100644 index 0000000..9409ab1 --- /dev/null +++ b/tests/synth/macho_synth_test.cpp @@ -0,0 +1,157 @@ +// Unit tests for synthesize_macho() — verifies Mach-O64 dylib output structure +// without executing it. Parses mach_header_64 and load commands directly. + +#include "loader/macos/macho_synth.hpp" +#include "format/reloc_ir.hpp" + +#include +#include +#include +#include + +using namespace voidlibc::loader::macos; +using voidlibc::format::RelocEntry; +using voidlibc::format::RelocOp; + +template +static T read_at(const std::vector& b, std::size_t off) { + T val{}; + if (off + sizeof(T) <= b.size()) std::memcpy(&val, b.data() + off, sizeof(T)); + return val; +} + +// Mach-O constants (matching macho_synth.cpp internals) +static constexpr std::uint32_t kMhMagic64 = 0xFEEDFACFu; +static constexpr std::uint32_t kMhDylib = 6u; +static constexpr std::uint32_t kLcLoadDylib = 0x0Cu; + +// mach_header_64 layout: +// [0] magic uint32 [4] cputype int32 +// [8] cpusubtype int32 [12] filetype uint32 +// [16] ncmds uint32 [20] sizeofcmds uint32 +// [24] flags uint32 [28] reserved uint32 +// Load commands start at byte 32. + +static int count_load_commands(const std::vector& b, std::uint32_t cmd_type) { + const std::uint32_t ncmds = read_at(b, 16); + std::size_t lc_off = 32; + int count = 0; + for (std::uint32_t i = 0; i < ncmds && lc_off + 8 <= b.size(); ++i) { + const std::uint32_t cmd = read_at(b, lc_off); + const std::uint32_t cmdsize = read_at(b, lc_off + 4); + if (cmdsize == 0) break; + if (cmd == cmd_type) ++count; + lc_off += cmdsize; + } + return count; +} + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL [%s]: %s (line %d)\n", \ + test_name, #cond, __LINE__); \ + ++failures; \ + } \ +} while (0) + +static int test_macho_magic_and_filetype(const char* test_name) { + int failures = 0; + MachoSynthInput in{}; + in.code = {0x90}; // nop + MachoExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + in.exports.push_back(e); + + const auto out = synthesize_macho(in); + REQUIRE(out.ok); + REQUIRE(out.bytes.size() >= 32); + REQUIRE(read_at(out.bytes, 0) == kMhMagic64); // magic + REQUIRE(read_at(out.bytes, 12) == kMhDylib); // filetype + return failures; +} + +// Verify that N entries in needed_libs → N LC_LOAD_DYLIB commands. +static int test_macho_multi_dylib_via_needed_libs(const char* test_name) { + int failures = 0; + MachoExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + + // Two explicit dylib requirements → two LC_LOAD_DYLIB + { + MachoSynthInput in{}; + in.code = {0x90}; + in.exports.push_back(e); + in.needed_libs = {"/usr/lib/libSystem.B.dylib", "/usr/lib/libm.dylib"}; + const auto out = synthesize_macho(in); + REQUIRE(out.ok); + REQUIRE(count_load_commands(out.bytes, kLcLoadDylib) == 2); + } + // One explicit dylib → one LC_LOAD_DYLIB + { + MachoSynthInput in{}; + in.code = {0x90}; + in.exports.push_back(e); + in.needed_libs = {"/usr/lib/libSystem.B.dylib"}; + const auto out = synthesize_macho(in); + REQUIRE(out.ok); + REQUIRE(count_load_commands(out.bytes, kLcLoadDylib) == 1); + } + return failures; +} + +// Verify per-import library attribution via PLT32 relocs drives LC_LOAD_DYLIB +// selection (the reloc-driven path inside synthesize_macho). +static int test_macho_import_library_attribution(const char* test_name) { + int failures = 0; + MachoExportedSymbol e{}; e.name = "fn"; e.code_offset = 5; e.is_function = true; + + // Two CALL instructions in the code blob, each referencing a different import. + // offset 0: e8 00 00 00 00 (CALL rel32 placeholder, import sym_id=10) + // offset 5: 90 (nop — exported fn entry) + // offset 6: e8 00 00 00 00 (CALL rel32 placeholder, import sym_id=20) + MachoSynthInput in{}; + in.code = {0xe8,0x00,0x00,0x00,0x00, 0x90, + 0xe8,0x00,0x00,0x00,0x00, 0x90}; + in.exports.push_back(e); + + MachoImportedSymbol im1{}; im1.sym_id = 10; im1.name = "strlen"; + im1.library = "/usr/lib/libSystem.B.dylib"; + MachoImportedSymbol im2{}; im2.sym_id = 20; im2.name = "sqrt"; + im2.library = "/usr/lib/libm.dylib"; + in.imports.push_back(im1); + in.imports.push_back(im2); + + // PLT32 relocs so the synthesizer sees nstubs=2 and picks up im.library. + RelocEntry r1{}; r1.op = RelocOp::PLT32; r1.dst_offset = 1; r1.sym_id = 10; r1.addend = -4; + RelocEntry r2{}; r2.op = RelocOp::PLT32; r2.dst_offset = 7; r2.sym_id = 20; r2.addend = -4; + in.relocs.push_back(r1); + in.relocs.push_back(r2); + + const auto out = synthesize_macho(in); + REQUIRE(out.ok); + // Two distinct libraries → two LC_LOAD_DYLIB + REQUIRE(count_load_commands(out.bytes, kLcLoadDylib) == 2); + return failures; +} + +struct Test { const char* name; int (*fn)(const char*); }; + +static const Test kTests[] = { + {"macho_magic_and_filetype", test_macho_magic_and_filetype}, + {"macho_multi_dylib_via_needed_libs", test_macho_multi_dylib_via_needed_libs}, + {"macho_import_library_attribution", test_macho_import_library_attribution}, +}; + +int main() { + int total_failures = 0; + for (const auto& t : kTests) { + const int f = t.fn(t.name); + total_failures += f; + std::printf("%s: %s\n", f == 0 ? "PASS" : "FAIL", t.name); + } + if (total_failures > 0) { + std::fprintf(stderr, "%d assertion(s) failed\n", total_failures); + return 1; + } + std::printf("All %zu Mach-O synth tests passed\n", + sizeof(kTests) / sizeof(kTests[0])); + return 0; +} diff --git a/tests/synth/pe_synth_test.cpp b/tests/synth/pe_synth_test.cpp new file mode 100644 index 0000000..bf6c97f --- /dev/null +++ b/tests/synth/pe_synth_test.cpp @@ -0,0 +1,129 @@ +// Unit tests for synthesize_pe() — verifies PE64 DLL output structure +// without executing it. Parses the raw bytes using known PE offsets. + +#include "loader/windows/pe_synth.hpp" + +#include +#include +#include +#include + +using namespace voidlibc::loader::windows; + +template +static T read_at(const std::vector& b, std::size_t off) { + T val{}; + if (off + sizeof(T) <= b.size()) std::memcpy(&val, b.data() + off, sizeof(T)); + return val; +} + +// From pe_synth.cpp layout (stable, documented in the file header): +// 0x000: DOS stub +// 0x040: "PE\0\0" PE signature +// 0x044: IMAGE_FILE_HEADER (20 bytes) +// 0x058: IMAGE_OPTIONAL_HEADER64 +// +112 (= 0xC8): DataDirectory[0] export RVA/Size +// +120 (= 0xD0): DataDirectory[1] import RVA +// +124 (= 0xD4): DataDirectory[1] import Size = (ndlls+1)*20 + +static constexpr std::uint32_t kPeSigOff = 0x040; +static constexpr std::uint32_t kFileHdrOff = 0x044; +static constexpr std::uint32_t kOptHdrOff = 0x058; +static constexpr std::uint32_t kImportSizeOff= kOptHdrOff + 112 + 12; // 0xD4 +static constexpr std::uint32_t kCharacteristicsOff = kFileHdrOff + 18; // 0x056 + +static constexpr std::uint16_t kCharDll = 0x2000; +static constexpr std::uint16_t kMachineAmd64 = 0x8664; + +#define REQUIRE(cond) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL [%s]: %s (line %d)\n", \ + test_name, #cond, __LINE__); \ + ++failures; \ + } \ +} while (0) + +static int test_pe_magic_and_dll_flag(const char* test_name) { + int failures = 0; + PeSynthInput in{}; + in.code = {0x90}; // nop + in.dll_name = "test.dll"; + WinExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + in.exports.push_back(e); + + const auto out = synthesize_pe(in); + REQUIRE(out.ok); + REQUIRE(out.bytes.size() > kImportSizeOff + 4); + + // MZ magic + REQUIRE(out.bytes[0] == 'M' && out.bytes[1] == 'Z'); + // PE signature + REQUIRE(out.bytes[kPeSigOff + 0] == 'P'); + REQUIRE(out.bytes[kPeSigOff + 1] == 'E'); + REQUIRE(out.bytes[kPeSigOff + 2] == '\0'); + REQUIRE(out.bytes[kPeSigOff + 3] == '\0'); + // Machine = AMD64 + REQUIRE(read_at(out.bytes, kFileHdrOff) == kMachineAmd64); + // IMAGE_FILE_DLL set + const auto chars = read_at(out.bytes, kCharacteristicsOff); + REQUIRE((chars & kCharDll) != 0); + + return failures; +} + +static int test_pe_multi_dll_import_dir_size(const char* test_name) { + int failures = 0; + PeSynthInput in{}; + in.code = {0x90}; + in.dll_name = "test.dll"; + WinExportedSymbol e{}; e.name = "fn"; e.code_offset = 0; e.is_function = true; + in.exports.push_back(e); + + WinImportedSymbol im1{}; im1.sym_id = 0; im1.name = "printf"; im1.library = "ucrtbase.dll"; + WinImportedSymbol im2{}; im2.sym_id = 1; im2.name = "ExitProcess"; im2.library = "KERNEL32.DLL"; + in.imports.push_back(im1); + in.imports.push_back(im2); + + const auto out = synthesize_pe(in); + REQUIRE(out.ok); + + // import dir size = (ndlls + 1) * 20; ndlls=2 → 60 + const auto imp_sz = read_at(out.bytes, kImportSizeOff); + REQUIRE(imp_sz == 60u); + + // Sanity: single-DLL import should give size 40 + PeSynthInput in1{}; + in1.code = {0x90}; + in1.dll_name = "test.dll"; + in1.exports.push_back(e); + WinImportedSymbol im_single{}; im_single.sym_id = 0; im_single.name = "puts"; im_single.library = "ucrtbase.dll"; + in1.imports.push_back(im_single); + const auto out1 = synthesize_pe(in1); + REQUIRE(out1.ok); + REQUIRE(read_at(out1.bytes, kImportSizeOff) == 40u); + + return failures; +} + +struct Test { const char* name; int (*fn)(const char*); }; + +static const Test kTests[] = { + {"pe_magic_and_dll_flag", test_pe_magic_and_dll_flag}, + {"pe_multi_dll_import_dir_size", test_pe_multi_dll_import_dir_size}, +}; + +int main() { + int total_failures = 0; + for (const auto& t : kTests) { + const int f = t.fn(t.name); + total_failures += f; + std::printf("%s: %s\n", f == 0 ? "PASS" : "FAIL", t.name); + } + if (total_failures > 0) { + std::fprintf(stderr, "%d assertion(s) failed\n", total_failures); + return 1; + } + std::printf("All %zu PE synth tests passed\n", + sizeof(kTests) / sizeof(kTests[0])); + return 0; +} diff --git a/tools/gen_symlib_table.py b/tools/gen_symlib_table.py new file mode 100755 index 0000000..98fb925 --- /dev/null +++ b/tools/gen_symlib_table.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Generate voidlink/symlib_table.cpp from data/symlib_{linux,windows,macos}.txt. + +Usage: + python3 tools/gen_symlib_table.py # from project root + python3 tools/gen_symlib_table.py --check # verify .cpp is up-to-date; exit 1 if not + +The .txt format: one entry per line — "symbol library" whitespace-separated. +Lines beginning with # are comments. Entries MUST be sorted by symbol name. +""" + +import sys +import os +import re +import argparse +from pathlib import Path + +SCRIPT_DIR = Path(__file__).parent +PROJECT_ROOT = SCRIPT_DIR.parent +DATA_DIR = PROJECT_ROOT / "data" +OUT_FILE = PROJECT_ROOT / "voidlink" / "symlib_table.cpp" + +PLATFORMS = [ + ("linux", "linux_table", DATA_DIR / "symlib_linux.txt"), + ("windows", "windows_table", DATA_DIR / "symlib_windows.txt"), + ("macos", "macos_table", DATA_DIR / "symlib_macos.txt"), +] + +HEADER = """\ +// Per-OS symbol → import library table. +// Generated from data/symlib_{linux,windows,macos}.txt — edit those files, +// then run: python3 tools/gen_symlib_table.py +// Arrays MUST remain sorted by first field (symbol name) for binary search. + +#include "symlib_table.hpp" +#include "format/vlc_format.hpp" + +#include +#include +#include + +using namespace std::string_view_literals; + +namespace { + +struct Entry { std::string_view name; std::string_view library; }; + +""" + +FOOTER = """\ +template +static std::string_view lookup(const Table& table, std::string_view name) { + auto it = std::lower_bound( + table.begin(), table.end(), name, + [](const Entry& e, std::string_view n) { return e.name < n; }); + if (it != table.end() && it->name == name) return it->library; + return {}; +} + +} // namespace + +namespace voidlibc::voidlink { + +std::string_view library_for(voidlibc::format::TargetOS os, std::string_view name) { + using voidlibc::format::TargetOS; + switch (os) { + case TargetOS::Linux: return lookup(linux_table, name); + case TargetOS::Windows: return lookup(windows_table, name); + case TargetOS::MacOS: return lookup(macos_table, name); + default: return {}; + } +} + +std::string_view default_library(voidlibc::format::TargetOS os) { + using voidlibc::format::TargetOS; + switch (os) { + case TargetOS::Linux: return "libc.so.6"; + case TargetOS::Windows: return "ucrtbase.dll"; + case TargetOS::MacOS: return "/usr/lib/libSystem.B.dylib"; + default: return ""; + } +} + +} // namespace voidlibc::voidlink +""" + + +def parse_txt(path: Path) -> list[tuple[str, str]]: + """Parse a symlib .txt file and return entries sorted by symbol name. + + Entries within sections may be sorted locally but not globally. + The generator sorts them globally for the constexpr binary-search array. + """ + entries = [] + seen: dict[str, str] = {} + for lineno, raw in enumerate(path.read_text().splitlines(), 1): + line = raw.strip() + if not line or line.startswith("#"): + continue + parts = line.split() + if len(parts) != 2: + sys.exit(f"{path}:{lineno}: expected 'symbol library', got: {raw!r}") + sym, lib = parts + if sym in seen: + sys.exit(f"{path}:{lineno}: duplicate symbol '{sym}' (previous: {seen[sym]})") + seen[sym] = lib + entries.append((sym, lib)) + entries.sort(key=lambda x: x[0]) + return entries + + +def format_table(var_name: str, label: str, entries: list[tuple[str, str]]) -> str: + if not entries: + return f"static constexpr std::array {var_name}{{}};\n" + name_width = max(len(sym) for sym, _ in entries) + 2 # +2 for quotes + lines = [f"// ── {label} {'─' * max(0, 77 - len(label))}\n"] + lines.append(f"static constexpr std::array {var_name} = {{\n") + for sym, lib in entries: + quoted_sym = f'"{sym}"' + lines.append(f" Entry{{{quoted_sym:<{name_width}}, \"{lib}\"}},\n") + lines.append("};\n\n") + return "".join(lines) + + +def generate() -> str: + parts = [HEADER] + for label, var_name, txt_path in PLATFORMS: + entries = parse_txt(txt_path) + parts.append(format_table(var_name, label.capitalize(), entries)) + parts.append(FOOTER) + return "".join(parts) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", + help="verify .cpp is current; exit 1 if stale") + args = parser.parse_args() + + content = generate() + + if args.check: + if not OUT_FILE.exists(): + print(f"STALE: {OUT_FILE} does not exist", file=sys.stderr) + sys.exit(1) + current = OUT_FILE.read_text() + if current != content: + print( + f"STALE: {OUT_FILE} differs from generated output.\n" + "Run: python3 tools/gen_symlib_table.py", + file=sys.stderr, + ) + sys.exit(1) + print(f"OK: {OUT_FILE} is up-to-date") + return + + OUT_FILE.write_text(content) + total = sum(len(parse_txt(p)) for _, _, p in PLATFORMS) + print(f"Wrote {OUT_FILE} ({total} entries across {len(PLATFORMS)} platforms)") + + +if __name__ == "__main__": + main() diff --git a/tools/vlc.magic b/tools/vlc.magic new file mode 100644 index 0000000..8d9e138 --- /dev/null +++ b/tools/vlc.magic @@ -0,0 +1,29 @@ +# magic(5) entry for VoidLibC container files. +# +# File extensions: +# .vle executable (bit 2 = Executable) +# .vls shared library (default when neither executable nor static) +# .vla static archive (bit 4 = StaticLibrary) +# +# Offset layout (FileHeader, packed, LE): +# 0 u32 magic = 0x00434C56 +# 4 u16 version_major +# 6 u16 version_minor +# 8 u32 flags (bit 0=HasDebug, bit 1=HasCppExports, bit 2=Executable, +# bit 3=HasDynamicImports, bit 4=StaticLibrary) +# 12 u16 arch (1 = x86_64) +# +# Quick test: file -m vlc.magic +# System-wide: sudo cp vlc.magic /usr/share/file/magic/vlc +# cd /usr/share/file && sudo file -C -m magic + +0 lelong 0x00434C56 VoidLibC container +>4 leshort x \b v%d +>6 leshort x \b.%d +>12 leshort 1 \b, x86_64 +>8 lelong &0x04 \b, executable +>8 lelong ^0x04 \b, shared library +>8 lelong &0x10 \b, static archive +>8 lelong &0x08 \b, dynamically linked +>8 lelong ^0x08 \b, statically linked +>8 lelong &0x01 \b, with debug diff --git a/voidlink/CMakeLists.txt b/voidlink/CMakeLists.txt new file mode 100644 index 0000000..633d421 --- /dev/null +++ b/voidlink/CMakeLists.txt @@ -0,0 +1,26 @@ +add_executable(voidlink + main.cpp + writer.cpp + reader.cpp + builder.cpp + elf_reader.cpp + coff_reader.cpp + macho_reader.cpp + reloc_lowering.cpp + merge.cpp + symlib_table.cpp + # Synthesis: produce native blobs at pack time so ldd/file work on .vlc + ${CMAKE_SOURCE_DIR}/loader/common/elf_synth.cpp + ${CMAKE_SOURCE_DIR}/loader/windows/pe_synth.cpp + ${CMAKE_SOURCE_DIR}/loader/macos/macho_synth.cpp +) + +target_link_libraries(voidlink PRIVATE voidlibc_format) +target_include_directories(voidlink PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_SOURCE_DIR} +) +install(TARGETS voidlink + EXPORT VoidLibCTargets + RUNTIME DESTINATION bin +) diff --git a/voidlink/builder.cpp b/voidlink/builder.cpp new file mode 100644 index 0000000..cde58ed --- /dev/null +++ b/voidlink/builder.cpp @@ -0,0 +1,257 @@ +#include "builder.hpp" + +#include "writer.hpp" + +#include +#include + +namespace voidlibc::voidlink { + +using namespace voidlibc::format; + +std::uint32_t ContainerBuilder::add_symbol(SymbolSpec spec) { + const auto id = static_cast(symbols_.size()); + symbols_.push_back(std::move(spec)); + return id; +} + +void ContainerBuilder::add_section(SectionSpec section) { + sections_.push_back(std::move(section)); +} + +namespace { + +constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) { + return (v + (a - 1)) & ~(a - 1); +} + +struct LayoutPlan { + std::uint64_t header_off = 0; + std::uint64_t section_dir_off = 0; + std::uint64_t symtab_off = 0; + std::uint64_t symtab_size = 0; + std::vector reloc_offs; + std::vector code_offs; + std::vector data_offs; // writable data blob offsets + std::uint64_t file_size = 0; + // Computed name-pool data so the writer doesn't recompute it. + std::vector name_pool; + std::vector sym_entries; +}; + +void plan_layout(const std::vector& symbols, + const std::vector& sections, + LayoutPlan& plan) { + plan.header_off = 0; + plan.section_dir_off = sizeof(FileHeader); + + const auto sec_dir_end = + plan.section_dir_off + sections.size() * sizeof(SectionEntry); + + // --- Symbol table: header + entries + name pool --- + plan.symtab_off = align_up(sec_dir_end, 8); + + auto append_name = [&](std::string_view s, + std::uint32_t& off, + std::uint32_t& len) { + if (s.empty()) { off = 0; len = 0; return; } + off = static_cast(plan.name_pool.size()); + len = static_cast(s.size()); + plan.name_pool.insert(plan.name_pool.end(), s.begin(), s.end()); + }; + + plan.sym_entries.reserve(symbols.size()); + for (const auto& s : symbols) { + SymbolEntry e{}; + append_name(s.name, e.name_off, e.name_len); + append_name(s.itanium_name, e.itanium_name_off, e.itanium_name_len); + append_name(s.msvc_name, e.msvc_name_off, e.msvc_name_len); + e.value = s.value; + e.size = s.size; + e.section_index = s.section_index; + e.kind = s.kind; + std::uint8_t flags = 0; + if (s.exported) flags |= static_cast(SymbolFlags::Exported); + if (s.weak) flags |= static_cast(SymbolFlags::Weak); + if (s.hidden) flags |= static_cast(SymbolFlags::Hidden); + if (s.data_section) flags |= static_cast(SymbolFlags::DataSection); + e.flags = flags; + e.reserved = 0; + plan.sym_entries.push_back(e); + } + + const auto symtab_body = + sizeof(SymbolTableHeader) + + plan.sym_entries.size() * sizeof(SymbolEntry) + + plan.name_pool.size(); + plan.symtab_size = symtab_body; + + std::uint64_t cursor = align_up(plan.symtab_off + symtab_body, 8); + + // --- Per-section reloc chunks (NativeBlob sections have none) --- + plan.reloc_offs.reserve(sections.size()); + for (const auto& sec : sections) { + if (sec.kind == SectionKind::NativeBlob || sec.relocs.empty()) { + plan.reloc_offs.push_back(0); + } else { + plan.reloc_offs.push_back(cursor); + cursor = align_up(cursor + sizeof(RelocChunk) + + sec.relocs.size() * sizeof(RelocEntry), 16); + } + } + + // --- Per-section code --- + plan.code_offs.reserve(sections.size()); + for (const auto& sec : sections) { + cursor = align_up(cursor, 16); + plan.code_offs.push_back(cursor); + cursor += sec.code.size(); + } + + // --- Per-section writable data blob (optional) --- + plan.data_offs.reserve(sections.size()); + for (const auto& sec : sections) { + if (!sec.data.empty()) { + cursor = align_up(cursor, 16); + plan.data_offs.push_back(cursor); + cursor += sec.data.size(); + } else { + plan.data_offs.push_back(0); + } + } + + plan.file_size = cursor; +} + +} // namespace + +WriteResult ContainerBuilder::write(const std::filesystem::path& out_path) const { + LayoutPlan plan; + plan_layout(symbols_, sections_, plan); + + std::ofstream out(out_path, std::ios::binary | std::ios::trunc); + if (!out) { + return {false, "could not open output: " + out_path.string()}; + } + + auto seek = [&](std::uint64_t off) { + out.seekp(static_cast(off)); + }; + auto write_raw = [&](const void* p, std::size_t n) { + out.write(reinterpret_cast(p), static_cast(n)); + }; + auto pad_to = [&](std::uint64_t off) { + const auto cur = static_cast(out.tellp()); + if (cur < off) { + std::vector zeros(off - cur, 0); + write_raw(zeros.data(), zeros.size()); + } + }; + + // --- FileHeader --- + FileHeader hdr{}; + hdr.magic = kMagic; + hdr.version_major = kVersionMajor; + hdr.version_minor = kVersionMinor; + std::uint32_t flags = static_cast(ContainerFlags::None); + if (is_executable_) flags |= static_cast(ContainerFlags::Executable); + if (is_static_library_) flags |= static_cast(ContainerFlags::StaticLibrary); + // Set HasDynamicImports if any symbol is an import (undefined section). + for (const auto& sym : symbols_) { + if (sym.section_index == kSymUndefined) { + flags |= static_cast(ContainerFlags::HasDynamicImports); + break; + } + } + hdr.flags = flags; + hdr.arch = TargetArch::X86_64; + hdr.reserved = 0; + hdr.section_count = static_cast(sections_.size()); + hdr.section_dir_off = plan.section_dir_off; + hdr.symtab_off = plan.symtab_off; + hdr.symtab_size = plan.symtab_size; + hdr.imports_off = plan.symtab_off; // placeholder until M1 + hdr.imports_size = 0; + hdr.exports_off = plan.symtab_off; // placeholder until M1 + hdr.exports_size = 0; + hdr.file_size = plan.file_size; + seek(0); + write_raw(&hdr, sizeof(hdr)); + + // --- Section directory --- + seek(plan.section_dir_off); + for (std::size_t i = 0; i < sections_.size(); ++i) { + const auto& s = sections_[i]; + SectionEntry e{}; + e.target_os = s.target_os; + e.kind = s.kind; + e.reserved1 = 0; + e.code_off = plan.code_offs[i]; + e.code_size = s.code.size(); + if (s.kind == SectionKind::NativeBlob || s.relocs.empty()) { + e.reloc_off = 0; + e.reloc_size = 0; + } else { + e.reloc_off = plan.reloc_offs[i]; + e.reloc_size = sizeof(RelocChunk) + s.relocs.size() * sizeof(RelocEntry); + } + e.data_off = plan.data_offs[i]; + e.data_size = s.data.size(); + e.entry_offset = s.entry_offset; + write_raw(&e, sizeof(e)); + } + + // --- Symbol table --- + pad_to(plan.symtab_off); + SymbolTableHeader sth{}; + sth.entry_count = static_cast(plan.sym_entries.size()); + sth.name_pool_size = static_cast(plan.name_pool.size()); + write_raw(&sth, sizeof(sth)); + if (!plan.sym_entries.empty()) { + write_raw(plan.sym_entries.data(), + plan.sym_entries.size() * sizeof(SymbolEntry)); + } + if (!plan.name_pool.empty()) { + write_raw(plan.name_pool.data(), plan.name_pool.size()); + } + + // --- Per-section reloc chunks (skipped for NativeBlob sections) --- + for (std::size_t i = 0; i < sections_.size(); ++i) { + const auto& s = sections_[i]; + if (s.kind == SectionKind::NativeBlob || plan.reloc_offs[i] == 0) continue; + pad_to(plan.reloc_offs[i]); + RelocChunk rc{}; + rc.target_os = s.target_os; + rc.reserved0 = 0; + rc.entry_count = static_cast(s.relocs.size()); + write_raw(&rc, sizeof(rc)); + if (!s.relocs.empty()) { + write_raw(s.relocs.data(), + s.relocs.size() * sizeof(RelocEntry)); + } + } + + // --- Per-section code --- + for (std::size_t i = 0; i < sections_.size(); ++i) { + pad_to(plan.code_offs[i]); + if (!sections_[i].code.empty()) { + write_raw(sections_[i].code.data(), sections_[i].code.size()); + } + } + + // --- Per-section writable data blob --- + for (std::size_t i = 0; i < sections_.size(); ++i) { + if (plan.data_offs[i] != 0) { + pad_to(plan.data_offs[i]); + write_raw(sections_[i].data.data(), sections_[i].data.size()); + } + } + + pad_to(plan.file_size); + if (!out) { + return {false, "write failed"}; + } + return {true, {}}; +} + +} // namespace voidlibc::voidlink diff --git a/voidlink/builder.hpp b/voidlink/builder.hpp new file mode 100644 index 0000000..ff633ea --- /dev/null +++ b/voidlink/builder.hpp @@ -0,0 +1,80 @@ +#pragma once + +#include "format/reloc_ir.hpp" +#include "format/vlc_format.hpp" +#include "writer.hpp" + +#include +#include +#include +#include + +namespace voidlibc::voidlink { + +struct SymbolSpec { + std::string name; // canonical (C) name + std::string itanium_name; // empty if not C++ Itanium + std::string msvc_name; // empty if not C++ MSVC + voidlibc::format::SymbolKind kind = voidlibc::format::SymbolKind::Function; + std::uint64_t value = 0; // offset within owning blob (code or data) + std::uint64_t size = 0; + std::uint16_t section_index = voidlibc::format::kSymUndefined; + bool exported = true; + bool weak = false; + bool hidden = false; + bool data_section = false; // lives in data blob, not code blob + // For undefined (imported) symbols: which host library provides this symbol. + // Populated by voidlink at synthesis time from symlib_table or --symlib overrides. + // Empty means "use per-OS default libc". + std::string library; + // GNU symbol version requirement forwarded from input .o (SHT_GNU_versym + verneed). + // Empty version_name means no version requirement (emit VER_NDX_GLOBAL in .gnu.version). + std::string version_name; + std::uint32_t version_hash = 0; + std::uint16_t version_flags = 0; +}; + +struct SectionSpec { + voidlibc::format::TargetOS target_os; + voidlibc::format::SectionKind kind = voidlibc::format::SectionKind::RawCode; + std::vector code; // raw PIC code (RawCode) or native blob (NativeBlob) + std::vector relocs; // empty when kind == NativeBlob + std::uint64_t entry_offset = 0; + std::vector data; // .data + .bss zeros (RW); unused for NativeBlob +}; + +class ContainerBuilder { +public: + // Mark the container as an executable with the given entry symbol name. + // Exactly one section should have entry_offset != 0 to match this. + void set_executable(std::string entry_symbol) { + is_executable_ = true; + entry_symbol_ = std::move(entry_symbol); + } + + void set_static_library() { + is_static_library_ = true; + } + + // Returns the assigned symbol id (index into the symbol table). + std::uint32_t add_symbol(SymbolSpec spec); + + void add_section(SectionSpec section); + + std::uint32_t symbol_count() const { return static_cast(symbols_.size()); } + std::uint16_t section_count() const { return static_cast(sections_.size()); } + + // Serialize to disk. Lays out: FileHeader → section directory → + // symbol table → per-section reloc chunks → per-section code → + // per-section debug. file_size is computed. + WriteResult write(const std::filesystem::path& out_path) const; + +private: + std::vector symbols_; + std::vector sections_; + bool is_executable_ = false; + bool is_static_library_ = false; + std::string entry_symbol_; +}; + +} // namespace voidlibc::voidlink diff --git a/voidlink/coff_reader.cpp b/voidlink/coff_reader.cpp new file mode 100644 index 0000000..3c0da22 --- /dev/null +++ b/voidlink/coff_reader.cpp @@ -0,0 +1,318 @@ +#include "coff_reader.hpp" + +#include +#include +#include + +namespace voidlibc::voidlink::coff { + +namespace { + +std::string err(std::string s) { return s; } + +bool read_file(const std::filesystem::path& path, std::vector& out) { + std::ifstream in(path, std::ios::binary | std::ios::ate); + if (!in) return false; + const auto sz = static_cast(in.tellg()); + in.seekg(0, std::ios::beg); + out.resize(static_cast(sz)); + in.read(reinterpret_cast(out.data()), sz); + return static_cast(in); +} + +template +bool read_at(const std::vector& buf, std::size_t off, T& out) { + if (off + sizeof(T) > buf.size()) return false; + std::memcpy(&out, buf.data() + off, sizeof(T)); + return true; +} + +// COFF on-disk structures (packed, little-endian). +#pragma pack(push, 1) + +struct FileHeader { + std::uint16_t Machine; + std::uint16_t NumberOfSections; + std::uint32_t TimeDateStamp; + std::uint32_t PointerToSymbolTable; + std::uint32_t NumberOfSymbols; + std::uint16_t SizeOfOptionalHeader; + std::uint16_t Characteristics; +}; +static_assert(sizeof(FileHeader) == 20); + +struct SectionHeader { + char Name[8]; + std::uint32_t VirtualSize; + std::uint32_t VirtualAddress; + std::uint32_t SizeOfRawData; + std::uint32_t PointerToRawData; + std::uint32_t PointerToRelocations; + std::uint32_t PointerToLinenumbers; + std::uint16_t NumberOfRelocations; + std::uint16_t NumberOfLinenumbers; + std::uint32_t Characteristics; +}; +static_assert(sizeof(SectionHeader) == 40); + +struct Symbol { + union { + char ShortName[8]; + struct { std::uint32_t Zeros; std::uint32_t Offset; } LongName; + } N; + std::uint32_t Value; + std::int16_t SectionNumber; + std::uint16_t Type; + std::uint8_t StorageClass; + std::uint8_t NumberOfAuxSymbols; +}; +static_assert(sizeof(Symbol) == 18); + +struct Relocation { + std::uint32_t VirtualAddress; + std::uint32_t SymbolTableIndex; + std::uint16_t Type; +}; +static_assert(sizeof(Relocation) == 10); + +#pragma pack(pop) + +constexpr std::uint16_t kMachineAmd64 = 0x8664; + +// COFF symbol storage classes +constexpr std::uint8_t kStorExternal = 2; +constexpr std::uint8_t kStorStatic = 3; +constexpr std::uint8_t kStorWeakExternal = 105; + +// Extract section name (may use string-table indirection for >8-char names). +std::string section_name(const SectionHeader& sh, + const char* strtab, std::size_t strtab_size) { + if (sh.Name[0] == '/') { + // Long name: "/" into string table. + char buf[9] = {}; + std::memcpy(buf, sh.Name + 1, 7); + const auto off = static_cast(std::strtoul(buf, nullptr, 10)); + if (strtab && off < strtab_size) + return std::string(strtab + off); + } + // Short name (up to 8 chars, NOT necessarily null-terminated). + const std::size_t len = strnlen(sh.Name, 8); + return std::string(sh.Name, len); +} + +// Extract symbol name. +std::string symbol_name(const Symbol& sym, + const char* strtab, std::size_t strtab_size) { + if (sym.N.LongName.Zeros == 0) { + const auto off = static_cast(sym.N.LongName.Offset); + if (strtab && off < strtab_size) + return std::string(strtab + off); + return {}; + } + const std::size_t len = strnlen(sym.N.ShortName, 8); + return std::string(sym.N.ShortName, len); +} + +// Read an inline addend from the code: 4 bytes for 32-bit relocs, 8 for 64-bit. +std::int64_t read_inline4(const std::vector& sec_bytes, std::uint32_t off) { + if (off + 4 > sec_bytes.size()) return 0; + std::int32_t v; + std::memcpy(&v, sec_bytes.data() + off, 4); + return v; +} +std::int64_t read_inline8(const std::vector& sec_bytes, std::uint32_t off) { + if (off + 8 > sec_bytes.size()) return 0; + std::int64_t v; + std::memcpy(&v, sec_bytes.data() + off, 8); + return v; +} + +} // namespace + +ParseResult parse_coff_object(const std::filesystem::path& path) { + std::vector buf; + if (!read_file(path, buf)) + return err("cannot read " + path.string()); + + FileHeader fh{}; + if (!read_at(buf, 0, fh)) + return err("file too small for COFF header"); + + if (fh.Machine != kMachineAmd64) + return err("not an x86-64 COFF object (machine 0x" + + [&]{ std::ostringstream o; o << std::hex << fh.Machine; return o.str(); }() + ")"); + + if (fh.SizeOfOptionalHeader != 0) + return err("file has optional header — expected a .obj (ET_REL equivalent), not a PE image"); + + // Section headers follow the file header. + const std::size_t shdrs_off = sizeof(FileHeader); + if (shdrs_off + fh.NumberOfSections * sizeof(SectionHeader) > buf.size()) + return err("section header table truncated"); + + // String table starts right after the symbol table. + const std::size_t symtab_off = fh.PointerToSymbolTable; + const std::size_t symtab_bytes = fh.NumberOfSymbols * sizeof(Symbol); + const std::size_t strtab_off = symtab_off + symtab_bytes; + std::uint32_t strtab_size32 = 0; + const char* strtab = nullptr; + std::size_t strtab_size = 0; + if (strtab_off + 4 <= buf.size()) { + std::memcpy(&strtab_size32, buf.data() + strtab_off, 4); + strtab_size = static_cast(strtab_size32); + if (strtab_off + strtab_size <= buf.size()) + strtab = reinterpret_cast(buf.data() + strtab_off); + } + + ParsedObject obj; + obj.sections.resize(fh.NumberOfSections); + + // First pass: read sections. + for (std::uint16_t i = 0; i < fh.NumberOfSections; ++i) { + SectionHeader sh{}; + std::memcpy(&sh, buf.data() + shdrs_off + i * sizeof(SectionHeader), sizeof(sh)); + + auto& ps = obj.sections[i]; + ps.name = section_name(sh, strtab, strtab_size); + ps.characteristics = sh.Characteristics; + ps.mem_size = sh.SizeOfRawData; // for BSS: SizeOfRawData=0, VirtualSize has the size + + // BSS: SizeOfRawData==0 but VirtualSize may be non-zero. + if (sh.SizeOfRawData == 0) { + ps.mem_size = sh.VirtualSize; + } else if (sh.PointerToRawData != 0) { + if (sh.PointerToRawData + sh.SizeOfRawData > buf.size()) { + std::ostringstream os; + os << "section " << ps.name << " raw data out of range"; + return err(os.str()); + } + ps.bytes.assign(buf.data() + sh.PointerToRawData, + buf.data() + sh.PointerToRawData + sh.SizeOfRawData); + } + + // Identify primary .text section. + if (ps.name == ".text" + && (ps.characteristics & kScnCntCode) + && obj.text_index == static_cast(-1)) { + obj.text_index = i; + } + } + + // Second pass: read symbol table. + // COFF symbols are 18 bytes each; auxiliary symbol records follow inline. + // Symbol table index used by relocs maps directly to obj.symbols indices, + // so we keep a parallel "coff_idx → obj_sym_idx" map. + std::vector coff_to_obj(fh.NumberOfSymbols, + static_cast(-1)); + if (symtab_off != 0 && symtab_bytes <= buf.size() - symtab_off) { + std::uint32_t ci = 0; + while (ci < fh.NumberOfSymbols) { + Symbol sym{}; + std::memcpy(&sym, buf.data() + symtab_off + ci * sizeof(Symbol), sizeof(sym)); + + const std::uint32_t obj_idx = static_cast(obj.symbols.size()); + coff_to_obj[ci] = obj_idx; + // Also map auxiliary record indices to the same obj symbol (they may be + // referenced by some relocs, though rarely). + for (std::uint8_t a = 0; a < sym.NumberOfAuxSymbols && ci + 1 + a < fh.NumberOfSymbols; ++a) + coff_to_obj[ci + 1 + a] = obj_idx; + + ParsedSymbol ps{}; + ps.name = symbol_name(sym, strtab, strtab_size); + ps.value = sym.Value; + ps.size = 0; // COFF doesn't store symbol size in the base record + + const bool is_absolute = (sym.SectionNumber == -1); + const bool is_undef = (sym.SectionNumber == 0); + const bool is_debug = (sym.SectionNumber == -2); + (void)is_debug; + + if (!is_undef && !is_absolute) { + const int sec1 = static_cast(sym.SectionNumber) - 1; + if (sec1 >= 0 && sec1 < fh.NumberOfSections) { + ps.section_index = static_cast(sec1 + 1); + ps.defined = true; + } + } + + // Normalize bind / type. + if (sym.StorageClass == kStorExternal) + ps.bind = kBindGlobal; + else if (sym.StorageClass == kStorWeakExternal) + ps.bind = kBindWeak; + else + ps.bind = kBindLocal; + + // COFF type: high byte = complex type (0=none, 1=pointer, 2=function, 3=array) + // low byte = base type + // type >> 4 = 2 means "function". + if ((sym.Type >> 4) == 2) + ps.type = kTypeFunc; + else if (sym.StorageClass == kStorStatic && sym.Value == 0 && sym.NumberOfAuxSymbols > 0) + ps.type = kTypeSection; // section symbol + else + ps.type = kTypeNone; + + obj.symbols.push_back(std::move(ps)); + ci += 1 + sym.NumberOfAuxSymbols; + } + } + + // Third pass: read relocations (stored per section). + for (std::uint16_t i = 0; i < fh.NumberOfSections; ++i) { + SectionHeader sh{}; + std::memcpy(&sh, buf.data() + shdrs_off + i * sizeof(SectionHeader), sizeof(sh)); + + if (sh.NumberOfRelocations == 0 || sh.PointerToRelocations == 0) + continue; + + const std::size_t relocs_off = sh.PointerToRelocations; + const std::size_t nrelocs = sh.NumberOfRelocations; + if (relocs_off + nrelocs * sizeof(Relocation) > buf.size()) { + std::ostringstream os; + os << "section " << obj.sections[i].name << " relocations out of range"; + return err(os.str()); + } + + auto& sec = obj.sections[i]; + sec.relocs.reserve(nrelocs); + for (std::size_t ri = 0; ri < nrelocs; ++ri) { + Relocation r{}; + std::memcpy(&r, buf.data() + relocs_off + ri * sizeof(Relocation), sizeof(r)); + + if (r.SymbolTableIndex >= fh.NumberOfSymbols) + continue; + + const std::uint32_t obj_sym_idx = coff_to_obj[r.SymbolTableIndex]; + if (obj_sym_idx == static_cast(-1)) + continue; + + ParsedRelocation pr{}; + pr.offset = r.VirtualAddress; + pr.sym_index = obj_sym_idx; + pr.type = r.Type; + + // Read inline addend from the code bytes. + switch (r.Type) { + case kRelocAddr64: + pr.addend = read_inline8(sec.bytes, r.VirtualAddress); + break; + case kRelocRel32: case kRelocRel32_1: case kRelocRel32_2: + case kRelocRel32_3: case kRelocRel32_4: case kRelocRel32_5: + case kRelocAddr32: case kRelocAddr32NB: + case kRelocSecRel: + pr.addend = read_inline4(sec.bytes, r.VirtualAddress); + break; + default: + pr.addend = 0; + break; + } + + sec.relocs.push_back(pr); + } + } + + return obj; +} + +} // namespace voidlibc::voidlink::coff diff --git a/voidlink/coff_reader.hpp b/voidlink/coff_reader.hpp new file mode 100644 index 0000000..8f65d86 --- /dev/null +++ b/voidlink/coff_reader.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include +#include +#include +#include +#include + +// IMAGE_REL_AMD64_* relocation type constants (stored in ParsedRelocation.type). +// These are distinct from R_X86_64_* values; lower_coff_text() handles them. +namespace voidlibc::voidlink::coff { + +constexpr std::uint32_t kRelocAbsolute = 0x0000; +constexpr std::uint32_t kRelocAddr64 = 0x0001; +constexpr std::uint32_t kRelocAddr32 = 0x0002; +constexpr std::uint32_t kRelocAddr32NB = 0x0003; +constexpr std::uint32_t kRelocRel32 = 0x0004; +constexpr std::uint32_t kRelocRel32_1 = 0x0005; +constexpr std::uint32_t kRelocRel32_2 = 0x0006; +constexpr std::uint32_t kRelocRel32_3 = 0x0007; +constexpr std::uint32_t kRelocRel32_4 = 0x0008; +constexpr std::uint32_t kRelocRel32_5 = 0x0009; +constexpr std::uint32_t kRelocSection = 0x000A; +constexpr std::uint32_t kRelocSecRel = 0x000B; + +// Normalized bind values (same integers as ELF STB_*; reused for compatibility +// with lower_coff_text which operates on the same ParsedObject fields). +constexpr std::uint8_t kBindLocal = 0; // STB_LOCAL +constexpr std::uint8_t kBindGlobal = 1; // STB_GLOBAL +constexpr std::uint8_t kBindWeak = 2; // STB_WEAK + +// Normalized type values (same integers as ELF STT_*). +constexpr std::uint8_t kTypeNone = 0; +constexpr std::uint8_t kTypeObject = 1; +constexpr std::uint8_t kTypeFunc = 2; +constexpr std::uint8_t kTypeSection = 3; + +// Section characteristics flags. +constexpr std::uint32_t kScnCntCode = 0x00000020; +constexpr std::uint32_t kScnCntInitData = 0x00000040; +constexpr std::uint32_t kScnCntUninitData = 0x00000080; +constexpr std::uint32_t kScnLnkComdat = 0x00001000; +constexpr std::uint32_t kScnMemExecute = 0x20000000; +constexpr std::uint32_t kScnMemRead = 0x40000000; +constexpr std::uint32_t kScnMemWrite = 0x80000000u; + +struct ParsedSymbol { + std::string name; + std::uint64_t value = 0; // offset within its section + std::uint64_t size = 0; // usually unknown in COFF + std::uint32_t section_index = 0; // 0 = undefined (SHN_UNDEF analogue) + std::uint8_t bind = 0; // kBind* + std::uint8_t type = 0; // kType* + bool defined = false; +}; + +struct ParsedRelocation { + std::uint64_t offset = 0; // byte offset within the target section + std::uint32_t sym_index = 0; // index into ParsedObject::symbols + std::uint32_t type = 0; // kReloc* + std::int64_t addend = 0; // inline addend read from code bytes +}; + +struct ParsedSection { + std::string name; + std::uint32_t characteristics = 0; + std::vector bytes; + std::uint64_t mem_size = 0; + std::vector relocs; +}; + +struct ParsedObject { + std::vector sections; + std::vector symbols; + // Primary .text section index (first executable section with that name). + std::size_t text_index = static_cast(-1); +}; + +using ParseResult = std::variant; + +ParseResult parse_coff_object(const std::filesystem::path& path); + +} // namespace voidlibc::voidlink::coff diff --git a/voidlink/elf_reader.cpp b/voidlink/elf_reader.cpp new file mode 100644 index 0000000..9f13bad --- /dev/null +++ b/voidlink/elf_reader.cpp @@ -0,0 +1,265 @@ +#include "elf_reader.hpp" + +#include "loader/common/elf64.hpp" + +#include +#include +#include + +namespace voidlibc::voidlink::elf { + +using namespace voidlibc::loader; + +namespace { + +std::string err(std::string s) { return s; } + +bool read_file(const std::filesystem::path& path, std::vector& out) { + std::ifstream in(path, std::ios::binary | std::ios::ate); + if (!in) return false; + const auto size = static_cast(in.tellg()); + in.seekg(0, std::ios::beg); + out.resize(static_cast(size)); + in.read(reinterpret_cast(out.data()), size); + return static_cast(in); +} + +template +bool read_struct(const std::vector& buf, std::size_t off, T& out) { + if (off + sizeof(T) > buf.size()) return false; + std::memcpy(&out, buf.data() + off, sizeof(T)); + return true; +} + +} // namespace + +ParseResult parse_elf64_object(const std::filesystem::path& path) { + std::vector buf; + if (!read_file(path, buf)) { + return err("cannot read " + path.string()); + } + if (buf.size() < sizeof(Ehdr)) { + return err("file too small for ELF header"); + } + + Ehdr eh{}; + std::memcpy(&eh, buf.data(), sizeof(eh)); + if (!(eh.e_ident[0] == kElfMag0 && eh.e_ident[1] == kElfMag1 + && eh.e_ident[2] == kElfMag2 && eh.e_ident[3] == kElfMag3)) { + return err("not an ELF file"); + } + if (eh.e_ident[4] != kElfClass64) return err("not ELF64"); + if (eh.e_ident[5] != kElfData2LSB) return err("not little-endian"); + if (eh.e_machine != kEmX86_64) return err("not x86_64"); + if (eh.e_type != kEtRel) return err("not a relocatable object (ET_REL)"); + if (eh.e_shentsize != sizeof(Shdr)) return err("bad sh_entsize"); + if (eh.e_shnum == 0) return err("no sections"); + + // Section table + if (eh.e_shoff + static_cast(eh.e_shnum) * sizeof(Shdr) > buf.size()) { + return err("section table truncated"); + } + std::vector sh(eh.e_shnum); + std::memcpy(sh.data(), buf.data() + eh.e_shoff, sh.size() * sizeof(Shdr)); + + if (eh.e_shstrndx >= sh.size()) return err("bad e_shstrndx"); + const auto& shstr_sec = sh[eh.e_shstrndx]; + if (shstr_sec.sh_offset + shstr_sec.sh_size > buf.size()) { + return err("shstrtab out of bounds"); + } + const char* shstr = + reinterpret_cast(buf.data() + shstr_sec.sh_offset); + const std::size_t shstr_size = shstr_sec.sh_size; + + auto section_name = [&](std::uint32_t name_off) -> std::string { + if (name_off >= shstr_size) return {}; + return std::string(shstr + name_off); + }; + + ParsedObject obj{}; + obj.sections.reserve(sh.size()); + + // First pass: materialize sections. + for (std::size_t i = 0; i < sh.size(); ++i) { + const auto& s = sh[i]; + ParsedSection ps{}; + ps.name = section_name(s.sh_name); + ps.type = s.sh_type; + ps.flags = s.sh_flags; + ps.file_offset = s.sh_offset; + ps.size_in_file = (s.sh_type == kShtNobits) ? 0 : s.sh_size; + ps.mem_size = s.sh_size; // always the memory footprint + if (ps.size_in_file > 0) { + if (s.sh_offset + s.sh_size > buf.size()) { + std::ostringstream os; + os << "section " << ps.name << " truncated"; + return err(os.str()); + } + ps.bytes.assign(buf.data() + s.sh_offset, + buf.data() + s.sh_offset + s.sh_size); + } + if (ps.name == ".text" && s.sh_type == kShtProgbits) { + obj.text_index = i; + } + obj.sections.push_back(std::move(ps)); + } + + // Second pass: walk .symtab, materialize symbols using .strtab. + // Track which .symtab section we used so .rela.* parsing can map + // its symbol indices into ParsedObject::symbols. + std::size_t symtab_section_index = static_cast(-1); + std::size_t symbols_base = 0; // first symbol index from this .symtab + for (std::size_t i = 0; i < sh.size(); ++i) { + const auto& s = sh[i]; + if (s.sh_type != kShtSymtab) continue; + if (s.sh_entsize != sizeof(Sym)) { + return err(".symtab entry size mismatch"); + } + if (s.sh_link >= sh.size()) { + return err(".symtab points at out-of-range strtab"); + } + const auto& strtab = sh[s.sh_link]; + if (strtab.sh_type != kShtStrtab) { + return err(".symtab sh_link not strtab"); + } + if (strtab.sh_offset + strtab.sh_size > buf.size()) { + return err(".strtab out of bounds"); + } + const char* strs = + reinterpret_cast(buf.data() + strtab.sh_offset); + const std::size_t strs_size = strtab.sh_size; + auto str = [&](std::uint32_t off) -> std::string { + if (off >= strs_size) return {}; + return std::string(strs + off); + }; + + const std::size_t nsyms = s.sh_size / sizeof(Sym); + std::vector syms(nsyms); + std::memcpy(syms.data(), buf.data() + s.sh_offset, s.sh_size); + symbols_base = obj.symbols.size(); + symtab_section_index = i; + obj.symbols.reserve(obj.symbols.size() + nsyms); + for (const auto& sm : syms) { + ParsedSymbol p{}; + p.name = str(sm.st_name); + p.value = sm.st_value; + p.size = sm.st_size; + p.section_index = sm.st_shndx; + p.bind = st_bind(sm.st_info); + p.type = st_type(sm.st_info); + p.defined = sm.st_shndx != kShnUndef; + obj.symbols.push_back(std::move(p)); + } + break; // exactly one .symtab in well-formed ET_REL + } + + // Third pass: GNU versym + verneed. Forward version requirements for undefined symbols. + // SHT_GNU_versym (sh_link = symtab idx): one uint16_t per symtab entry; assigns version index. + // SHT_GNU_verneed (sh_link = strtab idx): chain of Verneed + Vernaux with version metadata. + // + // We parse verneed first to build an index→VersionRequirement map, then apply versym. + { + using voidlibc::loader::kShtGnuVerneed; + using voidlibc::loader::kShtGnuVersym; + using voidlibc::loader::Verneed; + using voidlibc::loader::Vernaux; + + // Find and parse SHT_GNU_verneed. + for (std::size_t i = 0; i < sh.size(); ++i) { + if (sh[i].sh_type != kShtGnuVerneed) continue; + if (sh[i].sh_link >= sh.size()) break; + const auto& vn_strtab_hdr = sh[sh[i].sh_link]; + if (vn_strtab_hdr.sh_offset + vn_strtab_hdr.sh_size > buf.size()) break; + if (sh[i].sh_offset + sh[i].sh_size > buf.size()) break; + + const char* vn_str = reinterpret_cast( + buf.data() + vn_strtab_hdr.sh_offset); + const std::size_t vn_str_sz = vn_strtab_hdr.sh_size; + + auto safe_str = [&](std::uint32_t off) -> std::string { + if (off >= vn_str_sz) return {}; + return std::string(vn_str + off); + }; + + const std::uint8_t* base = buf.data() + sh[i].sh_offset; + const std::uint8_t* end = base + sh[i].sh_size; + const std::uint32_t n_vn = sh[i].sh_info; // number of Verneed entries + const std::uint8_t* ptr = base; + + for (std::uint32_t vi = 0; vi < n_vn && ptr + sizeof(Verneed) <= end; ++vi) { + Verneed vn{}; + std::memcpy(&vn, ptr, sizeof(vn)); + const std::string lib_name = safe_str(vn.vn_file); + const std::uint8_t* aux = ptr + vn.vn_aux; + + for (std::uint16_t ai = 0; ai < vn.vn_cnt && aux + sizeof(Vernaux) <= end; ++ai) { + Vernaux va{}; + std::memcpy(&va, aux, sizeof(va)); + VersionRequirement vr{}; + vr.index = va.vna_other; + vr.hash = va.vna_hash; + vr.flags = va.vna_flags; + vr.version_name = safe_str(va.vna_name); + vr.library = lib_name; + obj.version_reqs.push_back(std::move(vr)); + if (va.vna_next == 0) break; + aux += va.vna_next; + } + if (vn.vn_next == 0) break; + ptr += vn.vn_next; + } + break; + } + + // Find and apply SHT_GNU_versym linked to our symtab. + for (std::size_t i = 0; i < sh.size(); ++i) { + if (sh[i].sh_type != kShtGnuVersym) continue; + if (sh[i].sh_link != symtab_section_index) continue; + if (sh[i].sh_offset + sh[i].sh_size > buf.size()) break; + const std::size_t n = sh[i].sh_size / 2; + const std::uint16_t* versym = reinterpret_cast( + buf.data() + sh[i].sh_offset); + for (std::size_t j = 0; j < n && symbols_base + j < obj.symbols.size(); ++j) + obj.symbols[symbols_base + j].version_index = versym[j]; + break; + } + } + + // Fourth pass: SHT_RELA sections. Each one's sh_info is the target + // section index (the section being relocated); sh_link is the symtab. + for (std::size_t i = 0; i < sh.size(); ++i) { + const auto& s = sh[i]; + if (s.sh_type != kShtRela) continue; + if (s.sh_entsize != sizeof(Rela)) { + return err(".rela.* entry size mismatch"); + } + if (s.sh_link != symtab_section_index) { + return err(".rela.* sh_link does not match .symtab we parsed"); + } + if (s.sh_info >= obj.sections.size()) { + return err(".rela.* sh_info out of range"); + } + if (s.sh_offset + s.sh_size > buf.size()) { + return err(".rela.* out of bounds"); + } + const std::size_t nrelas = s.sh_size / sizeof(Rela); + std::vector rels(nrelas); + std::memcpy(rels.data(), buf.data() + s.sh_offset, s.sh_size); + + auto& target = obj.sections[s.sh_info]; + target.relocs.reserve(target.relocs.size() + nrelas); + for (const auto& r : rels) { + ParsedRelocation pr{}; + pr.offset = r.r_offset; + pr.sym_index = static_cast( + symbols_base + r_sym(r.r_info)); + pr.type = r_type(r.r_info); + pr.addend = r.r_addend; + target.relocs.push_back(pr); + } + } + + return obj; +} + +} // namespace voidlibc::voidlink::elf diff --git a/voidlink/elf_reader.hpp b/voidlink/elf_reader.hpp new file mode 100644 index 0000000..5af9333 --- /dev/null +++ b/voidlink/elf_reader.hpp @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace voidlibc::voidlink::elf { + +struct ParsedSymbol { + std::string name; + std::uint64_t value = 0; // offset within its section + std::uint64_t size = 0; + std::uint16_t section_index = 0; // 0 = SHN_UNDEF + std::uint8_t bind = 0; // STB_* + std::uint8_t type = 0; // STT_* + bool defined = false; // false iff section_index == SHN_UNDEF + // Version index from .gnu.version (SHT_GNU_versym): 0=absent, 1=global, 2+=versioned. + std::uint16_t version_index = 0; +}; + +struct ParsedRelocation { + std::uint64_t offset = 0; // byte offset within the target section + std::uint32_t sym_index = 0; // index into ParsedObject::symbols + std::uint32_t type = 0; // R_X86_64_* + std::int64_t addend = 0; +}; + +struct ParsedSection { + std::string name; + std::uint32_t type = 0; + std::uint64_t flags = 0; + std::vector bytes; + std::uint64_t file_offset = 0; + std::uint64_t size_in_file = 0; // 0 for NOBITS (BSS) + std::uint64_t mem_size = 0; // sh_size; for BSS: memory footprint + std::vector relocs; // relocs applied TO this section +}; + +// One entry per unique version index found in SHT_GNU_verneed. +struct VersionRequirement { + std::uint16_t index; // vna_other (version index referenced in .gnu.version) + std::uint32_t hash; // vna_hash + std::uint16_t flags; // vna_flags + std::string version_name; // e.g., "GLIBC_2.14" + std::string library; // DT_NEEDED name from parent Verneed, e.g., "libc.so.6" +}; + +struct ParsedObject { + std::vector sections; + std::vector symbols; + std::vector version_reqs; // from .gnu.version_r + std::size_t text_index = static_cast(-1); +}; + +using ParseResult = std::variant; + +ParseResult parse_elf64_object(const std::filesystem::path& path); + +} // namespace voidlibc::voidlink::elf diff --git a/voidlink/macho_reader.cpp b/voidlink/macho_reader.cpp new file mode 100644 index 0000000..0a41b6a --- /dev/null +++ b/voidlink/macho_reader.cpp @@ -0,0 +1,324 @@ +#include "macho_reader.hpp" + +#include +#include +#include + +namespace voidlibc::voidlink::macho { + +namespace { + +// --------------------------------------------------------------------------- +// On-disk Mach-O structures (packed, little-endian) +// --------------------------------------------------------------------------- + +struct MachHeader64 { + std::uint32_t magic; + std::uint32_t cputype; + std::uint32_t cpusubtype; + std::uint32_t filetype; + std::uint32_t ncmds; + std::uint32_t sizeofcmds; + std::uint32_t flags; + std::uint32_t reserved; +}; + +struct LoadCommand { + std::uint32_t cmd; + std::uint32_t cmdsize; +}; + +struct SegmentCommand64 { + std::uint32_t cmd; + std::uint32_t cmdsize; + char segname[16]; + std::uint64_t vmaddr; + std::uint64_t vmsize; + std::uint64_t fileoff; + std::uint64_t filesize; + std::uint32_t maxprot; + std::uint32_t initprot; + std::uint32_t nsects; + std::uint32_t flags; +}; + +struct Section64 { + char sectname[16]; + char segname[16]; + std::uint64_t addr; + std::uint64_t size; + std::uint32_t offset; + std::uint32_t align; + std::uint32_t reloff; + std::uint32_t nreloc; + std::uint32_t flags; + std::uint32_t reserved1; + std::uint32_t reserved2; + std::uint32_t reserved3; +}; + +struct SymtabCommand { + std::uint32_t cmd; + std::uint32_t cmdsize; + std::uint32_t symoff; + std::uint32_t nsyms; + std::uint32_t stroff; + std::uint32_t strsize; +}; + +struct NList64 { + std::uint32_t n_strx; + std::uint8_t n_type; + std::uint8_t n_sect; + std::uint16_t n_desc; + std::uint64_t n_value; +}; + +// Relocation info (compact 8-byte form; bit 31 of r_address → scattered, but +// x86_64 object files never use scattered relocations). +struct RelocationInfo { + std::int32_t r_address; + std::uint32_t r_info; // [23:0]=symbolnum, [24]=pcrel, [26:25]=length, [27]=extern, [31:28]=type +}; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +static std::string trim_null(const char* s, std::size_t maxlen) { + std::size_t len = 0; + while (len < maxlen && s[len]) ++len; + return std::string(s, len); +} + +static std::int64_t read_inline_addend(const std::uint8_t* data, std::size_t file_size, + std::uint64_t sec_offset, std::uint32_t reloc_offset, + std::uint32_t length) { + const std::uint64_t pos = sec_offset + reloc_offset; + if (length == 2 && pos + 4 <= file_size) { + std::int32_t v = 0; + std::memcpy(&v, data + pos, 4); + return v; + } + if (length == 3 && pos + 8 <= file_size) { + std::int64_t v = 0; + std::memcpy(&v, data + pos, 8); + return v; + } + return 0; +} + +} // namespace + +// --------------------------------------------------------------------------- +// Public parser +// --------------------------------------------------------------------------- + +ParseResult parse_macho_object(const std::filesystem::path& path) { + std::ifstream f(path, std::ios::binary | std::ios::ate); + if (!f) + return ParseError{"cannot open: " + path.string()}; + + const auto fsz = static_cast(f.tellg()); + f.seekg(0); + std::vector buf(fsz); + f.read(reinterpret_cast(buf.data()), static_cast(fsz)); + if (!f) + return ParseError{"read failed: " + path.string()}; + + if (fsz < sizeof(MachHeader64)) + return ParseError{"file too small"}; + + MachHeader64 hdr{}; + std::memcpy(&hdr, buf.data(), sizeof(hdr)); + + if (hdr.magic != kMagic64) + return ParseError{"not a 64-bit little-endian Mach-O"}; + if (hdr.cputype != kCpuX86_64) + return ParseError{"not x86_64 (cputype=0x" + std::to_string(hdr.cputype) + ")"}; + if (hdr.filetype != kMhObject) + return ParseError{"not an object file (filetype=" + std::to_string(hdr.filetype) + ")"}; + + ParsedObject obj; + std::uint32_t strtab_off = 0, strtab_size = 0; + std::uint32_t symtab_off = 0, nsyms = 0; + + // Walk load commands. + std::size_t lc_pos = sizeof(MachHeader64); + for (std::uint32_t ci = 0; ci < hdr.ncmds; ++ci) { + if (lc_pos + sizeof(LoadCommand) > fsz) + return ParseError{"load command truncated"}; + LoadCommand lc{}; + std::memcpy(&lc, buf.data() + lc_pos, sizeof(lc)); + if (lc.cmdsize < sizeof(LoadCommand) || lc_pos + lc.cmdsize > fsz) + return ParseError{"bad load command size"}; + + if (lc.cmd == 0x19 /* LC_SEGMENT_64 */) { + if (lc.cmdsize < sizeof(SegmentCommand64)) + return ParseError{"LC_SEGMENT_64 too small"}; + SegmentCommand64 seg{}; + std::memcpy(&seg, buf.data() + lc_pos, sizeof(seg)); + + const std::size_t sec_base = lc_pos + sizeof(SegmentCommand64); + for (std::uint32_t si = 0; si < seg.nsects; ++si) { + const std::size_t sec_off = sec_base + si * sizeof(Section64); + if (sec_off + sizeof(Section64) > fsz) + return ParseError{"section header truncated"}; + Section64 sec{}; + std::memcpy(&sec, buf.data() + sec_off, sizeof(sec)); + + ParsedSection ps; + ps.segname = trim_null(sec.segname, 16); + ps.sectname = trim_null(sec.sectname, 16); + ps.flags = sec.flags; + ps.mem_size = sec.size; + ps.addr = sec.addr; + ps.align_exp = sec.align; + + // Read section data. + if (sec.offset > 0 && sec.size > 0) { + if (sec.offset + sec.size > fsz) + return ParseError{"section data truncated: " + ps.sectname}; + ps.bytes.assign(buf.data() + sec.offset, + buf.data() + sec.offset + sec.size); + } else { + ps.bytes.assign(sec.size, 0); // BSS-like + } + + // Read relocations for this section. + if (sec.nreloc > 0) { + if (sec.reloff + sec.nreloc * sizeof(RelocationInfo) > fsz) + return ParseError{"reloc table truncated"}; + for (std::uint32_t ri = 0; ri < sec.nreloc; ++ri) { + RelocationInfo ri_raw{}; + std::memcpy(&ri_raw, + buf.data() + sec.reloff + ri * sizeof(RelocationInfo), + sizeof(ri_raw)); + + // Scattered relocs (bit31 set) are not used on x86_64. + if (ri_raw.r_address < 0) + return ParseError{"scattered reloc in x86_64 object (unexpected)"}; + + const std::uint32_t sym_num = ri_raw.r_info & 0x00FFFFFFu; + const bool is_pcrel = (ri_raw.r_info >> 24) & 1; + const std::uint32_t length = (ri_raw.r_info >> 25) & 3; + const bool is_extern = (ri_raw.r_info >> 27) & 1; + const std::uint32_t rtype = (ri_raw.r_info >> 28) & 0xFu; + + // Read inline addend from the section bytes. + const auto addend = read_inline_addend( + buf.data(), fsz, + sec.offset, + static_cast(ri_raw.r_address), + length); + + ParsedRelocation pr; + pr.offset = static_cast(ri_raw.r_address); + pr.sym_index = sym_num; + pr.type = rtype; + pr.addend = addend; + pr.is_extern = is_extern; + pr.is_pcrel = is_pcrel; + pr.length = length; + ps.relocs.push_back(pr); + } + } + + obj.sections.push_back(std::move(ps)); + } + } else if (lc.cmd == 0x02 /* LC_SYMTAB */) { + if (lc.cmdsize < sizeof(SymtabCommand)) + return ParseError{"LC_SYMTAB too small"}; + SymtabCommand sc{}; + std::memcpy(&sc, buf.data() + lc_pos, sizeof(sc)); + symtab_off = sc.symoff; + nsyms = sc.nsyms; + strtab_off = sc.stroff; + strtab_size = sc.strsize; + } + + lc_pos += lc.cmdsize; + } + + // Parse symbol table. + if (nsyms > 0) { + if (symtab_off + nsyms * sizeof(NList64) > fsz) + return ParseError{"symbol table truncated"}; + if (strtab_off + strtab_size > fsz) + return ParseError{"string table truncated"}; + + const char* strtab = reinterpret_cast(buf.data() + strtab_off); + + for (std::uint32_t si = 0; si < nsyms; ++si) { + NList64 nl{}; + std::memcpy(&nl, buf.data() + symtab_off + si * sizeof(NList64), sizeof(nl)); + + // Skip debug/stab entries. + if (nl.n_type & kNTypeStab) continue; + + ParsedSymbol ps; + // Name: index into string table (n_strx=0 means empty name). + if (nl.n_strx > 0 && nl.n_strx < strtab_size) { + // Mach-O symbol names have a leading underscore by convention; + // strip it so callers see C names. + const char* raw = strtab + nl.n_strx; + if (raw[0] == '_') ++raw; + ps.name = raw; + } + + const std::uint8_t ntype = nl.n_type & kNTypeMask; + ps.defined = (ntype == kNTypeSect); + ps.section_index = ps.defined ? nl.n_sect : 0; // 1-based + ps.value = nl.n_value; + + // In .o files, n_value for N_SECT is the address within the + // section's vm range; for object files that start at 0, this IS + // the section-relative offset. + // Subtract the section's vmaddr to get a real section offset. + if (ps.defined && nl.n_sect >= 1 + && static_cast(nl.n_sect - 1) < obj.sections.size()) { + // We don't have vmaddr stored in ParsedSection yet; for .o + // files the vmaddr is usually 0 per section, so n_value IS + // the offset. Store it as-is; lower_macho_text will verify. + } + + // External bit determines visibility. + if (nl.n_type & kNExternal) { + ps.bind = 1; // global + } else { + ps.bind = 0; // local + } + + // Type: check if N_SECT symbol is in a text section (code). + if (ps.defined && nl.n_sect >= 1 + && static_cast(nl.n_sect - 1) < obj.sections.size()) { + const auto& sec = obj.sections[nl.n_sect - 1]; + const bool in_text = (sec.sectname == "__text") + || (sec.flags & 0x00000400u) /* some_instructions */ + || (sec.flags & 0x80000000u) /* pure_instructions */; + ps.type = in_text ? 2 : 0; // 2 = kTypeFunc + } + + // Undefined (import) symbols. + if (!ps.defined && (nl.n_type & kNExternal)) { + ps.bind = 1; + } + + obj.symbols.push_back(std::move(ps)); + } + } + + // Locate the primary __text section. + for (std::size_t i = 0; i < obj.sections.size(); ++i) { + if (obj.sections[i].sectname == "__text") { + obj.text_index = i; + break; + } + } + if (obj.text_index == static_cast(-1)) + return ParseError{"no __text section found"}; + + return obj; +} + +} // namespace voidlibc::voidlink::macho diff --git a/voidlink/macho_reader.hpp b/voidlink/macho_reader.hpp new file mode 100644 index 0000000..8258979 --- /dev/null +++ b/voidlink/macho_reader.hpp @@ -0,0 +1,76 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace voidlibc::voidlink::macho { + +// Mach-O magic (64-bit little-endian, x86_64 or ARM64) +inline constexpr std::uint32_t kMagic64 = 0xFEEDFACFu; +inline constexpr std::uint32_t kCpuX86_64 = 0x01000007u; +inline constexpr std::uint32_t kMhObject = 0x1u; + +// Relocation types for x86_64 +inline constexpr std::uint32_t kRelocUnsigned = 0; // abs64 / abs32 +inline constexpr std::uint32_t kRelocSigned = 1; // PC32 (inline addend is signed, includes -4) +inline constexpr std::uint32_t kRelocBranch = 2; // PC32 (call/jmp) +inline constexpr std::uint32_t kRelocGotLoad = 3; // GOTPCREL (movq via GOT) +inline constexpr std::uint32_t kRelocGot = 4; // GOT reference +inline constexpr std::uint32_t kRelocSubtractor = 5; // pair: SUBTRACTOR followed by UNSIGNED +inline constexpr std::uint32_t kRelocSigned1 = 6; // PC32 with extra -1 skew +inline constexpr std::uint32_t kRelocSigned2 = 7; // PC32 with extra -2 skew +inline constexpr std::uint32_t kRelocSigned4 = 8; // PC32 with extra -4 skew +inline constexpr std::uint32_t kRelocTls = 9; // thread-local + +// nlist_64 type byte +inline constexpr std::uint8_t kNTypeStab = 0xE0; +inline constexpr std::uint8_t kNTypeMask = 0x0E; +inline constexpr std::uint8_t kNTypeUndef = 0x00; +inline constexpr std::uint8_t kNTypeSect = 0x0E; +inline constexpr std::uint8_t kNExternal = 0x01; + +struct ParsedSymbol { + std::string name; + std::uint64_t value = 0; // section-relative offset (N_SECT) or 0 (N_UNDF) + std::uint32_t section_index = 0; // 1-based Mach-O section ordinal; 0 = undefined + std::uint8_t bind = 0; // 0=local, 1=global, 2=weak + std::uint8_t type = 0; // 0=notype, 2=func + bool defined = false; +}; + +struct ParsedRelocation { + std::uint64_t offset = 0; + std::uint32_t sym_index = 0; // index into ParsedObject::symbols (extern) or section ordinal (local) + std::uint32_t type = 0; // kReloc* constant + std::int64_t addend = 0; // inline addend (read from the target bytes) + bool is_extern = false; + bool is_pcrel = false; + std::uint32_t length = 0; // 0=byte, 1=short, 2=long, 3=quad +}; + +struct ParsedSection { + std::string segname; // e.g. "__TEXT" + std::string sectname; // e.g. "__text" + std::vector bytes; + std::uint64_t mem_size = 0; + std::uint64_t addr = 0; // section vmaddr in the .o file (used for layout delta) + std::uint32_t align_exp = 0; // log2 of section alignment + std::uint32_t flags = 0; + std::vector relocs; +}; + +struct ParsedObject { + std::vector sections; // indexed by 1-based section ordinal - 1 + std::vector symbols; + std::size_t text_index = static_cast(-1); +}; + +struct ParseError { std::string message; }; +using ParseResult = std::variant; + +ParseResult parse_macho_object(const std::filesystem::path& path); + +} // namespace voidlibc::voidlink::macho diff --git a/voidlink/main.cpp b/voidlink/main.cpp new file mode 100644 index 0000000..742d8bb --- /dev/null +++ b/voidlink/main.cpp @@ -0,0 +1,1099 @@ +#include "builder.hpp" +#include "coff_reader.hpp" +#include "elf_reader.hpp" +#include "format/vlc_format.hpp" +#include "loader/common/elf_synth.hpp" +#include "loader/macos/macho_synth.hpp" +#include "loader/windows/pe_synth.hpp" +#include "macho_reader.hpp" +#include "merge.hpp" +#include "reader.hpp" +#include "reloc_lowering.hpp" +#include "symlib_table.hpp" +#include "writer.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Detect object format from the first four bytes of a file. +// ELF: 0x7F 0x45 ('E'); COFF AMD64: LE 0x8664; Mach-O 64-bit LE: 0xFEEDFACF. +enum class ObjFormat { Unknown, Elf, Coff, Macho }; + +static ObjFormat detect_format(const std::string& path) { + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) return ObjFormat::Unknown; + unsigned char h[4] = {}; + const bool got = std::fread(h, 1, 4, f) == 4; + std::fclose(f); + if (!got) return ObjFormat::Unknown; + if (h[0] == 0x7F && h[1] == 0x45) return ObjFormat::Elf; // \x7fE + if (h[0] == 0x64 && h[1] == 0x86) return ObjFormat::Coff; // LE 0x8664 + if (h[0] == 0xCF && h[1] == 0xFA && h[2] == 0xED && h[3] == 0xFE) + return ObjFormat::Macho; // 0xFEEDFACF little-endian + return ObjFormat::Unknown; +} + +using namespace voidlibc::voidlink; + +namespace { + +int usage(const char* argv0) { + std::fprintf(stderr, + "voidlink — VoidLibC universal linker\n" + "\n" + "File extensions:\n" + " .vle executable (has entry point, run via voidloader)\n" + " .vls shared library (loadable via voidlib_load / dlopen)\n" + " .vla static archive (for build-time linking, not loadable at runtime)\n" + "\n" + "usage:\n" + " %s create-empty \n" + " write a minimal empty container\n" + " %s dump \n" + " parse and print container header\n" + " %s pack-blob --os linux --code --symbol [--entry ] \n" + " build a single-section container from a raw machine-code blob\n" + " %s pack-elf --os [--need ]... [--entry ] [--static] ... -o \n" + " build a single-OS container; --need libc.so.6 for dynamic linkage, omit for static\n" + " --entry sets executable mode (.vle); --static sets archive mode (.vla); else .vls\n" + " %s fuse [--linux f.o ...] [--windows f.obj ...] [--macos f.o ...]\n" + " [--need ]... [--entry ] [--static] -o \n" + " pack per-OS object files into a universal multi-OS container\n" + " %s wrap [--linux ] [--windows ] [--macos ]\n" + " [--entry ] -o \n" + " embed pre-linked native binaries verbatim as NativeBlob sections\n" + " %s vlcldd \n" + " show dynamic dependencies of the Linux section (like ldd)\n" + " %s verify \n" + " structural check all sections: magic bytes, format, and dependency lists\n", + argv0, argv0, argv0, argv0, argv0, argv0, argv0, argv0); + return 2; +} + +int cmd_create_empty(const char* argv0, int argc, char** argv) { + if (argc != 1) { + return usage(argv0); + } + const auto r = write_empty(argv[0]); + if (!r.ok) { + std::fprintf(stderr, "voidlink: %s\n", r.error.c_str()); + return 1; + } + return 0; +} + +int cmd_pack_blob(const char* argv0, int argc, char** argv) { + using namespace voidlibc::format; + using namespace voidlibc::voidlink; + + TargetOS os = TargetOS::Unknown; + std::string code_path; + std::string symbol_name; + std::uint64_t entry_off = 0; + std::string out_path; + + for (int i = 0; i < argc; ++i) { + const std::string_view a = argv[i]; + auto need = [&](const char* flag) -> const char* { + if (i + 1 >= argc) { + std::fprintf(stderr, "voidlink: %s requires a value\n", flag); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--os") { + const std::string_view v = need("--os"); + if (v == "linux") os = TargetOS::Linux; + else if (v == "windows") os = TargetOS::Windows; + else if (v == "macos") os = TargetOS::MacOS; + else { std::fprintf(stderr, "voidlink: unknown os '%.*s'\n", + static_cast(v.size()), v.data()); return 2; } + } + else if (a == "--code") code_path = need("--code"); + else if (a == "--symbol") symbol_name = need("--symbol"); + else if (a == "--entry") entry_off = std::strtoull(need("--entry"), nullptr, 0); + else if (out_path.empty()) out_path = std::string(a); + else { return usage(argv0); } + } + + if (os == TargetOS::Unknown || code_path.empty() + || symbol_name.empty() || out_path.empty()) { + return usage(argv0); + } + + std::ifstream in(code_path, std::ios::binary | std::ios::ate); + if (!in) { + std::fprintf(stderr, "voidlink: cannot open code blob %s\n", code_path.c_str()); + return 1; + } + const auto size = static_cast(in.tellg()); + in.seekg(0, std::ios::beg); + std::vector code(static_cast(size)); + in.read(reinterpret_cast(code.data()), size); + + ContainerBuilder b; + SymbolSpec sym{}; + sym.name = symbol_name; + sym.kind = SymbolKind::Function; + sym.size = 0; + sym.exported = true; + b.add_symbol(std::move(sym)); + + SectionSpec sec{}; + sec.target_os = os; + sec.code = std::move(code); + sec.entry_offset = entry_off; + b.add_section(std::move(sec)); + + const auto w = b.write(out_path); + if (!w.ok) { + std::fprintf(stderr, "voidlink: %s\n", w.error.c_str()); + return 1; + } + return 0; +} + +// Lower one object file (ELF, COFF, or Mach-O, auto-detected) into LoweredText. +static bool lower_one_obj(const char* argv0, + const std::string& path, + voidlibc::format::TargetOS os, + LoweredText& out) { + const auto fmt = detect_format(path); + + if (fmt == ObjFormat::Coff) { + auto parsed = coff::parse_coff_object(path); + if (const auto* e = std::get_if(&parsed)) { + std::fprintf(stderr, "%s: %s: %s\n", argv0, path.c_str(), e->c_str()); + return false; + } + auto lowered = lower_coff_text(std::get(parsed), os); + if (const auto* e = std::get_if(&lowered)) { + std::fprintf(stderr, "%s: %s: %s\n", argv0, path.c_str(), e->c_str()); + return false; + } + out = std::move(std::get(lowered)); + return true; + } + + if (fmt == ObjFormat::Macho) { + auto parsed = macho::parse_macho_object(path); + if (const auto* e = std::get_if(&parsed)) { + std::fprintf(stderr, "%s: %s: %s\n", argv0, path.c_str(), e->message.c_str()); + return false; + } + auto lowered = lower_macho_text(std::get(parsed), os); + if (const auto* e = std::get_if(&lowered)) { + std::fprintf(stderr, "%s: %s: %s\n", argv0, path.c_str(), e->c_str()); + return false; + } + out = std::move(std::get(lowered)); + return true; + } + + // Default: ELF + auto parsed = elf::parse_elf64_object(path); + if (const auto* e = std::get_if(&parsed)) { + std::fprintf(stderr, "%s: %s: %s\n", argv0, path.c_str(), e->c_str()); + return false; + } + auto lowered = lower_elf_text(std::get(parsed), os); + if (const auto* e = std::get_if(&lowered)) { + std::fprintf(stderr, "%s: %s: %s\n", argv0, path.c_str(), e->c_str()); + return false; + } + out = std::move(std::get(lowered)); + return true; +} + +// Lower a list of object files (ELF or COFF) and return a merged LoweredText. +static bool lower_elf_group(const char* argv0, + const std::vector& paths, + voidlibc::format::TargetOS os, + LoweredText& out) { + std::vector objs; + objs.reserve(paths.size()); + for (const auto& path : paths) { + LoweredText lt; + if (!lower_one_obj(argv0, path, os, lt)) return false; + objs.push_back(std::move(lt)); + } + auto merged = merge_lowered(std::move(objs)); + if (const auto* e = std::get_if(&merged)) { + std::fprintf(stderr, "%s: %s\n", argv0, e->c_str()); + return false; + } + out = std::move(std::get(merged)); + return true; +} + +// Resolve the import library for a symbol, using (in priority order): +// 1. symlib_overrides (from --symlib name=lib on CLI) +// 2. built-in symlib_table +// 3. per-OS default (libc.so.6 / ucrtbase.dll / libSystem.B.dylib) +// Emits a warning (or error when strict) if falling back to default. +static std::string resolve_library( + const std::string& sym_name, + voidlibc::format::TargetOS os, + const std::unordered_map& overrides, + bool strict_libs) { + auto oit = overrides.find(sym_name); + if (oit != overrides.end()) return oit->second; + + auto sv = voidlibc::voidlink::library_for(os, sym_name); + if (!sv.empty()) return std::string(sv); + + auto def = voidlibc::voidlink::default_library(os); + if (strict_libs) { + std::fprintf(stderr, + "voidlink: warning: unknown library for symbol '%s' on %s;" + " defaulting to '%.*s'. Use --symlib to suppress.\n", + sym_name.c_str(), + os == voidlibc::format::TargetOS::Linux ? "linux" + : os == voidlibc::format::TargetOS::Windows ? "windows" : "macos", + static_cast(def.size()), def.data()); + } + return std::string(def); +} + +// Convert LoweredText into a pre-synthesized native blob (ELF/PE/Mach-O). +// On success, lt.section.kind == NativeBlob and lt.section.code holds +// the complete native object image; lt.section.relocs is cleared. +// Returns an error string on failure. +static std::string synthesize_native_blob( + LoweredText& lt, + const std::unordered_map& symlib_overrides = {}, + bool strict_libs = false, + const std::vector& explicit_needed = {}) { + using namespace voidlibc::format; + using namespace voidlibc::loader; + + const TargetOS os = lt.section.target_os; + + if (os == TargetOS::Linux) { + ElfSynthInput in{}; + in.code = lt.section.code; + in.data_blob = lt.section.data; + in.relocs = lt.section.relocs; + // explicit_needed (--need) overrides the auto-derived list entirely. + in.needed_libs = explicit_needed; + for (std::size_t i = 0; i < lt.symbols.size(); ++i) { + const auto& s = lt.symbols[i]; + if (s.exported && !s.data_section && s.section_index != kSymUndefined) { + ExportedSymbol e{}; + e.name = s.name; e.code_offset = s.value; e.size = s.size; + e.is_function = s.kind == SymbolKind::Function; e.weak = s.weak; + in.exports.push_back(std::move(e)); + } + if (!s.data_section && s.section_index != kSymUndefined) { + InternalSymbol is{}; is.sym_id = static_cast(i); + is.code_offset = s.value; is.name = s.name; + in.internal_symbols.push_back(std::move(is)); + } + if (s.data_section && s.section_index != kSymUndefined) { + DataSymbol ds{}; ds.sym_id = static_cast(i); + ds.data_offset = s.value; ds.name = s.name; + in.data_symbols.push_back(std::move(ds)); + } + if (s.section_index == kSymUndefined && !s.name.empty()) { + ImportedSymbol im{}; im.sym_id = static_cast(i); + im.name = s.name; + im.library = !s.library.empty() + ? s.library + : (explicit_needed.empty() + ? resolve_library(s.name, os, symlib_overrides, strict_libs) + : std::string{}); + im.version_name = s.version_name; + im.version_hash = s.version_hash; + im.version_flags = s.version_flags; + in.imports.push_back(std::move(im)); + } + } + const auto out = synthesize_elf(in); + if (!out.ok) return out.error; + lt.section.code = out.bytes; + lt.section.relocs = {}; + lt.section.data = {}; + lt.section.kind = SectionKind::NativeBlob; + return {}; + } + + if (os == TargetOS::Windows) { + windows::PeSynthInput in{}; + in.code = lt.section.code; + in.data_blob = lt.section.data; + in.relocs = lt.section.relocs; + in.dll_name = "output.dll"; // synthesized DLL's own name + for (std::size_t i = 0; i < lt.symbols.size(); ++i) { + const auto& s = lt.symbols[i]; + if (s.exported && !s.data_section && s.section_index != kSymUndefined) { + windows::WinExportedSymbol e{}; + e.name = s.name; e.code_offset = s.value; e.size = s.size; + e.is_function = s.kind == SymbolKind::Function; + in.exports.push_back(std::move(e)); + } + if (!s.data_section && s.section_index != kSymUndefined) { + windows::WinInternalSymbol is{}; is.sym_id = static_cast(i); + is.code_offset = s.value; is.name = s.name; + in.internal_symbols.push_back(std::move(is)); + } + if (s.data_section && s.section_index != kSymUndefined) { + windows::WinDataSymbol ds{}; ds.sym_id = static_cast(i); + ds.data_offset = s.value; ds.name = s.name; + in.data_symbols.push_back(std::move(ds)); + } + if (s.section_index == kSymUndefined && !s.name.empty()) { + windows::WinImportedSymbol im{}; im.sym_id = static_cast(i); + im.name = s.name; + im.library = !s.library.empty() + ? s.library + : resolve_library(s.name, os, symlib_overrides, strict_libs); + in.imports.push_back(std::move(im)); + } + } + const auto out = windows::synthesize_pe(in); + if (!out.ok) return out.error; + lt.section.code = out.bytes; + lt.section.relocs = {}; + lt.section.data = {}; + lt.section.kind = SectionKind::NativeBlob; + return {}; + } + + if (os == TargetOS::MacOS) { + macos::MachoSynthInput in{}; + in.code = lt.section.code; + in.data_blob = lt.section.data; + in.relocs = lt.section.relocs; + in.needed_libs = explicit_needed; + for (std::size_t i = 0; i < lt.symbols.size(); ++i) { + const auto& s = lt.symbols[i]; + if (s.exported && !s.data_section && s.section_index != kSymUndefined) { + macos::MachoExportedSymbol e{}; + e.name = s.name; e.code_offset = s.value; e.size = s.size; + e.is_function = s.kind == SymbolKind::Function; e.weak = s.weak; + in.exports.push_back(std::move(e)); + } + if (!s.data_section && s.section_index != kSymUndefined) { + macos::MachoInternalSymbol is{}; + is.sym_id = static_cast(i); + is.code_offset = s.value; is.name = s.name; + in.internal_symbols.push_back(std::move(is)); + } + if (s.data_section && s.section_index != kSymUndefined) { + macos::MachoDataSymbol ds{}; + ds.sym_id = static_cast(i); + ds.data_offset = s.value; ds.name = s.name; + in.data_symbols.push_back(std::move(ds)); + } + if (s.section_index == kSymUndefined && !s.name.empty()) { + macos::MachoImportedSymbol im{}; + im.sym_id = static_cast(i); im.name = s.name; + im.library = !s.library.empty() + ? s.library + : (explicit_needed.empty() + ? resolve_library(s.name, os, symlib_overrides, strict_libs) + : std::string{}); + in.imports.push_back(std::move(im)); + } + } + const auto out_m = macos::synthesize_macho(in); + if (!out_m.ok) return out_m.error; + lt.section.code = out_m.bytes; + lt.section.relocs = {}; + lt.section.data = {}; + lt.section.kind = SectionKind::NativeBlob; + return {}; + } + + return "synthesize_native_blob: unsupported OS"; +} + +int cmd_pack_elf(const char* argv0, int argc, char** argv) { + using namespace voidlibc::format; + using namespace voidlibc::voidlink; + + TargetOS os = TargetOS::Unknown; + std::vector in_paths; + std::string out_path; + std::string entry_symbol; // non-empty → executable mode + std::vector needed_libs; // explicit DT_NEEDED override (--need) + std::unordered_map symlib_overrides; // --symlib name=lib + bool is_static = false; + bool strict_libs = false; + + for (int i = 0; i < argc; ++i) { + const std::string_view a = argv[i]; + auto need = [&](const char* flag) -> const char* { + if (i + 1 >= argc) { + std::fprintf(stderr, "voidlink: %s requires a value\n", flag); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--os") { + const std::string_view v = need("--os"); + if (v == "linux") os = TargetOS::Linux; + else if (v == "windows") os = TargetOS::Windows; + else if (v == "macos") os = TargetOS::MacOS; + else { std::fprintf(stderr, "voidlink: unknown os\n"); return 2; } + } + else if (a == "--entry") entry_symbol = need("--entry"); + else if (a == "--need") needed_libs.emplace_back(need("--need")); + else if (a == "--static") is_static = true; + else if (a == "--strict-libs") strict_libs = true; + else if (a == "--symlib") { + std::string_view kv = need("--symlib"); + const auto eq = kv.find('='); + if (eq == std::string_view::npos) { + std::fprintf(stderr, "voidlink: --symlib requires name=library\n"); + return 2; + } + symlib_overrides[std::string(kv.substr(0, eq))] = + std::string(kv.substr(eq + 1)); + } + else if (a == "-o") out_path = need("-o"); + else in_paths.emplace_back(a); + } + + if (os == TargetOS::Unknown || in_paths.empty() || out_path.empty()) { + return usage(argv0); + } + + std::vector lowered_objects; + lowered_objects.reserve(in_paths.size()); + for (const auto& path : in_paths) { + LoweredText lt; + if (!lower_one_obj(argv0, path, os, lt)) return 1; + lowered_objects.push_back(std::move(lt)); + } + + auto merged = merge_lowered(std::move(lowered_objects)); + if (const auto* e = std::get_if(&merged)) { + std::fprintf(stderr, "voidlink: %s\n", e->c_str()); + return 1; + } + auto& lt = std::get(merged); + + // If --entry was given, locate the symbol and record its offset. + if (!entry_symbol.empty()) { + bool found = false; + for (const auto& s : lt.symbols) { + if (s.name == entry_symbol && s.section_index != kSymUndefined) { + lt.section.entry_offset = s.value; + found = true; + break; + } + } + if (!found) { + std::fprintf(stderr, "voidlink: entry symbol '%s' not found\n", + entry_symbol.c_str()); + return 1; + } + } + + bool any_exports = false; + for (const auto& s : lt.symbols) if (s.exported) { any_exports = true; break; } + if (!any_exports) { + std::fprintf(stderr, "voidlink: no exported symbols found\n"); + return 1; + } + + if (const auto err = synthesize_native_blob(lt, symlib_overrides, strict_libs, needed_libs); !err.empty()) { + std::fprintf(stderr, "voidlink: synthesis failed: %s\n", err.c_str()); + return 1; + } + + ContainerBuilder b; + if (!entry_symbol.empty()) b.set_executable(entry_symbol); + if (is_static) b.set_static_library(); + for (auto& s : lt.symbols) b.add_symbol(std::move(s)); + b.add_section(std::move(lt.section)); + + if (out_path.find('.') == std::string::npos) { + std::uint32_t flags = 0; + if (!entry_symbol.empty()) flags |= static_cast(ContainerFlags::Executable); + if (is_static) flags |= static_cast(ContainerFlags::StaticLibrary); + out_path += infer_extension(flags); + } + + const auto w = b.write(out_path); + if (!w.ok) { + std::fprintf(stderr, "voidlink: %s\n", w.error.c_str()); + return 1; + } + return 0; +} + +// fuse [--linux f.o ...] [--windows f.obj ...] [--macos f.o ...] -o out.vlc +// +// Packs per-OS object files into one universal .vlc. Multiple --linux / +// --windows / --macos groups may appear; each group's objects are merged and +// stored as one section in the output container. All three platform readers +// are implemented: ELF (.o) for --linux, COFF (.obj) for --windows, Mach-O +// (.o) for --macos. +int cmd_fuse(const char* argv0, int argc, char** argv) { + using namespace voidlibc::format; + + struct OsGroup { + TargetOS os; + std::vector paths; + }; + + std::vector groups; + std::string out_path; + std::string entry_symbol; + std::vector needed_libs; // global --need (all OSes) + std::vector linux_needs; // --linux-need + std::vector windows_needs; // --windows-need + std::vector macos_needs; // --macos-need + std::unordered_map symlib_overrides; // --symlib name=lib + bool is_static = false; + bool strict_libs = false; + OsGroup* cur = nullptr; + + auto find_or_add = [&](TargetOS os) -> OsGroup& { + for (auto& g : groups) if (g.os == os) return g; + groups.push_back({os, {}}); + return groups.back(); + }; + + for (int i = 0; i < argc; ++i) { + const std::string_view a = argv[i]; + if (a == "--linux") { cur = &find_or_add(TargetOS::Linux); } + else if (a == "--windows") { cur = &find_or_add(TargetOS::Windows); } + else if (a == "--macos") { cur = &find_or_add(TargetOS::MacOS); } + else if (a == "--entry") { + if (i + 1 >= argc) { std::fprintf(stderr, "%s: --entry needs a value\n", argv0); return 2; } + entry_symbol = argv[++i]; + } + else if (a == "--need") { + if (i + 1 >= argc) { std::fprintf(stderr, "%s: --need requires a value\n", argv0); return 2; } + needed_libs.emplace_back(argv[++i]); + } + else if (a == "--linux-need") { + if (i + 1 >= argc) { std::fprintf(stderr, "%s: --linux-need requires a value\n", argv0); return 2; } + linux_needs.emplace_back(argv[++i]); + } + else if (a == "--windows-need") { + if (i + 1 >= argc) { std::fprintf(stderr, "%s: --windows-need requires a value\n", argv0); return 2; } + windows_needs.emplace_back(argv[++i]); + } + else if (a == "--macos-need") { + if (i + 1 >= argc) { std::fprintf(stderr, "%s: --macos-need requires a value\n", argv0); return 2; } + macos_needs.emplace_back(argv[++i]); + } + else if (a == "--symlib") { + if (i + 1 >= argc) { std::fprintf(stderr, "%s: --symlib requires name=library\n", argv0); return 2; } + std::string_view kv = argv[++i]; + const auto eq = kv.find('='); + if (eq == std::string_view::npos) { + std::fprintf(stderr, "%s: --symlib requires name=library\n", argv0); return 2; + } + symlib_overrides[std::string(kv.substr(0, eq))] = std::string(kv.substr(eq + 1)); + } + else if (a == "--strict-libs") { + strict_libs = true; + } + else if (a == "--static") { + is_static = true; + } + else if (a == "-o") { + if (i + 1 >= argc) { + std::fprintf(stderr, "%s: -o requires a value\n", argv0); + return 2; + } + out_path = argv[++i]; + } else { + if (!cur) { + std::fprintf(stderr, + "%s: fuse: input file '%.*s' appears before any --linux / --windows / --macos flag\n", + argv0, static_cast(a.size()), a.data()); + return 2; + } + cur->paths.emplace_back(a); + } + } + + if (groups.empty() || out_path.empty()) { + std::fprintf(stderr, + "usage: %s fuse [--linux f.o ...] [--windows f.obj ...] [--macos f.o ...]\n" + " [--entry sym] [--static]\n" + " [--need ]...\n" + " [--linux-need ]... [--windows-need ]..." + " [--macos-need ]...\n" + " [--symlib name=lib]... [--strict-libs]\n" + " -o \n", + argv0); + return 2; + } + + ContainerBuilder b; + + for (auto& g : groups) { + if (g.paths.empty()) continue; + + LoweredText lt; + if (!lower_elf_group(argv0, g.paths, g.os, lt)) return 1; + + bool any_exports = false; + for (const auto& s : lt.symbols) if (s.exported) { any_exports = true; break; } + if (!any_exports) { + const char* osname = + g.os == TargetOS::Linux ? "linux" : + g.os == TargetOS::Windows ? "windows" : "macos"; + std::fprintf(stderr, "%s: fuse: no exported symbols in %s group\n", + argv0, osname); + return 1; + } + + // If --entry specified, find the symbol's offset in this group. + if (!entry_symbol.empty()) { + for (const auto& s : lt.symbols) { + if (s.name == entry_symbol && s.section_index != kSymUndefined) { + lt.section.entry_offset = s.value; + break; + } + } + } + + // Pre-synthesize native blob (ELF/PE/Mach-O) so ldd/file work on the .vlc. + // Merge global --need with per-OS --linux-need / --windows-need / --macos-need. + std::vector merged_needs = needed_libs; + { + const auto* per_os = + (g.os == TargetOS::Linux) ? &linux_needs + : (g.os == TargetOS::Windows) ? &windows_needs + : &macos_needs; + merged_needs.insert(merged_needs.end(), per_os->begin(), per_os->end()); + } + if (const auto err = synthesize_native_blob(lt, symlib_overrides, strict_libs, merged_needs); !err.empty()) { + std::fprintf(stderr, "%s: fuse: synthesis failed: %s\n", argv0, err.c_str()); + return 1; + } + + const std::uint32_t sym_offset = b.symbol_count(); + const std::uint16_t sec_index = b.section_count(); + + for (auto& r : lt.section.relocs) { + r.sym_id += sym_offset; + } + + // Fix section_index: defined symbols have section_index==0 from the + // lowerer (one section per LoweredText); remap to the actual slot. + for (auto& s : lt.symbols) { + if (s.section_index != kSymUndefined) { + s.section_index = sec_index; + } + } + + for (auto& s : lt.symbols) b.add_symbol(std::move(s)); + b.add_section(std::move(lt.section)); + } + + if (!entry_symbol.empty()) b.set_executable(entry_symbol); + if (is_static) b.set_static_library(); + + if (out_path.find('.') == std::string::npos) { + std::uint32_t flags = 0; + if (!entry_symbol.empty()) flags |= static_cast(ContainerFlags::Executable); + if (is_static) flags |= static_cast(ContainerFlags::StaticLibrary); + out_path += infer_extension(flags); + } + + const auto w = b.write(out_path); + if (!w.ok) { + std::fprintf(stderr, "%s: %s\n", argv0, w.error.c_str()); + return 1; + } + return 0; +} + +// wrap [--linux ] [--windows ] [--macos ] +// [--entry ] -o +// Pack pre-built native shared libraries verbatim as NativeBlob sections. +// Unlike pack-elf/fuse (which start from .o files and synthesize ELF/PE), +// wrap embeds an already-linked binary directly. +int cmd_wrap(const char* argv0, int argc, char** argv) { + using namespace voidlibc::format; + + std::string linux_path; + std::string windows_path; + std::string macos_path; + std::string out_path; + std::string entry_symbol; + + for (int i = 0; i < argc; ++i) { + const std::string_view a = argv[i]; + auto need = [&](const char* flag) -> const char* { + if (i + 1 >= argc) { + std::fprintf(stderr, "%s: %s requires a value\n", argv0, flag); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--linux") linux_path = need("--linux"); + else if (a == "--windows") windows_path = need("--windows"); + else if (a == "--macos") macos_path = need("--macos"); + else if (a == "--entry") entry_symbol = need("--entry"); + else if (a == "-o") out_path = need("-o"); + else { + std::fprintf(stderr, "%s: wrap: unknown argument '%.*s'\n", + argv0, static_cast(a.size()), a.data()); + return usage(argv0); + } + } + + if (linux_path.empty() && windows_path.empty() && macos_path.empty()) { + std::fprintf(stderr, "%s: wrap: at least one of --linux/--windows/--macos required\n", argv0); + return 2; + } + if (out_path.empty()) { + std::fprintf(stderr, "%s: wrap: -o required\n", argv0); + return 2; + } + + auto read_blob = [&](const std::string& path) -> std::vector { + std::ifstream f(path, std::ios::binary | std::ios::ate); + if (!f) { + std::fprintf(stderr, "%s: wrap: cannot open '%s'\n", argv0, path.c_str()); + std::exit(1); + } + const auto sz = static_cast(f.tellg()); + f.seekg(0); + std::vector buf(sz); + f.read(reinterpret_cast(buf.data()), static_cast(sz)); + if (!f) { + std::fprintf(stderr, "%s: wrap: read failed: '%s'\n", argv0, path.c_str()); + std::exit(1); + } + return buf; + }; + + ContainerBuilder b; + if (!entry_symbol.empty()) b.set_executable(entry_symbol); + + if (!linux_path.empty()) { + SectionSpec sec; + sec.target_os = TargetOS::Linux; + sec.kind = SectionKind::NativeBlob; + sec.code = read_blob(linux_path); + b.add_section(std::move(sec)); + } + if (!windows_path.empty()) { + SectionSpec sec; + sec.target_os = TargetOS::Windows; + sec.kind = SectionKind::NativeBlob; + sec.code = read_blob(windows_path); + b.add_section(std::move(sec)); + } + if (!macos_path.empty()) { + SectionSpec sec; + sec.target_os = TargetOS::MacOS; + sec.kind = SectionKind::NativeBlob; + sec.code = read_blob(macos_path); + b.add_section(std::move(sec)); + } + + if (out_path.find('.') == std::string::npos) { + std::uint32_t flags = 0; + if (!entry_symbol.empty()) + flags |= static_cast(ContainerFlags::Executable); + out_path += infer_extension(flags); + } + + const auto w = b.write(out_path); + if (!w.ok) { + std::fprintf(stderr, "%s: %s\n", argv0, w.error.c_str()); + return 1; + } + return 0; +} + +// vlcldd — extract the Linux NativeBlob, write to a temp file, +// run ldd on it, and print the output. Acts like `ldd` but for .vlc files. +int cmd_vlcldd(const char* argv0, int argc, char** argv) { + using namespace voidlibc::format; + + if (argc != 1) { + std::fprintf(stderr, "usage: %s vlcldd \n", argv0); + return 2; + } + + // Load the entire .vlc into memory for direct section parsing. + std::ifstream f(argv[0], std::ios::binary | std::ios::ate); + if (!f) { + std::fprintf(stderr, "%s: vlcldd: cannot open %s\n", argv0, argv[0]); + return 1; + } + const auto fsz = static_cast(f.tellg()); + f.seekg(0); + std::vector buf(fsz); + f.read(reinterpret_cast(buf.data()), static_cast(fsz)); + if (!f || fsz < sizeof(FileHeader)) { + std::fprintf(stderr, "%s: vlcldd: read failed\n", argv0); + return 1; + } + + const auto* hdr = reinterpret_cast(buf.data()); + if (hdr->magic != kMagic) { + std::fprintf(stderr, "%s: vlcldd: bad magic\n", argv0); + return 1; + } + + const auto sec_end = hdr->section_dir_off + + static_cast(hdr->section_count) * sizeof(SectionEntry); + if (sec_end > fsz) { + std::fprintf(stderr, "%s: vlcldd: section directory truncated\n", argv0); + return 1; + } + const auto* entries = reinterpret_cast(buf.data() + hdr->section_dir_off); + + // Find the Linux NativeBlob section. + const SectionEntry* linux_sec = nullptr; + for (std::uint32_t i = 0; i < hdr->section_count; ++i) { + if (entries[i].target_os == TargetOS::Linux + && entries[i].kind == SectionKind::NativeBlob) { + linux_sec = &entries[i]; + break; + } + } + if (!linux_sec) { + std::fprintf(stderr, "%s: vlcldd: no Linux NativeBlob section in this file\n" + " (was it built with an older voidlink that used RawCode sections?)\n", + argv0); + return 1; + } + if (linux_sec->code_off + linux_sec->code_size > fsz) { + std::fprintf(stderr, "%s: vlcldd: section blob truncated\n", argv0); + return 1; + } + + // Write blob to a temp file and run ldd on it. + char tmp[256]; + std::snprintf(tmp, sizeof(tmp), "/tmp/vlcldd_%d.so", static_cast(getpid())); + { + std::ofstream out(tmp, std::ios::binary | std::ios::trunc); + out.write(reinterpret_cast(buf.data() + linux_sec->code_off), + static_cast(linux_sec->code_size)); + if (!out) { + std::fprintf(stderr, "%s: vlcldd: write to %s failed\n", argv0, tmp); + return 1; + } + } + + ::chmod(tmp, 0755); + std::string ldd_cmd = "ldd "; + ldd_cmd += tmp; + const int rc = std::system(ldd_cmd.c_str()); + std::remove(tmp); + return rc == 0 ? 0 : 1; +} + +// verify — structural check of every platform section. +// Validates magic bytes, uses file(1) for format identification, and runs +// readelf/objdump to list shared library dependencies. Exits 0 if all +// present sections pass magic validation, 1 if any fail. +int cmd_verify(const char* argv0, int argc, char** argv) { + using namespace voidlibc::format; + + if (argc != 1) { + std::fprintf(stderr, "usage: %s verify \n", argv0); + return 2; + } + + const char* path = argv[0]; + std::ifstream f(path, std::ios::binary | std::ios::ate); + if (!f) { + std::fprintf(stderr, "%s: verify: cannot open %s\n", argv0, path); + return 1; + } + const auto fsz = static_cast(f.tellg()); + f.seekg(0); + std::vector buf(fsz); + f.read(reinterpret_cast(buf.data()), static_cast(fsz)); + if (!f || fsz < sizeof(FileHeader)) { + std::fprintf(stderr, "%s: verify: read failed or file too small\n", argv0); + return 1; + } + + const auto* hdr = reinterpret_cast(buf.data()); + if (hdr->magic != kMagic) { + std::fprintf(stderr, "%s: verify: bad magic — not a .vlc file\n", argv0); + return 1; + } + + std::printf("file: %s\n", path); + std::printf("version: %u.%u\n", hdr->version_major, hdr->version_minor); + std::printf("arch: %s\n", + hdr->arch == TargetArch::X86_64 ? "x86_64" : "unknown"); + std::printf("sections: %u\n\n", hdr->section_count); + + const auto sec_end = hdr->section_dir_off + + static_cast(hdr->section_count) + * sizeof(SectionEntry); + if (sec_end > fsz) { + std::fprintf(stderr, "%s: verify: section directory truncated\n", argv0); + return 1; + } + const auto* entries = + reinterpret_cast(buf.data() + hdr->section_dir_off); + + // Helper: run a shell command, return its exit code. + auto run = [](const char* cmd) { return std::system(cmd); }; + + int failures = 0; + + for (std::uint32_t i = 0; i < hdr->section_count; ++i) { + const auto& sec = entries[i]; + + const char* os_name = + sec.target_os == TargetOS::Linux ? "linux" : + sec.target_os == TargetOS::Windows ? "windows" : + sec.target_os == TargetOS::MacOS ? "macos" : "unknown"; + const char* ext = + sec.target_os == TargetOS::Windows ? ".dll" : + sec.target_os == TargetOS::MacOS ? ".dylib" : ".so"; + + std::printf("section[%u] os=%-8s code=%llu bytes", + i, os_name, + static_cast(sec.code_size)); + if (sec.data_size > 0) + std::printf(" data=%llu bytes", + static_cast(sec.data_size)); + std::printf("\n"); + + if (sec.code_off + sec.code_size > fsz) { + std::printf(" FAIL blob truncated\n\n"); + ++failures; + continue; + } + + const std::uint8_t* blob = buf.data() + sec.code_off; + + // Validate magic bytes. + bool magic_ok = false; + const char* magic_desc = "?"; + if (sec.target_os == TargetOS::Linux && sec.code_size >= 4) { + magic_ok = blob[0]==0x7F && blob[1]=='E' && blob[2]=='L' && blob[3]=='F'; + magic_desc = "ELF (7f 45 4c 46)"; + } else if (sec.target_os == TargetOS::Windows && sec.code_size >= 2) { + magic_ok = blob[0]=='M' && blob[1]=='Z'; + magic_desc = "PE/MZ (4d 5a)"; + } else if (sec.target_os == TargetOS::MacOS && sec.code_size >= 4) { + magic_ok = blob[0]==0xCF && blob[1]==0xFA && blob[2]==0xED && blob[3]==0xFE; + magic_desc = "Mach-O LE64 (cf fa ed fe)"; + } + + if (magic_ok) { + std::printf(" magic OK %s\n", magic_desc); + } else { + const std::size_t nb = std::min(sec.code_size, 4); + std::printf(" magic FAIL expected %s got", magic_desc); + for (std::size_t b = 0; b < nb; ++b) + std::printf(" %02x", blob[b]); + std::printf("\n"); + ++failures; + } + + // Write blob to temp file for tool inspection. + char tmp[256]; + std::snprintf(tmp, sizeof(tmp), "/tmp/vlcverify_%d_%u%s", + static_cast(::getpid()), i, ext); + { + std::ofstream out(tmp, std::ios::binary | std::ios::trunc); + out.write(reinterpret_cast(blob), + static_cast(sec.code_size)); + } + ::chmod(tmp, 0755); + + // file(1) — format identification. + char cmd[1024]; + std::snprintf(cmd, sizeof(cmd), "file -b %s 2>/dev/null", tmp); + std::printf(" file "); + std::fflush(stdout); + if (run(cmd) != 0) + std::printf("(file(1) not available)\n"); + + // Dependency listing — tool varies by platform. + if (sec.target_os == TargetOS::Linux) { + std::printf(" needs (DT_NEEDED via readelf -d):\n"); + std::fflush(stdout); + std::snprintf(cmd, sizeof(cmd), + "readelf -d %s 2>/dev/null" + " | grep '(NEEDED)' | sed 's/^/ /'", tmp); + if (run(cmd) != 0) + std::printf(" (readelf not available)\n"); + } else if (sec.target_os == TargetOS::Windows) { + std::printf(" needs (PE import DLL names):\n"); + std::fflush(stdout); + // Prefer llvm-readobj; fall back to objdump (cross-PE capable on Linux). + std::snprintf(cmd, sizeof(cmd), + "{ llvm-readobj --coff-imports %s 2>/dev/null" + " | grep 'Name:' | sed 's/^/ /'" + "; } || { objdump -p %s 2>/dev/null" + " | grep 'DLL Name:' | sed 's/^/ /'; }", + tmp, tmp); + run(cmd); + } else if (sec.target_os == TargetOS::MacOS) { + std::printf(" needs (LC_LOAD_DYLIB names):\n"); + std::fflush(stdout); + std::snprintf(cmd, sizeof(cmd), + "{ llvm-readobj --macho-dylibs-used %s 2>/dev/null" + " | grep 'name:' | sed 's/^/ /'" + "; } || { objdump -p %s 2>/dev/null" + " | grep 'name ' | sed 's/^/ /'; }", + tmp, tmp); + run(cmd); + } + + std::remove(tmp); + std::printf("\n"); + } + + if (failures == 0) + std::printf("OK all %u section(s) passed\n", hdr->section_count); + else + std::fprintf(stderr, "FAIL %d section(s) failed verification\n", failures); + + return failures == 0 ? 0 : 1; +} + +int cmd_dump(const char* argv0, int argc, char** argv) { + if (argc != 1) { + return usage(argv0); + } + const auto r = read_container(argv[0]); + if (const auto* e = std::get_if(&r)) { + std::fprintf(stderr, "voidlink: %s\n", e->message.c_str()); + return 1; + } + dump_container(std::get(r)); + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + return usage(argv[0]); + } + const std::string_view cmd = argv[1]; + if (cmd == "create-empty") return cmd_create_empty(argv[0], argc - 2, argv + 2); + if (cmd == "pack-blob") return cmd_pack_blob (argv[0], argc - 2, argv + 2); + if (cmd == "pack-elf") return cmd_pack_elf (argv[0], argc - 2, argv + 2); + if (cmd == "fuse") return cmd_fuse (argv[0], argc - 2, argv + 2); + if (cmd == "wrap") return cmd_wrap (argv[0], argc - 2, argv + 2); + if (cmd == "dump") return cmd_dump (argv[0], argc - 2, argv + 2); + if (cmd == "vlcldd") return cmd_vlcldd (argv[0], argc - 2, argv + 2); + if (cmd == "verify") return cmd_verify (argv[0], argc - 2, argv + 2); + return usage(argv[0]); +} diff --git a/voidlink/merge.cpp b/voidlink/merge.cpp new file mode 100644 index 0000000..c6ef1b2 --- /dev/null +++ b/voidlink/merge.cpp @@ -0,0 +1,143 @@ +#include "merge.hpp" + +#include "format/vlc_format.hpp" + +#include +#include + +namespace voidlibc::voidlink { + +namespace { + +constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) { + return (v + (a - 1)) & ~(a - 1); +} + +} // namespace + +std::variant +merge_lowered(std::vector objects) { + if (objects.empty()) + return std::string("merge_lowered: no objects to merge"); + if (objects.size() == 1) + return std::move(objects[0]); + + using format::kSymUndefined; + const std::size_t N = objects.size(); + + LoweredText merged{}; + merged.section.target_os = objects[0].section.target_os; + merged.section.entry_offset = 0; + + // --- Step 1: Compute blob starts and build merged code/data blobs --- + std::vector code_starts(N), data_starts(N); + + for (std::size_t oi = 0; oi < N; ++oi) { + const auto& sec = objects[oi].section; + + code_starts[oi] = + align_up(static_cast(merged.section.code.size()), 16); + merged.section.code.resize(static_cast(code_starts[oi]), 0); + merged.section.code.insert(merged.section.code.end(), + sec.code.begin(), sec.code.end()); + + data_starts[oi] = + align_up(static_cast(merged.section.data.size()), 8); + merged.section.data.resize(static_cast(data_starts[oi]), 0); + merged.section.data.insert(merged.section.data.end(), + sec.data.begin(), sec.data.end()); + } + + // --- Step 2a: Intern all defined symbols from all objects --- + // Named defined symbols are deduplicated (first strong definition wins). + // Anonymous defined symbols (empty name, e.g. section symbols) are always unique. + std::unordered_map name_to_global; + // Per-object local sym_id → global sym_id map. + std::vector> l2g(N); + + for (std::size_t oi = 0; oi < N; ++oi) { + const auto& syms = objects[oi].symbols; + for (std::uint32_t li = 0; li < static_cast(syms.size()); ++li) { + const auto& sym = syms[li]; + if (sym.section_index == kSymUndefined) continue; // imports handled below + + std::uint32_t gid; + // Local symbols (not exported, not weak) are never deduplicated + // across objects — GCC emits many per-TU local names like .LC0, + // .LC1 that are distinct even when identically spelled. + const bool is_local = !sym.exported && !sym.weak; + if (sym.name.empty() || is_local) { + // Anonymous or local: always a new unique entry. + gid = static_cast(merged.symbols.size()); + } else { + auto it = name_to_global.find(sym.name); + if (it != name_to_global.end()) { + // Duplicate name: strong+strong = error; weak is overridden by strong. + const auto& existing = merged.symbols[it->second]; + if (!sym.weak && !existing.weak) { + return "merge_lowered: duplicate strong definition of '" + sym.name + "'"; + } + if (!sym.weak && existing.weak) { + // New strong definition overrides weak — update in place. + auto& ms = merged.symbols[it->second]; + ms = sym; + ms.value += sym.data_section ? data_starts[oi] : code_starts[oi]; + } + // If existing is strong and new is weak, keep existing. + l2g[oi][li] = it->second; + continue; + } + gid = static_cast(merged.symbols.size()); + name_to_global[sym.name] = gid; + } + + SymbolSpec adjusted = sym; + adjusted.value += sym.data_section ? data_starts[oi] : code_starts[oi]; + merged.symbols.push_back(std::move(adjusted)); + l2g[oi][li] = gid; + } + } + + // --- Step 2b: Intern all imports, resolving cross-object references --- + for (std::size_t oi = 0; oi < N; ++oi) { + const auto& syms = objects[oi].symbols; + for (std::uint32_t li = 0; li < static_cast(syms.size()); ++li) { + const auto& sym = syms[li]; + if (sym.section_index != kSymUndefined) continue; // defined, already handled + if (l2g[oi].count(li)) continue; // already mapped (shouldn't happen) + + auto it = name_to_global.find(sym.name); + if (it != name_to_global.end()) { + // Resolved internally — maps to the defining global entry. + l2g[oi][li] = it->second; + } else { + // Genuinely external import — add once. + std::uint32_t gid = static_cast(merged.symbols.size()); + name_to_global[sym.name] = gid; + merged.symbols.push_back(sym); // section_index remains kSymUndefined + l2g[oi][li] = gid; + } + } + } + + // --- Step 3: Merge relocs with adjusted offsets and global sym_ids --- + for (std::size_t oi = 0; oi < N; ++oi) { + for (auto r : objects[oi].section.relocs) { + r.dst_offset += static_cast(code_starts[oi]); + auto it = l2g[oi].find(r.sym_id); + if (it == l2g[oi].end()) { + std::ostringstream os; + os << "merge_lowered: object " << oi + << " reloc at 0x" << std::hex << (r.dst_offset - code_starts[oi]) + << " references unmapped sym_id " << std::dec << r.sym_id; + return os.str(); + } + r.sym_id = it->second; + merged.section.relocs.push_back(r); + } + } + + return std::move(merged); +} + +} // namespace voidlibc::voidlink diff --git a/voidlink/merge.hpp b/voidlink/merge.hpp new file mode 100644 index 0000000..d79267f --- /dev/null +++ b/voidlink/merge.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include "reloc_lowering.hpp" + +#include +#include +#include + +namespace voidlibc::voidlink { + +// Merge N independently-lowered objects into a single LoweredText. +// +// Code blobs are concatenated (16-byte aligned between objects). +// Data blobs are concatenated (8-byte aligned between objects). +// Symbol tables are unified: named defined symbols are deduplicated by name; +// anonymous defined symbols (e.g. section symbols) each get their own entry. +// Imports that are defined in any of the input objects are resolved internally +// — their sym_ids map to the defining object's global symbol entry. +// Truly external imports (undefined in all input objects) are kept as imports. +// +// Reloc dst_offsets are adjusted by the owning object's code_start. +// Reloc sym_ids are remapped to global symbol table indices. +std::variant +merge_lowered(std::vector objects); + +} // namespace voidlibc::voidlink diff --git a/voidlink/reader.cpp b/voidlink/reader.cpp new file mode 100644 index 0000000..3fa8b78 --- /dev/null +++ b/voidlink/reader.cpp @@ -0,0 +1,177 @@ +#include "reader.hpp" + +#include +#include +#include +#include + +namespace voidlibc::voidlink { + +using namespace voidlibc::format; + +ReadResult read_container(const std::filesystem::path& in_path) { + std::error_code ec; + const auto file_size = std::filesystem::file_size(in_path, ec); + if (ec) { + return ReadError{"stat failed: " + ec.message()}; + } + if (file_size < sizeof(FileHeader)) { + return ReadError{"file too small to be a VoidLibC file"}; + } + + std::ifstream in(in_path, std::ios::binary); + if (!in) { + return ReadError{"could not open " + in_path.string()}; + } + + Container c{}; + in.read(reinterpret_cast(&c.header), sizeof(c.header)); + if (!in) { + return ReadError{"short read on header"}; + } + + if (c.header.magic != kMagic) { + return ReadError{"bad magic; not a VoidLibC file"}; + } + if (c.header.version_major != kVersionMajor) { + std::ostringstream os; + os << "unsupported major version " << c.header.version_major; + return ReadError{os.str()}; + } + if (c.header.arch != TargetArch::X86_64) { + return ReadError{"unsupported architecture (MVP is x86_64-only)"}; + } + if (c.header.file_size != file_size) { + std::ostringstream os; + os << "header file_size " << c.header.file_size + << " disagrees with on-disk size " << file_size; + return ReadError{os.str()}; + } + + c.actual_file_size = file_size; + c.path = in_path; + return c; +} + +static const char* os_name(TargetOS os) { + switch (os) { + case TargetOS::Linux: return "linux"; + case TargetOS::Windows: return "windows"; + case TargetOS::MacOS: return "macos"; + case TargetOS::Unknown: return "unknown"; + } + return "?"; +} +[[maybe_unused]] static auto silence_unused_os_name = &os_name; + +void dump_container(const Container& c) { + const auto& h = c.header; + const bool is_exec = flag_set(h.flags, ContainerFlags::Executable); + const bool is_stat = flag_set(h.flags, ContainerFlags::StaticLibrary); + std::printf("magic : 0x%08x (VLC\\0)\n", h.magic); + std::printf("type : %s (%s)\n", + is_stat ? "static library" : is_exec ? "executable" : "shared library", + infer_extension(h.flags)); + std::printf("version : %u.%u\n", h.version_major, h.version_minor); + const bool has_dyn = flag_set(h.flags, ContainerFlags::HasDynamicImports); + std::printf("linkage : %s\n", has_dyn ? "dynamic" : "static"); + std::printf("flags : 0x%08x%s%s%s%s\n", h.flags, + flag_set(h.flags, ContainerFlags::HasDebug) ? " HasDebug" : "", + flag_set(h.flags, ContainerFlags::HasCppExports) ? " HasCppExports" : "", + has_dyn ? " HasDynamicImports" : "", + is_stat ? " StaticLibrary" : ""); + std::printf("arch : %s\n", + h.arch == TargetArch::X86_64 ? "x86_64" : "unknown"); + std::printf("section_count : %u\n", h.section_count); + std::printf("section_dir_off : %llu\n", + static_cast(h.section_dir_off)); + std::printf("symtab : off=%llu size=%llu\n", + static_cast(h.symtab_off), + static_cast(h.symtab_size)); + std::printf("imports : off=%llu size=%llu\n", + static_cast(h.imports_off), + static_cast(h.imports_size)); + std::printf("exports : off=%llu size=%llu\n", + static_cast(h.exports_off), + static_cast(h.exports_size)); + std::printf("file_size : %llu (on disk: %llu)\n", + static_cast(h.file_size), + static_cast(c.actual_file_size)); + + if (c.path.empty() || h.section_count == 0) return; + + std::ifstream f(c.path, std::ios::binary); + if (!f) return; + + // Per-section details + f.seekg(static_cast(h.section_dir_off)); + std::vector sects(h.section_count); + f.read(reinterpret_cast(sects.data()), + static_cast(h.section_count * sizeof(SectionEntry))); + if (!f) return; + + std::printf("sections:\n"); + for (std::uint32_t i = 0; i < h.section_count; ++i) { + const auto& s = sects[i]; + const char* osn = + (s.target_os == TargetOS::Linux) ? "linux" : + (s.target_os == TargetOS::Windows) ? "windows" : + (s.target_os == TargetOS::MacOS) ? "macos" : "unknown"; + const char* kind = + (s.kind == SectionKind::NativeBlob) ? "NativeBlob" : "RawCode "; + std::printf(" [%u] %-7s %s code=@%llu+%llu", + i, osn, kind, + static_cast(s.code_off), + static_cast(s.code_size)); + if (s.data_size > 0) + std::printf(" data=@%llu+%llu", + static_cast(s.data_off), + static_cast(s.data_size)); + if (s.entry_offset > 0) + std::printf(" entry=+%llu", static_cast(s.entry_offset)); + std::printf("\n"); + } + + // Symbol table + if (h.symtab_size < sizeof(SymbolTableHeader)) return; + f.seekg(static_cast(h.symtab_off)); + SymbolTableHeader sth{}; + f.read(reinterpret_cast(&sth), sizeof(sth)); + if (!f || sth.entry_count == 0) return; + + std::vector syms(sth.entry_count); + f.read(reinterpret_cast(syms.data()), + static_cast(sth.entry_count * sizeof(SymbolEntry))); + std::string pool(sth.name_pool_size, '\0'); + f.read(pool.data(), static_cast(sth.name_pool_size)); + if (!f) return; + + auto name_of = [&](const SymbolEntry& e) -> std::string { + if (e.name_off + e.name_len > sth.name_pool_size) return "?"; + return pool.substr(e.name_off, e.name_len); + }; + + std::vector exports_list, imports_list; + for (const auto& sym : syms) { + if (sym.section_index == kSymUndefined) + imports_list.push_back(name_of(sym)); + else if (sym.flags & static_cast(SymbolFlags::Exported)) + exports_list.push_back(name_of(sym)); + } + + auto print_names = [](const char* label, const std::vector& names) { + constexpr std::size_t kMax = 8; + std::printf(" %-8s (%zu):", label, names.size()); + for (std::size_t i = 0; i < std::min(names.size(), kMax); ++i) + std::printf(" %s", names[i].c_str()); + if (names.size() > kMax) + std::printf(" ... +%zu more", names.size() - kMax); + std::printf("\n"); + }; + + std::printf("symbols (%u total):\n", sth.entry_count); + if (!exports_list.empty()) print_names("exports", exports_list); + if (!imports_list.empty()) print_names("imports", imports_list); +} + +} // namespace voidlibc::voidlink diff --git a/voidlink/reader.hpp b/voidlink/reader.hpp new file mode 100644 index 0000000..05605d9 --- /dev/null +++ b/voidlink/reader.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include "format/vlc_format.hpp" + +#include +#include +#include + +namespace voidlibc::voidlink { + +struct ReadError { + std::string message; +}; + +struct Container { + voidlibc::format::FileHeader header; + std::uint64_t actual_file_size = 0; + std::filesystem::path path; +}; + +using ReadResult = std::variant; + +ReadResult read_container(const std::filesystem::path& in_path); + +void dump_container(const Container& c); + +} // namespace voidlibc::voidlink diff --git a/voidlink/reloc_lowering.cpp b/voidlink/reloc_lowering.cpp new file mode 100644 index 0000000..fbdd229 --- /dev/null +++ b/voidlink/reloc_lowering.cpp @@ -0,0 +1,850 @@ +#include "reloc_lowering.hpp" + +#include "format/reloc_ir.hpp" +#include "format/vlc_format.hpp" +#include "loader/common/elf64.hpp" + +#include +#include +#include +#include + +namespace voidlibc::voidlink { + +using namespace voidlibc::format; +using voidlibc::loader::kRX86_64_None; +using voidlibc::loader::kRX86_64_64; +using voidlibc::loader::kRX86_64_PC32; +using voidlibc::loader::kRX86_64_PLT32; +using voidlibc::loader::kRX86_64_32; +using voidlibc::loader::kRX86_64_32S; +using voidlibc::loader::kRX86_64_GOTPCREL; +using voidlibc::loader::kRX86_64_GOTPCRELX; +using voidlibc::loader::kRX86_64_REX_GOTPCRELX; +using voidlibc::loader::kShtProgbits; +using voidlibc::loader::kShtNobits; + +namespace { + +constexpr std::uint8_t kStbLocal = 0; +constexpr std::uint8_t kStbGlobal = 1; +constexpr std::uint8_t kStbWeak = 2; + +constexpr std::uint8_t kSttNotype = 0; +constexpr std::uint8_t kSttObject = 1; +constexpr std::uint8_t kSttFunc = 2; +constexpr std::uint8_t kSttSection = 3; + +// .text.startup, .text.hot, .text.unlikely, .text.N comdat sections, etc. +// These are code sections that GCC emits separately from .text. They get +// merged into the RX code blob with their relocs processed identically. +bool is_text_companion_section(const std::string& name) { + return name.rfind(".text.", 0) == 0; +} + +// .rodata and all .rodata.* sections — read-only data merged into RX blob. +// Only PC32 relocs from .text to these are expected (string literals, etc.); +// they are base-invariant so no separate reloc processing is needed here. +bool is_rodata_companion_section(const std::string& name) { + return name.rfind(".rodata", 0) == 0; +} + +// .bss, .bss.*, .data, .data.* (excluding .data.rel.*) — writable data blob. +bool is_data_section(const std::string& name) { + if (name == ".bss" || name.rfind(".bss.", 0) == 0) return true; + if (name == ".data") return true; + if (name.rfind(".data.", 0) == 0 && name.rfind(".data.rel", 0) != 0) return true; + return false; +} + +constexpr std::uint64_t align_up(std::uint64_t v, std::uint64_t a) { + return (v + (a - 1)) & ~(a - 1); +} + +struct Lowering { + LoweredText out; + // ELF .symtab index → portable symbol id in out.symbols. + std::unordered_map elf_to_portable; + // ELF section index → byte offset within the merged code blob. + // Used for: .rodata.* companions AND .text.* companions. + std::unordered_map section_blob_start; + // ELF section index → byte offset within the data blob (.data/.bss). + std::unordered_map data_section_blob_start; + std::string error; + + std::uint32_t intern(const elf::ParsedObject& obj, + std::size_t text_idx, + std::uint32_t elf_sym) { + if (auto it = elf_to_portable.find(elf_sym); + it != elf_to_portable.end()) { + return it->second; + } + const auto& s = obj.symbols[elf_sym]; + SymbolSpec ss{}; + ss.name = s.name; + ss.kind = (s.type == kSttObject) ? SymbolKind::Object + : SymbolKind::Function; + ss.size = s.size; + ss.weak = (s.bind == kStbWeak); + + if (s.defined && s.section_index == text_idx) { + // Symbol lives in .text (primary text section). + ss.section_index = 0; + ss.value = s.value; + ss.exported = (s.bind == kStbGlobal || s.bind == kStbWeak); + } else if (s.defined) { + auto it = section_blob_start.find(s.section_index); + if (it != section_blob_start.end()) { + ss.section_index = 0; + ss.value = it->second + s.value; + // .text.* companions CAN export symbols (e.g. main in .text.startup). + // .rodata.* companions do not export addressable symbols. + const auto& sec_name = obj.sections[s.section_index].name; + ss.exported = is_text_companion_section(sec_name) + && (s.bind == kStbGlobal || s.bind == kStbWeak); + } else { + auto dit = data_section_blob_start.find(s.section_index); + if (dit != data_section_blob_start.end()) { + ss.section_index = 0; + ss.value = dit->second + s.value; + ss.exported = false; + ss.data_section = true; + } else { + std::ostringstream os; + os << "symbol '" << s.name + << "' defined in unsupported section (idx " + << s.section_index << ")"; + error = os.str(); + return 0; + } + } + } else { + // External import. + ss.section_index = kSymUndefined; + ss.value = 0; + ss.exported = false; + // Forward version requirement (version_index > 1 means versioned). + if (s.version_index > 1) { + for (const auto& vr : obj.version_reqs) { + if (vr.index == s.version_index) { + ss.version_name = vr.version_name; + ss.version_hash = vr.hash; + ss.version_flags = vr.flags; + break; + } + } + } + } + + const auto id = static_cast(out.symbols.size()); + out.symbols.push_back(std::move(ss)); + elf_to_portable.emplace(elf_sym, id); + return id; + } + + // Process relocations from one section (the source section's relocs + // reference symbols in the global .symtab). blob_start is the byte offset + // of that section's content within the merged code blob. + bool process_relocs(const elf::ParsedObject& obj, + std::size_t text_idx, + const std::vector& relocs, + std::uint64_t blob_start) { + for (const auto& r : relocs) { + if (r.sym_index >= obj.symbols.size()) { + std::ostringstream os; + os << "reloc at 0x" << std::hex << r.offset + << " references out-of-range sym " << std::dec << r.sym_index; + error = os.str(); + return false; + } + const auto& referenced = obj.symbols[r.sym_index]; + + // Section symbols for supported sections. + if (referenced.type == kSttSection) { + if (referenced.section_index == text_idx) { + // .text section symbol — OK. + } else if (section_blob_start.count(referenced.section_index)) { + // .rodata.* or .text.* companion — OK. + } else if (data_section_blob_start.count(referenced.section_index)) { + // .data/.bss — OK. + } else { + std::ostringstream os; + os << "reloc at 0x" << std::hex << r.offset + << " references section symbol for unsupported section" + << " (idx " << std::dec << referenced.section_index << ")"; + error = os.str(); + return false; + } + } + + const std::uint32_t sym_id = intern(obj, text_idx, r.sym_index); + if (!error.empty()) return false; + + const bool is_external = !referenced.defined; + + RelocEntry e{}; + e.reserved = 0; + e.dst_offset = static_cast(blob_start + r.offset); + e.sym_id = sym_id; + e.addend = static_cast(r.addend); + + switch (r.type) { + case kRX86_64_None: + continue; + case kRX86_64_PC32: + if (is_external) { + std::ostringstream os; + os << "R_X86_64_PC32 against external symbol '" + << referenced.name << "' at 0x" << std::hex << r.offset + << "; use PLT32 for function calls"; + error = os.str(); + return false; + } + e.op = RelocOp::PC32; + break; + case kRX86_64_PLT32: + e.op = is_external ? RelocOp::PLT32 : RelocOp::PC32; + break; + case kRX86_64_64: + e.op = RelocOp::Abs64; + break; + case kRX86_64_32: + e.op = RelocOp::Abs32; + break; + case kRX86_64_32S: + e.op = RelocOp::Abs32Signed; + break; + case kRX86_64_GOTPCREL: + e.op = RelocOp::GotPC32; + break; + case kRX86_64_GOTPCRELX: + e.op = RelocOp::GotPC32X; + break; + case kRX86_64_REX_GOTPCRELX: + e.op = RelocOp::GotPC32XRex; + break; + default: { + std::ostringstream os; + os << "unsupported R_X86_64_" << r.type + << " at offset 0x" << std::hex << r.offset; + error = os.str(); + return false; + } + } + out.section.relocs.push_back(e); + } + return true; + } +}; + +} // namespace + +std::variant +lower_elf_text(const elf::ParsedObject& obj, TargetOS target_os) { + if (obj.text_index == static_cast(-1)) { + return std::string("no .text section in object"); + } + const auto& text = obj.sections[obj.text_index]; + + Lowering L; + L.out.section.target_os = target_os; + L.out.section.entry_offset = 0; + + // --- Build the merged code blob --- + // + // Layout: [.text] [.text.* companions (16-byte aligned)] [.rodata.* companions (16-byte aligned)] + // + // .text.* (e.g. .text.startup, .text.hot): code emitted by GCC for specific + // function groups. Their relocs must also be processed. + // .rodata.*: read-only data (string literals, const tables). PC32 relocs + // from .text to .rodata are base-invariant — no separate reloc processing. + + L.out.section.code = text.bytes; + + // Append .text.* companions first. + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == obj.text_index) continue; + const auto& sec = obj.sections[si]; + if (!is_text_companion_section(sec.name)) continue; + if (sec.type != kShtProgbits) continue; + if (sec.bytes.empty()) continue; + + const std::uint64_t aligned = + align_up(static_cast(L.out.section.code.size()), 16); + L.out.section.code.resize(static_cast(aligned), 0); + L.section_blob_start[si] = aligned; + L.out.section.code.insert(L.out.section.code.end(), + sec.bytes.begin(), sec.bytes.end()); + } + + // Append .rodata.* companions. + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == obj.text_index) continue; + const auto& sec = obj.sections[si]; + if (!is_rodata_companion_section(sec.name)) continue; + if (sec.type != kShtProgbits) continue; + if (sec.bytes.empty()) continue; + + const std::uint64_t aligned = + align_up(static_cast(L.out.section.code.size()), 16); + L.out.section.code.resize(static_cast(aligned), 0); + L.section_blob_start[si] = aligned; + L.out.section.code.insert(L.out.section.code.end(), + sec.bytes.begin(), sec.bytes.end()); + } + + // --- Build the data blob: [.data] [.bss zeros] --- + { + std::vector data_blob; + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == obj.text_index) continue; + const auto& sec = obj.sections[si]; + if (!is_data_section(sec.name)) continue; + + const std::uint64_t aligned = + align_up(static_cast(data_blob.size()), 8); + data_blob.resize(static_cast(aligned), 0); + L.data_section_blob_start[si] = aligned; + + if (sec.type == kShtNobits) { + data_blob.resize(static_cast(aligned + sec.mem_size), 0); + } else { + data_blob.insert(data_blob.end(), sec.bytes.begin(), sec.bytes.end()); + } + } + L.out.section.data = std::move(data_blob); + } + + // --- Pre-intern all globally-visible function symbols --- + // Covers .text and all .text.* companions (e.g. main in .text.startup). + for (std::uint32_t i = 0; i < obj.symbols.size(); ++i) { + const auto& s = obj.symbols[i]; + if (!s.defined) continue; + const bool in_text = (s.section_index == obj.text_index); + const bool in_text_comp = !in_text + && L.section_blob_start.count(s.section_index) + && is_text_companion_section(obj.sections[s.section_index].name); + if (!in_text && !in_text_comp) continue; + if (s.bind == kStbLocal) continue; + if (s.type != kSttFunc && s.type != kSttNotype) continue; + (void)L.intern(obj, obj.text_index, i); + if (!L.error.empty()) return L.error; + } + + // --- Process relocs from .text --- + if (!L.process_relocs(obj, obj.text_index, text.relocs, 0)) { + return L.error; + } + + // --- Process relocs from .text.* companions --- + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + const auto& sec = obj.sections[si]; + if (!is_text_companion_section(sec.name)) continue; + if (sec.relocs.empty()) continue; + auto it = L.section_blob_start.find(si); + if (it == L.section_blob_start.end()) continue; + if (!L.process_relocs(obj, obj.text_index, sec.relocs, it->second)) { + return L.error; + } + } + + // --- Process relocs from .rodata.* companions --- + // GCC places switch-statement jump tables in .rodata with R_X86_64_PC32 + // entries that point back into .text (the case labels). Without applying + // these, table entries remain zero and indirect jumps go to wrong targets. + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + const auto& sec = obj.sections[si]; + if (!is_rodata_companion_section(sec.name)) continue; + if (sec.relocs.empty()) continue; + auto it = L.section_blob_start.find(si); + if (it == L.section_blob_start.end()) continue; + if (!L.process_relocs(obj, obj.text_index, sec.relocs, it->second)) { + return L.error; + } + } + + return std::move(L.out); +} + +// --------------------------------------------------------------------------- +// COFF lowering + +namespace { + +constexpr std::uint64_t coff_align_up(std::uint64_t v, std::uint64_t a) { + return (v + (a - 1)) & ~(a - 1); +} + +bool is_coff_code_section(const coff::ParsedSection& s) { + return (s.characteristics & coff::kScnCntCode) != 0 + && (s.characteristics & coff::kScnMemExecute) != 0; +} + +bool is_coff_rdata_section(const coff::ParsedSection& s) { + return (s.characteristics & coff::kScnCntInitData) != 0 + && (s.characteristics & coff::kScnMemRead) != 0 + && (s.characteristics & coff::kScnMemWrite) == 0; +} + +bool is_coff_data_section(const coff::ParsedSection& s) { + const bool init = (s.characteristics & coff::kScnCntInitData) != 0; + const bool uninit = (s.characteristics & coff::kScnCntUninitData) != 0; + const bool write = (s.characteristics & coff::kScnMemWrite) != 0; + return (init || uninit) && write; +} + +struct CoffLowering { + LoweredText out; + std::unordered_map coff_to_portable; // sym_idx → portable id + // section_index (0-based) → blob start in code blob (for code+rdata sections) + std::unordered_map code_sec_blob_start; + // section_index → blob start in data blob (for .data/.bss sections) + std::unordered_map data_sec_blob_start; + std::string error; + + std::uint32_t intern(const coff::ParsedObject& obj, + std::size_t text_sec_idx, + std::uint32_t coff_sym) { + if (auto it = coff_to_portable.find(coff_sym); + it != coff_to_portable.end()) + return it->second; + + const auto& s = obj.symbols[coff_sym]; + SymbolSpec ss{}; + ss.name = s.name; + ss.size = s.size; + ss.weak = (s.bind == coff::kBindWeak); + ss.kind = (s.type == coff::kTypeFunc) ? SymbolKind::Function + : SymbolKind::Object; + + if (s.defined) { + const std::size_t sec0 = static_cast(s.section_index - 1); + if (sec0 == text_sec_idx) { + ss.section_index = 0; + ss.value = s.value; + ss.exported = (s.bind == coff::kBindGlobal || s.bind == coff::kBindWeak); + } else if (auto it = code_sec_blob_start.find(sec0); + it != code_sec_blob_start.end()) { + ss.section_index = 0; + ss.value = it->second + s.value; + ss.exported = is_coff_code_section(obj.sections[sec0]) + && (s.bind == coff::kBindGlobal || s.bind == coff::kBindWeak); + } else if (auto it = data_sec_blob_start.find(sec0); + it != data_sec_blob_start.end()) { + ss.section_index = 0; + ss.value = it->second + s.value; + ss.exported = false; + ss.data_section = true; + } else { + std::ostringstream os; + os << "symbol '" << s.name + << "' in unsupported section (idx " << sec0 << ")"; + error = os.str(); + return 0; + } + } else { + // External import. + ss.section_index = kSymUndefined; + ss.value = 0; + ss.exported = false; + } + + const auto id = static_cast(out.symbols.size()); + out.symbols.push_back(std::move(ss)); + coff_to_portable.emplace(coff_sym, id); + return id; + } + + bool process_relocs(const coff::ParsedObject& obj, + std::size_t text_sec_idx, + const std::vector& relocs, + std::uint64_t blob_start) { + using coff::kRelocRel32; + using coff::kRelocRel32_1; using coff::kRelocRel32_2; + using coff::kRelocRel32_4; using coff::kRelocRel32_5; + using coff::kRelocAddr64; + using coff::kRelocAddr32; using coff::kRelocAddr32NB; + + for (const auto& r : relocs) { + if (r.sym_index >= obj.symbols.size()) { + std::ostringstream os; + os << "COFF reloc at 0x" << std::hex << r.offset + << " references out-of-range sym " << std::dec << r.sym_index; + error = os.str(); + return false; + } + + const auto& sym = obj.symbols[r.sym_index]; + const std::uint32_t pid = intern(obj, text_sec_idx, r.sym_index); + if (!error.empty()) return false; + + RelocEntry e{}; + e.reserved = 0; + e.dst_offset = static_cast(blob_start + r.offset); + e.sym_id = pid; + + switch (r.type) { + case kRelocRel32: + // COFF REL32: value = S + inline - (P+4). + // Portable PC32: value = S - P + addend, where addend = inline - 4. + e.op = RelocOp::PC32; + e.addend = static_cast(r.addend - 4); + break; + case kRelocRel32_1: + e.op = RelocOp::PC32_1; + e.addend = static_cast(r.addend - 4); + break; + case kRelocRel32_2: + e.op = RelocOp::PC32_2; + e.addend = static_cast(r.addend - 4); + break; + case coff::kRelocRel32_3: + // No dedicated PC32_3 opcode; treat as PC32 with adjusted addend. + e.op = RelocOp::PC32; + e.addend = static_cast(r.addend - 7); + break; + case kRelocRel32_4: + e.op = RelocOp::PC32_4; + e.addend = static_cast(r.addend - 4); + break; + case kRelocRel32_5: + e.op = RelocOp::PC32_5; + e.addend = static_cast(r.addend - 4); + break; + case kRelocAddr64: + e.op = RelocOp::Abs64; + e.addend = static_cast(r.addend); + break; + case kRelocAddr32: + e.op = RelocOp::Abs32; + e.addend = static_cast(r.addend); + break; + case kRelocAddr32NB: + // Relative to image base — only meaningful in PE context. + // Silently skip for portable IR (VLC is PIC; these don't appear in code). + continue; + default: { + // Skip SECTION / SECREL / unknown types. + (void)sym; + continue; + } + } + out.section.relocs.push_back(e); + } + return true; + } +}; + +} // namespace + +std::variant +lower_coff_text(const coff::ParsedObject& obj, + voidlibc::format::TargetOS target_os) { + if (obj.text_index == static_cast(-1)) + return std::string("no executable .text section in COFF object"); + + const std::size_t text_si = obj.text_index; + const auto& text_sec = obj.sections[text_si]; + + CoffLowering L; + L.out.section.target_os = target_os; + L.out.section.entry_offset = 0; + + // --- Build merged code blob: [.text][companion code+rdata sections (16-aligned)] --- + L.out.section.code = text_sec.bytes; + + // Append additional code sections (.text$... COMDAT sections and .rdata). + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == text_si) continue; + const auto& sec = obj.sections[si]; + const bool is_code = is_coff_code_section(sec); + const bool is_rdata = is_coff_rdata_section(sec); + if (!is_code && !is_rdata) continue; + if (sec.bytes.empty() && sec.mem_size == 0) continue; + + const std::uint64_t aligned = + coff_align_up(static_cast(L.out.section.code.size()), 16); + L.out.section.code.resize(static_cast(aligned), 0); + L.code_sec_blob_start[si] = aligned; + L.out.section.code.insert(L.out.section.code.end(), + sec.bytes.begin(), sec.bytes.end()); + // Pad to mem_size if bytes < mem_size. + if (sec.mem_size > sec.bytes.size()) { + L.out.section.code.resize( + L.out.section.code.size() + (sec.mem_size - sec.bytes.size()), 0); + } + } + + // --- Build data blob: [.data][.bss] (8-byte aligned between items) --- + { + std::vector data_blob; + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == text_si) continue; + const auto& sec = obj.sections[si]; + if (!is_coff_data_section(sec)) continue; + + const std::uint64_t aligned = + coff_align_up(static_cast(data_blob.size()), 8); + data_blob.resize(static_cast(aligned), 0); + L.data_sec_blob_start[si] = aligned; + + if (sec.bytes.empty()) { + data_blob.resize(data_blob.size() + sec.mem_size, 0); + } else { + data_blob.insert(data_blob.end(), sec.bytes.begin(), sec.bytes.end()); + if (sec.mem_size > sec.bytes.size()) + data_blob.resize(data_blob.size() + (sec.mem_size - sec.bytes.size()), 0); + } + } + L.out.section.data = std::move(data_blob); + } + + // --- Pre-intern exported symbols from .text and companion code sections --- + for (std::uint32_t i = 0; i < obj.symbols.size(); ++i) { + const auto& s = obj.symbols[i]; + if (!s.defined) continue; + if (s.bind == coff::kBindLocal) continue; + const std::size_t sec0 = static_cast(s.section_index - 1); + const bool in_text = (sec0 == text_si); + const bool in_code_c = !in_text && L.code_sec_blob_start.count(sec0) + && is_coff_code_section(obj.sections[sec0]); + if (!in_text && !in_code_c) continue; + if (s.type != coff::kTypeFunc && s.type != coff::kTypeNone) continue; + (void)L.intern(obj, text_si, i); + if (!L.error.empty()) return L.error; + } + + // --- Process relocs from .text --- + if (!L.process_relocs(obj, text_si, text_sec.relocs, 0)) + return L.error; + + // --- Process relocs from companion sections --- + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == text_si) continue; + const auto& sec = obj.sections[si]; + if (sec.relocs.empty()) continue; + auto it = L.code_sec_blob_start.find(si); + if (it == L.code_sec_blob_start.end()) continue; + if (!L.process_relocs(obj, text_si, sec.relocs, it->second)) + return L.error; + } + + return std::move(L.out); +} + +// =========================================================================== +// Mach-O (x86-64 macOS) lowering +// =========================================================================== + +namespace { + +using namespace voidlibc::voidlink::macho; + +struct MachoLowering { + LoweredText out; + std::string error; + + // Maps Mach-O 1-based section ordinal → byte offset within the merged code blob. + std::unordered_map sec_blob_start; + // Maps Mach-O 1-based section ordinal → .o section vmaddr (for non-extern delta patching). + std::unordered_map sec_o_addr; + std::unordered_map sym_id_map; + + std::uint32_t intern_sym(const ParsedObject& obj, std::uint32_t macho_idx) { + auto it = sym_id_map.find(macho_idx); + if (it != sym_id_map.end()) return it->second; + + const auto& s = obj.symbols[macho_idx]; + SymbolSpec ss{}; + ss.name = s.name; + ss.exported = (s.bind == 1 && s.defined); + ss.section_index = kSymUndefined; + + if (s.defined && s.section_index >= 1 + && static_cast(s.section_index - 1) < obj.sections.size()) { + auto bit = sec_blob_start.find(static_cast(s.section_index)); + ss.value = s.value + (bit != sec_blob_start.end() ? bit->second : 0); + ss.section_index = 0; + } + ss.kind = (s.type == 2) ? SymbolKind::Function : SymbolKind::Object; + const auto id = static_cast(out.symbols.size()); + out.symbols.push_back(std::move(ss)); + sym_id_map[macho_idx] = id; + return id; + } + + bool process_relocs(const ParsedObject& obj, + const std::vector& relocs, + std::uint64_t blob_offset) { + for (std::size_t ri = 0; ri < relocs.size(); ++ri) { + const auto& r = relocs[ri]; + + if (!r.is_extern) { + // Non-extern (section-relative) PC-rel relocs: the inline displacement was + // computed by the assembler using the .o section layout. Our blob layout may + // differ (different alignment padding), so patch the delta in. + if (r.is_pcrel && r.length == 2 && + (r.type == kRelocSigned || r.type == kRelocBranch || + r.type == kRelocSigned1 || r.type == kRelocSigned2 || + r.type == kRelocSigned4)) { + // r.sym_index is a 1-based section ordinal (not a symbol index). + const std::uint32_t sec_ord = r.sym_index; + auto bit = sec_blob_start.find(sec_ord); + auto ait = sec_o_addr.find(sec_ord); + if (bit != sec_blob_start.end() && ait != sec_o_addr.end()) { + const std::int64_t delta = static_cast(bit->second) + - static_cast(ait->second); + if (delta != 0) { + const std::uint64_t patch = blob_offset + r.offset; + if (patch + 4 <= out.section.code.size()) { + std::int32_t cur = 0; + std::memcpy(&cur, out.section.code.data() + patch, 4); + cur += static_cast(delta); + std::memcpy(out.section.code.data() + patch, &cur, 4); + } + } + } + } else if (r.type == kRelocSubtractor && ri + 1 < relocs.size()) { + ++ri; // skip the paired UNSIGNED + } + continue; + } + + if (r.sym_index >= obj.symbols.size()) { + error = "reloc sym_index out of range"; + return false; + } + + RelocEntry re{}; + re.dst_offset = static_cast(blob_offset + r.offset); + re.sym_id = intern_sym(obj, r.sym_index); + + switch (r.type) { + case kRelocSigned: + // Signed PC32 to an external symbol: treat as direct PC32 (data or func). + re.op = RelocOp::PC32; + re.addend = static_cast(r.addend); + break; + case kRelocBranch: + // Branch (call/jmp) to an external symbol → PLT stub (same as ELF PLT32). + re.op = RelocOp::PLT32; + re.addend = static_cast(r.addend); + break; + case kRelocGotLoad: + case kRelocGot: + re.op = RelocOp::GotPC32; + re.addend = static_cast(r.addend); + break; + case kRelocUnsigned: + re.op = (r.length == 3) ? RelocOp::Abs64 : RelocOp::Abs32; + re.addend = static_cast(r.addend); + break; + case kRelocSigned1: + re.op = RelocOp::PC32; + re.addend = static_cast(r.addend) - 1; + break; + case kRelocSigned2: + re.op = RelocOp::PC32; + re.addend = static_cast(r.addend) - 2; + break; + case kRelocSigned4: + re.op = RelocOp::PC32; + re.addend = static_cast(r.addend) - 4; + break; + case kRelocSubtractor: + if (ri + 1 < relocs.size()) ++ri; + continue; + case kRelocTls: + re.op = RelocOp::TlsGD; + re.addend = 0; + break; + default: + error = "unhandled Mach-O reloc type " + std::to_string(r.type); + return false; + } + + out.section.relocs.push_back(re); + } + return true; + } +}; + +} // anonymous namespace + +std::variant +lower_macho_text(const macho::ParsedObject& obj, + voidlibc::format::TargetOS target_os) { + if (obj.text_index == static_cast(-1)) + return std::string{"no __text section"}; + + MachoLowering L; + L.out.section.target_os = target_os; + + const auto& text_sec = obj.sections[obj.text_index]; + L.sec_blob_start[static_cast(obj.text_index + 1)] = 0; + L.sec_o_addr[static_cast(obj.text_index + 1)] = text_sec.addr; + L.out.section.code = text_sec.bytes; + + // Append read-only companion sections (__const, __cstring, etc.). + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == obj.text_index) continue; + const auto& sec = obj.sections[si]; + const bool is_ro = (sec.sectname == "__const") + || (sec.sectname == "__rodata") + || (sec.sectname == "__cstring") + || sec.sectname.rfind("__literal", 0) == 0 + || sec.sectname.rfind("__gcc_except", 0) == 0; + if (!is_ro) continue; + // Align to max(16, section's natural alignment) to match the section's own alignment + // so that non-extern SIGNED reloc deltas stay zero when the .o already aligns to ≤16. + const std::uint64_t align = std::max(std::uint64_t(16), + std::uint64_t(1) << sec.align_exp); + while (L.out.section.code.size() % align != 0) L.out.section.code.push_back(0); + L.sec_blob_start[static_cast(si + 1)] = L.out.section.code.size(); + L.sec_o_addr[static_cast(si + 1)] = sec.addr; + L.out.section.code.insert(L.out.section.code.end(), + sec.bytes.begin(), sec.bytes.end()); + } + + // Writable sections → data blob. + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == obj.text_index) continue; + const auto& sec = obj.sections[si]; + const bool is_rw = (sec.sectname == "__data") + || (sec.sectname == "__bss") + || (sec.sectname == "__common") + || sec.sectname.rfind("__thread_", 0) == 0; + if (!is_rw) continue; + while (L.out.section.data.size() % 16 != 0) L.out.section.data.push_back(0); + const std::uint64_t off = + static_cast(L.out.section.code.size()) + + L.out.section.data.size(); + L.sec_blob_start[static_cast(si + 1)] = off; + L.sec_o_addr[static_cast(si + 1)] = sec.addr; + L.out.section.data.insert(L.out.section.data.end(), + sec.bytes.begin(), sec.bytes.end()); + if (sec.mem_size > sec.bytes.size()) + L.out.section.data.resize( + L.out.section.data.size() + (sec.mem_size - sec.bytes.size()), 0); + } + + // Intern all named symbols. + for (std::uint32_t si = 0; si < obj.symbols.size(); ++si) { + if (!obj.symbols[si].name.empty()) L.intern_sym(obj, si); + } + + if (!L.process_relocs(obj, text_sec.relocs, 0)) return L.error; + + for (std::size_t si = 0; si < obj.sections.size(); ++si) { + if (si == obj.text_index) continue; + const auto& sec = obj.sections[si]; + if (sec.relocs.empty()) continue; + auto bit = L.sec_blob_start.find(static_cast(si + 1)); + if (bit == L.sec_blob_start.end()) continue; + if (!L.process_relocs(obj, sec.relocs, bit->second)) return L.error; + } + + return std::move(L.out); +} + +} // namespace voidlibc::voidlink diff --git a/voidlink/reloc_lowering.hpp b/voidlink/reloc_lowering.hpp new file mode 100644 index 0000000..2fe5fa8 --- /dev/null +++ b/voidlink/reloc_lowering.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include "builder.hpp" +#include "coff_reader.hpp" +#include "elf_reader.hpp" +#include "macho_reader.hpp" + +#include +#include + +namespace voidlibc::voidlink { + +struct LoweredText { + SectionSpec section; // code + relocs (portable IR) + std::vector symbols; // unified: exports first, then imports +}; + +// Lower the .text section of an ELF .o into a portable VoidLibC +// SectionSpec + unified SymbolSpec list. +std::variant +lower_elf_text(const elf::ParsedObject& obj, + voidlibc::format::TargetOS target_os); + +// Lower a COFF .obj (x86-64 Windows) into portable VoidLibC representation. +// Handles IMAGE_REL_AMD64_REL32 / REL32_1..5 / ADDR64 and produces the same +// LoweredText as lower_elf_text() so that fuse / pack-elf work uniformly. +std::variant +lower_coff_text(const coff::ParsedObject& obj, + voidlibc::format::TargetOS target_os); + +// Lower a Mach-O .o (x86-64 macOS) into portable VoidLibC representation. +// Handles X86_64_RELOC_SIGNED / BRANCH / UNSIGNED / GOT_LOAD / SUBTRACTOR. +std::variant +lower_macho_text(const macho::ParsedObject& obj, + voidlibc::format::TargetOS target_os); + +} // namespace voidlibc::voidlink diff --git a/voidlink/symlib_table.cpp b/voidlink/symlib_table.cpp new file mode 100644 index 0000000..2e0ba04 --- /dev/null +++ b/voidlink/symlib_table.cpp @@ -0,0 +1,1323 @@ +// Per-OS symbol → import library table. +// Generated from data/symlib_{linux,windows,macos}.txt — edit those files, +// then run: python3 tools/gen_symlib_table.py +// Arrays MUST remain sorted by first field (symbol name) for binary search. + +#include "symlib_table.hpp" +#include "format/vlc_format.hpp" + +#include +#include +#include + +using namespace std::string_view_literals; + +namespace { + +struct Entry { std::string_view name; std::string_view library; }; + +// ── Linux ──────────────────────────────────────────────────────────────────────── +static constexpr std::array linux_table = { + Entry{"__assert_fail" , "libc.so.6"}, + Entry{"__cxa_atexit" , "libc.so.6"}, + Entry{"__cxa_finalize" , "libc.so.6"}, + Entry{"__cxa_pure_virtual" , "libc.so.6"}, + Entry{"__cxa_throw" , "libc.so.6"}, + Entry{"__errno_location" , "libc.so.6"}, + Entry{"__stack_chk_fail" , "libc.so.6"}, + Entry{"_exit" , "libc.so.6"}, + Entry{"abort" , "libc.so.6"}, + Entry{"abs" , "libc.so.6"}, + Entry{"accept" , "libc.so.6"}, + Entry{"access" , "libc.so.6"}, + Entry{"acos" , "libm.so.6"}, + Entry{"acosf" , "libm.so.6"}, + Entry{"acosh" , "libm.so.6"}, + Entry{"acoshf" , "libm.so.6"}, + Entry{"aligned_alloc" , "libc.so.6"}, + Entry{"asin" , "libm.so.6"}, + Entry{"asinf" , "libm.so.6"}, + Entry{"asinh" , "libm.so.6"}, + Entry{"asinhf" , "libm.so.6"}, + Entry{"asprintf" , "libc.so.6"}, + Entry{"atan" , "libm.so.6"}, + Entry{"atan2" , "libm.so.6"}, + Entry{"atan2f" , "libm.so.6"}, + Entry{"atanf" , "libm.so.6"}, + Entry{"atanh" , "libm.so.6"}, + Entry{"atanhf" , "libm.so.6"}, + Entry{"atexit" , "libc.so.6"}, + Entry{"atof" , "libc.so.6"}, + Entry{"atoi" , "libc.so.6"}, + Entry{"atol" , "libc.so.6"}, + Entry{"atoll" , "libc.so.6"}, + Entry{"bind" , "libc.so.6"}, + Entry{"bsearch" , "libc.so.6"}, + Entry{"calloc" , "libc.so.6"}, + Entry{"cbrt" , "libm.so.6"}, + Entry{"cbrtf" , "libm.so.6"}, + Entry{"ceil" , "libm.so.6"}, + Entry{"ceilf" , "libm.so.6"}, + Entry{"chdir" , "libc.so.6"}, + Entry{"chmod" , "libc.so.6"}, + Entry{"chown" , "libc.so.6"}, + Entry{"clearerr" , "libc.so.6"}, + Entry{"clock" , "libc.so.6"}, + Entry{"clock_getres" , "libc.so.6"}, + Entry{"clock_gettime" , "libc.so.6"}, + Entry{"clock_nanosleep" , "libc.so.6"}, + Entry{"close" , "libc.so.6"}, + Entry{"closedir" , "libc.so.6"}, + Entry{"confstr" , "libc.so.6"}, + Entry{"connect" , "libc.so.6"}, + Entry{"copysign" , "libm.so.6"}, + Entry{"copysignf" , "libm.so.6"}, + Entry{"cos" , "libm.so.6"}, + Entry{"cosf" , "libm.so.6"}, + Entry{"cosh" , "libm.so.6"}, + Entry{"coshf" , "libm.so.6"}, + Entry{"creat" , "libc.so.6"}, + Entry{"difftime" , "libc.so.6"}, + Entry{"div" , "libc.so.6"}, + Entry{"dladdr" , "libc.so.6"}, + Entry{"dlclose" , "libc.so.6"}, + Entry{"dlerror" , "libc.so.6"}, + Entry{"dlinfo" , "libc.so.6"}, + Entry{"dlopen" , "libc.so.6"}, + Entry{"dlsym" , "libc.so.6"}, + Entry{"dprintf" , "libc.so.6"}, + Entry{"dup" , "libc.so.6"}, + Entry{"dup2" , "libc.so.6"}, + Entry{"dup3" , "libc.so.6"}, + Entry{"epoll_create" , "libc.so.6"}, + Entry{"epoll_create1" , "libc.so.6"}, + Entry{"epoll_ctl" , "libc.so.6"}, + Entry{"epoll_pwait" , "libc.so.6"}, + Entry{"epoll_wait" , "libc.so.6"}, + Entry{"erf" , "libm.so.6"}, + Entry{"erfc" , "libm.so.6"}, + Entry{"erfcf" , "libm.so.6"}, + Entry{"erff" , "libm.so.6"}, + Entry{"execl" , "libc.so.6"}, + Entry{"execle" , "libc.so.6"}, + Entry{"execlp" , "libc.so.6"}, + Entry{"execv" , "libc.so.6"}, + Entry{"execve" , "libc.so.6"}, + Entry{"execvp" , "libc.so.6"}, + Entry{"exit" , "libc.so.6"}, + Entry{"exp" , "libm.so.6"}, + Entry{"exp2" , "libm.so.6"}, + Entry{"exp2f" , "libm.so.6"}, + Entry{"expf" , "libm.so.6"}, + Entry{"expm1" , "libm.so.6"}, + Entry{"expm1f" , "libm.so.6"}, + Entry{"fabs" , "libm.so.6"}, + Entry{"fabsf" , "libm.so.6"}, + Entry{"fchdir" , "libc.so.6"}, + Entry{"fchmod" , "libc.so.6"}, + Entry{"fchown" , "libc.so.6"}, + Entry{"fclose" , "libc.so.6"}, + Entry{"fcntl" , "libc.so.6"}, + Entry{"fdatasync" , "libc.so.6"}, + Entry{"fdim" , "libm.so.6"}, + Entry{"fdimf" , "libm.so.6"}, + Entry{"fdopen" , "libc.so.6"}, + Entry{"feof" , "libc.so.6"}, + Entry{"ferror" , "libc.so.6"}, + Entry{"fflush" , "libc.so.6"}, + Entry{"fgetc" , "libc.so.6"}, + Entry{"fgetpos" , "libc.so.6"}, + Entry{"fgets" , "libc.so.6"}, + Entry{"fileno" , "libc.so.6"}, + Entry{"floor" , "libm.so.6"}, + Entry{"floorf" , "libm.so.6"}, + Entry{"fma" , "libm.so.6"}, + Entry{"fmaf" , "libm.so.6"}, + Entry{"fmax" , "libm.so.6"}, + Entry{"fmaxf" , "libm.so.6"}, + Entry{"fmin" , "libm.so.6"}, + Entry{"fminf" , "libm.so.6"}, + Entry{"fmod" , "libm.so.6"}, + Entry{"fmodf" , "libm.so.6"}, + Entry{"fopen" , "libc.so.6"}, + Entry{"fork" , "libc.so.6"}, + Entry{"fprintf" , "libc.so.6"}, + Entry{"fputc" , "libc.so.6"}, + Entry{"fputs" , "libc.so.6"}, + Entry{"fread" , "libc.so.6"}, + Entry{"free" , "libc.so.6"}, + Entry{"freeaddrinfo" , "libc.so.6"}, + Entry{"freopen" , "libc.so.6"}, + Entry{"frexp" , "libm.so.6"}, + Entry{"frexpf" , "libm.so.6"}, + Entry{"fscanf" , "libc.so.6"}, + Entry{"fseek" , "libc.so.6"}, + Entry{"fseeko" , "libc.so.6"}, + Entry{"fsetpos" , "libc.so.6"}, + Entry{"fstat" , "libc.so.6"}, + Entry{"fsync" , "libc.so.6"}, + Entry{"ftell" , "libc.so.6"}, + Entry{"ftello" , "libc.so.6"}, + Entry{"ftruncate" , "libc.so.6"}, + Entry{"futimens" , "libc.so.6"}, + Entry{"fwrite" , "libc.so.6"}, + Entry{"getaddrinfo" , "libc.so.6"}, + Entry{"getc" , "libc.so.6"}, + Entry{"getchar" , "libc.so.6"}, + Entry{"getcwd" , "libc.so.6"}, + Entry{"getegid" , "libc.so.6"}, + Entry{"getenv" , "libc.so.6"}, + Entry{"geteuid" , "libc.so.6"}, + Entry{"getgid" , "libc.so.6"}, + Entry{"getgroups" , "libc.so.6"}, + Entry{"gethostbyname" , "libc.so.6"}, + Entry{"gethostname" , "libc.so.6"}, + Entry{"getline" , "libc.so.6"}, + Entry{"getnameinfo" , "libc.so.6"}, + Entry{"getpeername" , "libc.so.6"}, + Entry{"getpid" , "libc.so.6"}, + Entry{"getppid" , "libc.so.6"}, + Entry{"getsockname" , "libc.so.6"}, + Entry{"getsockopt" , "libc.so.6"}, + Entry{"gettimeofday" , "libc.so.6"}, + Entry{"getuid" , "libc.so.6"}, + Entry{"gmtime" , "libc.so.6"}, + Entry{"gmtime_r" , "libc.so.6"}, + Entry{"htonl" , "libc.so.6"}, + Entry{"htons" , "libc.so.6"}, + Entry{"hypot" , "libm.so.6"}, + Entry{"hypotf" , "libm.so.6"}, + Entry{"ilogb" , "libm.so.6"}, + Entry{"ilogbf" , "libm.so.6"}, + Entry{"inet_addr" , "libc.so.6"}, + Entry{"inet_ntoa" , "libc.so.6"}, + Entry{"inet_ntop" , "libc.so.6"}, + Entry{"inet_pton" , "libc.so.6"}, + Entry{"ioctl" , "libc.so.6"}, + Entry{"isalnum" , "libc.so.6"}, + Entry{"isalpha" , "libc.so.6"}, + Entry{"isblank" , "libc.so.6"}, + Entry{"iscntrl" , "libc.so.6"}, + Entry{"isdigit" , "libc.so.6"}, + Entry{"isgraph" , "libc.so.6"}, + Entry{"islower" , "libc.so.6"}, + Entry{"isprint" , "libc.so.6"}, + Entry{"ispunct" , "libc.so.6"}, + Entry{"isspace" , "libc.so.6"}, + Entry{"isupper" , "libc.so.6"}, + Entry{"isxdigit" , "libc.so.6"}, + Entry{"kill" , "libc.so.6"}, + Entry{"labs" , "libc.so.6"}, + Entry{"lchown" , "libc.so.6"}, + Entry{"ldexp" , "libm.so.6"}, + Entry{"ldexpf" , "libm.so.6"}, + Entry{"ldiv" , "libc.so.6"}, + Entry{"lgamma" , "libm.so.6"}, + Entry{"lgammaf" , "libm.so.6"}, + Entry{"link" , "libc.so.6"}, + Entry{"listen" , "libc.so.6"}, + Entry{"llabs" , "libc.so.6"}, + Entry{"lldiv" , "libc.so.6"}, + Entry{"localtime" , "libc.so.6"}, + Entry{"localtime_r" , "libc.so.6"}, + Entry{"log" , "libm.so.6"}, + Entry{"log10" , "libm.so.6"}, + Entry{"log10f" , "libm.so.6"}, + Entry{"log1p" , "libm.so.6"}, + Entry{"log1pf" , "libm.so.6"}, + Entry{"log2" , "libm.so.6"}, + Entry{"log2f" , "libm.so.6"}, + Entry{"logb" , "libm.so.6"}, + Entry{"logbf" , "libm.so.6"}, + Entry{"logf" , "libm.so.6"}, + Entry{"lseek" , "libc.so.6"}, + Entry{"lstat" , "libc.so.6"}, + Entry{"malloc" , "libc.so.6"}, + Entry{"memalign" , "libc.so.6"}, + Entry{"memchr" , "libc.so.6"}, + Entry{"memcmp" , "libc.so.6"}, + Entry{"memcpy" , "libc.so.6"}, + Entry{"memmove" , "libc.so.6"}, + Entry{"memset" , "libc.so.6"}, + Entry{"mkdir" , "libc.so.6"}, + Entry{"mkdtemp" , "libc.so.6"}, + Entry{"mkstemp" , "libc.so.6"}, + Entry{"mktime" , "libc.so.6"}, + Entry{"mmap" , "libc.so.6"}, + Entry{"modf" , "libm.so.6"}, + Entry{"modff" , "libm.so.6"}, + Entry{"mprotect" , "libc.so.6"}, + Entry{"mq_close" , "libc.so.6"}, + Entry{"mq_open" , "libc.so.6"}, + Entry{"mq_receive" , "libc.so.6"}, + Entry{"mq_send" , "libc.so.6"}, + Entry{"mq_timedreceive" , "libc.so.6"}, + Entry{"mq_timedsend" , "libc.so.6"}, + Entry{"munmap" , "libc.so.6"}, + Entry{"nan" , "libm.so.6"}, + Entry{"nanf" , "libm.so.6"}, + Entry{"nanosleep" , "libc.so.6"}, + Entry{"nearbyint" , "libm.so.6"}, + Entry{"nearbyintf" , "libm.so.6"}, + Entry{"nextafter" , "libm.so.6"}, + Entry{"nextafterf" , "libm.so.6"}, + Entry{"ntohl" , "libc.so.6"}, + Entry{"ntohs" , "libc.so.6"}, + Entry{"on_exit" , "libc.so.6"}, + Entry{"open" , "libc.so.6"}, + Entry{"opendir" , "libc.so.6"}, + Entry{"pathconf" , "libc.so.6"}, + Entry{"pclose" , "libc.so.6"}, + Entry{"perror" , "libc.so.6"}, + Entry{"pipe" , "libc.so.6"}, + Entry{"pipe2" , "libc.so.6"}, + Entry{"poll" , "libc.so.6"}, + Entry{"popen" , "libc.so.6"}, + Entry{"posix_memalign" , "libc.so.6"}, + Entry{"pow" , "libm.so.6"}, + Entry{"powf" , "libm.so.6"}, + Entry{"pread" , "libc.so.6"}, + Entry{"printf" , "libc.so.6"}, + Entry{"pthread_attr_destroy" , "libc.so.6"}, + Entry{"pthread_attr_init" , "libc.so.6"}, + Entry{"pthread_attr_setdetachstate", "libc.so.6"}, + Entry{"pthread_attr_setschedparam" , "libc.so.6"}, + Entry{"pthread_attr_setstacksize" , "libc.so.6"}, + Entry{"pthread_barrier_destroy" , "libc.so.6"}, + Entry{"pthread_barrier_init" , "libc.so.6"}, + Entry{"pthread_barrier_wait" , "libc.so.6"}, + Entry{"pthread_cancel" , "libc.so.6"}, + Entry{"pthread_cond_broadcast" , "libc.so.6"}, + Entry{"pthread_cond_destroy" , "libc.so.6"}, + Entry{"pthread_cond_init" , "libc.so.6"}, + Entry{"pthread_cond_signal" , "libc.so.6"}, + Entry{"pthread_cond_timedwait" , "libc.so.6"}, + Entry{"pthread_cond_wait" , "libc.so.6"}, + Entry{"pthread_create" , "libc.so.6"}, + Entry{"pthread_detach" , "libc.so.6"}, + Entry{"pthread_equal" , "libc.so.6"}, + Entry{"pthread_exit" , "libc.so.6"}, + Entry{"pthread_getspecific" , "libc.so.6"}, + Entry{"pthread_join" , "libc.so.6"}, + Entry{"pthread_key_create" , "libc.so.6"}, + Entry{"pthread_key_delete" , "libc.so.6"}, + Entry{"pthread_mutex_destroy" , "libc.so.6"}, + Entry{"pthread_mutex_init" , "libc.so.6"}, + Entry{"pthread_mutex_lock" , "libc.so.6"}, + Entry{"pthread_mutex_timedlock" , "libc.so.6"}, + Entry{"pthread_mutex_trylock" , "libc.so.6"}, + Entry{"pthread_mutex_unlock" , "libc.so.6"}, + Entry{"pthread_once" , "libc.so.6"}, + Entry{"pthread_rwlock_destroy" , "libc.so.6"}, + Entry{"pthread_rwlock_init" , "libc.so.6"}, + Entry{"pthread_rwlock_rdlock" , "libc.so.6"}, + Entry{"pthread_rwlock_timedrdlock" , "libc.so.6"}, + Entry{"pthread_rwlock_timedwrlock" , "libc.so.6"}, + Entry{"pthread_rwlock_tryrdlock" , "libc.so.6"}, + Entry{"pthread_rwlock_trywrlock" , "libc.so.6"}, + Entry{"pthread_rwlock_unlock" , "libc.so.6"}, + Entry{"pthread_rwlock_wrlock" , "libc.so.6"}, + Entry{"pthread_self" , "libc.so.6"}, + Entry{"pthread_setspecific" , "libc.so.6"}, + Entry{"pthread_sigmask" , "libc.so.6"}, + Entry{"pthread_spin_destroy" , "libc.so.6"}, + Entry{"pthread_spin_init" , "libc.so.6"}, + Entry{"pthread_spin_lock" , "libc.so.6"}, + Entry{"pthread_spin_trylock" , "libc.so.6"}, + Entry{"pthread_spin_unlock" , "libc.so.6"}, + Entry{"pthread_testcancel" , "libc.so.6"}, + Entry{"putc" , "libc.so.6"}, + Entry{"putchar" , "libc.so.6"}, + Entry{"putenv" , "libc.so.6"}, + Entry{"puts" , "libc.so.6"}, + Entry{"pwrite" , "libc.so.6"}, + Entry{"qsort" , "libc.so.6"}, + Entry{"raise" , "libc.so.6"}, + Entry{"rand" , "libc.so.6"}, + Entry{"rand_r" , "libc.so.6"}, + Entry{"read" , "libc.so.6"}, + Entry{"readdir" , "libc.so.6"}, + Entry{"readlink" , "libc.so.6"}, + Entry{"realloc" , "libc.so.6"}, + Entry{"recv" , "libc.so.6"}, + Entry{"recvfrom" , "libc.so.6"}, + Entry{"recvmsg" , "libc.so.6"}, + Entry{"remainder" , "libm.so.6"}, + Entry{"remainderf" , "libm.so.6"}, + Entry{"remquo" , "libm.so.6"}, + Entry{"remquof" , "libm.so.6"}, + Entry{"rename" , "libc.so.6"}, + Entry{"rewind" , "libc.so.6"}, + Entry{"rint" , "libm.so.6"}, + Entry{"rintf" , "libm.so.6"}, + Entry{"rmdir" , "libc.so.6"}, + Entry{"round" , "libm.so.6"}, + Entry{"roundf" , "libm.so.6"}, + Entry{"scalbn" , "libm.so.6"}, + Entry{"scalbnf" , "libm.so.6"}, + Entry{"scanf" , "libc.so.6"}, + Entry{"select" , "libc.so.6"}, + Entry{"sem_close" , "libc.so.6"}, + Entry{"sem_destroy" , "libc.so.6"}, + Entry{"sem_getvalue" , "libc.so.6"}, + Entry{"sem_init" , "libc.so.6"}, + Entry{"sem_open" , "libc.so.6"}, + Entry{"sem_post" , "libc.so.6"}, + Entry{"sem_timedwait" , "libc.so.6"}, + Entry{"sem_trywait" , "libc.so.6"}, + Entry{"sem_unlink" , "libc.so.6"}, + Entry{"sem_wait" , "libc.so.6"}, + Entry{"send" , "libc.so.6"}, + Entry{"sendmsg" , "libc.so.6"}, + Entry{"sendto" , "libc.so.6"}, + Entry{"setbuf" , "libc.so.6"}, + Entry{"setbuffer" , "libc.so.6"}, + Entry{"setenv" , "libc.so.6"}, + Entry{"setgid" , "libc.so.6"}, + Entry{"setpgid" , "libc.so.6"}, + Entry{"setsid" , "libc.so.6"}, + Entry{"setsockopt" , "libc.so.6"}, + Entry{"setuid" , "libc.so.6"}, + Entry{"setvbuf" , "libc.so.6"}, + Entry{"shm_open" , "libc.so.6"}, + Entry{"shm_unlink" , "libc.so.6"}, + Entry{"shutdown" , "libc.so.6"}, + Entry{"sigaction" , "libc.so.6"}, + Entry{"sigaddset" , "libc.so.6"}, + Entry{"sigdelset" , "libc.so.6"}, + Entry{"sigemptyset" , "libc.so.6"}, + Entry{"sigfillset" , "libc.so.6"}, + Entry{"signal" , "libc.so.6"}, + Entry{"sigpending" , "libc.so.6"}, + Entry{"sigprocmask" , "libc.so.6"}, + Entry{"sigsuspend" , "libc.so.6"}, + Entry{"sin" , "libm.so.6"}, + Entry{"sinf" , "libm.so.6"}, + Entry{"sinh" , "libm.so.6"}, + Entry{"sinhf" , "libm.so.6"}, + Entry{"sleep" , "libc.so.6"}, + Entry{"snprintf" , "libc.so.6"}, + Entry{"socket" , "libc.so.6"}, + Entry{"socketpair" , "libc.so.6"}, + Entry{"sprintf" , "libc.so.6"}, + Entry{"sqrt" , "libm.so.6"}, + Entry{"sqrtf" , "libm.so.6"}, + Entry{"srand" , "libc.so.6"}, + Entry{"sscanf" , "libc.so.6"}, + Entry{"stat" , "libc.so.6"}, + Entry{"strcat" , "libc.so.6"}, + Entry{"strchr" , "libc.so.6"}, + Entry{"strcmp" , "libc.so.6"}, + Entry{"strcoll" , "libc.so.6"}, + Entry{"strcpy" , "libc.so.6"}, + Entry{"strcspn" , "libc.so.6"}, + Entry{"strdup" , "libc.so.6"}, + Entry{"strerror" , "libc.so.6"}, + Entry{"strerror_r" , "libc.so.6"}, + Entry{"strftime" , "libc.so.6"}, + Entry{"strlen" , "libc.so.6"}, + Entry{"strncat" , "libc.so.6"}, + Entry{"strncmp" , "libc.so.6"}, + Entry{"strncpy" , "libc.so.6"}, + Entry{"strndup" , "libc.so.6"}, + Entry{"strnlen" , "libc.so.6"}, + Entry{"strpbrk" , "libc.so.6"}, + Entry{"strptime" , "libc.so.6"}, + Entry{"strrchr" , "libc.so.6"}, + Entry{"strspn" , "libc.so.6"}, + Entry{"strstr" , "libc.so.6"}, + Entry{"strtod" , "libc.so.6"}, + Entry{"strtof" , "libc.so.6"}, + Entry{"strtok" , "libc.so.6"}, + Entry{"strtok_r" , "libc.so.6"}, + Entry{"strtol" , "libc.so.6"}, + Entry{"strtold" , "libc.so.6"}, + Entry{"strtoll" , "libc.so.6"}, + Entry{"strtoul" , "libc.so.6"}, + Entry{"strtoull" , "libc.so.6"}, + Entry{"strxfrm" , "libc.so.6"}, + Entry{"symlink" , "libc.so.6"}, + Entry{"sysconf" , "libc.so.6"}, + Entry{"system" , "libc.so.6"}, + Entry{"tan" , "libm.so.6"}, + Entry{"tanf" , "libm.so.6"}, + Entry{"tanh" , "libm.so.6"}, + Entry{"tanhf" , "libm.so.6"}, + Entry{"tgamma" , "libm.so.6"}, + Entry{"tgammaf" , "libm.so.6"}, + Entry{"time" , "libc.so.6"}, + Entry{"timer_create" , "libc.so.6"}, + Entry{"timer_delete" , "libc.so.6"}, + Entry{"timer_gettime" , "libc.so.6"}, + Entry{"timer_settime" , "libc.so.6"}, + Entry{"tmpfile" , "libc.so.6"}, + Entry{"tmpnam" , "libc.so.6"}, + Entry{"tolower" , "libc.so.6"}, + Entry{"toupper" , "libc.so.6"}, + Entry{"trunc" , "libm.so.6"}, + Entry{"truncate" , "libc.so.6"}, + Entry{"truncf" , "libm.so.6"}, + Entry{"umask" , "libc.so.6"}, + Entry{"uname" , "libc.so.6"}, + Entry{"ungetc" , "libc.so.6"}, + Entry{"unlink" , "libc.so.6"}, + Entry{"unsetenv" , "libc.so.6"}, + Entry{"usleep" , "libc.so.6"}, + Entry{"utimes" , "libc.so.6"}, + Entry{"vasprintf" , "libc.so.6"}, + Entry{"vdprintf" , "libc.so.6"}, + Entry{"vfprintf" , "libc.so.6"}, + Entry{"vfscanf" , "libc.so.6"}, + Entry{"vprintf" , "libc.so.6"}, + Entry{"vscanf" , "libc.so.6"}, + Entry{"vsnprintf" , "libc.so.6"}, + Entry{"vsprintf" , "libc.so.6"}, + Entry{"vsscanf" , "libc.so.6"}, + Entry{"wait" , "libc.so.6"}, + Entry{"waitpid" , "libc.so.6"}, + Entry{"wcscat" , "libc.so.6"}, + Entry{"wcscmp" , "libc.so.6"}, + Entry{"wcscpy" , "libc.so.6"}, + Entry{"wcslen" , "libc.so.6"}, + Entry{"wmemcpy" , "libc.so.6"}, + Entry{"write" , "libc.so.6"}, +}; + +// ── Windows ────────────────────────────────────────────────────────────────────── +static constexpr std::array windows_table = { + Entry{"AdjustTokenPrivileges" , "ADVAPI32.DLL"}, + Entry{"CloseHandle" , "KERNEL32.DLL"}, + Entry{"ConvertSidToStringSidA" , "ADVAPI32.DLL"}, + Entry{"ConvertSidToStringSidW" , "ADVAPI32.DLL"}, + Entry{"ConvertStringSidToSidA" , "ADVAPI32.DLL"}, + Entry{"ConvertStringSidToSidW" , "ADVAPI32.DLL"}, + Entry{"CreateDirectoryA" , "KERNEL32.DLL"}, + Entry{"CreateDirectoryW" , "KERNEL32.DLL"}, + Entry{"CreateEventA" , "KERNEL32.DLL"}, + Entry{"CreateEventW" , "KERNEL32.DLL"}, + Entry{"CreateFileA" , "KERNEL32.DLL"}, + Entry{"CreateFileW" , "KERNEL32.DLL"}, + Entry{"CreateMutexA" , "KERNEL32.DLL"}, + Entry{"CreateMutexW" , "KERNEL32.DLL"}, + Entry{"CreateProcessA" , "KERNEL32.DLL"}, + Entry{"CreateProcessW" , "KERNEL32.DLL"}, + Entry{"CreateSemaphoreA" , "KERNEL32.DLL"}, + Entry{"CreateSemaphoreW" , "KERNEL32.DLL"}, + Entry{"CreateThread" , "KERNEL32.DLL"}, + Entry{"CreateWindowExA" , "USER32.DLL"}, + Entry{"CreateWindowExW" , "USER32.DLL"}, + Entry{"DefWindowProcA" , "USER32.DLL"}, + Entry{"DefWindowProcW" , "USER32.DLL"}, + Entry{"DeleteCriticalSection" , "KERNEL32.DLL"}, + Entry{"DeleteFileA" , "KERNEL32.DLL"}, + Entry{"DeleteFileW" , "KERNEL32.DLL"}, + Entry{"DestroyWindow" , "USER32.DLL"}, + Entry{"DeviceIoControl" , "KERNEL32.DLL"}, + Entry{"DispatchMessageA" , "USER32.DLL"}, + Entry{"DispatchMessageW" , "USER32.DLL"}, + Entry{"EnterCriticalSection" , "KERNEL32.DLL"}, + Entry{"ExitProcess" , "KERNEL32.DLL"}, + Entry{"ExitThread" , "KERNEL32.DLL"}, + Entry{"FindClose" , "KERNEL32.DLL"}, + Entry{"FindFirstFileA" , "KERNEL32.DLL"}, + Entry{"FindFirstFileW" , "KERNEL32.DLL"}, + Entry{"FindNextFileA" , "KERNEL32.DLL"}, + Entry{"FindNextFileW" , "KERNEL32.DLL"}, + Entry{"FlushFileBuffers" , "KERNEL32.DLL"}, + Entry{"FormatMessageA" , "KERNEL32.DLL"}, + Entry{"FormatMessageW" , "KERNEL32.DLL"}, + Entry{"FreeLibrary" , "KERNEL32.DLL"}, + Entry{"GetClientRect" , "USER32.DLL"}, + Entry{"GetCommandLineA" , "KERNEL32.DLL"}, + Entry{"GetCommandLineW" , "KERNEL32.DLL"}, + Entry{"GetConsoleMode" , "KERNEL32.DLL"}, + Entry{"GetCurrentDirectoryA" , "KERNEL32.DLL"}, + Entry{"GetCurrentDirectoryW" , "KERNEL32.DLL"}, + Entry{"GetCurrentProcess" , "KERNEL32.DLL"}, + Entry{"GetCurrentProcessId" , "KERNEL32.DLL"}, + Entry{"GetCurrentThread" , "KERNEL32.DLL"}, + Entry{"GetCurrentThreadId" , "KERNEL32.DLL"}, + Entry{"GetEnvironmentVariableA" , "KERNEL32.DLL"}, + Entry{"GetEnvironmentVariableW" , "KERNEL32.DLL"}, + Entry{"GetFileAttributesA" , "KERNEL32.DLL"}, + Entry{"GetFileAttributesW" , "KERNEL32.DLL"}, + Entry{"GetFileSizeEx" , "KERNEL32.DLL"}, + Entry{"GetFileType" , "KERNEL32.DLL"}, + Entry{"GetLastError" , "KERNEL32.DLL"}, + Entry{"GetMessageA" , "USER32.DLL"}, + Entry{"GetMessageW" , "USER32.DLL"}, + Entry{"GetModuleFileNameA" , "KERNEL32.DLL"}, + Entry{"GetModuleFileNameW" , "KERNEL32.DLL"}, + Entry{"GetModuleHandleA" , "KERNEL32.DLL"}, + Entry{"GetModuleHandleW" , "KERNEL32.DLL"}, + Entry{"GetProcAddress" , "KERNEL32.DLL"}, + Entry{"GetProcessHeap" , "KERNEL32.DLL"}, + Entry{"GetStdHandle" , "KERNEL32.DLL"}, + Entry{"GetSystemInfo" , "KERNEL32.DLL"}, + Entry{"GetSystemTime" , "KERNEL32.DLL"}, + Entry{"GetSystemTimeAsFileTime" , "KERNEL32.DLL"}, + Entry{"GetTempPathA" , "KERNEL32.DLL"}, + Entry{"GetTempPathW" , "KERNEL32.DLL"}, + Entry{"GetThreadContext" , "KERNEL32.DLL"}, + Entry{"GetTickCount" , "KERNEL32.DLL"}, + Entry{"GetTickCount64" , "KERNEL32.DLL"}, + Entry{"GetTokenInformation" , "ADVAPI32.DLL"}, + Entry{"GetUserNameA" , "ADVAPI32.DLL"}, + Entry{"GetUserNameW" , "ADVAPI32.DLL"}, + Entry{"GlobalAlloc" , "KERNEL32.DLL"}, + Entry{"GlobalFree" , "KERNEL32.DLL"}, + Entry{"HeapAlloc" , "KERNEL32.DLL"}, + Entry{"HeapCreate" , "KERNEL32.DLL"}, + Entry{"HeapDestroy" , "KERNEL32.DLL"}, + Entry{"HeapFree" , "KERNEL32.DLL"}, + Entry{"HeapReAlloc" , "KERNEL32.DLL"}, + Entry{"HeapSize" , "KERNEL32.DLL"}, + Entry{"InitializeConditionVariable" , "KERNEL32.DLL"}, + Entry{"InitializeCriticalSection" , "KERNEL32.DLL"}, + Entry{"InitializeCriticalSectionAndSpinCount", "KERNEL32.DLL"}, + Entry{"InitializeSecurityDescriptor" , "ADVAPI32.DLL"}, + Entry{"InvalidateRect" , "USER32.DLL"}, + Entry{"LeaveCriticalSection" , "KERNEL32.DLL"}, + Entry{"LoadCursorA" , "USER32.DLL"}, + Entry{"LoadCursorW" , "USER32.DLL"}, + Entry{"LoadLibraryA" , "KERNEL32.DLL"}, + Entry{"LoadLibraryExA" , "KERNEL32.DLL"}, + Entry{"LoadLibraryExW" , "KERNEL32.DLL"}, + Entry{"LoadLibraryW" , "KERNEL32.DLL"}, + Entry{"LocalAlloc" , "KERNEL32.DLL"}, + Entry{"LocalFree" , "KERNEL32.DLL"}, + Entry{"LookupAccountNameA" , "ADVAPI32.DLL"}, + Entry{"LookupAccountNameW" , "ADVAPI32.DLL"}, + Entry{"LookupPrivilegeValueA" , "ADVAPI32.DLL"}, + Entry{"LookupPrivilegeValueW" , "ADVAPI32.DLL"}, + Entry{"MapViewOfFile" , "KERNEL32.DLL"}, + Entry{"MapViewOfFileEx" , "KERNEL32.DLL"}, + Entry{"MessageBoxA" , "USER32.DLL"}, + Entry{"MessageBoxW" , "USER32.DLL"}, + Entry{"MoveFileA" , "KERNEL32.DLL"}, + Entry{"MoveFileExA" , "KERNEL32.DLL"}, + Entry{"MoveFileExW" , "KERNEL32.DLL"}, + Entry{"MoveFileW" , "KERNEL32.DLL"}, + Entry{"MultiByteToWideChar" , "KERNEL32.DLL"}, + Entry{"OpenEventA" , "KERNEL32.DLL"}, + Entry{"OpenEventW" , "KERNEL32.DLL"}, + Entry{"OpenFileMappingA" , "KERNEL32.DLL"}, + Entry{"OpenFileMappingW" , "KERNEL32.DLL"}, + Entry{"OpenMutexA" , "KERNEL32.DLL"}, + Entry{"OpenMutexW" , "KERNEL32.DLL"}, + Entry{"OpenProcess" , "KERNEL32.DLL"}, + Entry{"OpenProcessToken" , "ADVAPI32.DLL"}, + Entry{"OpenSemaphoreA" , "KERNEL32.DLL"}, + Entry{"OpenSemaphoreW" , "KERNEL32.DLL"}, + Entry{"OpenThread" , "KERNEL32.DLL"}, + Entry{"OpenThreadToken" , "ADVAPI32.DLL"}, + Entry{"PeekMessageA" , "USER32.DLL"}, + Entry{"PeekMessageW" , "USER32.DLL"}, + Entry{"PostMessageA" , "USER32.DLL"}, + Entry{"PostMessageW" , "USER32.DLL"}, + Entry{"PostQuitMessage" , "USER32.DLL"}, + Entry{"QueryPerformanceCounter" , "KERNEL32.DLL"}, + Entry{"QueryPerformanceFrequency" , "KERNEL32.DLL"}, + Entry{"ReadFile" , "KERNEL32.DLL"}, + Entry{"RegCloseKey" , "ADVAPI32.DLL"}, + Entry{"RegCreateKeyExA" , "ADVAPI32.DLL"}, + Entry{"RegCreateKeyExW" , "ADVAPI32.DLL"}, + Entry{"RegDeleteKeyA" , "ADVAPI32.DLL"}, + Entry{"RegDeleteKeyW" , "ADVAPI32.DLL"}, + Entry{"RegDeleteValueA" , "ADVAPI32.DLL"}, + Entry{"RegDeleteValueW" , "ADVAPI32.DLL"}, + Entry{"RegEnumKeyExA" , "ADVAPI32.DLL"}, + Entry{"RegEnumKeyExW" , "ADVAPI32.DLL"}, + Entry{"RegEnumValueA" , "ADVAPI32.DLL"}, + Entry{"RegEnumValueW" , "ADVAPI32.DLL"}, + Entry{"RegOpenKeyExA" , "ADVAPI32.DLL"}, + Entry{"RegOpenKeyExW" , "ADVAPI32.DLL"}, + Entry{"RegQueryValueExA" , "ADVAPI32.DLL"}, + Entry{"RegQueryValueExW" , "ADVAPI32.DLL"}, + Entry{"RegSetValueExA" , "ADVAPI32.DLL"}, + Entry{"RegSetValueExW" , "ADVAPI32.DLL"}, + Entry{"RegisterClassA" , "USER32.DLL"}, + Entry{"RegisterClassExA" , "USER32.DLL"}, + Entry{"RegisterClassExW" , "USER32.DLL"}, + Entry{"RegisterClassW" , "USER32.DLL"}, + Entry{"ReleaseMutex" , "KERNEL32.DLL"}, + Entry{"ReleaseSemaphore" , "KERNEL32.DLL"}, + Entry{"RemoveDirectoryA" , "KERNEL32.DLL"}, + Entry{"RemoveDirectoryW" , "KERNEL32.DLL"}, + Entry{"ResetEvent" , "KERNEL32.DLL"}, + Entry{"ResumeThread" , "KERNEL32.DLL"}, + Entry{"SendMessageA" , "USER32.DLL"}, + Entry{"SendMessageW" , "USER32.DLL"}, + Entry{"SetCurrentDirectoryA" , "KERNEL32.DLL"}, + Entry{"SetCurrentDirectoryW" , "KERNEL32.DLL"}, + Entry{"SetEndOfFile" , "KERNEL32.DLL"}, + Entry{"SetEnvironmentVariableA" , "KERNEL32.DLL"}, + Entry{"SetEnvironmentVariableW" , "KERNEL32.DLL"}, + Entry{"SetEvent" , "KERNEL32.DLL"}, + Entry{"SetFileAttributesA" , "KERNEL32.DLL"}, + Entry{"SetFileAttributesW" , "KERNEL32.DLL"}, + Entry{"SetFilePointerEx" , "KERNEL32.DLL"}, + Entry{"SetLastError" , "KERNEL32.DLL"}, + Entry{"SetThreadPriority" , "KERNEL32.DLL"}, + Entry{"SetUnhandledExceptionFilter" , "KERNEL32.DLL"}, + Entry{"SetWindowPos" , "USER32.DLL"}, + Entry{"SetWindowTextA" , "USER32.DLL"}, + Entry{"SetWindowTextW" , "USER32.DLL"}, + Entry{"ShowWindow" , "USER32.DLL"}, + Entry{"Sleep" , "KERNEL32.DLL"}, + Entry{"SleepConditionVariableCS" , "KERNEL32.DLL"}, + Entry{"SleepEx" , "KERNEL32.DLL"}, + Entry{"SuspendThread" , "KERNEL32.DLL"}, + Entry{"TerminateProcess" , "KERNEL32.DLL"}, + Entry{"TerminateThread" , "KERNEL32.DLL"}, + Entry{"TlsAlloc" , "KERNEL32.DLL"}, + Entry{"TlsFree" , "KERNEL32.DLL"}, + Entry{"TlsGetValue" , "KERNEL32.DLL"}, + Entry{"TlsSetValue" , "KERNEL32.DLL"}, + Entry{"TranslateMessage" , "USER32.DLL"}, + Entry{"TryEnterCriticalSection" , "KERNEL32.DLL"}, + Entry{"UnmapViewOfFile" , "KERNEL32.DLL"}, + Entry{"UpdateWindow" , "USER32.DLL"}, + Entry{"VirtualAlloc" , "KERNEL32.DLL"}, + Entry{"VirtualAllocEx" , "KERNEL32.DLL"}, + Entry{"VirtualFree" , "KERNEL32.DLL"}, + Entry{"VirtualFreeEx" , "KERNEL32.DLL"}, + Entry{"VirtualProtect" , "KERNEL32.DLL"}, + Entry{"VirtualProtectEx" , "KERNEL32.DLL"}, + Entry{"VirtualQuery" , "KERNEL32.DLL"}, + Entry{"WSACleanup" , "WS2_32.DLL"}, + Entry{"WSACloseEvent" , "WS2_32.DLL"}, + Entry{"WSACreateEvent" , "WS2_32.DLL"}, + Entry{"WSAGetLastError" , "WS2_32.DLL"}, + Entry{"WSAPoll" , "WS2_32.DLL"}, + Entry{"WSARecv" , "WS2_32.DLL"}, + Entry{"WSASend" , "WS2_32.DLL"}, + Entry{"WSASetLastError" , "WS2_32.DLL"}, + Entry{"WSAStartup" , "WS2_32.DLL"}, + Entry{"WaitForMultipleObjects" , "KERNEL32.DLL"}, + Entry{"WaitForMultipleObjectsEx" , "KERNEL32.DLL"}, + Entry{"WaitForSingleObject" , "KERNEL32.DLL"}, + Entry{"WaitForSingleObjectEx" , "KERNEL32.DLL"}, + Entry{"WakeAllConditionVariable" , "KERNEL32.DLL"}, + Entry{"WakeConditionVariable" , "KERNEL32.DLL"}, + Entry{"WideCharToMultiByte" , "KERNEL32.DLL"}, + Entry{"WriteFile" , "KERNEL32.DLL"}, + Entry{"WriteProcessMemory" , "KERNEL32.DLL"}, + Entry{"_access" , "ucrtbase.dll"}, + Entry{"_chdir" , "ucrtbase.dll"}, + Entry{"_close" , "ucrtbase.dll"}, + Entry{"_dup" , "ucrtbase.dll"}, + Entry{"_dup2" , "ucrtbase.dll"}, + Entry{"_exit" , "ucrtbase.dll"}, + Entry{"_fileno" , "ucrtbase.dll"}, + Entry{"_fstat64" , "ucrtbase.dll"}, + Entry{"_getcwd" , "ucrtbase.dll"}, + Entry{"_getpid" , "ucrtbase.dll"}, + Entry{"_isnan" , "ucrtbase.dll"}, + Entry{"_lseeki64" , "ucrtbase.dll"}, + Entry{"_mkdir" , "ucrtbase.dll"}, + Entry{"_mktemp" , "ucrtbase.dll"}, + Entry{"_open" , "ucrtbase.dll"}, + Entry{"_pclose" , "ucrtbase.dll"}, + Entry{"_popen" , "ucrtbase.dll"}, + Entry{"_read" , "ucrtbase.dll"}, + Entry{"_rmdir" , "ucrtbase.dll"}, + Entry{"_stat64" , "ucrtbase.dll"}, + Entry{"_strdup" , "ucrtbase.dll"}, + Entry{"_stricmp" , "ucrtbase.dll"}, + Entry{"_strnicmp" , "ucrtbase.dll"}, + Entry{"_write" , "ucrtbase.dll"}, + Entry{"abort" , "ucrtbase.dll"}, + Entry{"abs" , "ucrtbase.dll"}, + Entry{"accept" , "WS2_32.DLL"}, + Entry{"acos" , "ucrtbase.dll"}, + Entry{"acosf" , "ucrtbase.dll"}, + Entry{"aligned_free" , "ucrtbase.dll"}, + Entry{"aligned_malloc" , "ucrtbase.dll"}, + Entry{"asin" , "ucrtbase.dll"}, + Entry{"asinf" , "ucrtbase.dll"}, + Entry{"atan" , "ucrtbase.dll"}, + Entry{"atan2" , "ucrtbase.dll"}, + Entry{"atan2f" , "ucrtbase.dll"}, + Entry{"atanf" , "ucrtbase.dll"}, + Entry{"atof" , "ucrtbase.dll"}, + Entry{"atoi" , "ucrtbase.dll"}, + Entry{"atol" , "ucrtbase.dll"}, + Entry{"atoll" , "ucrtbase.dll"}, + Entry{"bind" , "WS2_32.DLL"}, + Entry{"bsearch" , "ucrtbase.dll"}, + Entry{"bsearch_s" , "ucrtbase.dll"}, + Entry{"calloc" , "ucrtbase.dll"}, + Entry{"cbrt" , "ucrtbase.dll"}, + Entry{"cbrtf" , "ucrtbase.dll"}, + Entry{"ceil" , "ucrtbase.dll"}, + Entry{"ceilf" , "ucrtbase.dll"}, + Entry{"clearerr" , "ucrtbase.dll"}, + Entry{"closesocket" , "WS2_32.DLL"}, + Entry{"connect" , "WS2_32.DLL"}, + Entry{"cos" , "ucrtbase.dll"}, + Entry{"cosf" , "ucrtbase.dll"}, + Entry{"cosh" , "ucrtbase.dll"}, + Entry{"coshf" , "ucrtbase.dll"}, + Entry{"div" , "ucrtbase.dll"}, + Entry{"exit" , "ucrtbase.dll"}, + Entry{"exp" , "ucrtbase.dll"}, + Entry{"exp2" , "ucrtbase.dll"}, + Entry{"exp2f" , "ucrtbase.dll"}, + Entry{"expf" , "ucrtbase.dll"}, + Entry{"fabs" , "ucrtbase.dll"}, + Entry{"fabsf" , "ucrtbase.dll"}, + Entry{"fclose" , "ucrtbase.dll"}, + Entry{"fdim" , "ucrtbase.dll"}, + Entry{"feof" , "ucrtbase.dll"}, + Entry{"ferror" , "ucrtbase.dll"}, + Entry{"fflush" , "ucrtbase.dll"}, + Entry{"fgetc" , "ucrtbase.dll"}, + Entry{"fgetpos" , "ucrtbase.dll"}, + Entry{"fgets" , "ucrtbase.dll"}, + Entry{"floor" , "ucrtbase.dll"}, + Entry{"floorf" , "ucrtbase.dll"}, + Entry{"fma" , "ucrtbase.dll"}, + Entry{"fmax" , "ucrtbase.dll"}, + Entry{"fmin" , "ucrtbase.dll"}, + Entry{"fmod" , "ucrtbase.dll"}, + Entry{"fmodf" , "ucrtbase.dll"}, + Entry{"fopen" , "ucrtbase.dll"}, + Entry{"fprintf" , "ucrtbase.dll"}, + Entry{"fputc" , "ucrtbase.dll"}, + Entry{"fputs" , "ucrtbase.dll"}, + Entry{"fread" , "ucrtbase.dll"}, + Entry{"free" , "ucrtbase.dll"}, + Entry{"freeaddrinfo" , "WS2_32.DLL"}, + Entry{"freopen" , "ucrtbase.dll"}, + Entry{"fscanf" , "ucrtbase.dll"}, + Entry{"fseek" , "ucrtbase.dll"}, + Entry{"fsetpos" , "ucrtbase.dll"}, + Entry{"ftell" , "ucrtbase.dll"}, + Entry{"fwrite" , "ucrtbase.dll"}, + Entry{"getaddrinfo" , "WS2_32.DLL"}, + Entry{"getc" , "ucrtbase.dll"}, + Entry{"getchar" , "ucrtbase.dll"}, + Entry{"getenv" , "ucrtbase.dll"}, + Entry{"gethostbyname" , "WS2_32.DLL"}, + Entry{"gethostname" , "WS2_32.DLL"}, + Entry{"getnameinfo" , "WS2_32.DLL"}, + Entry{"getpeername" , "WS2_32.DLL"}, + Entry{"getsockname" , "WS2_32.DLL"}, + Entry{"getsockopt" , "WS2_32.DLL"}, + Entry{"htonl" , "WS2_32.DLL"}, + Entry{"htons" , "WS2_32.DLL"}, + Entry{"hypot" , "ucrtbase.dll"}, + Entry{"hypotf" , "ucrtbase.dll"}, + Entry{"inet_addr" , "WS2_32.DLL"}, + Entry{"inet_ntoa" , "WS2_32.DLL"}, + Entry{"inet_ntop" , "WS2_32.DLL"}, + Entry{"inet_pton" , "WS2_32.DLL"}, + Entry{"isalnum" , "ucrtbase.dll"}, + Entry{"isalpha" , "ucrtbase.dll"}, + Entry{"isblank" , "ucrtbase.dll"}, + Entry{"iscntrl" , "ucrtbase.dll"}, + Entry{"isdigit" , "ucrtbase.dll"}, + Entry{"isgraph" , "ucrtbase.dll"}, + Entry{"islower" , "ucrtbase.dll"}, + Entry{"isprint" , "ucrtbase.dll"}, + Entry{"ispunct" , "ucrtbase.dll"}, + Entry{"isspace" , "ucrtbase.dll"}, + Entry{"isupper" , "ucrtbase.dll"}, + Entry{"isxdigit" , "ucrtbase.dll"}, + Entry{"labs" , "ucrtbase.dll"}, + Entry{"ldexp" , "ucrtbase.dll"}, + Entry{"ldiv" , "ucrtbase.dll"}, + Entry{"listen" , "WS2_32.DLL"}, + Entry{"llabs" , "ucrtbase.dll"}, + Entry{"lldiv" , "ucrtbase.dll"}, + Entry{"log" , "ucrtbase.dll"}, + Entry{"log10" , "ucrtbase.dll"}, + Entry{"log10f" , "ucrtbase.dll"}, + Entry{"log2" , "ucrtbase.dll"}, + Entry{"log2f" , "ucrtbase.dll"}, + Entry{"logf" , "ucrtbase.dll"}, + Entry{"malloc" , "ucrtbase.dll"}, + Entry{"memchr" , "ucrtbase.dll"}, + Entry{"memcmp" , "ucrtbase.dll"}, + Entry{"memcpy" , "ucrtbase.dll"}, + Entry{"memmove" , "ucrtbase.dll"}, + Entry{"memset" , "ucrtbase.dll"}, + Entry{"modf" , "ucrtbase.dll"}, + Entry{"modff" , "ucrtbase.dll"}, + Entry{"nearbyint" , "ucrtbase.dll"}, + Entry{"nearbyintf" , "ucrtbase.dll"}, + Entry{"ntohl" , "WS2_32.DLL"}, + Entry{"ntohs" , "WS2_32.DLL"}, + Entry{"perror" , "ucrtbase.dll"}, + Entry{"pow" , "ucrtbase.dll"}, + Entry{"powf" , "ucrtbase.dll"}, + Entry{"printf" , "ucrtbase.dll"}, + Entry{"putc" , "ucrtbase.dll"}, + Entry{"putchar" , "ucrtbase.dll"}, + Entry{"puts" , "ucrtbase.dll"}, + Entry{"qsort" , "ucrtbase.dll"}, + Entry{"qsort_s" , "ucrtbase.dll"}, + Entry{"rand" , "ucrtbase.dll"}, + Entry{"realloc" , "ucrtbase.dll"}, + Entry{"recv" , "WS2_32.DLL"}, + Entry{"recvfrom" , "WS2_32.DLL"}, + Entry{"remainder" , "ucrtbase.dll"}, + Entry{"rewind" , "ucrtbase.dll"}, + Entry{"rint" , "ucrtbase.dll"}, + Entry{"rintf" , "ucrtbase.dll"}, + Entry{"round" , "ucrtbase.dll"}, + Entry{"roundf" , "ucrtbase.dll"}, + Entry{"scanf" , "ucrtbase.dll"}, + Entry{"select" , "WS2_32.DLL"}, + Entry{"send" , "WS2_32.DLL"}, + Entry{"sendto" , "WS2_32.DLL"}, + Entry{"setenv" , "ucrtbase.dll"}, + Entry{"setsockopt" , "WS2_32.DLL"}, + Entry{"shutdown" , "WS2_32.DLL"}, + Entry{"sin" , "ucrtbase.dll"}, + Entry{"sinf" , "ucrtbase.dll"}, + Entry{"sinh" , "ucrtbase.dll"}, + Entry{"sinhf" , "ucrtbase.dll"}, + Entry{"snprintf" , "ucrtbase.dll"}, + Entry{"socket" , "WS2_32.DLL"}, + Entry{"sprintf" , "ucrtbase.dll"}, + Entry{"sqrt" , "ucrtbase.dll"}, + Entry{"sqrtf" , "ucrtbase.dll"}, + Entry{"srand" , "ucrtbase.dll"}, + Entry{"sscanf" , "ucrtbase.dll"}, + Entry{"strcat" , "ucrtbase.dll"}, + Entry{"strchr" , "ucrtbase.dll"}, + Entry{"strcmp" , "ucrtbase.dll"}, + Entry{"strcpy" , "ucrtbase.dll"}, + Entry{"strcspn" , "ucrtbase.dll"}, + Entry{"strerror" , "ucrtbase.dll"}, + Entry{"strlen" , "ucrtbase.dll"}, + Entry{"strncat" , "ucrtbase.dll"}, + Entry{"strncmp" , "ucrtbase.dll"}, + Entry{"strncpy" , "ucrtbase.dll"}, + Entry{"strnlen" , "ucrtbase.dll"}, + Entry{"strpbrk" , "ucrtbase.dll"}, + Entry{"strrchr" , "ucrtbase.dll"}, + Entry{"strspn" , "ucrtbase.dll"}, + Entry{"strstr" , "ucrtbase.dll"}, + Entry{"strtod" , "ucrtbase.dll"}, + Entry{"strtof" , "ucrtbase.dll"}, + Entry{"strtok" , "ucrtbase.dll"}, + Entry{"strtok_s" , "ucrtbase.dll"}, + Entry{"strtol" , "ucrtbase.dll"}, + Entry{"strtoll" , "ucrtbase.dll"}, + Entry{"strtoul" , "ucrtbase.dll"}, + Entry{"strtoull" , "ucrtbase.dll"}, + Entry{"tan" , "ucrtbase.dll"}, + Entry{"tanf" , "ucrtbase.dll"}, + Entry{"tanh" , "ucrtbase.dll"}, + Entry{"tanhf" , "ucrtbase.dll"}, + Entry{"time" , "ucrtbase.dll"}, + Entry{"tmpfile" , "ucrtbase.dll"}, + Entry{"tmpnam" , "ucrtbase.dll"}, + Entry{"tolower" , "ucrtbase.dll"}, + Entry{"toupper" , "ucrtbase.dll"}, + Entry{"trunc" , "ucrtbase.dll"}, + Entry{"truncf" , "ucrtbase.dll"}, + Entry{"ungetc" , "ucrtbase.dll"}, + Entry{"vfprintf" , "ucrtbase.dll"}, + Entry{"vprintf" , "ucrtbase.dll"}, + Entry{"vsnprintf" , "ucrtbase.dll"}, + Entry{"vsprintf" , "ucrtbase.dll"}, + Entry{"wcscat" , "ucrtbase.dll"}, + Entry{"wcscmp" , "ucrtbase.dll"}, + Entry{"wcscpy" , "ucrtbase.dll"}, + Entry{"wcslen" , "ucrtbase.dll"}, +}; + +// ── Macos ──────────────────────────────────────────────────────────────────────── +static constexpr std::array macos_table = { + Entry{"CFArrayCreate" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"CFArrayGetCount" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"CFArrayGetValueAtIndex" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"CFDataCreate" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"CFRelease" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"CFRetain" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"CFStringCreateWithCString" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"CFStringGetCString" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"CFStringGetLength" , "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"}, + Entry{"__assert_rtn" , "/usr/lib/libSystem.B.dylib"}, + Entry{"__cxa_atexit" , "/usr/lib/libSystem.B.dylib"}, + Entry{"__cxa_finalize" , "/usr/lib/libSystem.B.dylib"}, + Entry{"__cxa_pure_virtual" , "/usr/lib/libSystem.B.dylib"}, + Entry{"__cxa_throw" , "/usr/lib/libSystem.B.dylib"}, + Entry{"__stack_chk_fail" , "/usr/lib/libSystem.B.dylib"}, + Entry{"_exit" , "/usr/lib/libSystem.B.dylib"}, + Entry{"abort" , "/usr/lib/libSystem.B.dylib"}, + Entry{"abs" , "/usr/lib/libSystem.B.dylib"}, + Entry{"accept" , "/usr/lib/libSystem.B.dylib"}, + Entry{"acos" , "/usr/lib/libSystem.B.dylib"}, + Entry{"acosf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"acosh" , "/usr/lib/libSystem.B.dylib"}, + Entry{"acoshf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"aligned_alloc" , "/usr/lib/libSystem.B.dylib"}, + Entry{"asin" , "/usr/lib/libSystem.B.dylib"}, + Entry{"asinf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"asinh" , "/usr/lib/libSystem.B.dylib"}, + Entry{"asinhf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"asprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atan" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atan2" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atan2f" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atanf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atanh" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atanhf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atof" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atoi" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atol" , "/usr/lib/libSystem.B.dylib"}, + Entry{"atoll" , "/usr/lib/libSystem.B.dylib"}, + Entry{"bind" , "/usr/lib/libSystem.B.dylib"}, + Entry{"bsearch" , "/usr/lib/libSystem.B.dylib"}, + Entry{"calloc" , "/usr/lib/libSystem.B.dylib"}, + Entry{"cbrt" , "/usr/lib/libSystem.B.dylib"}, + Entry{"cbrtf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ceil" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ceilf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"chdir" , "/usr/lib/libSystem.B.dylib"}, + Entry{"chmod" , "/usr/lib/libSystem.B.dylib"}, + Entry{"chown" , "/usr/lib/libSystem.B.dylib"}, + Entry{"clearerr" , "/usr/lib/libSystem.B.dylib"}, + Entry{"clock" , "/usr/lib/libSystem.B.dylib"}, + Entry{"clock_getres" , "/usr/lib/libSystem.B.dylib"}, + Entry{"clock_gettime" , "/usr/lib/libSystem.B.dylib"}, + Entry{"close" , "/usr/lib/libSystem.B.dylib"}, + Entry{"closedir" , "/usr/lib/libSystem.B.dylib"}, + Entry{"connect" , "/usr/lib/libSystem.B.dylib"}, + Entry{"copysign" , "/usr/lib/libSystem.B.dylib"}, + Entry{"copysignf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"cos" , "/usr/lib/libSystem.B.dylib"}, + Entry{"cosf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"cosh" , "/usr/lib/libSystem.B.dylib"}, + Entry{"coshf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"div" , "/usr/lib/libSystem.B.dylib"}, + Entry{"dladdr" , "/usr/lib/libSystem.B.dylib"}, + Entry{"dlclose" , "/usr/lib/libSystem.B.dylib"}, + Entry{"dlerror" , "/usr/lib/libSystem.B.dylib"}, + Entry{"dlopen" , "/usr/lib/libSystem.B.dylib"}, + Entry{"dlsym" , "/usr/lib/libSystem.B.dylib"}, + Entry{"dup" , "/usr/lib/libSystem.B.dylib"}, + Entry{"dup2" , "/usr/lib/libSystem.B.dylib"}, + Entry{"exit" , "/usr/lib/libSystem.B.dylib"}, + Entry{"exp" , "/usr/lib/libSystem.B.dylib"}, + Entry{"exp2" , "/usr/lib/libSystem.B.dylib"}, + Entry{"exp2f" , "/usr/lib/libSystem.B.dylib"}, + Entry{"expf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"expm1" , "/usr/lib/libSystem.B.dylib"}, + Entry{"expm1f" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fabs" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fabsf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fchdir" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fchmod" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fclose" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fcntl" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fdatasync" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fdopen" , "/usr/lib/libSystem.B.dylib"}, + Entry{"feof" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ferror" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fflush" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fgetc" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fgets" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fileno" , "/usr/lib/libSystem.B.dylib"}, + Entry{"floor" , "/usr/lib/libSystem.B.dylib"}, + Entry{"floorf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fma" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fmaf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fmax" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fmaxf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fmin" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fminf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fmod" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fmodf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fopen" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fork" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fputs" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fread" , "/usr/lib/libSystem.B.dylib"}, + Entry{"free" , "/usr/lib/libSystem.B.dylib"}, + Entry{"freeaddrinfo" , "/usr/lib/libSystem.B.dylib"}, + Entry{"freopen" , "/usr/lib/libSystem.B.dylib"}, + Entry{"frexp" , "/usr/lib/libSystem.B.dylib"}, + Entry{"frexpf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fseek" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fstat" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fsync" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ftruncate" , "/usr/lib/libSystem.B.dylib"}, + Entry{"fwrite" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getaddrinfo" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getc" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getchar" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getcwd" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getenv" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getgid" , "/usr/lib/libSystem.B.dylib"}, + Entry{"gethostbyname" , "/usr/lib/libSystem.B.dylib"}, + Entry{"gethostname" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getnameinfo" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getpeername" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getpid" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getppid" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getsockname" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getsockopt" , "/usr/lib/libSystem.B.dylib"}, + Entry{"gettimeofday" , "/usr/lib/libSystem.B.dylib"}, + Entry{"getuid" , "/usr/lib/libSystem.B.dylib"}, + Entry{"gmtime" , "/usr/lib/libSystem.B.dylib"}, + Entry{"gmtime_r" , "/usr/lib/libSystem.B.dylib"}, + Entry{"htonl" , "/usr/lib/libSystem.B.dylib"}, + Entry{"htons" , "/usr/lib/libSystem.B.dylib"}, + Entry{"hypot" , "/usr/lib/libSystem.B.dylib"}, + Entry{"hypotf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"inet_addr" , "/usr/lib/libSystem.B.dylib"}, + Entry{"inet_ntoa" , "/usr/lib/libSystem.B.dylib"}, + Entry{"inet_ntop" , "/usr/lib/libSystem.B.dylib"}, + Entry{"inet_pton" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ioctl" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isalnum" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isalpha" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isblank" , "/usr/lib/libSystem.B.dylib"}, + Entry{"iscntrl" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isdigit" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isgraph" , "/usr/lib/libSystem.B.dylib"}, + Entry{"islower" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isprint" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ispunct" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isspace" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isupper" , "/usr/lib/libSystem.B.dylib"}, + Entry{"isxdigit" , "/usr/lib/libSystem.B.dylib"}, + Entry{"kill" , "/usr/lib/libSystem.B.dylib"}, + Entry{"labs" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ldexp" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ldexpf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ldiv" , "/usr/lib/libSystem.B.dylib"}, + Entry{"lgamma" , "/usr/lib/libSystem.B.dylib"}, + Entry{"lgammaf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"link" , "/usr/lib/libSystem.B.dylib"}, + Entry{"listen" , "/usr/lib/libSystem.B.dylib"}, + Entry{"llabs" , "/usr/lib/libSystem.B.dylib"}, + Entry{"lldiv" , "/usr/lib/libSystem.B.dylib"}, + Entry{"localtime" , "/usr/lib/libSystem.B.dylib"}, + Entry{"localtime_r" , "/usr/lib/libSystem.B.dylib"}, + Entry{"log" , "/usr/lib/libSystem.B.dylib"}, + Entry{"log10" , "/usr/lib/libSystem.B.dylib"}, + Entry{"log10f" , "/usr/lib/libSystem.B.dylib"}, + Entry{"log2" , "/usr/lib/libSystem.B.dylib"}, + Entry{"log2f" , "/usr/lib/libSystem.B.dylib"}, + Entry{"logf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"lseek" , "/usr/lib/libSystem.B.dylib"}, + Entry{"lstat" , "/usr/lib/libSystem.B.dylib"}, + Entry{"malloc" , "/usr/lib/libSystem.B.dylib"}, + Entry{"memchr" , "/usr/lib/libSystem.B.dylib"}, + Entry{"memcmp" , "/usr/lib/libSystem.B.dylib"}, + Entry{"memcpy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"memmove" , "/usr/lib/libSystem.B.dylib"}, + Entry{"memset" , "/usr/lib/libSystem.B.dylib"}, + Entry{"mkdir" , "/usr/lib/libSystem.B.dylib"}, + Entry{"mkdtemp" , "/usr/lib/libSystem.B.dylib"}, + Entry{"mkstemp" , "/usr/lib/libSystem.B.dylib"}, + Entry{"mktime" , "/usr/lib/libSystem.B.dylib"}, + Entry{"mmap" , "/usr/lib/libSystem.B.dylib"}, + Entry{"modf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"modff" , "/usr/lib/libSystem.B.dylib"}, + Entry{"mprotect" , "/usr/lib/libSystem.B.dylib"}, + Entry{"munmap" , "/usr/lib/libSystem.B.dylib"}, + Entry{"nan" , "/usr/lib/libSystem.B.dylib"}, + Entry{"nanf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"nanosleep" , "/usr/lib/libSystem.B.dylib"}, + Entry{"nearbyint" , "/usr/lib/libSystem.B.dylib"}, + Entry{"nearbyintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"nextafter" , "/usr/lib/libSystem.B.dylib"}, + Entry{"nextafterf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ntohl" , "/usr/lib/libSystem.B.dylib"}, + Entry{"ntohs" , "/usr/lib/libSystem.B.dylib"}, + Entry{"open" , "/usr/lib/libSystem.B.dylib"}, + Entry{"opendir" , "/usr/lib/libSystem.B.dylib"}, + Entry{"perror" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pipe" , "/usr/lib/libSystem.B.dylib"}, + Entry{"poll" , "/usr/lib/libSystem.B.dylib"}, + Entry{"posix_memalign" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pow" , "/usr/lib/libSystem.B.dylib"}, + Entry{"powf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"printf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_attr_destroy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_attr_init" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_attr_setdetachstate", "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_attr_setstacksize" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_barrier_destroy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_barrier_init" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_barrier_wait" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_cancel" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_cond_broadcast" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_cond_destroy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_cond_init" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_cond_signal" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_cond_timedwait" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_cond_wait" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_create" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_detach" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_exit" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_getspecific" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_join" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_key_create" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_key_delete" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_mutex_destroy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_mutex_init" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_mutex_lock" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_mutex_trylock" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_mutex_unlock" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_once" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_rwlock_destroy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_rwlock_init" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_rwlock_rdlock" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_rwlock_unlock" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_rwlock_wrlock" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_self" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_setspecific" , "/usr/lib/libSystem.B.dylib"}, + Entry{"pthread_sigmask" , "/usr/lib/libSystem.B.dylib"}, + Entry{"putchar" , "/usr/lib/libSystem.B.dylib"}, + Entry{"puts" , "/usr/lib/libSystem.B.dylib"}, + Entry{"qsort" , "/usr/lib/libSystem.B.dylib"}, + Entry{"raise" , "/usr/lib/libSystem.B.dylib"}, + Entry{"rand" , "/usr/lib/libSystem.B.dylib"}, + Entry{"read" , "/usr/lib/libSystem.B.dylib"}, + Entry{"readdir" , "/usr/lib/libSystem.B.dylib"}, + Entry{"readlink" , "/usr/lib/libSystem.B.dylib"}, + Entry{"realloc" , "/usr/lib/libSystem.B.dylib"}, + Entry{"recv" , "/usr/lib/libSystem.B.dylib"}, + Entry{"recvfrom" , "/usr/lib/libSystem.B.dylib"}, + Entry{"remainder" , "/usr/lib/libSystem.B.dylib"}, + Entry{"remainderf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"rename" , "/usr/lib/libSystem.B.dylib"}, + Entry{"rint" , "/usr/lib/libSystem.B.dylib"}, + Entry{"rintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"rmdir" , "/usr/lib/libSystem.B.dylib"}, + Entry{"round" , "/usr/lib/libSystem.B.dylib"}, + Entry{"roundf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"scalbn" , "/usr/lib/libSystem.B.dylib"}, + Entry{"scalbnf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"select" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_close" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_destroy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_init" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_open" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_post" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_timedwait" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_trywait" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_unlink" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sem_wait" , "/usr/lib/libSystem.B.dylib"}, + Entry{"send" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sendto" , "/usr/lib/libSystem.B.dylib"}, + Entry{"setenv" , "/usr/lib/libSystem.B.dylib"}, + Entry{"setsockopt" , "/usr/lib/libSystem.B.dylib"}, + Entry{"shutdown" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sigaction" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sigemptyset" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sigfillset" , "/usr/lib/libSystem.B.dylib"}, + Entry{"signal" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sin" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sinf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sinh" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sinhf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sleep" , "/usr/lib/libSystem.B.dylib"}, + Entry{"snprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"socket" , "/usr/lib/libSystem.B.dylib"}, + Entry{"socketpair" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sqrt" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sqrtf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"srand" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sscanf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"stat" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strcat" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strchr" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strcmp" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strcpy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strcspn" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strdup" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strerror" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strftime" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strlen" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strncat" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strncmp" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strncpy" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strndup" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strnlen" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strpbrk" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strrchr" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strspn" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strstr" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strtod" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strtof" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strtok" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strtok_r" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strtol" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strtoll" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strtoul" , "/usr/lib/libSystem.B.dylib"}, + Entry{"strtoull" , "/usr/lib/libSystem.B.dylib"}, + Entry{"symlink" , "/usr/lib/libSystem.B.dylib"}, + Entry{"sysconf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"tan" , "/usr/lib/libSystem.B.dylib"}, + Entry{"tanf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"tanh" , "/usr/lib/libSystem.B.dylib"}, + Entry{"tanhf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"tgamma" , "/usr/lib/libSystem.B.dylib"}, + Entry{"tgammaf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"time" , "/usr/lib/libSystem.B.dylib"}, + Entry{"tolower" , "/usr/lib/libSystem.B.dylib"}, + Entry{"toupper" , "/usr/lib/libSystem.B.dylib"}, + Entry{"trunc" , "/usr/lib/libSystem.B.dylib"}, + Entry{"truncate" , "/usr/lib/libSystem.B.dylib"}, + Entry{"truncf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"umask" , "/usr/lib/libSystem.B.dylib"}, + Entry{"uname" , "/usr/lib/libSystem.B.dylib"}, + Entry{"unlink" , "/usr/lib/libSystem.B.dylib"}, + Entry{"unsetenv" , "/usr/lib/libSystem.B.dylib"}, + Entry{"usleep" , "/usr/lib/libSystem.B.dylib"}, + Entry{"vasprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"vfprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"vprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"vsnprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"vsprintf" , "/usr/lib/libSystem.B.dylib"}, + Entry{"wait" , "/usr/lib/libSystem.B.dylib"}, + Entry{"waitpid" , "/usr/lib/libSystem.B.dylib"}, + Entry{"wcslen" , "/usr/lib/libSystem.B.dylib"}, + Entry{"write" , "/usr/lib/libSystem.B.dylib"}, +}; + +template +static std::string_view lookup(const Table& table, std::string_view name) { + auto it = std::lower_bound( + table.begin(), table.end(), name, + [](const Entry& e, std::string_view n) { return e.name < n; }); + if (it != table.end() && it->name == name) return it->library; + return {}; +} + +} // namespace + +namespace voidlibc::voidlink { + +std::string_view library_for(voidlibc::format::TargetOS os, std::string_view name) { + using voidlibc::format::TargetOS; + switch (os) { + case TargetOS::Linux: return lookup(linux_table, name); + case TargetOS::Windows: return lookup(windows_table, name); + case TargetOS::MacOS: return lookup(macos_table, name); + default: return {}; + } +} + +std::string_view default_library(voidlibc::format::TargetOS os) { + using voidlibc::format::TargetOS; + switch (os) { + case TargetOS::Linux: return "libc.so.6"; + case TargetOS::Windows: return "ucrtbase.dll"; + case TargetOS::MacOS: return "/usr/lib/libSystem.B.dylib"; + default: return ""; + } +} + +} // namespace voidlibc::voidlink diff --git a/voidlink/symlib_table.hpp b/voidlink/symlib_table.hpp new file mode 100644 index 0000000..a96e3fe --- /dev/null +++ b/voidlink/symlib_table.hpp @@ -0,0 +1,20 @@ +#pragma once +// Per-OS symbol → import library table. +// Source of truth: data/symlib_{linux,windows,macos}.txt + +#include "format/vlc_format.hpp" + +#include + +namespace voidlibc::voidlink { + +// Returns the import library for `name` on the given OS. +// Checks the builtin table; returns "" if not found (caller should use the +// per-OS default: libc.so.6 / ucrtbase.dll / /usr/lib/libSystem.B.dylib). +std::string_view library_for(voidlibc::format::TargetOS os, std::string_view name); + +// Returns the per-OS default import library used as a fallback when no +// table entry is found. +std::string_view default_library(voidlibc::format::TargetOS os); + +} // namespace voidlibc::voidlink diff --git a/voidlink/writer.cpp b/voidlink/writer.cpp new file mode 100644 index 0000000..6efa851 --- /dev/null +++ b/voidlink/writer.cpp @@ -0,0 +1,46 @@ +#include "writer.hpp" + +#include "format/vlc_format.hpp" + +#include + +namespace voidlibc::voidlink { + +using namespace voidlibc::format; + +WriteResult write_empty(const std::filesystem::path& out_path) { + std::ofstream out(out_path, std::ios::binary | std::ios::trunc); + if (!out) { + return {false, "could not open output: " + out_path.string()}; + } + + FileHeader hdr{}; + hdr.magic = kMagic; + hdr.version_major = kVersionMajor; + hdr.version_minor = kVersionMinor; + hdr.flags = static_cast(ContainerFlags::None); + hdr.arch = TargetArch::X86_64; + hdr.reserved = 0; + hdr.section_count = 0; + + // Everything after the header is empty; point offsets at the end of + // the header so a reader walking pointers lands on valid, zero-size + // regions instead of stale zeros. + const std::uint64_t tail = sizeof(FileHeader); + hdr.section_dir_off = tail; + hdr.symtab_off = tail; + hdr.symtab_size = 0; + hdr.imports_off = tail; + hdr.imports_size = 0; + hdr.exports_off = tail; + hdr.exports_size = 0; + hdr.file_size = tail; + + out.write(reinterpret_cast(&hdr), sizeof(hdr)); + if (!out) { + return {false, "write failed"}; + } + return {true, {}}; +} + +} // namespace voidlibc::voidlink diff --git a/voidlink/writer.hpp b/voidlink/writer.hpp new file mode 100644 index 0000000..6e5a85c --- /dev/null +++ b/voidlink/writer.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +namespace voidlibc::voidlink { + +struct WriteResult { + bool ok = false; + std::string error; +}; + +// Writes a syntactically-valid .vlc containing no sections, no symbols, +// no imports, no exports. Used for M0 round-trip testing of the format. +WriteResult write_empty(const std::filesystem::path& out_path); + +} // namespace voidlibc::voidlink diff --git a/voidloader/CMakeLists.txt b/voidloader/CMakeLists.txt new file mode 100644 index 0000000..4dad613 --- /dev/null +++ b/voidloader/CMakeLists.txt @@ -0,0 +1,7 @@ +add_executable(voidloader main.cpp) +target_include_directories(voidloader PRIVATE + ${CMAKE_SOURCE_DIR}/libvoid +) +target_link_libraries(voidloader PRIVATE void) + +install(TARGETS voidloader RUNTIME DESTINATION bin) diff --git a/voidloader/main.cpp b/voidloader/main.cpp new file mode 100644 index 0000000..05fd07f --- /dev/null +++ b/voidloader/main.cpp @@ -0,0 +1,104 @@ +// voidloader — exec-mode entry for .vle files. +// +// Usage: voidloader [args...] +// +// Loads the .vle as a native DSO via libvoid's internal API, resolves its +// "main" symbol, and calls it as main(argc, argv) where argv[0] is the path. +// Registered with the kernel via binfmt_misc so that `./hello.vle args` +// transparently invokes this binary (see installer/linux/). + +#include "internal.h" + +#include +#include +#include + +#if defined(_WIN32) +# define WIN32_LEAN_AND_MEAN +# include + +static const char* vlc_error_string() { + static char buf[512]; + const DWORD err = ::GetLastError(); + if (err == 0) return "unknown error"; + ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, err, 0, buf, sizeof(buf) - 1, nullptr); + for (char* p = buf; *p; ++p) { + if (*p == '\r' || *p == '\n') { *p = '\0'; break; } + } + return buf; +} +# define VLC_SYM(h, name) \ + reinterpret_cast(::GetProcAddress(static_cast(h), (name))) +# define VLC_CLOSE(h) ::FreeLibrary(static_cast(h)) +# define VLC_ERROR() vlc_error_string() +#else +# include +# define VLC_SYM(h, name) ::dlsym((h), (name)) +# define VLC_CLOSE(h) ::dlclose(h) +# define VLC_ERROR() ::dlerror() +#endif + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, + "usage: voidloader [args...]\n" + "\n" + "Load and run a VoidLibC executable in exec mode.\n" + "The .vle's main(argc, argv) is called; argv[0] is the .vle path.\n"); + return 2; + } + + const char* vlc_path = argv[1]; + + // Peek at the header to confirm this is an executable VLC, not a library. + { + std::FILE* f = std::fopen(vlc_path, "rb"); + if (!f) { + std::fprintf(stderr, "voidloader: %s: cannot open\n", vlc_path); + return 1; + } + // FileHeader layout: magic(4) + version_major(2) + version_minor(2) + flags(4) + std::uint8_t hdr[12] = {}; + const bool ok = std::fread(hdr, 1, sizeof(hdr), f) == sizeof(hdr); + std::fclose(f); + if (!ok) { + std::fprintf(stderr, "voidloader: %s: too small\n", vlc_path); + return 1; + } + std::uint32_t flags = 0; + std::memcpy(&flags, hdr + 8, 4); + constexpr std::uint32_t kExecutable = 1u << 2; + if (!(flags & kExecutable)) { + std::fprintf(stderr, + "voidloader: %s: not an executable (missing Executable flag)\n" + " Shared libraries (.vls) should be loaded via dlopen().\n" + " Static archives (.vla) should be linked with voidlink.\n", + vlc_path); + return 1; + } + } + + // Use the internal API to bypass the dlopen interposer's allow_exec check. + void* h = voidlibc::detail::load_vlc(vlc_path, /*allow_exec=*/true); + if (!h) { + const char* err = VLC_ERROR(); + std::fprintf(stderr, "voidloader: %s: %s\n", + vlc_path, err ? err : "unknown error"); + return 1; + } + + using MainFn = int (*)(int, char**); + auto* entry = reinterpret_cast(VLC_SYM(h, "main")); + if (!entry) { + std::fprintf(stderr, + "voidloader: %s: no exported 'main' symbol\n", vlc_path); + VLC_CLOSE(h); + return 1; + } + + // argv[1] becomes the loaded program's argv[0]; remaining args follow. + const int rc = entry(argc - 1, argv + 1); + VLC_CLOSE(h); + return rc; +}