commit
bba5c8a39a
109 files changed
+14085
No files matched your search
@@ -0,0 +1 @@
|
||||
build
|
||||
+326
@@ -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
|
||||
+127
@@ -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
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
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()
|
||||
@@ -0,0 +1 @@
|
||||
---
|
||||
@@ -0,0 +1,3 @@
|
||||
Start testing: May 18 15:22 MSK
|
||||
----------------------------------------------------------
|
||||
End testing: May 18 15:22 MSK
|
||||
@@ -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:
|
||||
# <bindir>/<target>.vls or <bindir>/<target>.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 <tgt_var> (name for generator expressions) and <dep_var> (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 <out_var> 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 <target>.vls or <target>.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 $<TARGET_FILE:${_vl_tgt}>)
|
||||
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 $<TARGET_FILE:${_vl_tgt}>
|
||||
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 $<TARGET_FILE:${_vl_tgt}>
|
||||
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 <target>.vls / <target>.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(<target> <entry-symbol>)
|
||||
# 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(<platform> <cc_kind> <cc_bin> <target_triple>
|
||||
# <sources_abs> <stem_prefix> <outdir>
|
||||
# <compile_opts> <inc_flags>
|
||||
# <obj_list_var>)
|
||||
#
|
||||
# Internal helper: compile each source for one platform and append objects to <obj_list_var>.
|
||||
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(<tgt>
|
||||
# SOURCES <src>...
|
||||
# [TARGETS linux|windows|macos...]
|
||||
# [LINUX_NEEDS <soname>...] # DT_NEEDED entries for Linux section
|
||||
# [WINDOWS_NEEDS <dll>...] # import DLLs for Windows section
|
||||
# [MACOS_NEEDS <install-name>...] # LC_LOAD_DYLIB entries for macOS section
|
||||
# [LINUX_SYMLIBS <sym=lib>...] # --symlib overrides for Linux
|
||||
# [WINDOWS_SYMLIBS <sym=lib>...] # --symlib overrides for Windows
|
||||
# [MACOS_SYMLIBS <sym=lib>...] # --symlib overrides for macOS
|
||||
# [STRICT_LIBS] # promote unresolved symbols to errors
|
||||
# )
|
||||
#
|
||||
# Cross-compiles SOURCES for each requested target OS and fuses them into
|
||||
# <CMAKE_CURRENT_BINARY_DIR>/<tgt>.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 $<TARGET_FILE:${_vl_tgt}>
|
||||
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(<tgt>
|
||||
# ENTRY <symbol>
|
||||
# SOURCES <src>...
|
||||
# [same optional keyword args as void_add_universal_library]
|
||||
# )
|
||||
#
|
||||
# Like void_add_universal_library but produces <tgt>.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 $<TARGET_FILE:${_vl_tgt}>
|
||||
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(<sym> <linux-lib> <windows-lib> <macos-lib>)
|
||||
# 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()
|
||||
@@ -0,0 +1,11 @@
|
||||
@PACKAGE_INIT@
|
||||
|
||||
# Bring in the auto-VLC hook so consumers can call:
|
||||
# voidlibc_enable_auto_vlc()
|
||||
# voidlibc_vlc_executable(<target> <entry>)
|
||||
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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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=<voidlibc>/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)
|
||||
@@ -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=<voidlibc>/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)
|
||||
@@ -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=<voidlibc>/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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,487 @@
|
||||
# Linux symbol → import library table.
|
||||
# Format: <symbol> <library-soname>
|
||||
# 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
|
||||
@@ -0,0 +1,359 @@
|
||||
# macOS symbol → import dylib table.
|
||||
# Format: <symbol> <dylib-install-name>
|
||||
# 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
|
||||
@@ -0,0 +1,458 @@
|
||||
# Windows symbol → import DLL table.
|
||||
# Format: <symbol> <DLL-name>
|
||||
# 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
|
||||
+204
@@ -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 `<dlfcn.h>`. 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 <dlfcn.h>
|
||||
|
||||
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`, `<builddir>/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
|
||||
+-------------------------------+ <symtab_off>
|
||||
| SymbolTableHeader |
|
||||
| SymbolEntry[...] | 36 bytes each
|
||||
| name pool (UTF-8) |
|
||||
+-------------------------------+ <reloc chunks, per section>
|
||||
| RelocChunk + RelocEntry[] | see reloc-ir.md
|
||||
+-------------------------------+ <per-OS code, per section>
|
||||
| raw machine code (PIC) |
|
||||
+-------------------------------+ <per-OS debug, per section, optional>
|
||||
| DWARF / PDB / DWARF blob |
|
||||
+-------------------------------+ <imports_off>
|
||||
| ImportsHeader + ... | (M1)
|
||||
+-------------------------------+ <exports_off>
|
||||
| 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`.
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
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
|
||||
@@ -0,0 +1,162 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
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<std::uint32_t>(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
|
||||
@@ -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:
|
||||
Executable
+101
@@ -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"
|
||||
@@ -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 <file>
|
||||
# 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
|
||||
Executable
+38
@@ -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"
|
||||
Executable
+47
@@ -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."
|
||||
@@ -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"
|
||||
@@ -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."
|
||||
@@ -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"
|
||||
@@ -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."
|
||||
@@ -0,0 +1,24 @@
|
||||
add_library(void STATIC
|
||||
api.cpp
|
||||
)
|
||||
target_include_directories(void
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_SOURCE_DIR}>
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
# 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
|
||||
$<$<BOOL:${UNIX}>:$<IF:$<PLATFORM_ID:Darwin>,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
|
||||
)
|
||||
+464
@@ -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 <dlfcn.h>
|
||||
#elif defined(__APPLE__)
|
||||
# include "loader/macos/macho_synth.hpp"
|
||||
# include "loader/macos/handoff.hpp"
|
||||
# include <dlfcn.h>
|
||||
#elif defined(_WIN32)
|
||||
# include "loader/windows/pe_synth.hpp"
|
||||
# include "loader/windows/handoff.hpp"
|
||||
# include <filesystem>
|
||||
#else
|
||||
# error "libvoid: unsupported platform"
|
||||
#endif
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t>& 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<std::streamsize>(in.tellg());
|
||||
in.seekg(0, std::ios::beg);
|
||||
out.resize(static_cast<std::size_t>(size));
|
||||
in.read(reinterpret_cast<char*>(out.data()), size);
|
||||
if (!in) {
|
||||
set_error("short read");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct ParsedVlc {
|
||||
FileHeader hdr;
|
||||
std::vector<SectionEntry> sections;
|
||||
std::vector<SymbolEntry> symbols;
|
||||
std::vector<char> name_pool;
|
||||
std::vector<std::vector<RelocEntry>> section_relocs;
|
||||
};
|
||||
|
||||
bool parse_vlc(const std::vector<std::uint8_t>& 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<std::uint64_t>(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<std::uint64_t>(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<const char*>(data.data() + pool_off),
|
||||
reinterpret_cast<const char*>(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<std::uint64_t>(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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint16_t>(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<SymInfo> 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<std::uint8_t>(SymbolFlags::Exported)) != 0;
|
||||
s.is_data = (sym.flags & static_cast<std::uint8_t>(SymbolFlags::DataSection)) != 0;
|
||||
s.weak = (sym.flags & static_cast<std::uint8_t>(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<voidlibc::format::RelocEntry> 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<std::uint8_t>('V'),
|
||||
static_cast<std::uint8_t>('L'),
|
||||
static_cast<std::uint8_t>('C'),
|
||||
static_cast<std::uint8_t>('\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<real_t>(::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<real_t>(::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__
|
||||
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
add_subdirectory(common)
|
||||
add_subdirectory(linux)
|
||||
add_subdirectory(windows)
|
||||
add_subdirectory(macos)
|
||||
@@ -0,0 +1,14 @@
|
||||
add_library(voidlibc_loader_common STATIC
|
||||
elf_synth.cpp
|
||||
)
|
||||
target_include_directories(voidlibc_loader_common PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_SOURCE_DIR}>
|
||||
$<BUILD_INTERFACE:${CMAKE_SOURCE_DIR}/loader>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
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
|
||||
)
|
||||
@@ -0,0 +1,216 @@
|
||||
#pragma once
|
||||
|
||||
// Minimal x86_64 ELF64 definitions, in-tree to avoid <elf.h> noise.
|
||||
// Only the subset we synthesize is here.
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
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<std::uint32_t>(info >> 32); }
|
||||
inline constexpr std::uint32_t r_type(std::uint64_t info) { return static_cast<std::uint32_t>(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<std::uint8_t>((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<std::uint8_t>(*name++);
|
||||
const std::uint32_t g = h & 0xF0000000u;
|
||||
if (g) h ^= g >> 24;
|
||||
h &= ~g;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
} // namespace voidlibc::loader
|
||||
@@ -0,0 +1,816 @@
|
||||
#include "elf_synth.hpp"
|
||||
|
||||
#include "elf64.hpp"
|
||||
#include "format/reloc_ir.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
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<std::uint8_t>& buf, std::uint64_t off, std::int32_t v) {
|
||||
std::uint32_t u;
|
||||
std::memcpy(&u, &v, 4);
|
||||
buf[off + 0] = static_cast<std::uint8_t>(u);
|
||||
buf[off + 1] = static_cast<std::uint8_t>(u >> 8);
|
||||
buf[off + 2] = static_cast<std::uint8_t>(u >> 16);
|
||||
buf[off + 3] = static_cast<std::uint8_t>(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<std::uint8_t>& combined,
|
||||
const std::vector<voidlibc::format::RelocEntry>& relocs,
|
||||
const std::vector<InternalSymbol>& internal_syms,
|
||||
const std::vector<DataSymbol>& data_syms,
|
||||
const std::unordered_map<std::uint32_t, std::uint32_t>& import_to_plt,
|
||||
const std::unordered_map<std::uint32_t, std::uint64_t>& 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<std::uint32_t, std::uint64_t> 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<std::uint32_t, std::uint64_t> 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<std::int32_t>(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<std::int64_t>(target_combined)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(data_vaddr + dit->second)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(target)
|
||||
- static_cast<std::int64_t>(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<std::uint64_t>(it->second + 1) * 16;
|
||||
const std::int64_t disp =
|
||||
static_cast<std::int64_t>(plt_stub)
|
||||
+ r.addend
|
||||
- static_cast<std::int64_t>(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<unsigned>(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<std::int64_t>(target)
|
||||
- static_cast<std::int64_t>(combined_off)
|
||||
+ r.addend;
|
||||
} else {
|
||||
disp = static_cast<std::int64_t>(data_vaddr + it_data->second)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(git->second)
|
||||
- static_cast<std::int64_t>(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<std::uint8_t>& 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<std::int32_t>(
|
||||
(gotplt_vaddr + 8) - (plt0_vaddr + 6));
|
||||
write32le(combined, 2, d1);
|
||||
combined[6] = 0xff; combined[7] = 0x25;
|
||||
const std::int32_t d2 = static_cast<std::int32_t>(
|
||||
(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<std::uint64_t>(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<std::int32_t>(
|
||||
(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<std::int32_t>(static_cast<std::uint32_t>(i)));
|
||||
combined[stub_off + 11] = 0xe9;
|
||||
const std::int32_t dp = static_cast<std::int32_t>(
|
||||
static_cast<std::int64_t>(code_vaddr)
|
||||
- static_cast<std::int64_t>(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<std::uint32_t> internal_sym_ids;
|
||||
for (const auto& s : input.internal_symbols) internal_sym_ids.insert(s.sym_id);
|
||||
std::unordered_set<std::uint32_t> 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<std::uint32_t, std::uint32_t> import_to_plt;
|
||||
// GOT-data imports (external sym referenced via GotPC32*; slot index within .got).
|
||||
std::unordered_map<std::uint32_t, std::uint32_t> 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<std::uint32_t>(got_data_import_to_slot.size());
|
||||
|
||||
// --- Build combined buffer: [PLT stubs][.text + .rodata] ---
|
||||
const std::uint64_t plt_size = nimports > 0
|
||||
? static_cast<std::uint64_t>(1 + nimports) * 16
|
||||
: 0;
|
||||
std::vector<std::uint8_t> 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<std::uint32_t, std::uint64_t> 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<char> dynstr;
|
||||
dynstr.push_back('\0');
|
||||
|
||||
std::vector<std::uint32_t> export_name_offs;
|
||||
export_name_offs.reserve(input.exports.size());
|
||||
for (const auto& e : input.exports) {
|
||||
export_name_offs.push_back(static_cast<std::uint32_t>(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<std::uint32_t> import_name_offs;
|
||||
import_name_offs.reserve(input.imports.size());
|
||||
for (const auto& im : input.imports) {
|
||||
import_name_offs.push_back(static_cast<std::uint32_t>(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<std::uint32_t> needed_name_offs;
|
||||
{
|
||||
std::vector<std::string> libs;
|
||||
if (!input.needed_libs.empty()) {
|
||||
libs = input.needed_libs;
|
||||
} else {
|
||||
// Collect unique libraries in insertion order.
|
||||
std::vector<std::string> seen_order;
|
||||
std::unordered_map<std::string, bool> 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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t, std::uint32_t> 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<std::uint32_t>(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<VerEntry> ver_entries; // unique versioned requirements, in order
|
||||
// per-import version index (parallel to input.imports); 1 if unversioned
|
||||
std::vector<std::uint16_t> 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<std::string, std::uint16_t> 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<std::uint8_t> gnu_version_bytes;
|
||||
// Build .gnu.version_r bytes: grouped by library.
|
||||
std::vector<std::uint8_t> 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<std::string> vn_libs_order;
|
||||
std::unordered_map<std::string, std::vector<std::size_t>> 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<std::size_t>{});
|
||||
if (inserted) vn_libs_order.push_back(ver_entries[i].library);
|
||||
it->second.push_back(i);
|
||||
}
|
||||
n_verneed = static_cast<std::uint32_t>(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<std::uint32_t> ver_offs; };
|
||||
std::vector<VnStrings> vn_strs;
|
||||
for (const auto& lib : vn_libs_order) {
|
||||
VnStrings vs;
|
||||
vs.lib_off = static_cast<std::uint32_t>(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<std::uint32_t>(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<std::uint16_t>(idxs.size());
|
||||
vn.vn_file = vstrs.lib_off;
|
||||
vn.vn_aux = sizeof(Verneed);
|
||||
vn.vn_next = last_lib ? 0u
|
||||
: static_cast<std::uint32_t>(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<std::uint32_t>(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<std::uint64_t>(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<std::uint32_t>(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> 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<std::uint64_t>(kDtRela));
|
||||
add_dyn(kDtJmpRel, relaplt_off);
|
||||
}
|
||||
if (needs_versioning) {
|
||||
add_dyn(kDtVersym, gnuver_off);
|
||||
add_dyn(kDtVerneed, gnuvnr_off);
|
||||
add_dyn(kDtVerneedNum, static_cast<std::uint64_t>(n_verneed));
|
||||
}
|
||||
add_dyn(kDtFlags, static_cast<std::uint64_t>(kDfBindNow));
|
||||
add_dyn(kDtFlags1, static_cast<std::uint64_t>(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<Sym> 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<std::uint32_t> 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<std::uint32_t>(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> 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<std::uint64_t>(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<const ImportedSymbol*> 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> 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
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include "format/reloc_ir.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t> code;
|
||||
std::vector<ExportedSymbol> exports;
|
||||
std::vector<voidlibc::format::RelocEntry> relocs;
|
||||
std::vector<InternalSymbol> internal_symbols;
|
||||
std::vector<ImportedSymbol> imports;
|
||||
std::vector<std::uint8_t> data_blob; // .data + .bss (RW)
|
||||
std::vector<DataSymbol> 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 <soname> at pack time.
|
||||
std::vector<std::string> needed_libs;
|
||||
};
|
||||
|
||||
struct ElfSynthOutput {
|
||||
std::vector<std::uint8_t> 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
|
||||
@@ -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
|
||||
)
|
||||
@@ -0,0 +1,136 @@
|
||||
#include "handoff.hpp"
|
||||
|
||||
#ifdef __linux__
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
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<int>(::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<std::size_t>(w);
|
||||
n -= static_cast<std::size_t>(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<std::uint8_t>& 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<real_dlopen_t>(::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<std::uint8_t>&, 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__
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t>& elf_bytes,
|
||||
const char* debug_name = "voidlibc.elf");
|
||||
|
||||
// Thin wrappers so the caller never includes <dlfcn.h>.
|
||||
void* sym(void* handle, const char* name);
|
||||
int close_(void* handle);
|
||||
|
||||
} // namespace voidlibc::loader::linux_handoff
|
||||
@@ -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
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
#include "handoff.hpp"
|
||||
|
||||
#ifdef __APPLE__
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace voidlibc::loader::macos_handoff {
|
||||
|
||||
LoadResult dlopen_buffer(const std::vector<std::uint8_t>& 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<int>(::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<std::size_t>(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<std::uint8_t>&) {
|
||||
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__
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t>& blob);
|
||||
|
||||
void* sym(void* handle, const char* name);
|
||||
int close_(void* handle);
|
||||
|
||||
} // namespace voidlibc::loader::macos_handoff
|
||||
@@ -0,0 +1,677 @@
|
||||
#include "macho_synth.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
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<std::uint8_t>& 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<std::uint8_t>& b, std::uint64_t v) {
|
||||
b.push_back(static_cast<std::uint8_t>((v & 0x7f) | 0x80));
|
||||
b.push_back(static_cast<std::uint8_t>((v >> 7) & 0x7f));
|
||||
}
|
||||
|
||||
static void write32le(std::vector<std::uint8_t>& 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<std::uint8_t> build_export_trie(
|
||||
const std::vector<MachoExportedSymbol>& exports,
|
||||
std::uint64_t text_sect_vmaddr) {
|
||||
if (exports.empty()) return {0, 0};
|
||||
|
||||
struct Leaf { std::string name; std::vector<std::uint8_t> bytes; };
|
||||
std::vector<Leaf> leaves;
|
||||
for (const auto& e : exports) {
|
||||
Leaf lf; lf.name = e.name;
|
||||
std::vector<std::uint8_t> 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<std::size_t> leaf_offs;
|
||||
std::size_t cursor = root_sz;
|
||||
for (const auto& lf : leaves) { leaf_offs.push_back(cursor); cursor += lf.bytes.size(); }
|
||||
|
||||
std::vector<std::uint8_t> trie;
|
||||
trie.push_back(0); // not terminal
|
||||
trie.push_back(static_cast<std::uint8_t>(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<std::uint8_t> build_bind_opcodes(
|
||||
const std::vector<const MachoImportedSymbol*>& ordered_imports,
|
||||
const std::unordered_map<std::string, int>& 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<std::uint8_t> 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<std::uint8_t>(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<std::uint32_t> 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<std::uint32_t, std::uint32_t> 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<std::uint32_t>(imp_to_stub.size());
|
||||
const auto ngot = static_cast<std::uint32_t>(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<std::uint32_t>(
|
||||
(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<std::uint32_t>(
|
||||
align_up(8u + 16u + dylib_name.size() + 1u, 4u));
|
||||
|
||||
std::vector<std::string> 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<std::string, bool> 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<std::string, int> lib_ordinal;
|
||||
for (std::size_t i = 0; i < needed_libs.size(); ++i)
|
||||
lib_ordinal[needed_libs[i]] = static_cast<int>(i + 1);
|
||||
|
||||
std::vector<std::uint32_t> loaddylib_szs;
|
||||
for (const auto& lib : needed_libs)
|
||||
loaddylib_szs.push_back(static_cast<std::uint32_t>(
|
||||
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<const MachoImportedSymbol*> stub_order(nstubs, nullptr);
|
||||
std::vector<const MachoImportedSymbol*> 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<const MachoImportedSymbol*> 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<char> strtab; strtab.push_back(0);
|
||||
std::vector<NList64> nlist;
|
||||
|
||||
const std::uint32_t iextdefsym = 0;
|
||||
for (const auto& e : input.exports) {
|
||||
NList64 n{};
|
||||
n.n_strx = static_cast<std::uint32_t>(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<std::uint32_t>(nlist.size());
|
||||
for (const auto& im : input.imports) {
|
||||
NList64 n{};
|
||||
n.n_strx = static_cast<std::uint32_t>(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<std::uint8_t> code_buf(input.code);
|
||||
|
||||
// Build stub bytes (6-byte JMP stubs → nl_symbol_ptr slots).
|
||||
// Each stub: FF 25 <disp32> (jmpq *slot(%rip))
|
||||
// Stubs use slots [0..nstubs-1] in nl_symbol_ptr.
|
||||
std::vector<std::uint8_t> 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<std::int32_t>(
|
||||
static_cast<std::int64_t>(slot_va) - static_cast<std::int64_t>(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<std::uint32_t, std::uint64_t> 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<std::int64_t>(ic->second)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(id->second)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(ic->second)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(sv)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(tv)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(sv)
|
||||
- static_cast<std::int64_t>(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<std::int32_t>(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<std::uint32_t>(needed_libs.size());
|
||||
|
||||
MachHeader64 mh{};
|
||||
mh.magic = kMhMagic64;
|
||||
mh.cputype_u = static_cast<std::uint32_t>(kCpuTypeX86_64);
|
||||
mh.cpusubtype_u = static_cast<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(bind_off);
|
||||
dc.bind_size = static_cast<std::uint32_t>(bind_bytes.size());
|
||||
dc.export_off = static_cast<std::uint32_t>(exp_off);
|
||||
dc.export_size = static_cast<std::uint32_t>(export_trie.size());
|
||||
emit(&dc, sizeof(dc));
|
||||
}
|
||||
|
||||
// LC_SYMTAB
|
||||
{
|
||||
SymtabCmd sc{};
|
||||
sc.cmd = kLcSymtab; sc.cmdsize = sizeof(sc);
|
||||
sc.symoff = static_cast<std::uint32_t>(sym_off);
|
||||
sc.nsyms = static_cast<std::uint32_t>(nlist.size());
|
||||
sc.stroff = static_cast<std::uint32_t>(str_off);
|
||||
sc.strsize = static_cast<std::uint32_t>(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<std::uint32_t>(nlist.size()) - iundefsym;
|
||||
emit(&dc, sizeof(dc));
|
||||
}
|
||||
|
||||
// LC_ID_DYLIB
|
||||
{
|
||||
std::vector<std::uint8_t> lc_buf(iddylib_sz, 0);
|
||||
auto* u = reinterpret_cast<std::uint32_t*>(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<std::uint8_t> lc_buf(sz, 0);
|
||||
auto* u = reinterpret_cast<std::uint32_t*>(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
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include "format/reloc_ir.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t> code;
|
||||
std::vector<MachoExportedSymbol> exports;
|
||||
std::vector<voidlibc::format::RelocEntry> relocs;
|
||||
std::vector<MachoInternalSymbol> internal_symbols;
|
||||
std::vector<MachoImportedSymbol> imports;
|
||||
std::vector<std::uint8_t> data_blob;
|
||||
std::vector<MachoDataSymbol> 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<std::string> needed_libs;
|
||||
};
|
||||
|
||||
struct MachoSynthOutput {
|
||||
std::vector<std::uint8_t> 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
|
||||
@@ -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)
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "handoff.hpp"
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#else
|
||||
// Stub for non-Windows builds (so the file compiles everywhere).
|
||||
#include <cstdio>
|
||||
#endif
|
||||
|
||||
namespace voidlibc::loader::windows_handoff {
|
||||
|
||||
LoadResult load_pe_buffer(const std::vector<std::uint8_t>& 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<DWORD>(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<void*>(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<void*>(
|
||||
GetProcAddress(static_cast<HMODULE>(handle), name));
|
||||
#else
|
||||
(void)handle; (void)name;
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
void unload(void* handle) {
|
||||
#ifdef _WIN32
|
||||
FreeLibrary(static_cast<HMODULE>(handle));
|
||||
#else
|
||||
(void)handle;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace voidlibc::loader::windows_handoff
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
|
||||
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<std::uint8_t>& 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
|
||||
@@ -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 <algorithm>
|
||||
#include <cstring>
|
||||
#include <unordered_map>
|
||||
|
||||
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<std::uint8_t>& v, std::uint32_t off, std::uint16_t x) {
|
||||
v[off] = static_cast<std::uint8_t>(x);
|
||||
v[off+1] = static_cast<std::uint8_t>(x >> 8);
|
||||
}
|
||||
static void w32(std::vector<std::uint8_t>& v, std::uint32_t off, std::uint32_t x) {
|
||||
v[off] = static_cast<std::uint8_t>(x);
|
||||
v[off+1] = static_cast<std::uint8_t>(x >> 8);
|
||||
v[off+2] = static_cast<std::uint8_t>(x >> 16);
|
||||
v[off+3] = static_cast<std::uint8_t>(x >> 24);
|
||||
}
|
||||
static void w64(std::vector<std::uint8_t>& v, std::uint32_t off, std::uint64_t x) {
|
||||
w32(v, off, static_cast<std::uint32_t>(x));
|
||||
w32(v, off+4, static_cast<std::uint32_t>(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<std::uint8_t>& 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<std::uint32_t>(input.imports.size());
|
||||
const std::uint32_t nexports = static_cast<std::uint32_t>(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<std::uint8_t> 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<std::uint32_t, std::uint32_t> 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<std::uint32_t, std::uint64_t> 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<std::uint32_t, std::uint64_t> 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<std::uint32_t>(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<std::uint8_t> 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<std::uint32_t> import_indices; // indices into input.imports
|
||||
};
|
||||
std::vector<DllGroup> dll_groups;
|
||||
std::unordered_map<std::string, std::size_t> 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<std::uint32_t>(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<std::uint32_t> 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<std::uint32_t, std::uint32_t> 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<std::uint32_t> import_name_rvas(nimports);
|
||||
for (std::uint32_t i = 0; i < nimports; ++i) {
|
||||
const std::uint32_t name_off = static_cast<std::uint32_t>(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<std::uint32_t> dll_name_rvas(ndlls);
|
||||
for (std::uint32_t d = 0; d < ndlls; ++d) {
|
||||
const std::uint32_t off = static_cast<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(rdata.size());
|
||||
rdata.resize(rdata.size() + nexports * 4, 0); // function RVA array
|
||||
|
||||
const std::uint32_t exp_name_rvas_off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.resize(rdata.size() + nexports * 4, 0); // name RVA array
|
||||
|
||||
const std::uint32_t exp_ordinals_off = static_cast<std::uint32_t>(rdata.size());
|
||||
rdata.resize(rdata.size() + nexports * 2, 0); // ordinal array
|
||||
|
||||
// Export name strings.
|
||||
std::vector<std::uint32_t> exp_name_rva(nexports);
|
||||
for (std::uint32_t i = 0; i < nexports; ++i) {
|
||||
exp_name_rva[i] = rdata_rva_of(static_cast<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(rdata.size());
|
||||
rdata.resize(rdata.size() + 40, 0);
|
||||
|
||||
const std::uint32_t rdata_vsz = static_cast<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::uint16_t>(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<std::uint32_t>(text_raw.size())) {
|
||||
reloc_error = "reloc patch out of range";
|
||||
return false;
|
||||
}
|
||||
const std::int32_t v32 = static_cast<std::int32_t>(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<std::uint32_t>(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<std::uint64_t>(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<std::uint64_t>(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<std::int64_t>(thunk_va)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(sym_va_val)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(thunk_va)
|
||||
- static_cast<std::int64_t>(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<std::int64_t>(
|
||||
code_vaddr + it->second) - static_cast<std::int64_t>(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<std::int64_t>(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<std::int64_t>(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 <disp32>
|
||||
// RIP at time of dispatch = stub_va + 6.
|
||||
const std::int64_t disp = static_cast<std::int64_t>(iat_entry_va)
|
||||
- static_cast<std::int64_t>(stub_va + 6);
|
||||
text_raw[stub_off + 0] = 0xFF;
|
||||
text_raw[stub_off + 1] = 0x25;
|
||||
std::int32_t disp32 = static_cast<std::int32_t>(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<std::uint8_t>(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<std::uint32_t>(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<std::uint16_t>(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
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include "format/reloc_ir.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t> code; // [.text] + [.rdata] blob
|
||||
std::vector<WinExportedSymbol> exports;
|
||||
std::vector<voidlibc::format::RelocEntry> relocs;
|
||||
std::vector<WinInternalSymbol> internal_symbols;
|
||||
std::vector<WinImportedSymbol> imports;
|
||||
std::vector<std::uint8_t> data_blob; // [.data] + [.bss]
|
||||
std::vector<WinDataSymbol> data_symbols;
|
||||
std::string dll_name; // suggested file name
|
||||
};
|
||||
|
||||
struct PeSynthOutput {
|
||||
std::vector<std::uint8_t> 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
|
||||
@@ -0,0 +1,10 @@
|
||||
add_subdirectory(format)
|
||||
|
||||
if(VOIDLIBC_BUILD_LOADER)
|
||||
add_subdirectory(synth)
|
||||
add_subdirectory(e2e)
|
||||
endif()
|
||||
|
||||
if(VOIDLIBC_BUILD_FUZZ)
|
||||
add_subdirectory(fuzz)
|
||||
endif()
|
||||
@@ -0,0 +1,212 @@
|
||||
# =============================================================================
|
||||
# VLC-producing library targets.
|
||||
# Each is a SHARED library that links 'void'; the auto-VLC hook (registered
|
||||
# at the bottom with voidlibc_enable_auto_vlc()) sees these, cross-compiles
|
||||
# their sources with zig cc, and produces fat .vls / .vle artifacts via
|
||||
# `voidlink fuse`. EXCLUDE_FROM_ALL keeps CMake from building the native .so.
|
||||
# =============================================================================
|
||||
|
||||
# --- add_real: add(int, int) — used by multiple tests ---
|
||||
add_library(add_real SHARED add_real.c)
|
||||
target_link_libraries(add_real PRIVATE void)
|
||||
set_target_properties(add_real PROPERTIES EXCLUDE_FROM_ALL TRUE)
|
||||
|
||||
# --- sum_squares: internal PC32/PLT32 reloc ---
|
||||
add_library(sum_squares SHARED sum_squares.c)
|
||||
target_link_libraries(sum_squares PRIVATE void)
|
||||
set_target_properties(sum_squares PROPERTIES EXCLUDE_FROM_ALL TRUE)
|
||||
|
||||
# --- hello_printf: external call to printf via PLT stub ---
|
||||
add_library(hello_printf SHARED hello_printf.c)
|
||||
target_link_libraries(hello_printf PRIVATE void)
|
||||
set_target_properties(hello_printf PROPERTIES EXCLUDE_FROM_ALL TRUE)
|
||||
|
||||
# --- static_counter: BSS + .data globals ---
|
||||
add_library(static_counter SHARED static_counter.c)
|
||||
target_link_libraries(static_counter PRIVATE void)
|
||||
set_target_properties(static_counter PROPERTIES EXCLUDE_FROM_ALL TRUE)
|
||||
|
||||
# --- extern_read: extern int resolved via GLOB_DAT ---
|
||||
# Windows PE synthesis can't handle GLOB_DAT for external globals; Linux only.
|
||||
add_library(extern_read SHARED extern_read.c)
|
||||
target_link_libraries(extern_read PRIVATE void)
|
||||
set_target_properties(extern_read PROPERTIES
|
||||
EXCLUDE_FROM_ALL TRUE
|
||||
VOIDLIBC_VLC_PLATFORMS "linux"
|
||||
)
|
||||
|
||||
# --- math_combined: multi-object merge (cross-object PLT32 → PC32) ---
|
||||
add_library(math_combined SHARED math_a.c math_b.c)
|
||||
target_link_libraries(math_combined PRIVATE void)
|
||||
set_target_properties(math_combined PROPERTIES EXCLUDE_FROM_ALL TRUE)
|
||||
|
||||
# --- hello_exec: executable VLC (.vle) with entry point ---
|
||||
add_library(hello_exec SHARED hello_exec.c)
|
||||
target_link_libraries(hello_exec PRIVATE void)
|
||||
set_target_properties(hello_exec PROPERTIES EXCLUDE_FROM_ALL TRUE)
|
||||
voidlibc_vlc_executable(hello_exec main)
|
||||
|
||||
# --- host_libc_pthread: pthread_create/join via host libpthread/libc ---
|
||||
add_library(host_libc_pthread SHARED host_libc_pthread.c)
|
||||
target_link_libraries(host_libc_pthread PRIVATE void)
|
||||
set_target_properties(host_libc_pthread PROPERTIES
|
||||
EXCLUDE_FROM_ALL TRUE
|
||||
VOIDLIBC_VLC_PLATFORMS "linux"
|
||||
)
|
||||
|
||||
# --- host_libc_multi: strlen (libc.so.6) + sqrt (libm.so.6) ---
|
||||
add_library(host_libc_multi SHARED host_libc_multi.c)
|
||||
target_link_libraries(host_libc_multi PRIVATE void)
|
||||
set_target_properties(host_libc_multi PROPERTIES
|
||||
EXCLUDE_FROM_ALL TRUE
|
||||
VOIDLIBC_VLC_PLATFORMS "linux"
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test executables — load .vls/.vle artifacts via dlopen (interposed).
|
||||
# All VLC paths use the deterministic naming: ${bindir}/<target-name>.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 $<TARGET_FILE:voidloader>
|
||||
${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()
|
||||
@@ -0,0 +1 @@
|
||||
int add(int a, int b) { return a + b; }
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int hello(void) {
|
||||
printf("hello from vlc: %d\n", 42);
|
||||
return 42;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
hello();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#include <math.h>
|
||||
#include <string.h>
|
||||
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
#include <filesystem>
|
||||
|
||||
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<add_fn_t>(::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(); }
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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<int_fn>(::dlsym(h, "get_the_answer"));
|
||||
auto* dbl = reinterpret_cast<int_fn>(::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(); }
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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<fn_t>(::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(); }
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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<fn_t>(::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;
|
||||
}
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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<fn_t>(::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;
|
||||
}
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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<int2_fn>(::dlsym(h, "add"));
|
||||
auto* square = reinterpret_cast<int1_fn>(::dlsym(h, "square"));
|
||||
auto* add_and_double = reinterpret_cast<int2_fn>(::dlsym(h, "add_and_double"));
|
||||
auto* sum_of_squares = reinterpret_cast<int2_fn>(::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(); }
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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<add_fn_t>(::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(); }
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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<void_fn>(::dlsym(h, "counter_reset"));
|
||||
auto* step_up = reinterpret_cast<int_fn> (::dlsym(h, "counter_step_up"));
|
||||
auto* get = reinterpret_cast<int_fn> (::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(); }
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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<fn_t>(::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(); }
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
|
||||
#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<std::uint8_t> read_section_bytes(
|
||||
std::ifstream& f, const SectionEntry& sec) {
|
||||
f.seekg(static_cast<std::streamoff>(sec.code_off));
|
||||
std::vector<std::uint8_t> buf(static_cast<std::size_t>(sec.code_size));
|
||||
f.read(reinterpret_cast<char*>(buf.data()),
|
||||
static_cast<std::streamsize>(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<char*>(&hdr), sizeof(hdr));
|
||||
REQUIRE(f.good());
|
||||
REQUIRE(hdr.magic == kMagic);
|
||||
REQUIRE(hdr.section_count >= 3); // must have linux + windows + macos
|
||||
|
||||
f.seekg(static_cast<std::streamoff>(hdr.section_dir_off));
|
||||
std::vector<SectionEntry> sects(hdr.section_count);
|
||||
f.read(reinterpret_cast<char*>(sects.data()),
|
||||
static_cast<std::streamsize>(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;
|
||||
}
|
||||
@@ -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")
|
||||
@@ -0,0 +1,50 @@
|
||||
#include "format/vlc_format.hpp"
|
||||
#include "reader.hpp"
|
||||
#include "writer.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
|
||||
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<Container>(&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(); }
|
||||
@@ -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})
|
||||
@@ -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 <cstdint>
|
||||
#include <cstdio>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) {
|
||||
const int fd = static_cast<int>(::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<std::size_t>(n);
|
||||
rem -= static_cast<std::size_t>(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;
|
||||
}
|
||||
@@ -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 <cstdint>
|
||||
#include <cstdio>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
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<int>(::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<std::size_t>(n);
|
||||
rem -= static_cast<std::size_t>(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;
|
||||
}
|
||||
@@ -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 <cstdint>
|
||||
#include <cstdio>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) {
|
||||
const int fd = static_cast<int>(::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<std::size_t>(n);
|
||||
rem -= static_cast<std::size_t>(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;
|
||||
}
|
||||
@@ -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")
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
using namespace voidlibc::loader;
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
template<typename T>
|
||||
static T read_at(const std::vector<std::uint8_t>& 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<std::uint8_t>& b, std::int64_t tag) {
|
||||
const Ehdr hdr = read_at<Ehdr>(b, 0);
|
||||
int count = 0;
|
||||
for (int pi = 0; pi < hdr.e_phnum; ++pi) {
|
||||
const Phdr ph = read_at<Phdr>(b, hdr.e_phoff + static_cast<std::size_t>(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<Dyn>(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<Ehdr>(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;
|
||||
}
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
using namespace voidlibc::loader::macos;
|
||||
using voidlibc::format::RelocEntry;
|
||||
using voidlibc::format::RelocOp;
|
||||
|
||||
template<typename T>
|
||||
static T read_at(const std::vector<std::uint8_t>& 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<std::uint8_t>& b, std::uint32_t cmd_type) {
|
||||
const std::uint32_t ncmds = read_at<std::uint32_t>(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<std::uint32_t>(b, lc_off);
|
||||
const std::uint32_t cmdsize = read_at<std::uint32_t>(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<std::uint32_t>(out.bytes, 0) == kMhMagic64); // magic
|
||||
REQUIRE(read_at<std::uint32_t>(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;
|
||||
}
|
||||
@@ -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 <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
using namespace voidlibc::loader::windows;
|
||||
|
||||
template<typename T>
|
||||
static T read_at(const std::vector<std::uint8_t>& 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<std::uint16_t>(out.bytes, kFileHdrOff) == kMachineAmd64);
|
||||
// IMAGE_FILE_DLL set
|
||||
const auto chars = read_at<std::uint16_t>(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<std::uint32_t>(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<std::uint32_t>(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;
|
||||
}
|
||||
Executable
+163
@@ -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 <algorithm>
|
||||
#include <array>
|
||||
#include <string_view>
|
||||
|
||||
using namespace std::string_view_literals;
|
||||
|
||||
namespace {
|
||||
|
||||
struct Entry { std::string_view name; std::string_view library; };
|
||||
|
||||
"""
|
||||
|
||||
FOOTER = """\
|
||||
template<typename Table>
|
||||
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<Entry, 0> {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()
|
||||
@@ -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 <file>
|
||||
# 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
|
||||
@@ -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
|
||||
)
|
||||
@@ -0,0 +1,257 @@
|
||||
#include "builder.hpp"
|
||||
|
||||
#include "writer.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
|
||||
namespace voidlibc::voidlink {
|
||||
|
||||
using namespace voidlibc::format;
|
||||
|
||||
std::uint32_t ContainerBuilder::add_symbol(SymbolSpec spec) {
|
||||
const auto id = static_cast<std::uint32_t>(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<std::uint64_t> reloc_offs;
|
||||
std::vector<std::uint64_t> code_offs;
|
||||
std::vector<std::uint64_t> 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<char> name_pool;
|
||||
std::vector<SymbolEntry> sym_entries;
|
||||
};
|
||||
|
||||
void plan_layout(const std::vector<SymbolSpec>& symbols,
|
||||
const std::vector<SectionSpec>& 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<std::uint32_t>(plan.name_pool.size());
|
||||
len = static_cast<std::uint32_t>(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<std::uint8_t>(SymbolFlags::Exported);
|
||||
if (s.weak) flags |= static_cast<std::uint8_t>(SymbolFlags::Weak);
|
||||
if (s.hidden) flags |= static_cast<std::uint8_t>(SymbolFlags::Hidden);
|
||||
if (s.data_section) flags |= static_cast<std::uint8_t>(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<std::streamoff>(off));
|
||||
};
|
||||
auto write_raw = [&](const void* p, std::size_t n) {
|
||||
out.write(reinterpret_cast<const char*>(p), static_cast<std::streamsize>(n));
|
||||
};
|
||||
auto pad_to = [&](std::uint64_t off) {
|
||||
const auto cur = static_cast<std::uint64_t>(out.tellp());
|
||||
if (cur < off) {
|
||||
std::vector<char> 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<std::uint32_t>(ContainerFlags::None);
|
||||
if (is_executable_) flags |= static_cast<std::uint32_t>(ContainerFlags::Executable);
|
||||
if (is_static_library_) flags |= static_cast<std::uint32_t>(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<std::uint32_t>(ContainerFlags::HasDynamicImports);
|
||||
break;
|
||||
}
|
||||
}
|
||||
hdr.flags = flags;
|
||||
hdr.arch = TargetArch::X86_64;
|
||||
hdr.reserved = 0;
|
||||
hdr.section_count = static_cast<std::uint32_t>(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<std::uint32_t>(plan.sym_entries.size());
|
||||
sth.name_pool_size = static_cast<std::uint32_t>(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<std::uint32_t>(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
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
|
||||
#include "format/reloc_ir.hpp"
|
||||
#include "format/vlc_format.hpp"
|
||||
#include "writer.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t> code; // raw PIC code (RawCode) or native blob (NativeBlob)
|
||||
std::vector<voidlibc::format::RelocEntry> relocs; // empty when kind == NativeBlob
|
||||
std::uint64_t entry_offset = 0;
|
||||
std::vector<std::uint8_t> 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<std::uint32_t>(symbols_.size()); }
|
||||
std::uint16_t section_count() const { return static_cast<std::uint16_t>(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<SymbolSpec> symbols_;
|
||||
std::vector<SectionSpec> sections_;
|
||||
bool is_executable_ = false;
|
||||
bool is_static_library_ = false;
|
||||
std::string entry_symbol_;
|
||||
};
|
||||
|
||||
} // namespace voidlibc::voidlink
|
||||
@@ -0,0 +1,318 @@
|
||||
#include "coff_reader.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
namespace voidlibc::voidlink::coff {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string err(std::string s) { return s; }
|
||||
|
||||
bool read_file(const std::filesystem::path& path, std::vector<std::uint8_t>& out) {
|
||||
std::ifstream in(path, std::ios::binary | std::ios::ate);
|
||||
if (!in) return false;
|
||||
const auto sz = static_cast<std::streamsize>(in.tellg());
|
||||
in.seekg(0, std::ios::beg);
|
||||
out.resize(static_cast<std::size_t>(sz));
|
||||
in.read(reinterpret_cast<char*>(out.data()), sz);
|
||||
return static_cast<bool>(in);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
bool read_at(const std::vector<std::uint8_t>& 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: "/<offset>" into string table.
|
||||
char buf[9] = {};
|
||||
std::memcpy(buf, sh.Name + 1, 7);
|
||||
const auto off = static_cast<std::size_t>(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<std::size_t>(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<std::uint8_t>& 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<std::uint8_t>& 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<std::uint8_t> 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<std::size_t>(strtab_size32);
|
||||
if (strtab_off + strtab_size <= buf.size())
|
||||
strtab = reinterpret_cast<const char*>(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<std::size_t>(-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<std::uint32_t> coff_to_obj(fh.NumberOfSymbols,
|
||||
static_cast<std::uint32_t>(-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<std::uint32_t>(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<int>(sym.SectionNumber) - 1;
|
||||
if (sec1 >= 0 && sec1 < fh.NumberOfSections) {
|
||||
ps.section_index = static_cast<std::uint32_t>(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<std::uint32_t>(-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
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
// 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<std::uint8_t> bytes;
|
||||
std::uint64_t mem_size = 0;
|
||||
std::vector<ParsedRelocation> relocs;
|
||||
};
|
||||
|
||||
struct ParsedObject {
|
||||
std::vector<ParsedSection> sections;
|
||||
std::vector<ParsedSymbol> symbols;
|
||||
// Primary .text section index (first executable section with that name).
|
||||
std::size_t text_index = static_cast<std::size_t>(-1);
|
||||
};
|
||||
|
||||
using ParseResult = std::variant<ParsedObject, std::string /*error*/>;
|
||||
|
||||
ParseResult parse_coff_object(const std::filesystem::path& path);
|
||||
|
||||
} // namespace voidlibc::voidlink::coff
|
||||
@@ -0,0 +1,265 @@
|
||||
#include "elf_reader.hpp"
|
||||
|
||||
#include "loader/common/elf64.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
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<std::uint8_t>& out) {
|
||||
std::ifstream in(path, std::ios::binary | std::ios::ate);
|
||||
if (!in) return false;
|
||||
const auto size = static_cast<std::streamsize>(in.tellg());
|
||||
in.seekg(0, std::ios::beg);
|
||||
out.resize(static_cast<std::size_t>(size));
|
||||
in.read(reinterpret_cast<char*>(out.data()), size);
|
||||
return static_cast<bool>(in);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool read_struct(const std::vector<std::uint8_t>& 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<std::uint8_t> 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<std::uint64_t>(eh.e_shnum) * sizeof(Shdr) > buf.size()) {
|
||||
return err("section table truncated");
|
||||
}
|
||||
std::vector<Shdr> 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<const char*>(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<std::size_t>(-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<const char*>(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<Sym> 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<const char*>(
|
||||
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<const std::uint16_t*>(
|
||||
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<Rela> 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<std::uint32_t>(
|
||||
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
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t> 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<ParsedRelocation> 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<ParsedSection> sections;
|
||||
std::vector<ParsedSymbol> symbols;
|
||||
std::vector<VersionRequirement> version_reqs; // from .gnu.version_r
|
||||
std::size_t text_index = static_cast<std::size_t>(-1);
|
||||
};
|
||||
|
||||
using ParseResult = std::variant<ParsedObject, std::string /*error*/>;
|
||||
|
||||
ParseResult parse_elf64_object(const std::filesystem::path& path);
|
||||
|
||||
} // namespace voidlibc::voidlink::elf
|
||||
@@ -0,0 +1,324 @@
|
||||
#include "macho_reader.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
|
||||
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<std::size_t>(f.tellg());
|
||||
f.seekg(0);
|
||||
std::vector<std::uint8_t> buf(fsz);
|
||||
f.read(reinterpret_cast<char*>(buf.data()), static_cast<std::streamsize>(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<std::uint32_t>(ri_raw.r_address),
|
||||
length);
|
||||
|
||||
ParsedRelocation pr;
|
||||
pr.offset = static_cast<std::uint64_t>(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<const char*>(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<std::size_t>(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<std::size_t>(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<std::size_t>(-1))
|
||||
return ParseError{"no __text section found"};
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
} // namespace voidlibc::voidlink::macho
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
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<std::uint8_t> 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<ParsedRelocation> relocs;
|
||||
};
|
||||
|
||||
struct ParsedObject {
|
||||
std::vector<ParsedSection> sections; // indexed by 1-based section ordinal - 1
|
||||
std::vector<ParsedSymbol> symbols;
|
||||
std::size_t text_index = static_cast<std::size_t>(-1);
|
||||
};
|
||||
|
||||
struct ParseError { std::string message; };
|
||||
using ParseResult = std::variant<ParsedObject, ParseError>;
|
||||
|
||||
ParseResult parse_macho_object(const std::filesystem::path& path);
|
||||
|
||||
} // namespace voidlibc::voidlink::macho
|
||||
+1099
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,143 @@
|
||||
#include "merge.hpp"
|
||||
|
||||
#include "format/vlc_format.hpp"
|
||||
|
||||
#include <sstream>
|
||||
#include <unordered_map>
|
||||
|
||||
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<LoweredText, std::string>
|
||||
merge_lowered(std::vector<LoweredText> 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<std::uint64_t> 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<std::uint64_t>(merged.section.code.size()), 16);
|
||||
merged.section.code.resize(static_cast<std::size_t>(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<std::uint64_t>(merged.section.data.size()), 8);
|
||||
merged.section.data.resize(static_cast<std::size_t>(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<std::string, std::uint32_t> name_to_global;
|
||||
// Per-object local sym_id → global sym_id map.
|
||||
std::vector<std::unordered_map<std::uint32_t, std::uint32_t>> 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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::uint32_t>(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
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include "reloc_lowering.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
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<LoweredText, std::string>
|
||||
merge_lowered(std::vector<LoweredText> objects);
|
||||
|
||||
} // namespace voidlibc::voidlink
|
||||
@@ -0,0 +1,177 @@
|
||||
#include "reader.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
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<char*>(&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<unsigned long long>(h.section_dir_off));
|
||||
std::printf("symtab : off=%llu size=%llu\n",
|
||||
static_cast<unsigned long long>(h.symtab_off),
|
||||
static_cast<unsigned long long>(h.symtab_size));
|
||||
std::printf("imports : off=%llu size=%llu\n",
|
||||
static_cast<unsigned long long>(h.imports_off),
|
||||
static_cast<unsigned long long>(h.imports_size));
|
||||
std::printf("exports : off=%llu size=%llu\n",
|
||||
static_cast<unsigned long long>(h.exports_off),
|
||||
static_cast<unsigned long long>(h.exports_size));
|
||||
std::printf("file_size : %llu (on disk: %llu)\n",
|
||||
static_cast<unsigned long long>(h.file_size),
|
||||
static_cast<unsigned long long>(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<std::streamoff>(h.section_dir_off));
|
||||
std::vector<SectionEntry> sects(h.section_count);
|
||||
f.read(reinterpret_cast<char*>(sects.data()),
|
||||
static_cast<std::streamsize>(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<unsigned long long>(s.code_off),
|
||||
static_cast<unsigned long long>(s.code_size));
|
||||
if (s.data_size > 0)
|
||||
std::printf(" data=@%llu+%llu",
|
||||
static_cast<unsigned long long>(s.data_off),
|
||||
static_cast<unsigned long long>(s.data_size));
|
||||
if (s.entry_offset > 0)
|
||||
std::printf(" entry=+%llu", static_cast<unsigned long long>(s.entry_offset));
|
||||
std::printf("\n");
|
||||
}
|
||||
|
||||
// Symbol table
|
||||
if (h.symtab_size < sizeof(SymbolTableHeader)) return;
|
||||
f.seekg(static_cast<std::streamoff>(h.symtab_off));
|
||||
SymbolTableHeader sth{};
|
||||
f.read(reinterpret_cast<char*>(&sth), sizeof(sth));
|
||||
if (!f || sth.entry_count == 0) return;
|
||||
|
||||
std::vector<SymbolEntry> syms(sth.entry_count);
|
||||
f.read(reinterpret_cast<char*>(syms.data()),
|
||||
static_cast<std::streamsize>(sth.entry_count * sizeof(SymbolEntry)));
|
||||
std::string pool(sth.name_pool_size, '\0');
|
||||
f.read(pool.data(), static_cast<std::streamsize>(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<std::string> 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<std::uint8_t>(SymbolFlags::Exported))
|
||||
exports_list.push_back(name_of(sym));
|
||||
}
|
||||
|
||||
auto print_names = [](const char* label, const std::vector<std::string>& 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
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user