From 0ecc1eb48885e555785af00e79dfe7077a7a2332 Mon Sep 17 00:00:00 2001 From: 3z4k <91467994+3z4k@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:01:34 +0545 Subject: [PATCH 1/2] Fix guest ABI semantics and replace simulated milestones with verifiable experiments --- .github/PULL_REQUEST_TEMPLATE.md | 22 ++ .github/ps5-sdk.json | 5 + .github/workflows/ci.yml | 192 ++++------ .gitignore | 2 + CMakeLists.txt | 74 +++- README.md | 157 ++++---- THIRD_PARTY_NOTICES.md | 19 + cmake/build_info.h.in | 3 + docs/apk-inspection.md | 54 +++ docs/architecture.md | 213 +++-------- docs/assets/banner.svg | 13 + docs/binder-scope.md | 40 ++ docs/console-validation.md | 82 ++++ docs/development.md | 164 ++++---- docs/elf-execution.md | 62 +++ docs/platform-constraints.md | 319 +++++----------- src/android/apk_inspector.cpp | 419 +++++++++++++++++++++ src/android/binder/binder_engine.cpp | 125 +++--- src/android/binder/binder_engine.h | 81 ++-- src/android/binder/binder_protocol.h | 37 +- src/android/evidence_report.cpp | 52 +++ src/android/evidence_report.h | 21 ++ src/android/image_manager.cpp | 81 ++-- src/android/image_manager.h | 4 + src/android/runtime_manager.cpp | 42 ++- src/android/runtime_manager.h | 2 +- src/app/main.cpp | 71 ++++ src/app/ps5_main.cpp | 62 ++- src/compat/bionic_loader.cpp | 265 +++++++------ src/compat/bionic_loader.h | 15 + src/compat/elf_runner.cpp | 154 ++++++++ src/compat/elf_runner.h | 20 + src/compat/fd_table.cpp | 544 +++++++++++++++------------ src/compat/fd_table.h | 24 +- src/compat/linux_abi.cpp | 37 +- src/compat/memory_compat.cpp | 24 +- src/compat/syscall_dispatch.cpp | 97 ++++- src/compat/syscall_dispatch.h | 2 +- src/platform/ps5/display_ps5.cpp | 17 +- src/platform/ps5/input_ps5.cpp | 2 + src/platform/ps5/sce_decls.h | 2 +- src/platform/threads.cpp | 66 ++++ tests/elf_fixture.h | 37 ++ tests/fixtures/AndroidManifest.xml | 1 + tests/fixtures/aapt2-manifest.apk | Bin 0 -> 575 bytes tests/fixtures/cooperative_entry.c | 25 ++ tests/fixtures/cooperative_entry.ld | 10 + tests/fuzz_parsers.cpp | 12 + tests/test_apk_inspection.cpp | 59 +++ tests/test_binder_and_apk.cpp | 13 +- tests/test_bionic_and_fd.cpp | 15 +- tests/test_compat_dispatch.cpp | 7 +- tests/test_elf_validation.cpp | 83 ++++ tests/test_evidence_report.cpp | 12 + tests/test_fd_semantics.cpp | 205 ++++++++++ tests/test_image_manager.cpp | 19 +- tests/test_platform_threads.cpp | 14 +- tests/test_rpc_semantics.cpp | 85 +++++ tools/annotate_console_report.py | 26 ++ tools/build_elf_fixture.py | 18 + tools/check_docs.py | 25 ++ tools/check_reports.py | 14 + tools/make_test_fixtures.py | 89 +++++ 63 files changed, 3102 insertions(+), 1354 deletions(-) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/ps5-sdk.json create mode 100644 cmake/build_info.h.in create mode 100644 docs/apk-inspection.md create mode 100644 docs/assets/banner.svg create mode 100644 docs/binder-scope.md create mode 100644 docs/console-validation.md create mode 100644 docs/elf-execution.md create mode 100644 src/android/apk_inspector.cpp create mode 100644 src/android/evidence_report.cpp create mode 100644 src/android/evidence_report.h create mode 100644 src/compat/elf_runner.cpp create mode 100644 src/compat/elf_runner.h create mode 100644 tests/elf_fixture.h create mode 100644 tests/fixtures/AndroidManifest.xml create mode 100644 tests/fixtures/aapt2-manifest.apk create mode 100644 tests/fixtures/cooperative_entry.c create mode 100644 tests/fixtures/cooperative_entry.ld create mode 100644 tests/fuzz_parsers.cpp create mode 100644 tests/test_apk_inspection.cpp create mode 100644 tests/test_elf_validation.cpp create mode 100644 tests/test_evidence_report.cpp create mode 100644 tests/test_fd_semantics.cpp create mode 100644 tests/test_rpc_semantics.cpp create mode 100644 tools/annotate_console_report.py create mode 100644 tools/build_elf_fixture.py create mode 100644 tools/check_docs.py create mode 100644 tools/check_reports.py create mode 100644 tools/make_test_fixtures.py diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..565f8eb --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,22 @@ +## Problem and resulting behavior + +Describe the concrete trigger, previous result, and corrected result. + +## Changes + +- List the implementation changes and affected public contracts. +- Identify supported subsets and explicit failure behavior. + +## Validation + +| Check | Result / evidence | +| --- | --- | +| Host tests | | +| Sanitizers / malformed inputs | | +| PS5 cross-build | | +| PS5 hardware | Unverified unless a real report is linked | + +## Limits and follow-up + +State remaining blockers. Distinguish configured CI jobs from completed runs, +and host behavior from console evidence. diff --git a/.github/ps5-sdk.json b/.github/ps5-sdk.json new file mode 100644 index 0000000..b266938 --- /dev/null +++ b/.github/ps5-sdk.json @@ -0,0 +1,5 @@ +{ + "version": "v0.45", + "url": "https://github.com/ps5-payload-dev/sdk/releases/download/v0.45/ps5-payload-sdk.zip", + "sha256": "5fac64093d0e3e69f2584ce7935f24f703f622d9681f1495c85b9f00d1291a2c" +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5f0189a..77ed43b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,146 +1,114 @@ name: ci - on: push: - branches: ["*"] + branches: ["**"] pull_request: workflow_dispatch: - +permissions: + contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: lint: - name: format & repo hygiene + name: Format and documentation hygiene runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - - - name: Install clang-format - run: pipx install clang-format==23.1.3 - - - name: clang-format check - run: | - find src tests -name '*.cpp' -o -name '*.h' | sort | \ - xargs clang-format --dry-run --Werror - - - name: Repository hygiene - run: | - set -e - for f in README.md LICENSE THIRD_PARTY_NOTICES.md CMakeLists.txt \ - docs/architecture.md docs/platform-constraints.md \ - docs/waydroid-analysis.md docs/development.md \ - .clang-format .gitignore; do - test -f "$f" || { echo "missing required file: $f"; exit 1; } - done - ! grep -RInE 'fake (SDK|implementation)|return success; *// *placeholder|TODO: pretend' src tests - + - run: pipx install clang-format==23.1.3 + - run: git ls-files '*.cpp' '*.h' '*.c' | xargs clang-format --dry-run --Werror + - run: python3 tools/check_docs.py host: - name: host build & tests (${{ matrix.compiler }}) + name: Host (${{ matrix.compiler }}, ${{ matrix.sanitizer }}) runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: - compiler: [gcc, clang] - + include: + - {compiler: gcc, sanitizer: none} + - {compiler: clang, sanitizer: none} + - {compiler: clang, sanitizer: "address,undefined"} + - {compiler: clang, sanitizer: thread} steps: - uses: actions/checkout@v4 - - - name: Install toolchain - run: | - sudo apt-get update - sudo apt-get install -y cmake ninja-build g++ clang - + - name: Install tools + run: sudo apt-get update && sudo apt-get install -y cmake ninja-build g++ clang lld zlib1g-dev - name: Configure + shell: bash run: | - if [ "${{ matrix.compiler }}" = "clang" ]; then - cmake -B build -G Ninja \ - -DCMAKE_CXX_COMPILER=clang++ \ - -DCMAKE_C_COMPILER=clang + if [ '${{ matrix.compiler }}' = clang ]; then + export CC=clang CXX=clang++ else - cmake -B build -G Ninja + export CC=gcc CXX=g++ fi - - - name: Build - run: cmake --build build 2>&1 | tee build.log - - - name: Unit tests - run: ctest --test-dir build --output-on-failure 2>&1 | tee test.log - - - name: Runtime smoke test (host binary is NOT a PS5 executable) + cmake -B build -G Ninja -DPS5DROID_SANITIZERS='${{ matrix.sanitizer }}' + - name: Build and test + run: | + cmake --build build 2>&1 | tee build.log + ctest --test-dir build --output-on-failure 2>&1 | tee test.log + - name: CLI and native ELF smoke tests + if: matrix.sanitizer == 'none' run: | - ./build/ps5droid-host | tee smoke.log + python3 tools/build_elf_fixture.py --output build/fixtures/cooperative.elf + ./build/ps5droid-host --run-cooperative-elf build/fixtures/cooperative.elf | tee elf.log ./build/ps5droid-host --matrix | tee matrix.log - ./build/ps5droid-host --start-attempt | tee start.log - - - name: Upload logs + ./build/ps5droid-host --start-attempt | tee blockers.log + ./build/ps5droid-host --report-json build/host-evidence.json --probe-exec + ./build/ps5droid-host --inspect-apk tests/fixtures/aapt2-manifest.apk > build/apk.json + python3 tools/check_reports.py build/host-evidence.json build/apk.json + - uses: actions/upload-artifact@v4 if: always() - uses: actions/upload-artifact@v4 with: - name: host-${{ matrix.compiler }}-logs + name: host-${{ matrix.compiler }}-${{ matrix.sanitizer }} path: | - build.log - test.log - smoke.log - matrix.log - start.log - + *.log + build/*evidence.json + build/apk.json + macos: + name: macOS portability + runs-on: macos-15 + steps: + - uses: actions/checkout@v4 + - run: cmake -B build && cmake --build build && ctest --test-dir build --output-on-failure + fuzz: + name: Bounded parser fuzz smoke + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - run: sudo apt-get update && sudo apt-get install -y clang cmake ninja-build zlib1g-dev + - run: CC=clang CXX=clang++ cmake -B build -G Ninja -DPS5DROID_BUILD_FUZZER=ON + - run: cmake --build build --target ps5droid_fuzz + - run: ./build/ps5droid_fuzz -runs=10000 -max_len=65536 ps5: - name: PS5 payload cross-build (ELF only) + name: PS5 cross-build (hardware execution unverified) runs-on: ubuntu-24.04 - steps: - uses: actions/checkout@v4 - - - name: Install cross toolchain prerequisites - run: | - sudo apt-get update - sudo apt-get install -y clang-18 lld-18 llvm-18-dev cmake ninja-build wget unzip - - - name: Install ps5-payload-sdk (open-source release) + - name: Install tools + run: sudo apt-get update && sudo apt-get install -y clang-18 lld-18 llvm-18-dev cmake ninja-build curl unzip + - name: Install checksum-verified SDK run: | - wget -q https://github.com/ps5-payload-dev/sdk/releases/latest/download/ps5-payload-sdk.zip - sudo unzip -d /opt ps5-payload-sdk.zip - echo "PS5_PAYLOAD_SDK=/opt/ps5-payload-sdk" >> "$GITHUB_ENV" - - - name: Configure (ps5-payload-sdk toolchain) - shell: bash + url=$(python3 -c 'import json; print(json.load(open(".github/ps5-sdk.json"))["url"])') + sha=$(python3 -c 'import json; print(json.load(open(".github/ps5-sdk.json"))["sha256"])') + curl --fail --location --retry 3 "$url" -o sdk.zip + echo "$sha sdk.zip" | sha256sum --check --strict + sudo unzip -q -d /opt sdk.zip + echo 'PS5_PAYLOAD_SDK=/opt/ps5-payload-sdk' >> "$GITHUB_ENV" + - name: Configure and build run: | - set -euo pipefail - - test -f "$PS5_PAYLOAD_SDK/toolchain/prospero.cmake" || { - echo "::error::PS5 toolchain file not found" - find "$PS5_PAYLOAD_SDK" -maxdepth 5 -type f \ - -name '*.cmake' -print - exit 1 - } - - cmake -S . -B build-ps5 -G Ninja \ + sdk_version=$(python3 -c 'import json; print(json.load(open(".github/ps5-sdk.json"))["version"])') + cmake -B build-ps5 -G Ninja \ -DCMAKE_TOOLCHAIN_FILE="$PS5_PAYLOAD_SDK/toolchain/prospero.cmake" \ - -DPS5DROID_BUILD_PS5=ON \ - 2>&1 | tee configure-ps5.log - - - name: Build ps5droid.elf - shell: bash - run: | - set -euo pipefail - - cmake --build build-ps5 --target ps5droid \ - 2>&1 | tee build-ps5.log - - test -f build-ps5/ps5droid.elf || { - echo "::error::Expected PS5 ELF was not produced" - find build-ps5 -maxdepth 4 -type f -print - exit 1 - } - - - name: Upload payload - if: success() - uses: actions/upload-artifact@v4 + -DPS5DROID_BUILD_PS5=ON -DPS5DROID_SDK_VERSION="$sdk_version" 2>&1 | tee configure-ps5.log + cmake --build build-ps5 --target ps5droid 2>&1 | tee build-ps5.log + test -s build-ps5/ps5droid.elf + sha256sum build-ps5/ps5droid.elf > build-ps5/ps5droid.elf.sha256 + - uses: actions/upload-artifact@v4 + if: always() with: - name: ps5droid-elf-payload - path: build-ps5/ps5droid.elf - if-no-files-found: error - - - name: Artifact note - run: | - echo "ps5droid.elf is a native ELF payload for use with an ELF" \ - "loader (e.g. ps5-payload-elfldr). It is NOT a PS5 PKG and" \ - "has not been executed on a console by CI." + name: ps5-elf-experimental + path: | + build-ps5/ps5droid.elf + build-ps5/ps5droid.elf.sha256 + *-ps5.log + .github/ps5-sdk.json diff --git a/.gitignore b/.gitignore index 5a611fd..dbadb0b 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ build-*/ *.pkg .cache/ compile_commands.json + +__pycache__/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 1503618..93082a2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,6 +18,18 @@ project(ps5droid DESCRIPTION "PS5Droid - native Android runtime research for PS5" LANGUAGES C CXX) +set(PS5DROID_SDK_VERSION "unrecorded" CACHE STRING "Pinned SDK version used by this build") +execute_process(COMMAND git rev-parse HEAD WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + OUTPUT_VARIABLE PS5DROID_BUILD_REVISION OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) +execute_process(COMMAND git status --porcelain WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + OUTPUT_VARIABLE PS5DROID_TREE_STATUS ERROR_QUIET) +if(NOT PS5DROID_BUILD_REVISION) + set(PS5DROID_BUILD_REVISION "unrecorded") +elseif(PS5DROID_TREE_STATUS) + string(APPEND PS5DROID_BUILD_REVISION "-dirty") +endif() +configure_file(cmake/build_info.h.in generated/build_info.h @ONLY) + set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_C_EXTENSIONS OFF) @@ -29,6 +41,8 @@ endif() option(PS5DROID_BUILD_PS5 "Build the native PS5 payload (needs ps5-payload-sdk toolchain)" OFF) +set(PS5DROID_SANITIZERS "none" CACHE STRING "Host sanitizers: none, address,undefined, or thread") +option(PS5DROID_BUILD_FUZZER "Build LLVM libFuzzer parser harness (host Clang only)" OFF) option(PS5DROID_BUILD_HOST "Build host runtime and tests" ON) option(PS5DROID_BUILD_TESTS "Build host unit tests" ON) @@ -45,6 +59,24 @@ else() set(PS5DROID_PLATFORM_PS5_VALUE OFF) endif() +# APK manifests use ZIP DEFLATE. Host builds use system zlib; console builds +# build the same pinned upstream source with the PS5 toolchain. +if(PROSPERO) + include(FetchContent) + set(ZLIB_BUILD_SHARED OFF CACHE BOOL "" FORCE) + set(ZLIB_INSTALL OFF CACHE BOOL "" FORCE) + set(ZLIB_BUILD_TESTING OFF CACHE BOOL "" FORCE) + set(ZLIB_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) + FetchContent_Declare(zlib + URL https://github.com/madler/zlib/archive/refs/tags/v1.3.2.tar.gz + URL_HASH SHA256=b99a0b86c0ba9360ec7e78c4f1e43b1cbdf1e6936c8fa0f6835c0cd694a495a1) + FetchContent_MakeAvailable(zlib) + set(PS5DROID_ZLIB zlibstatic) +else() + find_package(ZLIB REQUIRED) + set(PS5DROID_ZLIB ZLIB::ZLIB) +endif() + # --------------------------------------------------------------------------- # Portable core library (no OS headers leak through this target's API). # --------------------------------------------------------------------------- @@ -61,18 +93,41 @@ add_library(ps5droid_core STATIC src/compat/ipc_compat.cpp src/compat/fd_table.cpp src/compat/bionic_loader.cpp + src/compat/elf_runner.cpp src/android/sha256.cpp src/android/image_manager.cpp + src/android/apk_inspector.cpp src/android/runtime_manager.cpp + src/android/evidence_report.cpp src/android/binder/binder_engine.cpp src/ui/launcher.cpp src/ui/bitmap_font.cpp ) -target_include_directories(ps5droid_core PUBLIC src) +target_include_directories(ps5droid_core PUBLIC src PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated") +target_link_libraries(ps5droid_core PUBLIC ${PS5DROID_ZLIB}) target_compile_features(ps5droid_core PUBLIC cxx_std_17) target_compile_options(ps5droid_core PRIVATE -Wall -Wextra) +if(NOT PROSPERO AND NOT PS5DROID_SANITIZERS STREQUAL "none") + if(NOT PS5DROID_SANITIZERS MATCHES "^(address,undefined|thread)$") + message(FATAL_ERROR "Unsupported sanitizer selection") + endif() + target_compile_options(ps5droid_core PUBLIC -fsanitize=${PS5DROID_SANITIZERS} -fno-omit-frame-pointer) + target_link_options(ps5droid_core PUBLIC -fsanitize=${PS5DROID_SANITIZERS}) +endif() +if(PS5DROID_BUILD_FUZZER) + if(PROSPERO OR NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") + message(FATAL_ERROR "libFuzzer requires host Clang") + endif() + target_compile_options(ps5droid_core PRIVATE -fsanitize=fuzzer-no-link,address,undefined) + target_link_options(ps5droid_core INTERFACE -fsanitize=address,undefined) + add_executable(ps5droid_fuzz tests/fuzz_parsers.cpp) + target_link_libraries(ps5droid_fuzz PRIVATE ps5droid_core) + target_compile_options(ps5droid_fuzz PRIVATE -fsanitize=fuzzer,address,undefined) + target_link_options(ps5droid_fuzz PRIVATE -fsanitize=fuzzer,address,undefined) +endif() + if(PS5DROID_PLATFORM_PS5_VALUE) target_compile_definitions(ps5droid_core PUBLIC PS5DROID_PLATFORM_PS5) endif() @@ -91,6 +146,13 @@ endif() # --------------------------------------------------------------------------- if(PS5DROID_BUILD_TESTS AND PS5DROID_BUILD_HOST AND NOT PROSPERO) enable_testing() + find_package(Python3 COMPONENTS Interpreter REQUIRED) + add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stamp" + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/make_test_fixtures.py" + "${CMAKE_CURRENT_BINARY_DIR}/fixtures" + DEPENDS tools/make_test_fixtures.py tests/fixtures/aapt2-manifest.apk) + add_custom_target(ps5droid_fixtures DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stamp") + add_executable(ps5droid_tests tests/host_main.cpp @@ -103,8 +165,17 @@ if(PS5DROID_BUILD_TESTS AND PS5DROID_BUILD_HOST AND NOT PROSPERO) tests/test_runtime_manager.cpp tests/test_ui.cpp tests/test_bionic_and_fd.cpp + tests/test_fd_semantics.cpp + tests/test_elf_validation.cpp + tests/test_rpc_semantics.cpp + tests/test_apk_inspection.cpp + tests/test_evidence_report.cpp tests/test_binder_and_apk.cpp ) + add_dependencies(ps5droid_tests ps5droid_fixtures) + target_compile_definitions(ps5droid_tests PRIVATE + PS5DROID_TEST_FIXTURES="${CMAKE_CURRENT_BINARY_DIR}/fixtures" + PS5DROID_SOURCE_FIXTURES="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures") target_include_directories(ps5droid_tests PRIVATE tests src) target_link_libraries(ps5droid_tests PRIVATE ps5droid_core) target_compile_options(ps5droid_tests PRIVATE -Wall -Wextra) @@ -112,6 +183,7 @@ if(PS5DROID_BUILD_TESTS AND PS5DROID_BUILD_HOST AND NOT PROSPERO) add_test(NAME ps5droid_unit_tests COMMAND ps5droid_tests WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + set_tests_properties(ps5droid_unit_tests PROPERTIES TIMEOUT 30) endif() # --------------------------------------------------------------------------- diff --git a/README.md b/README.md index 105ccdc..8a98070 100644 --- a/README.md +++ b/README.md @@ -1,98 +1,99 @@ -# PS5Droid +
+ +![PS5Droid: native Android runtime research](docs/assets/banner.svg) **Native Android runtime research for jailbroken PlayStation 5 consoles.** -PS5Droid is an open-source systems-research project that investigates — -step by step, with test evidence — what it would take to run Android -application components directly inside a native PS5 homebrew payload. -It is *not* a Linux boot, a VM, an emulator image, or a Waydroid port, -and it does **not** claim to run Android apps today. Every capability -this repository ships is either tested on the host, implemented against -verified console APIs but not yet console-executed, or honestly marked -not implemented / blocked. - -Waydroid is used as an *architectural reference* only (see -[`docs/waydroid-analysis.md`](docs/waydroid-analysis.md)); no Waydroid -code is imported. Low-level console facts come from the open-source -[ps5-payload-sdk](https://github.com/ps5-payload-dev/sdk) ecosystem. - -## Current status - -| Area | Status | -|---|---| -| Portable platform layer (memory, threads, fs, IPC) | **Implemented and tested (host)** | -| Linux ABI dispatch experiment (guest fd table, epoll/eventfd, mmap/brk/futex subset) | **Implemented and tested (host)** | -| Compatibility matrix (77 syscalls: 22 emulated / 2 partial / 53 unsupported) | **Implemented and tested (host)** | -| Capability probes + runtime manager with structured blockers | **Implemented and tested (host)** | -| Android image manifest + SHA-256 + read-only ext4 superblock probe | **Implemented and tested (host)** | -| Launcher UI model + 8x8 framebuffer font | **Implemented and tested (host)** | -| Native PS5 payload (`ps5droid.elf`, video-out + pad + user service) | **Implemented, NOT tested on console** | -| PS5 PKG packaging | **Not implemented** (ELF-payload path only) | -| Linux binary loading / bionic re-hosting (Milestone 4) | **Implemented and tested (host)** | -| Binder re-hosting (Milestone 5) | **Implemented and tested (host)** | -| APK package inspection (Milestone 6) | **Implemented and tested (host)** | -| Audio output | **Not implemented** (explicitly reported unsupported) | -| Vulkan / GPU-accelerated Android graphics | **Blocked** (no Vulkan driver for homebrew; proprietary AGC/GNM only) | - -Build status: host build + 40 unit tests green (gcc and clang, ASan/UBSan -clean). The PS5 target is cross-built in CI only when explicitly -requested, using the official open-source SDK. - -## Architecture in one page +[Build & test](docs/development.md) · [Architecture](docs/architecture.md) · [Console validation](docs/console-validation.md) · [Execution boundary](docs/elf-execution.md) -``` -app/main.cpp (host CLI) app/ps5_main.cpp (PS5 payload) - ui/launcher + ui/bitmap_font - android/runtime_manager + android/image_manager (+ sha256) - compat/syscall_dispatch (Linux ABI experiment) - compat/memory_compat + compat/ipc_compat - platform/ (posix backend | ps5 backend) -``` +
+ +> **Research status:** Android applications do not run yet. The repository contains +> host-tested components, an explicitly cooperative native ELF execution experiment, +> and an experimental PS5 payload. A host pass or successful cross-build does not +> establish console compatibility. + +## What works, and what that proves -* **platform/** — portable memory/thread/fs/display/input primitives; - the PS5 backend uses ps5-payload-sdk facilities with hand-maintained, - provenance-documented firmware declarations. -* **compat/** — accepts Linux x86_64 syscall numbers and executes a - small, honestly classified subset (anonymous memory, clocks, futex - wait/wake, streams); everything else returns `-ENOSYS` with an - explanation. The verified Linux→FreeBSD number mapping (e.g. mmap - 9→477) is data in `src/compat/linux_abi.h`. -* **android/** — image handling (manifest, SHA-256, ext4 superblock - probe; no mounting is possible on Orbis) and the runtime manager whose - start attempt always reports structured, reasoned blockers today. -* **ui/** — pad/keyboard-driven launcher model and a framebuffer font. +| Component | Implemented behavior | Evidence boundary | +| :--- | :--- | :--- | +| Platform | Memory, threads, filesystem, synchronization and framebuffer primitives | Host tests; console probes available | +| Linux ABI | Explicit Linux flag/errno translation, shared descriptor lifetimes, positioned reads, bounded memory semantics | Partial compatibility; inspect `--matrix` | +| Event loops | Blocking/nonblocking eventfd counters and level-triggered eventfd readiness | Other epoll targets and advanced modes fail explicitly | +| ELF | Bounded ELF64 parsing, address-correct stack staging, RX segment loading and cooperative syscall gateway | Trusted x86-64 fixture only; no unmodified bionic startup | +| Android package inspection | ZIP directory validation, stored/DEFLATE binary manifests, actual package/SDK/DEX/ABI metadata | Read-only inspection; no installation or signature verification | +| Binder research | Bounded synchronous in-process RPC with explicit errors and concurrent/reentrant tests | No Android Binder wire protocol or ServiceManager | +| PS5 payload | Video-out, DualSense input and machine-readable evidence capture | Cross-build evidence only until a hardware run is recorded | +| Graphics, audio and packaging | CPU framebuffer launcher | Android GPU services, audio output and PKG packaging remain unimplemented | -Details: [`docs/architecture.md`](docs/architecture.md). +This project targets native PS5 homebrew. It does not boot Linux or bundle a VM, +Android system, Google Play Services, console keys or proprietary Sony SDKs. +Waydroid is an [architectural reference](docs/waydroid-analysis.md), not an imported runtime. -## Host build & test +## Try the host research harness + +Requires CMake ≥ 3.16, a C++17 compiler, zlib development files and Python 3 for tests. ```sh -cmake -B build -G Ninja +cmake -S . -B build cmake --build build ctest --test-dir build --output-on-failure -./build/ps5droid-host # probes + Linux ABI demo -./build/ps5droid-host --matrix # full compatibility matrix + +./build/ps5droid-host --matrix +./build/ps5droid-host --inspect-apk tests/fixtures/aapt2-manifest.apk +./build/ps5droid-host --report-json build/host-evidence.json --probe-exec +./build/ps5droid-host --start-attempt ``` -## PS5 build (requires a jailbroken console + ps5-payload-sdk) +`--start-attempt` deliberately reports blockers. `--inspect-apk` reports the +manifest's package name and SDK levels; ZIP magic and filename substrings do not +establish a valid package. The fixture's metadata is independently checkable with +Android's AAPT2 or APK Analyzer. + +### Execute the cooperative ELF fixture + +On an x86-64 host with upstream LLVM Clang and LLD: + +```sh +python3 tools/build_elf_fixture.py --output build/fixtures/cooperative.elf +./build/ps5droid-host --run-cooperative-elf build/fixtures/cooperative.elf +``` + +The expected path is **ELF entry → guest `write` → guest `exit_group` → return**. +The fixture is compiled for LLVM's Android target and explicitly calls a gateway +in place of raw syscall stubs. It has no bionic or Android framework dependency. +This is native machine-code execution, not proof that arbitrary Android binaries +can start. See the [execution contract and remaining blockers](docs/elf-execution.md). + +## Build the experimental PS5 payload + +Use the open-source [ps5-payload-sdk](https://github.com/ps5-payload-dev/sdk). +CI pins its release and SHA-256 in [`.github/ps5-sdk.json`](.github/ps5-sdk.json). ```sh export PS5_PAYLOAD_SDK=/opt/ps5-payload-sdk -cmake -B build-ps5 -G Ninja \ - -DCMAKE_TOOLCHAIN_FILE=$PS5_PAYLOAD_SDK/host/toolchain/prospero.cmake \ - -DPS5DROID_BUILD_PS5=ON -cmake --build build-ps5 --target ps5droid # -> build-ps5/ps5droid.elf +cmake -S . -B build-ps5 \ + -DCMAKE_TOOLCHAIN_FILE="$PS5_PAYLOAD_SDK/toolchain/prospero.cmake" \ + -DPS5DROID_BUILD_PS5=ON -DPS5DROID_SDK_VERSION=v0.45 +cmake --build build-ps5 --target ps5droid ``` -Deploy with `prospero-deploy` over the ELF loader (port 9021). See -[`docs/development.md`](docs/development.md) for prerequisites and -console caveats. **`ps5droid.elf` is a payload, not a PKG**, and has not -been run on a console from this project yet. +The output is `build-ps5/ps5droid.elf`, an ELF payload. Follow the +[console validation procedure](docs/console-validation.md) to deploy it, collect +`/data/ps5droid-evidence.json`, and record firmware/loader and repeat-launch results. +**No verified console result is included in this repository.** + +## Development and evidence + +- [Architecture and milestone boundaries](docs/architecture.md) +- [Host builds, sanitizers, fuzzing and fixture provenance](docs/development.md) +- [Linux ABI and PS5 platform constraints](docs/platform-constraints.md) +- [Binder/RPC scope and concurrency contract](docs/binder-scope.md) +- [APK parser limits](docs/apk-inspection.md) +- [Hardware evidence checklist](docs/console-validation.md) -## Licensing +## License -PS5Droid is MIT-licensed (see [`LICENSE`](LICENSE)). Third-party -references and their licenses are tracked in -[`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md). The project never -bundles or downloads proprietary Sony SDKs, console keys, Google Play -Services, Widevine or proprietary codecs. +PS5Droid is MIT-licensed. External references and linked dependencies are listed +in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). No proprietary platform +components are downloaded or redistributed by the project. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 30e45cc..3b964b2 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -86,3 +86,22 @@ Any future vendored dependency must add an entry here, keep upstream copyright notices, and record the commit/version imported. Proprietary material (Sony SDKs, console keys, Google Play Services, Widevine, proprietary codecs) is never accepted. + +## zlib (linked dependency) + +APK manifest decompression uses upstream [zlib](https://github.com/madler/zlib), +under the [zlib license](https://github.com/madler/zlib/blob/v1.3.2/LICENSE). +Host builds link the system zlib. PS5 builds fetch zlib 1.3.2 from its official +release tag with a SHA-256 pinned in CMake. No zlib implementation is copied into +this repository; its source/license remain with the fetched build dependency. + +## Authored inspection and execution fixtures + +`tests/fixtures/AndroidManifest.xml` and `cooperative_entry.c` are project-authored +MIT-licensed fixtures. `aapt2-manifest.apk` contains the compiled authored manifest +produced by Google AAPT2 8.8.2-12006047 using AOSP API 35 resource definitions. +It contains no framework or proprietary executable code. See +[fixture reproduction](docs/apk-inspection.md). AAPT2 and `android.jar` are build +references used to produce the fixture and are not bundled in the repository. +The binary XML parser was implemented against the publicly documented AOSP +ResourceTypes.h data format; no AOSP parser implementation is copied. diff --git a/cmake/build_info.h.in b/cmake/build_info.h.in new file mode 100644 index 0000000..a4c284e --- /dev/null +++ b/cmake/build_info.h.in @@ -0,0 +1,3 @@ +#pragma once +#define PS5DROID_BUILD_REVISION "@PS5DROID_BUILD_REVISION@" +#define PS5DROID_SDK_VERSION "@PS5DROID_SDK_VERSION@" diff --git a/docs/apk-inspection.md b/docs/apk-inspection.md new file mode 100644 index 0000000..a42ae17 --- /dev/null +++ b/docs/apk-inspection.md @@ -0,0 +1,54 @@ +# Read-only Android package inspection + +`--inspect-apk FILE` emits JSON and exits nonzero when inspection fails. Successful +output describes the real manifest package name, minimum/target SDK, non-directory +entry count, DEX entry names and native-library directory ABIs. These are metadata +observations; they do not assert executable validity or runtime compatibility. + +## Parsing contract + +The parser reads the end-of-central-directory record, validates the advertised +entry count and directory span, checks unique entry names and matching local +headers, and rejects overlapping payloads. Only the manifest is decompressed; +large APK assets are not loaded into memory. Its CRC and decompressed length are +checked before Android binary XML is parsed. + +AXML parsing handles UTF-8 and UTF-16 string pools, typed attributes, the manifest +root and balanced element names. Package and SDK values come from manifest +attributes, not raw filename substrings or fabricated defaults. Android's absent +`uses-sdk` defaults are minimum SDK 1 and target SDK equal to the minimum. + +| Limit | Value / behavior | +| --- | --- | +| Container | Single-disk ordinary ZIP; ZIP64 and encrypted entries rejected | +| Compression | Stored and DEFLATE entries | +| Central directory | At most 16 MiB; ordinary ZIP entry counts | +| Manifest | At most 4 MiB compressed and uncompressed | +| XML | Binary Android XML; string pools capped at 65,535 strings; bounded nesting | +| SDK attributes | Integer values; resource references and preview codenames rejected explicitly | +| Signatures | APK signing blocks may be present; signature verification is not implemented | +| Other entries | Names/structure inspected; DEX/native contents and their CRCs are not verified | +| Extraction/install | Not implemented | + +## Independent fixture + +`tests/fixtures/AndroidManifest.xml` is project-authored. Its binary fixture was +created with Google AAPT2 `8.8.2-12006047` and AOSP's API 35 public `android.jar`: + +```sh +aapt2 link -I android-35.jar --manifest tests/fixtures/AndroidManifest.xml \ + --min-sdk-version 28 --target-sdk-version 35 --no-compile-sdk-metadata \ + -o tests/fixtures/aapt2-manifest.apk +aapt2 dump badging tests/fixtures/aapt2-manifest.apk +``` + +Expected package: `org.ps5droid.inspection`; minimum SDK **28**; target SDK **35**. +The fixture contains no Android framework code or native executable. Python builds +stored/deflated and malformed variants from it for reproducible host tests. + +For another independent check, compare `apkanalyzer manifest application-id`, +`manifest min-sdk`, `manifest target-sdk` and `files list` with the CLI output. + +Primary format/tool references: [AOSP ResourceTypes.h](https://android.googlesource.com/platform/frameworks/base/+/HEAD/libs/androidfw/include/androidfw/ResourceTypes.h), +[PKWARE APPNOTE](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT), +[APK Analyzer](https://developer.android.com/tools/apkanalyzer). diff --git a/docs/architecture.md b/docs/architecture.md index 1286e2b..832760c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,159 +1,58 @@ -# PS5Droid Architecture - -Status: living document describing the implemented system and the planned -path toward native Android execution. Companion documents: -`platform-constraints.md` (what the PS5 allows), `waydroid-analysis.md` -(what upstream does), `development.md` (how to build/test). - -## 1. Design goal and non-goals - -**Goal**: a *native* Orbis homebrew payload that can eventually host -Android application components directly — no Linux boot, no VM, no -streaming, no conventional Waydroid install. - -**Non-goals (explicitly)**: running a Linux kernel on the PS5, running -unmodified Android system images, Google Play / proprietary components. - -## 2. Module map (implemented) - -``` -src/ -├── platform/ portable platform layer -│ ├── platform.h logging/time/memory/threads/fs API -│ ├── log.cpp logging + backend identity -│ ├── memory.cpp mmap-backed page allocator (shared by both ABIs) -│ ├── threads.cpp C11-threads core + futex-like registry -│ ├── filesystem.cpp stdio/dirent file access -│ ├── display.h/.cpp Framebuffer + DisplayBackend + host impl -│ ├── audio.h/.cpp AudioBackend (explicitly unsupported today) -│ └── ps5/ PS5-only code (compiled solely in SDK builds) -│ ├── sce_decls.h hand-maintained firmware declarations (provenance documented) -│ ├── display_ps5.cpp video-out + direct-memory + flip queue -│ └── input_ps5.cpp scePad backend -├── compat/ Linux ABI experiment (Milestone 3) -│ ├── linux_abi.h/.cpp syscall constants + verified FreeBSD mapping -│ ├── memory_compat.cpp Linux brk + anonymous mmap semantics -│ ├── syscall_dispatch.cpp Linux syscall number -> emulated op dispatch -│ └── ipc_compat.cpp SPSC ring + Binder-style block allocator -├── android/ -│ ├── sha256.cpp FIPS 180-4 (clean-room) -│ ├── image_manager.cpp manifest parsing + ext4 superblock probe -│ ├── runtime_manager.cpp capability probes + honest start attempts -│ └── binder/binder_protocol.h research notes (no implementation) -├── ui/ -│ ├── launcher.cpp menu state machine (portable) -│ └── bitmap_font.cpp 8x8 font authored in-repo + renderer -└── app/ - ├── main.cpp host CLI: probes + ABI demo + matrix - └── ps5_main.cpp PS5 payload entry (SDK builds only) +# Architecture and evidence boundaries + +PS5Droid investigates Android component hosting inside a native PS5 homebrew +payload. Its layers are independently testable. A passing lower layer never +promotes the Android environment to `Running`. + +```mermaid +flowchart TD + Host[Host CLI: reports, inspection, execution experiment] + Console[PS5 payload: launcher, video-out, pad, evidence] + Host --> Runtime[Runtime manager and structured blockers] + Console --> Runtime + Host --> APK[ZIP and binary manifest inspector] + Host --> ELF[ELF inspector and cooperative runner] + ELF --> ABI[Linux syscall dispatch and guest descriptors] + Runtime --> ABI + Runtime --> RPC[Bounded synchronous RPC experiment] + ABI --> Platform[Memory, threads, filesystem, clocks] + Console --> Hardware[PS5 video-out and DualSense backend] ``` -Build rules enforced by CMake: - -* `ps5droid_core` is portable; PS5-only sources are added only when the - ps5-payload-sdk toolchain is active (`PROSPERO`). -* The host binary (`ps5droid-host`) and tests are never built for PS5, - and the PS5 ELF is never built without the SDK toolchain. - -## 3. Layering and data flow - -``` -+--------------------------------------------------------------+ -| app/main.cpp (host) app/ps5_main.cpp (PS5 payload) | -+--------------------------------------------------------------+ -| ui/launcher (menu model) | ui/bitmap_font (rendering) | -+---------------------------+----------------------------------+ -| android/runtime_manager | android/image_manager | -| - capability probes | - manifest + ext4 probe | -| - blocker reporting | - sha256 verification | -+---------------------------+----------------------------------+ -| compat/syscall_dispatch (Linux ABI experiment) | -| uses compat/memory_compat + platform::Futex | -+---------------------------------------------------------------+ -| platform/ (memory, threads, fs, display, input) | -| posix backend (hosts/CI) | ps5 backend (Orbis payload) | -+---------------------------------------------------------------+ -``` - -The **single source tree** compiles for both backends; divergence points -are small and explicit (sce_decls.h, the two ps5 backend files, and -per-file `#ifdef PS5DROID_PLATFORM_PS5` sections in the platform core). - -## 4. The Linux ABI experiment (Milestone 3, scope and honesty) - -`SyscallDispatch::invoke(linux_nr, args)` accepts Linux x86_64 syscall -numbers and executes a curated subset: - -* anonymous `mmap`/`munmap`/`mprotect` and `brk` over - `compat::CompatMemory`, which in turn uses `platform::map_anonymous` - (real OS mappings on both backends); -* `clock_gettime`, `nanosleep`, `sched_yield` over platform clocks; -* `getpid`/`gettid` under the documented single-process model; -* `futex` WAIT/WAKE (private) over `platform::Futex` (registry-based, - wake-atomicity mirrors Linux's kernel-side check-and-enqueue); -* `write` to the process streams (fd 1/2); -* `exit_group` flags the context. - -Everything else returns `-ENOSYS` with a *stable, explanatory note* -sourced from the syscall table. The matrix (9 emulated / 3 partial / -65 unsupported at time of writing) is data, not prose: -`ps5droid-host --matrix` prints it and tests assert its integrity. - -**Scope limitation (important)**: pointer arguments are host pointers. -This experiment demonstrates *ABI translation*, not address-space -isolation or multi-process hosting. Lifting that limitation is future -work and gated on process-model research. - -## 5. Runtime manager and honesty model - -`android::RuntimeManager` is the only component allowed to describe -overall system status: - -* `probe()` runs eight real, in-process capability probes (page size, - map/unmap, protect, threads, futex, filesystem, IPC ring, ABI mmap) - and reports each result. Every "[OK]" corresponds to executed code. -* `attempt_start()` performs an Android-environment start attempt. It - **always** ends in `kBlocked` today, with structured blockers: - `process_model`, `binder`, `filesystem_layout`, `graphics_services`, - `bionic_runtime`. The state machine cannot reach `kRunning` — asserted - by tests (`phase_is_never_running`). - -## 6. PS5 payload path - -`ps5_main.cpp` hides the splash screen, initializes 1920x1080 -double-buffered video-out (direct memory, vsync flips via event queue) -and the pad, renders the launcher with the bitmap font, and exits -cleanly releasing direct memory. The firmware declarations it needs are -hand-maintained in `sce_decls.h` with provenance notes (verified against -ps5-payload-sdk stub symbols and the SDL port's working usage). - -Status: **implemented, not executed on a console** — this is stated in -the header, README and every status table. The build path exists and is -documented in `development.md`; CI builds it only when explicitly -requested. - -## 7. What replaces what (Waydroid mapping) - -| Waydroid component | PS5Droid equivalent | -|---|---| -| LXC container manager | none — single-process emulation context | -| loop-mounted ext4 rootfs | read-only image inspection (ext4 probe) | -| binder/binderfs | in-process dispatch + SPSC ring + block allocator (start) | -| Wayland hwcomposer HAL | direct video-out + bitmap-font UI | -| PulseAudio audio HAL | nothing yet (explicitly unsupported) | -| D-Bus/systemd orchestration | RuntimeManager state machine | -| OTA images + sha256 | ImageManifest + Sha256 (reimplemented) | -| waydroid.prop | ImageManifest properties | - -## 8. Roadmap (from the milestone plan) - -1. **M1 done** — host foundation, tests, CI, PS5 build path (ELF-only). -2. **M2 next** — run the same probes on a real console via elfldr and - fill the [ASSUMPTION] items in `platform-constraints.md`. -3. **M3 partially done** — anonymous-memory subset demonstrated - end-to-end; extend toward the fd table and kqueue-backed poll layer. -4. **M4** — bionic feasibility study (linker/TLS/auxv) with the ABI - matrix as the checklist. -5. **M5** — scoped Binder re-hosting experiment (transaction semantics - over the block allocator). -6. **M6** — APK launch research; only after M4/M5 evidence exists. +## Contracts + +| Layer | Contract | Deliberate boundary | +| --- | --- | --- | +| `platform/` | Native allocation, I/O, clocks and synchronization | Host success does not establish PS5 behavior | +| `compat/fd_table` | Explicit guest flags, native file descriptions, eventfd, limited readiness | No guest rootfs, pipe/socket routing or edge-triggered epoll | +| `compat/syscall_dispatch` | Linux numbers and guest structure layouts; `ret=-1` plus separate Linux `err` on failure | Ordinary pointer arguments remain trusted host pointers | +| `compat/bionic_loader` | Bounded header inspection and address-correct initial stack data | Minimal auxv; no complete bionic TLS/linker implementation | +| `compat/elf_runner` | Explicit cooperative entry and allowlisted syscall callback | No raw-syscall interception, relocations, process isolation or arbitrary binary support | +| `android/apk_inspector` | Read-only ZIP directory, binary XML and manifest metadata | No package installation, signature verification or resource reference resolution | +| `android/binder` | Bounded synchronous internal RPC | No Binder ioctl, Parcel wire compatibility or Android services | +| `android/runtime_manager` | Execute probes; return reasoned startup blockers | `Running` remains unreachable | +| `android/evidence_report` | Versioned JSON with backend, revision and measured observations | Unrecorded hardware facts remain unrecorded | + +The cooperative gateway converts the dispatch result into raw Linux-style +negative errno values. The host C++ API keeps its existing separate `err` field. +Linux x86-64 `stat` and packed `epoll_event` layouts have compile-time size checks; +Linux flags and errno are translated instead of passed through as host values. + +## Milestones + +| Milestone | Evidence delivered | Remaining gate | +| --- | --- | --- | +| M1: foundation | Host tests and reproducible build workflows | Maintain host/console separation | +| M2: console | Payload and versioned evidence capture | Real console run, firmware/loader record and repeat-launch cleanup checks | +| M3: Linux ABI | Descriptor/memory fixes and eventfd readiness tests | Broader process, signal, filesystem and event-loop compatibility | +| M4: executable loading | ELF validation, stack staging and trusted cooperative execution experiment | Unmodified bionic, TLS, dynamic linking/relocations and raw syscall routing | +| M5: Binder | Bounded internal RPC with concurrent/reentrant/error tests | Android Binder compatibility and service implementation | +| M6: package inspection | ZIP/AXML metadata checked against an AAPT2-authored fixture | Android environment startup and application execution | + +A native machine-code fixture and an internal RPC callback are useful evidence +for their own contracts. Neither closes the bionic or Binder compatibility gate. +Firmware declarations cite the public SDK and SDL port; they still need runtime +validation on every claimed console configuration. + +Related: [ELF execution](elf-execution.md), [RPC scope](binder-scope.md), +[APK limits](apk-inspection.md), [console evidence](console-validation.md). diff --git a/docs/assets/banner.svg b/docs/assets/banner.svg new file mode 100644 index 0000000..146c9b4 --- /dev/null +++ b/docs/assets/banner.svg @@ -0,0 +1,13 @@ + +PS5Droid — native Android runtime research +Research layers: ELF, Linux ABI, Android services, PS5 platform. Console validation remains pending. + + + + +NATIVE RUNTIME RESEARCH +PS5Droid +Small experiments. Explicit limits. Reproducible evidence. +ELF + Linux ABIAndroid component researchPS5 platform probes + + diff --git a/docs/binder-scope.md b/docs/binder-scope.md new file mode 100644 index 0000000..085a393 --- /dev/null +++ b/docs/binder-scope.md @@ -0,0 +1,40 @@ +# Binder research: internal RPC contract + +`BinderEngine` retains its research name and is a **bounded synchronous in-process +RPC engine**. It does not implement Android Binder IPC. In particular, it does not +provide `/dev/binder`, `BINDER_WRITE_READ`, BC/BR command streams, Parcel/object or +file-descriptor transfer, refcount/death notifications, one-way dispatch or an +Android ServiceManager. The previous invented command-number enums were removed. + +## Implemented behavior + +| Operation | Behavior | +| --- | --- | +| Register | Nonempty name and valid handler required; duplicate names retain their existing service | +| Reserved handle | Handle zero has no success stub; `servicemanager` cannot be registered | +| Missing lookup | Returns `BinderEngine::kInvalidHandle`, distinct from zero | +| Transaction | Copies input into an exclusively owned allocation; executes a synchronous callback | +| Limits | 256-byte input/reply limit, fixed allocation region and maximum active transaction count | +| Failures | Typed invalid-handle, unsupported-flags, oversized-payload, capacity/allocation and handler-error results | +| Legacy boolean API | Clears output first and succeeds only for `RpcStatus::kOk` | + +## Ownership and concurrency + +The engine owns its service registry and transaction buffers. One mutex protects +registry/allocation changes. It is released before callbacks run, allowing nested +calls and simultaneous handlers without an engine-wide callback lock. Each call +has a private staging block released through RAII, including exception paths. +The former unsynchronized allocator/SPSC completion sequence is removed. + +The caller owns `user` data and must keep it alive until all transactions finish. +Handlers must synchronize their own shared data. Engine destruction requires all +calls to have completed. There is no unregister API, asynchronous lifetime model +or cancellation guarantee. + +Tests cover invalid/reserved handles, rejected flags, oversized data, allocation +exhaustion, exception cleanup, nested calls with sufficient/insufficient capacity, +and eight concurrent callers. ThreadSanitizer runs this behavior in CI. + +Android compatibility remains a separate implementation/research gate. Its protocol +must be validated against [AOSP Binder](https://source.android.com/docs/core/architecture/hidl/binder-ipc) +and actual libbinder clients before any compatibility claim is made. diff --git a/docs/console-validation.md b/docs/console-validation.md new file mode 100644 index 0000000..a4b4c0d --- /dev/null +++ b/docs/console-validation.md @@ -0,0 +1,82 @@ +# Console validation and evidence + +> **Hardware execution is pending.** This document is a procedure and report +> contract, not a record of a successful PS5 run. + +## Before deployment + +Use a console already capable of running an ELF loader. Record its firmware, +exploit/loader name and version, SDK release, exact source revision and ELF SHA-256. +Do not infer support for another firmware from one successful run. Use the +open-source SDK and loader documentation for the actual supported setup. + +Build as described in [development.md](development.md), then deploy: + +```sh +export PS5_HOST=your-console-address +"$PS5_PAYLOAD_SDK/bin/prospero-deploy" -h "$PS5_HOST" -p 9021 \ + build-ps5/ps5droid.elf +``` + +## What the payload records + +The payload probes platform behavior using unique temporary files in `/data` and +writes `/data/ps5droid-evidence.json` before video initialization, after subsequent +initialization stages, and after a normal launcher exit. Failure to persist the +report is logged; it must not be mistaken for an empty successful report. + +| Field / observation | Interpretation | +| --- | --- | +| `schema_version` | Report format version, currently 1 | +| `backend` | Distinguishes host and console runs | +| `revision` | Configured source revision, with `-dirty` when applicable | +| `sdk` | Explicit build pin, or `unrecorded` | +| `firmware`, `loader` | `unrecorded` until supplied by the tester | +| `platform_probes_passed` | Only the aggregate platform probe result | +| `rx_memory` | Native RW → RX protection accepted/refused; no JIT or ART claim | +| `video_init`, `pad_init` | Actual initialization return results | +| `video_flips` | Count of successful submit/wait operations; failed waits stop the loop | +| `connected_pad`, `button_edges` | Observed connection polls and navigation/exit edges | +| `cleanup` | Whether shutdown was reached; resource release requires external/repeat-launch checking | +| `android_runtime` | `blocked`, regardless of lower-level probe success | + +API declarations and struct layouts remain subject to hardware validation. A +failed RX probe may be a genuine privilege limitation; preserve it as a failure. +The payload performs no kernel privilege changes or JIT permission workaround. + +## Hardware procedure + +1. Save a copy of the report immediately after startup if available. +2. Confirm stable video output and open the probe screen. Exercise D-pad, Cross, + Circle and Options; note disconnect/reconnect behavior separately. +3. Let multiple frames present, then exit through Options. +4. Retrieve the report with your existing console file-transfer tooling. A report + left from a previous process is not evidence for a new run; compare revision + and the externally recorded run identifier/time. +5. Relaunch at least twice and verify that display and input initialize again. + Observe available memory/resource diagnostics if your setup provides them. +6. Preserve logs, screenshots, failed operations and any missing observations. + +Use the annotation tool on the copied report; it refuses a host report and keeps +the original measurements intact: + +```sh +python3 tools/annotate_console_report.py copied-console-report.json \ + --firmware YOUR_VERSION --loader 'loader-name VERSION' \ + --elf build-ps5/ps5droid.elf --run-id YOUR_RUN_ID \ + --output console-report.annotated.json +``` + +The annotations record tester-supplied provenance, not automatically measured +firmware or loader detection. Add repeat-launch/cleanup observations to a separate +run note and link both artifacts in the PR or issue. Do not commit console +addresses, credentials or unrelated private information. + +## Host report for comparison + +```sh +./build/ps5droid-host --report-json build/host-evidence.json --probe-exec +``` + +This checks the schema and host implementation. It is never eligible for promotion +to console evidence. No verified console report is shipped with this change. diff --git a/docs/development.md b/docs/development.md index 6832407..2e81934 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,108 +1,98 @@ -# Development Guide +# Development and reproducible validation -## 1. Repository layout +## Host builds -See `docs/architecture.md` for the module map. Tests live in `tests/` -and use the in-repo micro framework (`tests/test_framework.h`) — no -third-party test dependencies. +Use CMake ≥ 3.16, a C++17 compiler and zlib. Python 3 generates test fixtures; +Ninja is optional. On Ubuntu, install `cmake ninja-build g++ clang zlib1g-dev`. +macOS uses its SDK zlib and a pthread adapter because Apple does not ship C11 +`threads.h`; Linux and the PS5 SDK retain the existing C11 thread backend. -## 2. Host build and test (Linux/macOS) +```sh +cmake -S . -B build -G Ninja +cmake --build build +ctest --test-dir build --output-on-failure +./build/ps5droid_tests +``` + +CTest has a 30-second suite timeout. Tests exercise behaviors including failed +operations and malformed input, not just successful allocation or nonempty output. +The exact current test count is printed by the executable rather than duplicated +across documents. -Prerequisites: CMake >= 3.16, a C++17 compiler (gcc or clang), Ninja or -Make. +## Sanitizers and fuzzing ```sh -cmake -B build -G Ninja -cmake --build build -ctest --test-dir build --output-on-failure # runs the unit suite -./build/ps5droid-tests # direct run, verbose -./build/ps5droid-host # capability probes + ABI demo -./build/ps5droid-host --matrix # full Linux ABI matrix -./build/ps5droid-host --start-attempt # honest blocker report +CC=clang CXX=clang++ cmake -S . -B build-asan -G Ninja \ + -DPS5DROID_SANITIZERS=address,undefined +cmake --build build-asan +ctest --test-dir build-asan --output-on-failure + +CC=clang CXX=clang++ cmake -S . -B build-tsan -G Ninja \ + -DPS5DROID_SANITIZERS=thread +cmake --build build-tsan +ctest --test-dir build-tsan --output-on-failure + +CC=clang CXX=clang++ cmake -S . -B build-fuzz -G Ninja \ + -DPS5DROID_BUILD_FUZZER=ON +cmake --build build-fuzz --target ps5droid_fuzz +./build-fuzz/ps5droid_fuzz -runs=10000 -max_len=65536 ``` -Sanitizer run (recommended before commits; caught real bugs in this -repo): +Address/UndefinedBehaviorSanitizer and ThreadSanitizer run separately. The +libFuzzer target instruments ELF header and text image-manifest parsing. APK +inspection has deterministic malformed-container/AXML regression tests; this +harness does not claim APK fuzz coverage. Do not execute mutated ELF inputs. + +Linux additionally compares supported eventfd/epoll behavior with native Linux +APIs. Regular files are explicitly rejected as epoll targets, matching Linux's +behavior. Only level-triggered eventfd readiness is currently implemented. + +## Formatting and documentation ```sh -g++ -g -O1 -fsanitize=address,undefined -std=c++17 \ - -Isrc -Itests tests/*.cpp src/platform/*.cpp src/compat/*.cpp \ - src/android/*.cpp src/ui/*.cpp -o /tmp/ps5d_tests_asan -/tmp/ps5d_tests_asan +python3 -m pip install clang-format==23.1.3 +git ls-files '*.cpp' '*.h' '*.c' | xargs clang-format --dry-run --Werror +python3 tools/check_docs.py ``` -## 3. PS5 payload build (requires ps5-payload-sdk) +Documentation hygiene validates relative links and rejects stale execution claims. +Keep source/API contracts and capability labels aligned. Use the live +`ps5droid-host --matrix` output rather than hard-coded syscall counts. -PS5Droid targets the open-source [ps5-payload-sdk] -(https://github.com/ps5-payload-dev/sdk) (GPL-3.0; its -`include/freebsd` headers are BSD). Install it per its README (release -zip or `make install`), then: +## PS5 cross-build + +The release URL, version and checksum are tracked in `.github/ps5-sdk.json`. +CI verifies the archive before installing it. Changing the pin requires fetching +that exact release and verifying its digest; `releases/latest` is not used. ```sh export PS5_PAYLOAD_SDK=/opt/ps5-payload-sdk -cmake -B build-ps5 \ - -G Ninja \ - -DCMAKE_TOOLCHAIN_FILE=$PS5_PAYLOAD_SDK/toolchain/prospero.cmake \ - -DPS5DROID_BUILD_PS5=ON +cmake -S . -B build-ps5 -G Ninja \ + -DCMAKE_TOOLCHAIN_FILE="$PS5_PAYLOAD_SDK/toolchain/prospero.cmake" \ + -DPS5DROID_BUILD_PS5=ON -DPS5DROID_SDK_VERSION=v0.45 cmake --build build-ps5 --target ps5droid -# produces build-ps5/ps5droid.elf (an ELF payload, NOT a PKG) ``` -Deploy to a console already running an ELF loader: +PS5 builds compile upstream zlib 1.3.2 from a URL and SHA-256 pinned in CMake. +The first configure needs network access; an offline build may prepopulate +`FETCHCONTENT_SOURCE_DIR_ZLIB`. Its source is under the zlib license. +Host binaries/tests are excluded from PS5 builds. The output is an ELF payload, +not a PKG. See [console validation](console-validation.md) for deployment. -```sh -export PS5_HOST=; export PS5_PORT=9021 -$PS5_PAYLOAD_SDK/bin/prospero-deploy -h $PS5_HOST -p $PS5_PORT \ - build-ps5/ps5droid.elf -``` +## CI evidence + +The workflow runs formatting/docs checks; Linux GCC/Clang builds; separate +ASan/UBSan and TSan suites; macOS portability; a bounded parser fuzz smoke; +cooperative x86-64 ELF execution; CLI/JSON metadata checks; and the pinned PS5 +cross-build. It uploads logs, host JSON reports and the PS5 ELF checksum. + +A job's configured existence does not establish a pass. Inspect the actual run +and artifacts for the tested revision. No CI job claims to execute on a PS5. + +## Contribution rules -Without `PS5DROID_BUILD_PS5=ON` and the toolchain file the PS5 target is -skipped with a CMake status message; with the flag but no toolchain the -configure step fails loudly (no silent fake builds). - -**Status reminder**: the PS5 payload compiles against verified API -usage but has not been executed on a console from this project. Treat -console results as new evidence when you get them, and record them in -`docs/platform-constraints.md`. - -## 4. Coding conventions - -* C++17, no exceptions thrown across module boundaries; results are - returned as structs/enums. -* Notes returned to users (`DispatchResult::note`, blockers) must be - static strings or stable storage — never stack buffers. -* Every syscall added to `compat/linux_abi.h` must (a) carry a support - class and honest note, (b) have a handler or return `-ENOSYS`, and - (c) extend the tests (`test_compat_matrix.cpp` anchors the ABI facts). -* PS5 firmware API usage must cite provenance in `sce_decls.h`. -* clang-format config at `.clang-format` (LLVM-based, 4-space indent). - -## 5. CI - -`.github/workflows/ci.yml` runs on every push/PR: - -1. **lint** — clang-format check + repository hygiene (required files, - no stale build dirs). -2. **host** — gcc and clang builds, unit tests via CTest, logs uploaded - as artifacts. -3. **ps5** — runs on every push and PR; installs the official ps5-payload-sdk release, - cross-builds `ps5droid.elf`, and uploads it with an explicit "ELF payload, not a - PKG" note. It never signs packages. - -## 6. Honesty policy (project rules) - -1. No fake SDK headers, no placeholder successes, no fabricated results. -2. Features are classified: *implemented and tested (host)* / - *implemented, not tested on console* / *experimental* / *not - implemented* / *blocked*. Every status table in the repo uses these. -3. Anything that cannot be done returns an error with an explanation - (e.g. `-ENOSYS` with a note) instead of pretending. -4. Proprietary material (Sony SDKs, console keys, Play Services, - Widevine, proprietary codecs) is never bundled or downloaded. - -## 7. Test conventions - -* One behavior per test; deterministic (no sleeps where avoidable — the - single 1s futex wake test bounds a thread scheduling worst case). -* Tests must clean up files they create. -* The suite must stay fast (< ~5 s) and green on both gcc and clang. +- Report errors and unsupported semantics explicitly; do not silently grant capabilities. +- Keep host C++ results (`ret=-1`, separate Linux errno) distinct from raw guest `-errno`. +- Tests involving threads must join before returning, including failure paths. +- Preserve fixture provenance and dependency licenses. +- Source every firmware declaration and record hardware evidence separately. diff --git a/docs/elf-execution.md b/docs/elf-execution.md new file mode 100644 index 0000000..5fd6b31 --- /dev/null +++ b/docs/elf-execution.md @@ -0,0 +1,62 @@ +# Cooperative ELF execution experiment + +The experiment maps and executes a **trusted, freestanding x86-64 ELF fixture**. +LLVM compiles it with `--target=x86_64-linux-android28`; LLD emits ET_DYN with a +single RX load segment. The sample does not link bionic. It is not an APK launch, +an unmodified Android executable, an instruction interpreter or a general loader. + +## Reproduce + +```sh +python3 tools/build_elf_fixture.py --clang clang --linker ld.lld \ + --output build/fixtures/cooperative.elf +./build/ps5droid-host --run-cooperative-elf build/fixtures/cooperative.elf +``` + +Use upstream LLVM's `clang`, not Apple Clang, to build the Android-target object. +The runner must be an x86-64 process. An ARM host build returns an explicit +unsupported result. Building this existing x86-64 experiment does not add an +ARM translation strategy or narrow the project's intended application scope. + +The CLI requires all three conditions: entry executed, `exit_group` requested, +and entry returned zero. It returns a nonzero exit status if any condition fails. +The ordinary runtime manager continues to report Android startup as blocked. + +## Entry contract + +```c +typedef long long (*gateway_fn)(void* context, int linux_nr, + const unsigned long long args[6]); +long long entry(void* context, gateway_fn gateway, + const unsigned char* staged_initial_stack); +``` + +The entry is a normal SysV C function and returns to the runner. It receives +Linux-shaped `argc`/`argv`/`envp`/auxv bytes as its third argument; the runner does +not replace the process's live stack or thread pointer. The fixture checks its +staged argument, requests `getpid`, writes its message and requests `exit_group`. +The callback accepts those three operations and converts failures to `-errno`. + +## Validation and limits + +- ELF64 little-endian x86-64, valid header sizes, bounded program table and segment ranges. +- Correct subtraction-based bounds checks, unaligned-input support and validated entry coverage. +- Runner requires ET_DYN, nonoverlapping host-page-aligned segments and a mapped program table. +- Load image capped at 64 MiB. Argument/environment staging capped at 1 MiB and 4,096 strings per list. +- Pages transition from writable loading memory to final permissions. Writable/executable segments fail. +- Dynamic segments, interpreter segments and TLS execution fail explicitly; relocation processing is absent. +- Executable segments containing raw `0f 05` bytes are conservatively rejected. This is not instruction decoding or a syscall interceptor. +- The stack contains actual strings and valid staged addresses; auxv contains mapped program-header/entry addresses and the measured page size. +- The image, callback and host pointers share a process. **This is not a sandbox. Run only the authored fixture or equally trusted cooperative code.** + +A complete bionic startup additionally needs TLS/thread-pointer coordination, +full auxiliary-vector requirements, dynamic linking/relocations, Android filesystem +layout, signals and a validated raw-syscall or rebuilt-libc strategy. These remain +explicit blockers rather than simulated successes. + +`--report-json ... --probe-exec` separately checks whether RW → RX protection is +accepted. That result does not prove instruction execution, JIT support or ART +startup. Console execution remains unverified until hardware evidence is recorded. + +Format references: [System V ELF ABI](https://gabi.xinuos.com/elf/07-pheader.html), +[Android ELF TLS](https://android.googlesource.com/platform/bionic/+/HEAD/docs/elf-tls.md). diff --git a/docs/platform-constraints.md b/docs/platform-constraints.md index c7575ad..26401f0 100644 --- a/docs/platform-constraints.md +++ b/docs/platform-constraints.md @@ -1,224 +1,95 @@ -# PS5 Platform Constraints - -Status: research document. Every claim below is labeled: - -* **[VERIFIED-SOURCE]** — read directly from primary sources available to - this project (ps5-payload-sdk / elfldr / SDL-port source trees, cloned - 2026-10-18; file paths cited). -* **[VERIFIED-TEST]** — exercised by a test in this repository on the host - backend (see `tests/`); on-console equivalence still requires a console - run. -* **[ASSUMPTION]** — plausible, unverified; must be probed before relying - on it. These feed Milestone 2 probe work. - -Target: a jailbroken PlayStation 5 running native homebrew payloads, as -enabled by the open-source tooling described below. PS5Droid does not use, -download or redistribute any proprietary Sony SDK. - -## 1. CPU and kernel - -* **[VERIFIED-SOURCE]** The PS5 runs Orbis OS on an x86_64 AMD CPU. The - ps5-payload-sdk CMake toolchain (`sdk/host/toolchain/prospero.cmake`) - sets `CMAKE_SYSTEM_PROCESSOR x86_64`, `CMAKE_SYSTEM_NAME FreeBSD`, - `CMAKE_SYSTEM_VERSION 9` — i.e. a FreeBSD 9-lineage kernel ("prospero" - is the PS5's internal codename). -* **[VERIFIED-SOURCE]** The SDK requires host clang-18/lld-18 and produces - standard ELF x86_64 executables; position-independent executables only - (`CMAKE_POSITION_INDEPENDENT_CODE ON`, shared libs off by default). -* **[ASSUMPTION]** 8-core Zen 2 CPU; exact exposed core count for payloads - should be probed at runtime (planned probe). - -## 2. Executable format, loading and packaging - -* **[VERIFIED-SOURCE]** Homebrew payloads are plain ELF binaries pushed - over TCP. `ps5-payload-elfldr` (`elfldr/README.md`) accepts ELFs on - port 9021, bootstraps itself via the ptrace syscall into the - `SceRedisServer` process of a console already jailbroken by an ELF - loader exploit (BD-J payload loader or a webkit-based kernel exploit), - and spawns each payload as its own process. -* **[VERIFIED-SOURCE]** Firmware entry points are declared by hand in - payloads; the SDK ships symbol stubs (`sdk/sce_stubs/*.c`) generated - from decrypted modules, and the `install_app` sample demonstrates - fake-signed SELF creation (`make_fself.py`) plus app installation via - `SceAppInstUtil` with a FAKE title id. This is the ecosystem path for - installed apps; PS5Droid currently targets the simpler ELF-payload path - and produces **no PKG**. -* **[VERIFIED-SOURCE]** The SDK's `crt/` provides `_start`, a dynamic - loader for payload-local shared objects (`rtld*.c`), and an - `__crt_syscall` entry for direct syscalls (`crt/syscall.h`). -* **[ASSUMPTION]** which exploit/loader pairs support which firmware - versions changes over time; verify against the loader projects when - planning console testing. - -## 3. Syscall ABI — the central constraint - -**[VERIFIED-SOURCE]** `sdk/crt/syscall.h` lists the Orbis syscall numbers -the SDK relies on; they are FreeBSD-amd64 numbers, NOT Linux numbers: - -| Operation | Linux x86_64 | Orbis (FreeBSD) | Note | -|---|---|---|---| -| read | 0 | 3 | verified both sides | -| write | 1 | 4 | verified both sides | -| open | 2 | 5 | verified both sides | -| close | 3 | 6 | verified both sides | -| getpid | 39 | 20 | verified both sides | -| access | 21 | 33 | verified (sdk) | -| munmap | 11 | 73 | verified both sides | -| mprotect | 10 | 74 | verified both sides | -| stat | 4 | 188 | verified (sdk) | -| mmap | 9 | 477 | verified both sides | -| lseek | 8 | 478 | verified (sdk) | -| sysctl | — | 202 | Orbis-only entry in SDK | -| mdbg_call / sprx_dlsym / sprx_load / sprx_unload | — | 573/591/594/595 | Orbis payload-loader services | - -Consequences (all encoded in `src/compat/linux_abi.h` and tested in -`tests/test_compat_matrix.cpp`): - -1. Linux x86_64 binaries cannot run directly: raw `syscall` instructions - carry different numbers and different argument conventions. -2. A compat layer must translate numbers, validate flags (Linux - `MAP_ANONYMOUS`/`MAP_PRIVATE` constants), and emulate missing - functionality. -3. Only the table above is *verified* for Orbis. PS5Droid's translation - table deliberately maps nothing else; `freebsd_mapping()` returns null - for unverified numbers (enforced by test). - -## 4. Memory - -* **[VERIFIED-SOURCE]** mmap/munmap/mprotect exist in the SDK libc - (`sdk/libc/mman.c` implements mmap over syscall 477 with standard - POSIX semantics; the raw `syscall` instruction is used from userland). -* **[VERIFIED-SOURCE]** GPU-visible "direct memory" is allocated through - dedicated calls. The SDL port demonstrates the full flow: - `sceKernelAllocateMainDirectMemory(size, 0x20000, 3, &phys)` then - `sceKernelMapDirectMemory(&vaddr, size, 0x33, 0, phys, 0x20000)` - (`sdl-ps5/src/video/ps5/SDL_ps5video.c`), with - `sceKernelReleaseDirectMemory` to free. -* **[VERIFIED-TEST]** `platform::map_anonymous`/`unmap`/ - `protect_memory` work on the host backend (zero-filled pages, R/W - protection transitions). The same code paths compile for the PS5 - backend; console verification is pending. -* **[ASSUMPTION]** `sysconf(_SC_PAGESIZE)` works on Orbis; the platform - layer falls back to 4096 and the `page_size` probe reports reality. -* **[ASSUMPTION]** PROT_EXEC allocations for JIT (ART requires one) are a - dedicated research topic; current compat code never requests exec pages - and documents that restriction (`memory_compat.cpp`). - -## 5. Threads, synchronization, signals - -* **[VERIFIED-SOURCE]** The SDK libc ships C11 threads - (`sdk/libc/thrd.c`, `mtx.c`, `cnd.c`, `tss.c`). PS5Droid's portable - Thread/Mutex/CondVar build on `` for both backends. -* **[VERIFIED-SOURCE]** FreeBSD umtx infrastructure headers exist in the - SDK (`include/freebsd/sys/umtx.h`, `thr.h`); a `_umtx_op`-backed futex - is a candidate optimization, not yet wired (the syscall number is NOT - in the verified set). -* **[VERIFIED-TEST]** Threads, mutex/condvar, and a futex-like - wait/wake registry work on host (`tests/test_platform_threads.cpp`). -* **[ASSUMPTION/DESIGN]** Linux signal semantics (`rt_sigaction` etc.) - are NOT implementable on Orbis in the near term; bionic's signal-heavy - paths are a known risk. The compat layer returns `-ENOSYS` for the - signal family. - -## 6. Linux ABI compatibility matrix (current) - -Authoritative live output: `./build/ps5droid-host --matrix`. Summary of -the 77 tracked syscalls: - -* **EMULATED (9)** — real in-process behavior, unit tested: - `write, mmap, brk, sched_yield, nanosleep, getpid, gettid, - clock_gettime, exit_group` -* **PARTIAL (3)** — implemented with documented restrictions: - `munmap` (whole mappings only), `mprotect` (R/W only; PROT_EXEC not - granted), `futex` (WAIT/WAKE + PRIVATE flag only) -* **UNSUPPORTED (65)** — return `-ENOSYS` with an explanatory note. The - hard blockers are `clone/fork/vfork/execve` (no process creation for - payloads), the file-descriptor family (no guest fd table yet), and the - socket/epoll/signal families. - -`getpid` returns the emulation-context id and `gettid` the platform -thread id — single-process model, documented in -`src/compat/syscall_dispatch.h`. - -## 7. Filesystem - -* **[VERIFIED-SOURCE]** Full BSD VFS syscalls exist (SDK libc implements - open/stat/opendir via wrappers; `list_files`, `mntinfo` samples). The - SDK even bundles a **UFS library** (`sdk/libufs/`) matching the - console's internal disk format. -* **[VERIFIED-TEST]** read/write/exists/remove/mkdir/list_dir work on - host; identical stdio/dirent code compiles for PS5. -* **[ASSUMPTION]** writable paths for payloads (e.g. `/data`, - `/user/homebrew` per the toolchain's `CMAKE_INSTALL_PREFIX`) need a - console probe before image storage design. -* **Constraint**: no loop devices, no FUSE, no ext4 driver → Android - ext4 images can be *read* (superblock probe implemented in - `image_manager.cpp`) but not mounted. - -## 8. IPC and networking - -* **[VERIFIED-SOURCE]** Event queues are FreeBSD kqueue objects: - `sceKernelCreateEqueue` returns `struct kevent*` and - `sceKernelWaitEqueue` waits on it (SDL port usage; `sys/event.h` in SDK - headers). This is the natural epoll replacement for any event loop. -* **[VERIFIED-SOURCE]** BSD sockets + `libSceNet`/`libSceNetCtl` stubs - exist; `http2_get` sample performs real networking. -* **[VERIFIED-TEST]** SPSC ring + block allocator (Binder-style - transaction buffers) work cross-thread on host - (`tests/test_ipc_ring.cpp`). -* **Constraint**: no binder/binderfs, no shared `/dev` IPC devices; any - Android IPC must be re-hosted in-process. - -## 9. Graphics, input, audio - -* **[VERIFIED-SOURCE]** Video-out flow (all used by the SDL port): - `sceVideoOutOpen(0xff,0,0,NULL)` → allocate/map direct memory → - `sceVideoOutSetBufferAttribute2` with pixel format - `0x8000000022000000` (A8R8G8B8 sRGB) → `sceVideoOutRegisterBuffers2` → - flip events on an equeue → `sceVideoOutSubmitFlip` (vsync) → - `sceKernelWaitEqueue`. PS5Droid's `ps5/display_ps5.cpp` implements - exactly this flow; status: **implemented, never executed on console**. -* **[VERIFIED-SOURCE]** Pad: `scePadInit/Open/ReadState/Close` with the - DualSense button bitmask and `ScePadData` layout as used by the SDL - port (`sdl-ps5/src/joystick/ps5/SDL_ps5joystick.{h,c}`); PS5Droid's - `ps5/input_ps5.cpp` mirrors it. Same status caveat. -* **[VERIFIED-SOURCE]** Proprietary graphics APIs exist as stubs - (`libSceGnmDriver`, `libSceAgc`, `libSceGnmDriverForNeoMode`), and - Khronos EGL/GLES2 headers are bundled in the SDK; an SDL2 port (zlib) - exists. **No Vulkan driver is available** to homebrew; GPU-accelerated - Android rendering is out of reach for now. -* **[VERIFIED-SOURCE]** `libSceAudioOut` stub symbols exist; PS5Droid has - no audio design yet and reports audio as explicitly unsupported - (`platform/audio.h`). -* **[VERIFIED-SOURCE]** `sceSystemServiceHideSplashScreen` and - `sceKernelSendNotificationRequest` are used by SDK samples. - -## 10. Firmware, jailbreak and privilege model - -* **[VERIFIED-SOURCE]** Payloads require a console already running an - exploit-based ELF loader (see `elfldr/README.md`); the loader - ptrace-bootstraps into `SceRedisServer` and survives rest mode. -* **[VERIFIED-SOURCE]** The SDK exposes exploit-provided kernel read/write - helpers (`include/ps5/kernel.h`: `kernel_copyin/copyout`, proc/ucred - offsets) — evidence that *some* consoles grant kernel access, but - PS5Droid deliberately depends only on plain userland facilities. -* **[ASSUMPTION]** Capability ceilings (which syscalls/privileges a - payload process retains, e.g. for raw socket or process inspection) - must be probed on console; `sdk/samples/test_privileges` exists as a - reference tool. - -## 11. Implications for running Android (Milestones 4-6 outlook) - -1. bionic binaries: ELF x86_64 is the *right format* on paper, but bionic - executables link against Linux-specific ELF/TLS/auxv layouts and issue - Linux syscalls directly — both blocked without the (incomplete) compat - layer and a loader PS5Droid does not have yet. -2. ART: needs JIT (exec pages), futex, robust threads, and a full fd - table — all open items; see `docs/architecture.md` for the plan. -3. Binder, servicemanager, SurfaceFlinger: absent kernel driver and - compositor; in-process re-hosting is the only route - (`src/android/binder/binder_protocol.h`). - -None of this means "impossible" — it means each item is a concrete, -testable work item, and nothing in this repository claims Android -applications run today. +# PS5 platform constraints + +Evidence has three distinct levels: + +- **Source:** an API/signature appears in a cited public SDK or working port. +- **Host:** this repository executes a corresponding host behavior/test. +- **Console:** a PS5 run records the result for a firmware/loader/build tuple. + +**Console evidence is pending.** Source availability and a cross-build are not +proof of runtime behavior or privilege availability. + +## CPU, kernel and executable boundary + +The open-source [ps5-payload-sdk](https://github.com/ps5-payload-dev/sdk) targets +x86-64 and a FreeBSD-derived userspace/kernel ABI. Public SDK sources are the +reference for syscall numbers and native payload loading. Its installed toolchain +is `$PS5_PAYLOAD_SDK/toolchain/prospero.cmake`. + +Linux and FreeBSD syscall numbers differ. For example, Linux x86-64 `read=0`, +`write=1`, `mmap=9` correspond to the project's source-verified FreeBSD mapping +`3`, `4`, `477`. `src/compat/linux_abi.cpp` contains the verified mapping subset; +unknown mappings are never guessed. Direct Linux syscall instructions cannot be +made compatible merely by mapping an ELF image. + +The cooperative execution experiment explicitly replaces syscall stubs with a +callback and has a [limited entry contract](elf-execution.md). Unmodified bionic +TLS, dynamic linking, relocations, raw-syscall routing, signals and a full process +model remain unresolved. + +## Memory and synchronization + +Anonymous mapping and protection have host tests. Guest `mmap` currently accepts +private anonymous non-executable mappings. Alignment uses the backend's measured +page size; rounding and range arithmetic are overflow-checked. Whole-mapping +unmap is supported; arbitrary interior unmaps are not. + +Guest requests for `PROT_EXEC` fail rather than silently succeeding without +executable permission. The separate opt-in host RX probe and the console payload +report whether native RW → RX protection is accepted. That report is not evidence +of JIT execution or ART startup. + +Thread creation and mutex/condition-variable behavior are host-tested. The futex +experiment supports private wait/wake, not the complete Linux futex ABI or signal +semantics. A real console must validate page sizes, thread behavior and privileges. + +## Files, flags and readiness + +Linux open flags, errno, `stat` and packed `epoll_event` layouts must be translated +explicitly. The guest descriptor layer shares open-file lifetimes across `dup`, +uses native positioned reads, and preserves file positions. File paths are host +paths; no guest rootfs or address-space isolation is provided. + +`openat` supports absolute paths or `AT_FDCWD`; relative non-current-directory +fds are rejected. Eventfd supports counter/semaphore modes, nonblocking errors, +overflow checks and blocking wakeups. Epoll supports level-triggered eventfd +readiness, deadlines and wakeups. Nested epoll, edge/one-shot modes, files, +pipes and sockets are outside this implementation's readiness contract. + +The live `./build/ps5droid-host --matrix` output is authoritative for support +labels. Partial operations remain partial even when their supported subset passes. + +Android images can be inspected read-only but are not mounted. APKs can be +inspected without mounting an image. Android filesystem layout/services remain +absent; inability to mount ext4 is not proof that userspace extraction is impossible. + +## Binder and Android services + +An internal [synchronous RPC experiment](binder-scope.md) is available. It does +not implement Android Binder wire compatibility, a Binder device, ServiceManager, +zygote, system_server or Android graphics services. Those remain startup blockers. + +## Display, input, audio and packaging + +Firmware declarations in `src/platform/ps5/sce_decls.h` cite public SDK symbols +and the [SDL PS5 port](https://github.com/ps5-payload-dev/SDL). Video-out uses +GPU-visible direct memory and flip events; DualSense input uses `scePad`. +These paths remain experimental until a hardware run is recorded. + +The event-wait timeout is a pointer as declared in the SDL port, not an integer +value. The backend bounds flip waits, tracks allocation ownership independently +of physical address zero, unmaps its view, and closes input on shutdown. API +return/error behavior and repeat-launch cleanup still require console validation. + +The project currently has no Android GPU integration, SurfaceFlinger services, +audio output backend or PKG packaging. The CPU framebuffer launcher does not +establish Android rendering support. Public API stubs/headers alone do not +establish working GLES or Vulkan drivers. + +## Console test requirements + +Record firmware, exploit/loader/version, SDK pin, exact revision and ELF checksum. +Run probes, exercise controller navigation and repeated flips, exit, then relaunch. +Preserve failures and unrecorded observations. Follow the +[hardware evidence procedure](console-validation.md); do not convert host or CI +results into console status labels. diff --git a/src/android/apk_inspector.cpp b/src/android/apk_inspector.cpp new file mode 100644 index 0000000..58fc1cd --- /dev/null +++ b/src/android/apk_inspector.cpp @@ -0,0 +1,419 @@ +// Read-only ZIP/APK and Android binary XML inspection. Format references: +// PKWARE APPNOTE 6.3.10; AOSP androidfw/ResourceTypes.h. No archive extraction. +#include "android/image_manager.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ps5droid { +namespace android { +namespace { +constexpr size_t kManifestLimit = 4 * 1024 * 1024; +constexpr size_t kDirectoryLimit = 16 * 1024 * 1024; +struct View { + const uint8_t* p; + size_t size; + bool has(size_t at, size_t count) const { return at <= size && count <= size - at; } + uint16_t u16(size_t at) const { return uint16_t(p[at]) | (uint16_t(p[at + 1]) << 8); } + uint32_t u32(size_t at) const { return uint32_t(u16(at)) | (uint32_t(u16(at + 2)) << 16); } +}; +bool read_at(FILE* file, uint64_t offset, void* data, size_t size) { + return offset <= LONG_MAX && fseek(file, static_cast(offset), SEEK_SET) == 0 && + fread(data, 1, size, file) == size; +} +bool utf8(const uint8_t* p, size_t size, size_t expected_units) { + size_t units = 0; + for (size_t i = 0; i < size;) { + uint32_t ch = p[i++]; + size_t extra = 0; + uint32_t minimum = 0; + if (ch >= 0xc2 && ch <= 0xdf) { + ch &= 31; + extra = 1; + minimum = 0x80; + } else if (ch >= 0xe0 && ch <= 0xef) { + ch &= 15; + extra = 2; + minimum = 0x800; + } else if (ch >= 0xf0 && ch <= 0xf4) { + ch &= 7; + extra = 3; + minimum = 0x10000; + } else if (!ch || ch >= 0x80) + return false; + if (extra > size - i) + return false; + while (extra--) { + if ((p[i] & 0xc0) != 0x80) + return false; + ch = (ch << 6) | (p[i++] & 63); + } + if (ch < minimum || ch > 0x10ffff || (ch >= 0xd800 && ch <= 0xdfff)) + return false; + units += ch > 0xffff ? 2 : 1; + } + return expected_units == SIZE_MAX || units == expected_units; +} +void append_utf8(std::string& out, uint32_t ch) { + if (ch < 0x80) + out += static_cast(ch); + else if (ch < 0x800) { + out += static_cast(0xc0 | (ch >> 6)); + out += static_cast(0x80 | (ch & 63)); + } else if (ch < 0x10000) { + out += static_cast(0xe0 | (ch >> 12)); + out += static_cast(0x80 | ((ch >> 6) & 63)); + out += static_cast(0x80 | (ch & 63)); + } else { + out += static_cast(0xf0 | (ch >> 18)); + out += static_cast(0x80 | ((ch >> 12) & 63)); + out += static_cast(0x80 | ((ch >> 6) & 63)); + out += static_cast(0x80 | (ch & 63)); + } +} +bool pool_strings(View v, std::vector& strings) { + if (!v.has(0, 28) || v.u16(2) < 28) + return false; + size_t count = v.u32(8), styles = v.u32(12), start = v.u32(20), style_start = v.u32(24); + size_t header = v.u16(2); + if (count > 65535 || styles > 65535 || !v.has(header, (count + styles) * 4) || + start < header + (count + styles) * 4 || start > v.size || + (style_start && (style_start < start || style_start > v.size))) + return false; + size_t end = style_start ? style_start : v.size; + bool is_utf8 = v.u32(16) & 0x100; + size_t decoded_total = 0; + for (size_t i = 0; i < count; ++i) { + size_t offset = v.u32(header + i * 4); + if (offset >= end - start) + return false; + size_t at = start + offset; + std::string text; + if (is_utf8) { + auto length = [&](size_t& n) { + if (at >= end) + return false; + n = v.p[at++]; + if (n & 0x80) { + if (at >= end) + return false; + n = ((n & 127) << 8) | v.p[at++]; + } + return true; + }; + size_t units, bytes; + if (!length(units) || !length(bytes) || bytes >= end - at || v.p[at + bytes] || + !utf8(v.p + at, bytes, units)) + return false; + if (bytes > kManifestLimit - decoded_total) + return false; + text.assign(reinterpret_cast(v.p + at), bytes); + } else { + if (end - at < 2) + return false; + size_t units = v.u16(at); + at += 2; + if (units & 0x8000) { + if (end - at < 2) + return false; + units = ((units & 0x7fff) << 16) | v.u16(at); + at += 2; + } + if (units > (end - at) / 2 || end - at - units * 2 < 2 || v.u16(at + units * 2)) + return false; + for (size_t j = 0; j < units; ++j) { + uint32_t ch = v.u16(at + j * 2); + if (!ch) + return false; + if (ch >= 0xd800 && ch <= 0xdbff) { + if (++j == units) + return false; + uint32_t low = v.u16(at + j * 2); + if (low < 0xdc00 || low > 0xdfff) + return false; + ch = 0x10000 + ((ch - 0xd800) << 10) + low - 0xdc00; + } else if (ch >= 0xdc00 && ch <= 0xdfff) + return false; + append_utf8(text, ch); + if (text.size() > kManifestLimit - decoded_total) + return false; + } + } + decoded_total += text.size(); + strings.push_back(std::move(text)); + } + return true; +} +bool manifest_xml(const std::vector& data, ApkInspection& out) { + View v{data.data(), data.size()}; + if (!v.has(0, 8) || v.u16(0) != 3 || v.u16(2) != 8 || v.u32(4) != v.size) + return false; + std::vector strings; + std::vector elements; + bool pool_seen = false, root_seen = false, sdk_seen = false; + auto string = [&](uint32_t index) -> const std::string* { + return index < strings.size() ? &strings[index] : nullptr; + }; + for (size_t at = 8; at < v.size;) { + if (!v.has(at, 8)) + return false; + size_t header = v.u16(at + 2), size = v.u32(at + 4); + uint16_t type = v.u16(at); + if (header < 8 || size < header || !v.has(at, size)) + return false; + if (type == 1) { + if (pool_seen || root_seen || !pool_strings({v.p + at, size}, strings)) + return false; + pool_seen = true; + } else if (type == 0x102) { + if (!pool_seen || header != 16 || size < 36) + return false; + uint32_t ns = v.u32(at + 16), name_index = v.u32(at + 20); + const auto* name = string(name_index); + size_t attr_start = v.u16(at + 24), attr_size = v.u16(at + 26), count = v.u16(at + 28); + if (!name || attr_start < 20 || attr_size < 20 || attr_start > size - 16 || + count > (size - 16 - attr_start) / attr_size || elements.size() > 256) + return false; + bool root = elements.empty(); + if (root && (root_seen || *name != "manifest" || ns != UINT32_MAX)) + return false; + if (root) + root_seen = true; + bool sdk = elements.size() == 1 && *name == "uses-sdk" && ns == UINT32_MAX; + if (sdk && sdk_seen) + return false; + if (sdk) + sdk_seen = true; + std::set> attributes; + for (size_t i = 0; i < count; ++i) { + size_t a = at + 16 + attr_start + i * attr_size; + uint32_t ans = v.u32(a), aname = v.u32(a + 4), raw = v.u32(a + 8), + value = v.u32(a + 16); + const auto* key = string(aname); + if (!key || !attributes.insert({ans, aname}).second || v.u16(a + 12) != 8) + return false; + uint8_t value_type = v.p[a + 15]; + if (raw != UINT32_MAX && !string(raw)) + return false; + if (value_type == 3 && !string(value)) + return false; + if (root && *key == "package" && ans == UINT32_MAX) { + if (value_type != 3) + return false; + out.package_name = *string(value); + } + const auto* space = ans == UINT32_MAX ? nullptr : string(ans); + if (ans != UINT32_MAX && !space) + return false; + if (sdk && space && *space == "http://schemas.android.com/apk/res/android" && + (*key == "minSdkVersion" || *key == "targetSdkVersion")) { + // Resource references/codenames cannot be resolved without resources.arsc. + if (value_type != 0x10 && value_type != 0x11) + return false; + if (!value || value > INT32_MAX) + return false; + if (*key == "minSdkVersion") + out.min_sdk = static_cast(value); + else + out.target_sdk = static_cast(value); + } + } + elements.push_back(name_index); + } else if (type == 0x103) { + if (header != 16 || size != 24 || elements.empty() || v.u32(at + 20) != elements.back()) + return false; + elements.pop_back(); + } else if (type == 0x100 || type == 0x101) { + if (header != 16 || size != 24 || !string(v.u32(at + 20)) || + (v.u32(at + 16) != UINT32_MAX && !string(v.u32(at + 16)))) + return false; + } else if (type == 0x180) { + if (header != 8 || (size - header) % 4) + return false; + } else if (type == 0x104) { + if (header != 16 || size != 28 || elements.empty() || !string(v.u32(at + 16))) + return false; + } else + return false; + at += size; + } + if (!root_seen || !elements.empty() || out.package_name.empty()) + return false; + for (char c : out.package_name) + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '_' || c == '.')) + return false; + if (!out.target_sdk) + out.target_sdk = out.min_sdk; + return true; +} +struct ZipEntry { + std::string name; + uint16_t flags, method; + uint32_t crc, compressed, uncompressed, offset; +}; +} // namespace +ApkInspection inspect_apk(const std::string& path) { + ApkInspection out; + auto fail = [&](const char* note) { + out.is_apk = false; + out.failure_note = note; + return out; + }; + std::unique_ptr fp(fopen(path.c_str(), "rb"), fclose); + if (!fp) + return fail("cannot open APK file"); + if (fseek(fp.get(), 0, SEEK_END)) + return fail("cannot seek APK"); + long length = ftell(fp.get()); + if (length < 22 || static_cast(length) > UINT32_MAX) + return fail("unsupported ZIP size (ZIP64 is not supported)"); + size_t tail_size = std::min(length, 65557); + std::vector tail(tail_size); + if (!read_at(fp.get(), length - tail_size, tail.data(), tail.size())) + return fail("cannot read ZIP directory trailer"); + View t{tail.data(), tail.size()}; + size_t end = tail_size; + for (size_t i = tail_size - 22;; --i) { + if (t.u32(i) == 0x06054b50 && t.u16(i + 20) == tail_size - i - 22) { + end = i; + break; + } + if (!i) + break; + } + if (end == tail_size) + return fail("missing ZIP end-of-central-directory record"); + size_t entries = t.u16(end + 10), dir_size = t.u32(end + 12), dir_offset = t.u32(end + 16); + if (t.u16(end + 4) || t.u16(end + 6) || t.u16(end + 8) != entries || entries == 0xffff || + dir_size == UINT32_MAX || dir_offset == UINT32_MAX || dir_size > kDirectoryLimit || + uint64_t(dir_offset) + dir_size != uint64_t(length) - tail_size + end) + return fail("unsupported or inconsistent ZIP directory"); + std::vector directory(dir_size); + if (!read_at(fp.get(), dir_offset, directory.data(), directory.size())) + return fail("truncated ZIP directory"); + View d{directory.data(), directory.size()}; + size_t at = 0; + std::set names; + std::set abis; + std::vector> ranges; + ZipEntry manifest{}; + bool found_manifest = false; + for (size_t i = 0; i < entries; ++i) { + if (!d.has(at, 46) || d.u32(at) != 0x02014b50) + return fail("invalid ZIP directory entry"); + size_t name_size = d.u16(at + 28), extra = d.u16(at + 30), comment = d.u16(at + 32); + if (!name_size || !d.has(at + 46, name_size + extra + comment) || d.u16(at + 34)) + return fail("invalid ZIP entry lengths"); + ZipEntry entry{std::string(reinterpret_cast(d.p + at + 46), name_size), + d.u16(at + 8), + d.u16(at + 10), + d.u32(at + 16), + d.u32(at + 20), + d.u32(at + 24), + d.u32(at + 42)}; + if (entry.name.find('\0') != std::string::npos || !names.insert(entry.name).second || + entry.flags & (1 | 0x40 | 0x2000) || (entry.method != 0 && entry.method != 8) || + entry.compressed == UINT32_MAX || entry.uncompressed == UINT32_MAX || + entry.offset >= dir_offset) + return fail("unsupported or duplicate ZIP entry"); + const auto* name_bytes = reinterpret_cast(entry.name.data()); + if ((entry.flags & 0x800) && !utf8(name_bytes, name_size, SIZE_MAX)) + return fail("invalid UTF-8 ZIP filename"); + if (!(entry.flags & 0x800)) + for (unsigned char ch : entry.name) + if (ch >= 0x80) + return fail("legacy non-ASCII ZIP filenames are not supported"); + uint8_t local[30]; + if (!read_at(fp.get(), entry.offset, local, 30)) + return fail("truncated ZIP local header"); + View l{local, 30}; + uint64_t data_at = uint64_t(entry.offset) + 30 + l.u16(26) + l.u16(28); + if (l.u32(0) != 0x04034b50 || l.u16(6) != entry.flags || l.u16(8) != entry.method || + l.u16(26) != name_size || data_at > dir_offset || + entry.compressed > dir_offset - data_at) + return fail("inconsistent ZIP local header"); + std::vector local_name(name_size); + if (!read_at(fp.get(), uint64_t(entry.offset) + 30, local_name.data(), name_size) || + std::memcmp(local_name.data(), entry.name.data(), name_size)) + return fail("ZIP local filename mismatch"); + if (!(entry.flags & 8) && (l.u32(14) != entry.crc || l.u32(18) != entry.compressed || + l.u32(22) != entry.uncompressed)) + return fail("ZIP local size or CRC mismatch"); + ranges.push_back({entry.offset, data_at + entry.compressed}); + if (entry.name.back() != '/') + ++out.file_count; + if (entry.name == "AndroidManifest.xml") { + manifest = entry; + found_manifest = true; + } + if (entry.name == "classes.dex" || + (entry.name.size() > 11 && entry.name.substr(0, 7) == "classes" && + entry.name.substr(entry.name.size() - 4) == ".dex" && + entry.name.find_first_not_of("0123456789", 7) == entry.name.size() - 4)) + out.dex_files.push_back(entry.name); + if (entry.name.substr(0, 4) == "lib/" && entry.name.size() > 7 && + entry.name.substr(entry.name.size() - 3) == ".so") { + size_t slash = entry.name.find('/', 4); + if (slash != std::string::npos && slash > 4 && + entry.name.find('/', slash + 1) == std::string::npos) + abis.insert(entry.name.substr(4, slash - 4)); + } + at += 46 + name_size + extra + comment; + } + if (at != directory.size()) + return fail("ZIP directory entry count mismatch"); + std::sort(ranges.begin(), ranges.end()); + for (size_t i = 1; i < ranges.size(); ++i) + if (ranges[i].first < ranges[i - 1].second) + return fail("overlapping ZIP entries"); + if (!found_manifest) + return fail("AndroidManifest.xml is absent"); + if (!manifest.uncompressed || manifest.uncompressed > kManifestLimit || + manifest.compressed > kManifestLimit) + return fail("manifest exceeds inspection limits"); + uint8_t local[30]; + if (!read_at(fp.get(), manifest.offset, local, 30)) + return fail("cannot read manifest header"); + View l{local, 30}; + uint64_t data_at = uint64_t(manifest.offset) + 30 + l.u16(26) + l.u16(28); + std::vector compressed(manifest.compressed), xml(manifest.uncompressed); + if (!read_at(fp.get(), data_at, compressed.data(), compressed.size())) + return fail("truncated manifest payload"); + if (!manifest.method) { + if (compressed.size() != xml.size()) + return fail("stored manifest size mismatch"); + xml = std::move(compressed); + } else { + z_stream stream{}; + stream.next_in = compressed.data(); + stream.avail_in = compressed.size(); + stream.next_out = xml.data(); + stream.avail_out = xml.size(); + if (inflateInit2(&stream, -MAX_WBITS) != Z_OK) + return fail("cannot initialize DEFLATE"); + int result = inflate(&stream, Z_FINISH); + bool complete = result == Z_STREAM_END && stream.total_in == compressed.size() && + stream.total_out == xml.size(); + inflateEnd(&stream); + if (!complete) + return fail("invalid compressed manifest"); + } + if (crc32(0, xml.data(), xml.size()) != manifest.crc) + return fail("manifest CRC mismatch"); + if (!manifest_xml(xml, out)) + return fail("invalid or unsupported Android binary XML manifest"); + out.has_manifest = true; + out.has_classes_dex = !out.dex_files.empty(); + out.native_abis.assign(abis.begin(), abis.end()); + out.has_native_libs = !out.native_abis.empty(); + out.is_apk = true; + return out; +} +} // namespace android +} // namespace ps5droid diff --git a/src/android/binder/binder_engine.cpp b/src/android/binder/binder_engine.cpp index 0d12dfd..7dd9c2f 100644 --- a/src/android/binder/binder_engine.cpp +++ b/src/android/binder/binder_engine.cpp @@ -1,97 +1,80 @@ -// PS5Droid - Binder Re-Hosting Engine (implementation). #include "android/binder/binder_engine.h" - #include +#include namespace ps5droid { namespace android { - -BinderEngine::BinderEngine(size_t ring_capacity, size_t alloc_region_size) - : ring_(ring_capacity), alloc_buf_(alloc_region_size, 0), - allocator_(alloc_buf_.data(), alloc_region_size, 256) { - // Handle 0 is implicitly reserved for ServiceManager - name_to_handle_["servicemanager"] = 0; -} - +BinderEngine::BinderEngine(size_t max_transactions, size_t region) + : storage_(region, 0), allocator_(storage_.data(), region, kMaxPayload), + max_transactions_(max_transactions) {} uint32_t BinderEngine::register_service(const std::string& name, ServiceHandler handler, void* user) { std::lock_guard lock(mutex_); - auto it = name_to_handle_.find(name); - if (it != name_to_handle_.end() && it->second != 0) { - return it->second; - } - + if (name.empty() || name == "servicemanager" || !handler || next_handle_ == kInvalidHandle) + return kInvalidHandle; + auto found = names_.find(name); + if (found != names_.end()) + return found->second; uint32_t handle = next_handle_++; - name_to_handle_[name] = handle; - services_[handle] = ServiceEntry{name, handle, handler, user}; + names_[name] = handle; + services_[handle] = {handler, user}; return handle; } - uint32_t BinderEngine::lookup_service(const std::string& name) const { std::lock_guard lock(mutex_); - auto it = name_to_handle_.find(name); - if (it != name_to_handle_.end()) { - return it->second; - } - return 0; // 0 or invalid + auto it = names_.find(name); + return it == names_.end() ? kInvalidHandle : it->second; } - -bool BinderEngine::transact(uint32_t handle, uint32_t code, const std::vector& in_data, - std::vector* out_reply) { - ServiceHandler handler = nullptr; - void* user = nullptr; +RpcResult BinderEngine::transact_checked(uint32_t handle, uint32_t code, + const std::vector& input, uint32_t flags) { + if (flags) + return {RpcStatus::kUnsupportedFlags, {}}; + if (input.size() > kMaxPayload) + return {RpcStatus::kTooLarge, {}}; + ServiceEntry service{}; + void* block; { std::lock_guard lock(mutex_); - if (handle == 0) { - // ServiceManager built-in ping/lookup - if (out_reply) { - out_reply->assign({'S', 'M', 'O', 'K'}); - } - return true; - } - auto it = services_.find(handle); - if (it == services_.end()) { - return false; - } - handler = it->second.handler; - user = it->second.user; - } - - if (!handler) - return false; - - // Allocate transaction buffer via BlockAllocator - void* block = allocator_.alloc(); - if (block) { - size_t copy_len = std::min(in_data.size(), allocator_.block_size()); - if (copy_len > 0) { - std::memcpy(block, in_data.data(), copy_len); - } - } - - // Execute in-process transaction - std::vector reply = handler(code, in_data, user); - if (out_reply) { - *out_reply = reply; + if (it == services_.end()) + return {RpcStatus::kInvalidHandle, {}}; + service = it->second; + if (active_ >= max_transactions_ || !(block = allocator_.alloc())) + return {RpcStatus::kNoMemory, {}}; + ++active_; } - - if (block) { - allocator_.free(block); + auto release = [this](void* p) { + std::lock_guard lock(mutex_); + allocator_.free(p); + --active_; + }; + std::unique_ptr owned(block, release); + try { + if (!input.empty()) + std::memcpy(block, input.data(), input.size()); + const auto* first = static_cast(block); + std::vector staged(first, first + input.size()); + // No engine lock is held across user code: nested calls are allowed. + auto reply = service.handler(code, staged, service.user); + if (reply.size() > kMaxPayload) + return {RpcStatus::kTooLarge, {}}; + return {RpcStatus::kOk, std::move(reply)}; + } catch (...) { + return {RpcStatus::kHandlerError, {}}; } - - // Push completion transaction signal through SpscRing - ring_.push(static_cast(BinderReturn::kBrReply)); - uint64_t dummy; - ring_.pop(&dummy); - - return true; } - +bool BinderEngine::transact(uint32_t handle, uint32_t code, const std::vector& input, + std::vector* output) { + if (output) + output->clear(); + auto result = transact_checked(handle, code, input); + if (output && result.ok()) + *output = std::move(result.reply); + return result.ok(); +} size_t BinderEngine::registered_service_count() const { std::lock_guard lock(mutex_); return services_.size(); } - } // namespace android } // namespace ps5droid diff --git a/src/android/binder/binder_engine.h b/src/android/binder/binder_engine.h index e2835ef..9960fe1 100644 --- a/src/android/binder/binder_engine.h +++ b/src/android/binder/binder_engine.h @@ -1,80 +1,59 @@ -// PS5Droid - Binder Re-Hosting Engine (In-Process RPC Engine). -// -// Milestone 5: Implementation of an in-process Binder RPC engine providing -// service manager handle mappings, transaction marshalling, object handle -// registration, and BC_TRANSACTION/BR_TRANSACTION message dispatch over -// SpscRing and BlockAllocator. +// Binder research: bounded synchronous IN-PROCESS RPC, not Android Binder IPC. +// No ioctl/BC_*/BR_* wire protocol, Parcel/object transfer, death notifications, +// one-way calls or Android ServiceManager is implemented. See docs/binder-scope.md. #pragma once - +#include "compat/ipc_compat.h" #include #include -#include #include #include #include #include -#include "compat/ipc_compat.h" - namespace ps5droid { namespace android { - -enum class BinderCommand : uint32_t { - kBcTransaction = 1, - kBcReply = 2, - kBcAcquire = 3, - kBcRelease = 4, +using ServiceHandler = std::vector (*)(uint32_t, const std::vector&, void*); +enum class RpcStatus { + kOk, + kInvalidHandle, + kUnsupportedFlags, + kTooLarge, + kNoMemory, + kHandlerError }; - -enum class BinderReturn : uint32_t { - kBrTransaction = 101, - kBrReply = 102, - kBrError = 103, - kBrOk = 104, -}; - -struct BinderTransaction { - uint32_t target_handle; - uint32_t code; - uint32_t flags; - std::vector data; +struct RpcResult { + RpcStatus status = RpcStatus::kInvalidHandle; + std::vector reply; + bool ok() const { return status == RpcStatus::kOk; } }; - -using ServiceHandler = std::vector (*)(uint32_t code, const std::vector& in_data, - void* user); - class BinderEngine { public: - BinderEngine(size_t ring_capacity = 2048, size_t alloc_region_size = 65536); - ~BinderEngine() = default; - + static constexpr uint32_t kInvalidHandle = UINT32_MAX; + static constexpr size_t kMaxPayload = 256; + explicit BinderEngine(size_t max_transactions = 2048, size_t alloc_region_size = 65536); + // The caller owns user data and must keep it alive until all calls finish. uint32_t register_service(const std::string& name, ServiceHandler handler, void* user = nullptr); uint32_t lookup_service(const std::string& name) const; - - bool transact(uint32_t handle, uint32_t code, const std::vector& in_data, - std::vector* out_reply); - + RpcResult transact_checked(uint32_t handle, uint32_t code, const std::vector& input, + uint32_t flags = 0); + bool transact(uint32_t handle, uint32_t code, const std::vector& input, + std::vector* output); size_t registered_service_count() const; private: - mutable std::mutex mutex_; - uint32_t next_handle_ = 1; - struct ServiceEntry { - std::string name; - uint32_t handle; ServiceHandler handler; void* user; }; - - std::unordered_map name_to_handle_; + mutable std::mutex mutex_; + uint32_t next_handle_ = 1; // 0 remains reserved; it has no success stub. + std::unordered_map names_; std::unordered_map services_; - - compat::SpscRing ring_; - std::vector alloc_buf_; + std::vector storage_; compat::BlockAllocator allocator_; + size_t max_transactions_; + size_t active_ = 0; }; - } // namespace android } // namespace ps5droid diff --git a/src/android/binder/binder_protocol.h b/src/android/binder/binder_protocol.h index 5770d97..5adf9aa 100644 --- a/src/android/binder/binder_protocol.h +++ b/src/android/binder/binder_protocol.h @@ -1,34 +1,5 @@ -// PS5Droid - Binder protocol research notes. -// -// THIS HEADER CONTAINS NO IMPLEMENTATION AND NO CLAIMS. -// -// Binder is the kernel-mediated RPC system Android services require -// (servicemanager, system_server, HIDL/AIDL services, zygote...). Its -// Linux kernel driver exposes /dev/binder (or binderfs mounts), which does -// not exist on Orbis OS - a FreeBSD descendant. The Waydroid project itself -// depends on a real binder device (binderfs on the host kernel) and even -// adds a second, host-side hwbinder bridge (/dev/host_hwbinder); both are -// Linux-kernel facilities and cannot be ported as-is. -// -// Protocol facts a future experiment must respect (to be re-verified -// against AOSP sources before any implementation): -// -// * Userspace talks to the driver with ioctl(BINDER_WRITE_READ) over two -// command streams: BC_* (context -> driver) and BR_* (driver -> -// context). Transactions travel as BC_TRANSACTION / BR_TRANSACTION -// pairs, with handles for remote objects and offsets into a flat -// buffer describing binder objects (flat_binder_object). -// * The driver owns transaction buffers in a per-process mapped region -// (binder_mmap) - this is why compat::BlockAllocator exists here as -// the eventual stand-in for that model. -// * Servicemanager performs name->handle lookups; Android frameworks -// hard-code its presence and its semantics. -// * bionic and libbinder embed SELinux/security assumptions; Waydroid -// carries a long list of patches (see waydroid-patches/ in -// android_vendor_waydroid) to disable them in a container. -// -// An Orbis "Binder" would therefore be an in-process re-implementation of -// the transaction/handle model (services as objects, marshalled calls), not -// a port of the kernel driver. That experiment is Milestone 5 and has NOT -// been started; the runtime manager reports it as a blocker. +// Android Binder compatibility is not implemented. +// The bounded in-process callback experiment is specified in docs/binder-scope.md. +// Wire-compatible BC/BR streams, Parcel/object transfer and Android services remain +// separate gates requiring AOSP/libbinder validation and console evidence. #pragma once diff --git a/src/android/evidence_report.cpp b/src/android/evidence_report.cpp new file mode 100644 index 0000000..1484ec0 --- /dev/null +++ b/src/android/evidence_report.cpp @@ -0,0 +1,52 @@ +#include "android/evidence_report.h" +#include "build_info.h" +#include +namespace ps5droid { +namespace android { +std::string json_quote(const std::string& text) { + std::string out = "\""; + for (unsigned char ch : text) { + if (ch == '\\' || ch == '"') { + out += '\\'; + out += static_cast(ch); + } else if (ch < 0x20) { + char escaped[7]; + snprintf(escaped, sizeof(escaped), "\\u%04x", ch); + out += escaped; + } else + out += static_cast(ch); + } + return out + '"'; +} +std::string evidence_json(const CapabilityReport& report, const EvidenceMetadata& metadata, + const std::vector& observations) { + std::string out = "{\n \"schema_version\": 1,\n \"backend\": " + json_quote(report.backend) + + ",\n \"revision\": " + json_quote(PS5DROID_BUILD_REVISION) + + ",\n \"sdk\": " + json_quote(PS5DROID_SDK_VERSION) + + ",\n \"firmware\": " + json_quote(metadata.firmware) + + ",\n \"loader\": " + json_quote(metadata.loader) + + ",\n \"android_runtime\": \"blocked\",\n \"platform_probes_passed\": " + + (report.all_passed ? "true" : "false") + ",\n \"probes\": ["; + bool first = true; + for (const auto& probe : report.results) { + if (!first) + out += ','; + first = false; + out += "\n {\"name\": " + json_quote(probe.name) + + ", \"passed\": " + (probe.passed ? "true" : "false") + + ", \"detail\": " + json_quote(probe.detail) + '}'; + } + out += "\n ],\n \"observations\": ["; + first = true; + for (const auto& observation : observations) { + if (!first) + out += ','; + first = false; + out += "\n {\"name\": " + json_quote(observation.name) + + ", \"status\": " + json_quote(observation.status) + + ", \"detail\": " + json_quote(observation.detail) + '}'; + } + return out + "\n ]\n}\n"; +} +} // namespace android +} // namespace ps5droid diff --git a/src/android/evidence_report.h b/src/android/evidence_report.h new file mode 100644 index 0000000..a39cab9 --- /dev/null +++ b/src/android/evidence_report.h @@ -0,0 +1,21 @@ +#pragma once +#include "android/runtime_manager.h" +#include +#include +namespace ps5droid { +namespace android { +struct Observation { + std::string name; + std::string status; // passed, failed, not_run, or not_observed + std::string detail; +}; +struct EvidenceMetadata { + std::string firmware = "unrecorded"; + std::string loader = "unrecorded"; +}; +std::string json_quote(const std::string& text); +// Unrecorded metadata and unexecuted checks stay explicit; host != console evidence. +std::string evidence_json(const CapabilityReport& report, const EvidenceMetadata& metadata, + const std::vector& observations = {}); +} // namespace android +} // namespace ps5droid diff --git a/src/android/image_manager.cpp b/src/android/image_manager.cpp index 8a3ecdc..07192e4 100644 --- a/src/android/image_manager.cpp +++ b/src/android/image_manager.cpp @@ -1,8 +1,12 @@ // PS5Droid - Android image handling (implementation). #include "android/image_manager.h" +#include +#include #include +#include #include +#include #include "android/sha256.h" #include "platform/platform.h" @@ -14,7 +18,10 @@ ParseStatus parse_manifest(const std::string& text, ImageManifest* out) { if (out == nullptr) return ParseStatus::kBadValue; + if (text.size() > 1024 * 1024) + return ParseStatus::kBadValue; ImageManifest m; + std::set seen; std::vector lines; size_t start = 0; while (start <= text.size()) { @@ -71,6 +78,8 @@ ParseStatus parse_manifest(const std::string& text, ImageManifest* out) { while (!value.empty() && (value.back() == ' ' || value.back() == '\t')) value.pop_back(); any = true; + if (!seen.insert(key).second) + return ParseStatus::kBadValue; if (key == "system_image") m.system_image = value; @@ -80,9 +89,15 @@ ParseStatus parse_manifest(const std::string& text, ImageManifest* out) { m.system_sha256 = value; else if (key == "vendor_sha256") m.vendor_sha256 = value; - else if (key == "android_api_level") - m.android_api_level = atoi(value.c_str()); - else if (key == "abi") + else if (key == "android_api_level") { + char* end = nullptr; + errno = 0; + long level = strtol(value.c_str(), &end, 10); + if (errno || !end || end != value.c_str() + value.size() || level <= 0 || + level > INT_MAX) + return ParseStatus::kBadValue; + m.android_api_level = static_cast(level); + } else if (key == "abi") m.abi = value; else if (key == "description") m.description = value; @@ -98,6 +113,11 @@ ParseStatus parse_manifest(const std::string& text, ImageManifest* out) { m.abi.empty()) { return ParseStatus::kMissingKeys; } + for (const auto* hash : {&m.system_sha256, &m.vendor_sha256}) { + if (!hash->empty() && (hash->size() != 64 || + hash->find_first_not_of("0123456789abcdef") != std::string::npos)) + return ParseStatus::kBadValue; + } *out = m; return ParseStatus::kOk; } @@ -167,7 +187,6 @@ Ext4Probe probe_ext4(const std::string& image_path) { return r; } - r.is_ext4 = true; auto rd32 = [&](int off) { return static_cast(sb[off]) | (static_cast(sb[off + 1]) << 8) | (static_cast(sb[off + 2]) << 16) | @@ -175,7 +194,12 @@ Ext4Probe probe_ext4(const std::string& image_path) { }; r.blocks_count = rd32(0x04); uint32_t log_block_size = rd32(0x18); + if (log_block_size > 6) { + r.failure_note = "invalid ext4 block size exponent"; + return r; + } r.block_size = 1024u << log_block_size; + r.is_ext4 = true; char label[17]; memcpy(label, sb + 0x78, 16); @@ -188,54 +212,5 @@ Ext4Probe probe_ext4(const std::string& image_path) { return r; } -ApkInspection inspect_apk(const std::string& apk_path) { - ApkInspection res; - FILE* fp = fopen(apk_path.c_str(), "rb"); - if (!fp) { - res.failure_note = "cannot open APK file"; - return res; - } - - fseek(fp, 0, SEEK_END); - long size = ftell(fp); - if (size < 30) { - res.failure_note = "file too small to be a ZIP/APK"; - fclose(fp); - return res; - } - - fseek(fp, 0, SEEK_SET); - uint8_t hdr[4]; - if (fread(hdr, 1, 4, fp) != 4 || hdr[0] != 'P' || hdr[1] != 'K' || hdr[2] != 0x03 || - hdr[3] != 0x04) { - res.failure_note = "invalid ZIP/APK magic"; - fclose(fp); - return res; - } - - res.is_apk = true; - res.file_count = 1; - - std::vector buf(static_cast(size)); - fseek(fp, 0, SEEK_SET); - size_t read_bytes = fread(buf.data(), 1, buf.size(), fp); - fclose(fp); - - const std::string content(reinterpret_cast(buf.data()), read_bytes); - if (content.find("AndroidManifest.xml") != std::string::npos) { - res.has_manifest = true; - } - if (content.find("classes.dex") != std::string::npos) { - res.has_classes_dex = true; - } - if (content.find("lib/x86_64") != std::string::npos || - content.find("lib/arm64-v8a") != std::string::npos) { - res.has_native_libs = true; - } - - res.package_name = "com.ps5droid.research.sample"; - return res; -} - } // namespace android } // namespace ps5droid diff --git a/src/android/image_manager.h b/src/android/image_manager.h index 376c2b5..24a255e 100644 --- a/src/android/image_manager.h +++ b/src/android/image_manager.h @@ -75,6 +75,10 @@ struct ApkInspection { bool has_native_libs = false; std::string package_name; size_t file_count = 0; + int min_sdk = 1; // Android default when uses-sdk is absent + int target_sdk = 0; + std::vector dex_files; + std::vector native_abis; std::string failure_note; }; diff --git a/src/android/runtime_manager.cpp b/src/android/runtime_manager.cpp index 2ea17c4..245f8e1 100644 --- a/src/android/runtime_manager.cpp +++ b/src/android/runtime_manager.cpp @@ -3,6 +3,8 @@ #include #include +#include +#include #include "compat/ipc_compat.h" #include "compat/memory_compat.h" @@ -27,7 +29,7 @@ void probe_thread_fn(void* raw) { } // namespace -CapabilityReport RuntimeManager::probe() { +CapabilityReport RuntimeManager::probe(const std::string& writable_dir) { phase_ = RuntimePhase::kProbing; CapabilityReport report; report.backend = platform::backend_name(); @@ -76,9 +78,9 @@ CapabilityReport RuntimeManager::probe() { platform::Thread threads[4]; bool ok = true; for (auto& t : threads) - ok = ok && t.start(probe_thread_fn, &ctx); + ok = t.start(probe_thread_fn, &ctx) && ok; for (auto& t : threads) - ok = ok && t.join(); + ok = t.join() && ok; ok = ok && counter.load() == 4; add("threads", ok, ok ? "4 threads started and joined" : "thread create/join failed"); } @@ -95,15 +97,26 @@ CapabilityReport RuntimeManager::probe() { // 6. filesystem write/read { - std::string tmp = "ps5droid_probe.tmp"; + std::string pattern = writable_dir + "/ps5droid-probe-XXXXXX"; + std::vector path(pattern.begin(), pattern.end()); + path.push_back(0); + int fd = mkstemp(path.data()); + std::string tmp = path.data(); const char* payload = "ps5droid fs probe"; - bool passed = platform::write_file(tmp, payload, strlen(payload)); + bool passed = fd >= 0; + if (fd >= 0) { + passed = ::write(fd, payload, strlen(payload)) == static_cast(strlen(payload)); + passed = (::close(fd) == 0) && passed; + } if (passed) { std::string readback; passed = platform::read_file(tmp, &readback) && readback == payload; - platform::remove_file(tmp); } - add("filesystem", passed, passed ? "write/read/remove ok" : "failed"); + if (fd >= 0) + passed = platform::remove_file(tmp) && passed; + add("filesystem", passed, + passed ? "exclusive temporary file write/read/remove ok in " + writable_dir + : "temporary file probe failed in " + writable_dir); } // 7. cross-thread IPC ring @@ -210,9 +223,10 @@ StartAttempt RuntimeManager::attempt_start() { "process_model", "Android requires fork()/clone() and a zygote. Orbis OS payloads " "have no process-creation API (no fork/exec surface in the " "ps5-payload-sdk libc; processes exist only via the ELF loader)."}); - attempt.blockers.push_back(Blocker{ - "binder", "In-process Binder RPC engine implemented (Milestone 5); kernel /dev/binder " - "device driver absent on FreeBSD/Orbis kernel."}); + attempt.blockers.push_back(Blocker{"binder", + "Bounded synchronous in-process RPC experiment only; no " + "Android Binder protocol; kernel /dev/binder " + "device driver absent on FreeBSD/Orbis kernel."}); attempt.blockers.push_back(Blocker{ "filesystem_layout", "Android images are ext4 (system.img/vendor.img). Orbis exposes " "no loop devices, no FUSE and no ext4 driver; images and APKs can be " @@ -221,10 +235,10 @@ StartAttempt RuntimeManager::attempt_start() { Blocker{"graphics_services", "SurfaceFlinger and the Waydroid hwcomposer HAL assume a " "compositor/wayland display server. PS5 video-out is a direct " "framebuffer flip; there is no surface compositor to host."}); - attempt.blockers.push_back( - Blocker{"bionic_runtime", - "Bionic ELF loader & auxv stack staging researched and verified (Milestone 4); " - "full dynamic linker namespaces remain un-hosted."}); + attempt.blockers.push_back(Blocker{ + "bionic_runtime", "ELF inspection, bounded stack staging and cooperative entry experiment " + "only; TLS and unmodified bionic startup are unsupported; " + "full dynamic linker namespaces remain un-hosted."}); attempt.phase_after = RuntimePhase::kBlocked; phase_ = RuntimePhase::kBlocked; diff --git a/src/android/runtime_manager.h b/src/android/runtime_manager.h index e3b1c1b..7a4828a 100644 --- a/src/android/runtime_manager.h +++ b/src/android/runtime_manager.h @@ -50,7 +50,7 @@ class RuntimeManager { // Runs real, in-process capability probes (memory, threads, futex, // filesystem, IPC). Every result reflects an executed test. - CapabilityReport probe(); + CapabilityReport probe(const std::string& writable_dir = "."); // Performs an honest Android-environment start attempt. On every // current platform this returns kBlocked with the concrete reasons. diff --git a/src/app/main.cpp b/src/app/main.cpp index 51252df..3d4b6fe 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -10,7 +10,10 @@ #include #include +#include "android/evidence_report.h" +#include "android/image_manager.h" #include "android/runtime_manager.h" +#include "compat/elf_runner.h" #include "compat/linux_abi.h" #include "compat/syscall_dispatch.h" #include "platform/platform.h" @@ -163,6 +166,74 @@ void attempt_android_start() { } // namespace int main(int argc, char** argv) { + if (argc > 1 && strcmp(argv[1], "--report-json") == 0) { + if (argc < 3) { + fprintf(stderr, "--report-json needs an output path or -\n"); + return 2; + } + android::EvidenceMetadata metadata; + bool probe_exec = false; + for (int i = 3; i < argc; ++i) { + if (strcmp(argv[i], "--probe-exec") == 0) + probe_exec = true; + else if (strcmp(argv[i], "--firmware") == 0 && i + 1 < argc) + metadata.firmware = argv[++i]; + else if (strcmp(argv[i], "--loader") == 0 && i + 1 < argc) + metadata.loader = argv[++i]; + else { + fprintf(stderr, "unknown or incomplete report option: %s\n", argv[i]); + return 2; + } + } + android::RuntimeManager manager; + auto report = manager.probe(); + std::vector observations; + if (probe_exec) { + std::string detail; + bool accepted = compat::probe_rx_memory(&detail); + observations.push_back({"rx_memory", accepted ? "passed" : "failed", detail}); + } else + observations.push_back( + {"rx_memory", "not_run", "use --probe-exec to request RW -> RX probe"}); + auto json = android::evidence_json(report, metadata, observations); + if (strcmp(argv[2], "-") == 0) + fputs(json.c_str(), stdout); + else if (!platform::write_file(argv[2], json.data(), json.size())) + return 1; + return report.all_passed ? 0 : 1; + } + if (argc == 3 && strcmp(argv[1], "--inspect-apk") == 0) { + auto apk = android::inspect_apk(argv[2]); + printf("{\"is_apk\":%s,\"package_name\":%s,\"min_sdk\":%d,\"target_sdk\":%d,\"file_count\":" + "%zu,\"dex_files\":[", + apk.is_apk ? "true" : "false", android::json_quote(apk.package_name).c_str(), + apk.min_sdk, apk.target_sdk, apk.file_count); + for (size_t i = 0; i < apk.dex_files.size(); ++i) + printf("%s%s", i ? "," : "", android::json_quote(apk.dex_files[i]).c_str()); + printf("],\"native_abis\":["); + for (size_t i = 0; i < apk.native_abis.size(); ++i) + printf("%s%s", i ? "," : "", android::json_quote(apk.native_abis[i]).c_str()); + printf("],\"failure_note\":%s}\n", android::json_quote(apk.failure_note).c_str()); + return apk.is_apk ? 0 : 1; + } + if (argc == 3 && strcmp(argv[1], "--run-cooperative-elf") == 0) { + std::string bytes; + if (!platform::read_file(argv[2], &bytes)) { + fprintf(stderr, "cannot read ELF\n"); + return 1; + } + auto result = compat::run_cooperative_elf(bytes.data(), bytes.size()); + printf("executed=%s stop_requested=%s entry_result=%lld\n%s\n", + result.executed ? "yes" : "no", result.stop_requested ? "yes" : "no", + static_cast(result.entry_result), result.note.c_str()); + return result.executed && result.stop_requested && result.entry_result == 0 ? 0 : 1; + } + if (argc > 1 && strcmp(argv[1], "--matrix") != 0 && strcmp(argv[1], "--start-attempt") != 0) { + fprintf(stderr, "usage: ps5droid-host [--matrix | --start-attempt | --inspect-apk FILE | " + "--run-cooperative-elf FILE | --report-json FILE [--probe-exec] " + "[--firmware VALUE] [--loader VALUE]]\n"); + return 2; + } print_banner(); run_probes(); diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cpp index 50e6721..6a6077d 100644 --- a/src/app/ps5_main.cpp +++ b/src/app/ps5_main.cpp @@ -16,7 +16,9 @@ #include #include +#include "android/evidence_report.h" #include "android/runtime_manager.h" +#include "compat/elf_runner.h" #include "platform/display.h" #include "platform/platform.h" #include "platform/ps5/sce_decls.h" @@ -53,10 +55,20 @@ void show_screen(platform::Framebuffer* fb, const char* title, const char* const kTextColor, 2); } -void run_launcher(platform::DisplayBackend* display, platform::InputBackend* input) { +void save_evidence(const android::CapabilityReport& report, + const std::vector& observations) { + auto text = android::evidence_json(report, {}, observations); + if (!platform::write_file("/data/ps5droid-evidence.json", text.data(), text.size())) + platform::log(platform::LogLevel::kError, "evidence", + "Cannot write /data/ps5droid-evidence.json"); +} + +void run_launcher(platform::DisplayBackend* display, platform::InputBackend* input, + const android::CapabilityReport& report, + std::vector& observations) { ui::LauncherModel launcher; - android::RuntimeManager manager; - android::CapabilityReport report = manager.probe(); + unsigned flips = 0, connected_polls = 0, button_edges = 0; + bool flip_failed = false; int screen = 0; // 0 = launcher menu, 1 = probe results, 2 = about bool running = true; @@ -106,14 +118,21 @@ void run_launcher(platform::DisplayBackend* display, platform::InputBackend* inp show_screen(fb, "ABOUT", kAbout, 4, -1); } - display->present(); + if (!display->present()) { + flip_failed = true; + break; + } + ++flips; - if (input->poll(&pad)) { + if (input->poll(&pad) && pad.connected) { + ++connected_polls; bool edge_up = pad.up && !prev_up; bool edge_down = pad.down && !prev_down; bool edge_cross = pad.cross && !prev_cross; bool edge_circle = pad.circle && !prev_circle; bool edge_options = pad.options && !prev_options; + if (edge_up || edge_down || edge_cross || edge_circle || edge_options) + ++button_edges; if (screen == 0) { if (edge_up) @@ -152,11 +171,28 @@ void run_launcher(platform::DisplayBackend* display, platform::InputBackend* inp platform::sleep_ns(1000000); // 1 ms; flips are vsync-locked } + observations.push_back({"video_flips", + flip_failed ? "failed" + : flips ? "passed" + : "not_observed", + std::to_string(flips) + " successful flip waits"}); + observations.push_back({"connected_pad", connected_polls ? "passed" : "not_observed", + std::to_string(connected_polls) + " connected pad polls"}); + observations.push_back({"button_edges", button_edges ? "passed" : "not_observed", + std::to_string(button_edges) + " navigation/exit edges"}); } } // namespace int main() { + android::RuntimeManager manager; + auto report = manager.probe("/data"); + std::vector observations; + std::string rx_detail; + bool rx = compat::probe_rx_memory(&rx_detail); + observations.push_back({"rx_memory", rx ? "passed" : "failed", rx_detail}); + observations.push_back({"cleanup", "not_run", "recorded after launcher exit"}); + save_evidence(report, observations); ps5::sceSystemServiceHideSplashScreen(); platform::DisplayBackend* display = platform::create_ps5_display(); @@ -168,26 +204,40 @@ int main() { memset(&req, 0, sizeof(req)); strncpy(req.message, "PS5Droid: video-out init failed", sizeof(req.message) - 1); ps5::sceKernelSendNotificationRequest(0, &req, sizeof(req), 0); + observations.push_back({"video_init", "failed", "video-out initialization failed"}); + save_evidence(report, observations); delete display; delete input; return 1; } + observations.push_back({"video_init", "passed", std::to_string(w) + "x" + std::to_string(h)}); + save_evidence(report, observations); if (!input->init()) { ps5::SceNotificationRequest req; memset(&req, 0, sizeof(req)); strncpy(req.message, "PS5Droid: pad init failed", sizeof(req.message) - 1); ps5::sceKernelSendNotificationRequest(0, &req, sizeof(req), 0); + observations.push_back({"pad_init", "failed", "pad initialization failed"}); + save_evidence(report, observations); display->shutdown(); delete display; delete input; return 2; } - run_launcher(display, input); + observations.push_back( + {"pad_init", "passed", "pad handle opened; connection verified separately"}); + save_evidence(report, observations); + run_launcher(display, input, report, observations); + input->shutdown(); display->shutdown(); delete display; delete input; + observations[1] = { + "cleanup", "not_observed", + "shutdown completed; resource release needs repeat-launch hardware verification"}; + save_evidence(report, observations); return 0; } diff --git a/src/compat/bionic_loader.cpp b/src/compat/bionic_loader.cpp index 3965448..b4eb4c3 100644 --- a/src/compat/bionic_loader.cpp +++ b/src/compat/bionic_loader.cpp @@ -1,159 +1,152 @@ -// PS5Droid - Bionic Loader & TLS/Auxv implementation. +// Bounded ELF inspection and address-correct initial stack staging. #include "compat/bionic_loader.h" - +#include #include +#include namespace ps5droid { namespace compat { - namespace { - -struct Elf64Ehdr { - uint8_t e_ident[16]; - uint16_t e_type; - uint16_t e_machine; - uint32_t e_version; - uint64_t e_entry; - uint64_t e_phoff; - uint64_t e_shoff; - uint32_t e_flags; - uint16_t e_ehsize; - uint16_t e_phentsize; - uint16_t e_phnum; - uint16_t e_shentsize; - uint16_t e_shnum; - uint16_t e_shstrndx; +struct Header { + uint8_t ident[16]; + uint16_t type, machine; + uint32_t version; + uint64_t entry, phoff, shoff; + uint32_t flags; + uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstrndx; }; - -struct RawElf64Phdr { - uint32_t p_type; - uint32_t p_flags; - uint64_t p_offset; - uint64_t p_vaddr; - uint64_t p_paddr; - uint64_t p_filesz; - uint64_t p_memsz; - uint64_t p_align; +struct Phdr { + uint32_t type, flags; + uint64_t offset, vaddr, paddr, filesz, memsz, align; }; - -constexpr uint32_t PT_INTERP = 3; -constexpr uint32_t PT_TLS = 7; - -constexpr uint64_t AT_NULL = 0; -constexpr uint64_t AT_PHDR = 3; -constexpr uint64_t AT_PHENT = 4; -constexpr uint64_t AT_PHNUM = 5; -constexpr uint64_t AT_PAGESZ = 6; -constexpr uint64_t AT_ENTRY = 9; - +static_assert(sizeof(Header) == 64 && sizeof(Phdr) == 56, "ELF64 layouts"); +bool range(uint64_t offset, uint64_t length, uint64_t size) { + return offset <= size && length <= size - offset; +} } // namespace - BionicElfInfo BionicLoader::parse_header(const void* data, size_t size) { - BionicElfInfo res; - if (!data || size < sizeof(Elf64Ehdr)) { - res.error = "buffer too small for ELF header"; - return res; - } - - const auto* ehdr = static_cast(data); - if (ehdr->e_ident[0] != 0x7f || ehdr->e_ident[1] != 'E' || ehdr->e_ident[2] != 'L' || - ehdr->e_ident[3] != 'F') { - res.error = "invalid ELF magic"; - return res; + BionicElfInfo out; + auto fail = [&](const char* note) { + out.valid = false; + out.error = note; + return out; + }; + if (!data || size < sizeof(Header)) + return fail("truncated ELF header"); + Header header{}; + std::memcpy(&header, data, sizeof(header)); + if (std::memcmp(header.ident, "\177ELF", 4)) + return fail("invalid ELF magic"); + if (header.ident[4] != 2 || header.ident[5] != 1 || header.ident[6] != 1 || + header.machine != 62 || header.version != 1) + return fail("requires little-endian ELF64 x86_64 version 1"); + if ((header.type != 2 && header.type != 3) || header.ehsize != sizeof(Header) || + header.phentsize != sizeof(Phdr) || !header.phnum || header.phnum > 1024) + return fail("invalid ELF type or program header layout"); + if (!range(header.phoff, uint64_t(header.phnum) * sizeof(Phdr), size)) + return fail("program headers exceed file buffer"); + out.entry_point = header.entry; + out.phdr_offset = header.phoff; + out.elf_type = header.type; + const auto* bytes = static_cast(data); + bool entry_mapped = false; + for (uint16_t i = 0; i < header.phnum; ++i) { + Phdr p{}; + std::memcpy(&p, bytes + header.phoff + i * sizeof(p), sizeof(p)); + if (!range(p.offset, p.filesz, size) || p.memsz < p.filesz || + p.memsz > UINT64_MAX - p.vaddr) + return fail("invalid segment range"); + if (p.align > 1 && ((p.align & (p.align - 1)) || p.vaddr % p.align != p.offset % p.align)) + return fail("invalid segment alignment"); + out.phdrs.push_back( + {p.type, p.flags, p.offset, p.vaddr, p.paddr, p.filesz, p.memsz, p.align}); + if (p.type == 1 && (p.flags & 1) && header.entry >= p.vaddr && + header.entry - p.vaddr < p.memsz) + entry_mapped = true; + if (p.type == 3) { + if (!out.interp.empty() || p.filesz < 2 || p.filesz > 4096 || + bytes[p.offset + p.filesz - 1] != 0) + return fail("invalid PT_INTERP string"); + out.interp.assign(reinterpret_cast(bytes + p.offset), p.filesz - 1); + if (out.interp.find('\0') != std::string::npos) + return fail("embedded NUL in interpreter"); + out.is_bionic = out.interp == "/system/bin/linker64" || + out.interp == "/apex/com.android.runtime/bin/linker64"; + } else if (p.type == 7) { + out.tls_filesz = p.filesz; + out.tls_memsz = p.memsz; + out.tls_align = p.align; + } } - - if (ehdr->e_ident[4] != 2 /* 64-bit */ || ehdr->e_machine != 62 /* x86_64 */) { - res.error = "not ELF64 x86_64"; - return res; + if (!entry_mapped) + return fail("entry point is outside executable PT_LOAD segments"); + out.valid = true; + return out; +} +std::vector BionicLoader::build_auxv(uint64_t entry, uint64_t phdr, uint64_t phnum, + uint64_t pagesz) { + return {{3, phdr}, {4, 56}, {5, phnum}, {6, pagesz}, {9, entry}, {0, 0}}; +} +InitialStack BionicLoader::build_initial_stack(const BionicElfInfo& info, + const std::vector& args, + const std::vector& env, + uint64_t guest_base, uint64_t phdr_address, + uint64_t load_bias, uint64_t pagesz) { + InitialStack out; + if (!info.valid || !pagesz || (pagesz & (pagesz - 1)) || + load_bias > UINT64_MAX - info.entry_point) { + out.error = "invalid ELF or stack addresses"; + return out; } - - res.valid = true; - res.entry_point = ehdr->e_entry; - - if (ehdr->e_phoff + static_cast(ehdr->e_phnum) * sizeof(RawElf64Phdr) > size) { - res.error = "program headers exceed file buffer"; - res.valid = false; - return res; + constexpr size_t limit = 1024 * 1024; + if (args.size() > 4096 || env.size() > 4096) { + out.error = "argument count exceeds limit"; + return out; } - - const auto* phdrs = - reinterpret_cast(static_cast(data) + ehdr->e_phoff); - - for (uint16_t i = 0; i < ehdr->e_phnum; ++i) { - Elf64PhdrInfo info; - info.type = phdrs[i].p_type; - info.flags = phdrs[i].p_flags; - info.offset = phdrs[i].p_offset; - info.vaddr = phdrs[i].p_vaddr; - info.paddr = phdrs[i].p_paddr; - info.filesz = phdrs[i].p_filesz; - info.memsz = phdrs[i].p_memsz; - info.align = phdrs[i].p_align; - res.phdrs.push_back(info); - - if (phdrs[i].p_type == PT_INTERP) { - if (phdrs[i].p_offset + phdrs[i].p_filesz <= size) { - const char* interp_str = reinterpret_cast( - static_cast(data) + phdrs[i].p_offset); - res.interp.assign(interp_str, phdrs[i].p_filesz); - if (!res.interp.empty() && res.interp.back() == '\0') { - res.interp.pop_back(); - } - if (res.interp.find("linker") != std::string::npos) { - res.is_bionic = true; - } + auto auxv = build_auxv(load_bias + info.entry_point, phdr_address, info.phdrs.size(), pagesz); + size_t total = (1 + args.size() + 1 + env.size() + 1 + auxv.size() * 2) * 8; + const size_t strings_begin = total; + for (const auto* list : {&args, &env}) + for (const auto& text : *list) { + if (text.find('\0') != std::string::npos || text.size() >= limit - total) { + out.error = "invalid or oversized argument data"; + return out; } - } else if (phdrs[i].p_type == PT_TLS) { - res.tls_filesz = phdrs[i].p_filesz; - res.tls_memsz = phdrs[i].p_memsz; - res.tls_align = phdrs[i].p_align; + total += text.size() + 1; } + total = (total + 15) & ~size_t(15); + out.bytes.resize(total, 0); + uint64_t base = guest_base ? guest_base : reinterpret_cast(out.bytes.data()); + if (base % 16 || base > UINT64_MAX - total) { + out.bytes.clear(); + out.error = "stack base must be aligned and non-overflowing"; + return out; } - - return res; -} - -std::vector BionicLoader::build_auxv(uint64_t entry, uint64_t phdr, uint64_t phnum, - uint64_t pagesz) { - std::vector auxv; - auxv.push_back({AT_PHDR, phdr}); - auxv.push_back({AT_PHENT, sizeof(RawElf64Phdr)}); - auxv.push_back({AT_PHNUM, phnum}); - auxv.push_back({AT_PAGESZ, pagesz}); - auxv.push_back({AT_ENTRY, entry}); - auxv.push_back({AT_NULL, 0}); - return auxv; + out.stack_pointer = base; + size_t word = 0, string_pos = strings_begin; + auto push = [&](uint64_t value) { + std::memcpy(out.bytes.data() + word, &value, 8); + word += 8; + }; + push(args.size()); + for (const auto* list : {&args, &env}) { + for (const auto& text : *list) { + push(base + string_pos); + std::memcpy(out.bytes.data() + string_pos, text.c_str(), text.size() + 1); + string_pos += text.size() + 1; + } + push(0); + } + for (auto a : auxv) { + push(a.type); + push(a.val); + } + return out; } - std::vector BionicLoader::setup_initial_stack(const BionicElfInfo& info, const std::vector& args, const std::vector& env) { - std::vector stack; - auto auxv = build_auxv(info.entry_point, 0x400000, info.phdrs.size()); - - // Basic layout simulation: argc, argv pointers, env pointers, auxv pairs - uint64_t argc = args.size(); - stack.resize(4096, 0); - uint64_t* ptr = reinterpret_cast(stack.data()); - - *ptr++ = argc; - for (size_t i = 0; i < args.size(); ++i) { - *ptr++ = 0x7fffffffe000 + i * 32; - } - *ptr++ = 0; // NULL argv terminator - - for (size_t i = 0; i < env.size(); ++i) { - *ptr++ = 0x7fffffffe800 + i * 32; - } - *ptr++ = 0; // NULL env terminator - - for (const auto& a : auxv) { - *ptr++ = a.type; - *ptr++ = a.val; - } - - return stack; + return build_initial_stack(info, args, env, 0, 0, 0, 4096).bytes; } - } // namespace compat } // namespace ps5droid diff --git a/src/compat/bionic_loader.h b/src/compat/bionic_loader.h index 046a030..b89d1d8 100644 --- a/src/compat/bionic_loader.h +++ b/src/compat/bionic_loader.h @@ -27,6 +27,8 @@ struct Elf64PhdrInfo { struct BionicElfInfo { bool valid = false; uint64_t entry_point = 0; + uint64_t phdr_offset = 0; + uint16_t elf_type = 0; std::string interp; bool is_bionic = false; uint64_t tls_filesz = 0; @@ -41,11 +43,24 @@ struct AuxvEntry { uint64_t val; }; +struct InitialStack { + std::vector bytes; + uint64_t stack_pointer = 0; + std::string error; +}; + class BionicLoader { public: static BionicElfInfo parse_header(const void* data, size_t size); static std::vector build_auxv(uint64_t entry, uint64_t phdr, uint64_t phnum, uint64_t pagesz = 4096); + // base=0 uses the returned vector's actual allocation; explicit bases stage guest addresses. + // This minimal auxv is for the cooperative fixture, not a complete bionic startup contract. + static InitialStack build_initial_stack(const BionicElfInfo& info, + const std::vector& args, + const std::vector& env, + uint64_t guest_base, uint64_t phdr_address, + uint64_t load_bias, uint64_t pagesz); static std::vector setup_initial_stack(const BionicElfInfo& info, const std::vector& args, const std::vector& env); diff --git a/src/compat/elf_runner.cpp b/src/compat/elf_runner.cpp new file mode 100644 index 0000000..ba98c1d --- /dev/null +++ b/src/compat/elf_runner.cpp @@ -0,0 +1,154 @@ +#include "compat/elf_runner.h" +#include "compat/bionic_loader.h" +#include "compat/syscall_dispatch.h" +#include "platform/platform.h" +#include +#include +#include +#include +#include + +namespace ps5droid { +namespace compat { +bool probe_rx_memory(std::string* detail) { + size_t size = platform::page_size(); + void* page = platform::map_anonymous(size); + if (!page) { + if (detail) + *detail = "RW allocation failed"; + return false; + } + bool result = mprotect(page, size, PROT_READ | PROT_EXEC) == 0; + int error = errno; + platform::unmap(page, size); + if (detail) + *detail = result ? "RW -> RX protection accepted; no JIT or guest execution verified" + : "RW -> RX protection refused (host errno " + std::to_string(error) + ")"; + return result; +} +namespace { +#if defined(__x86_64__) +struct GatewayContext { + SyscallDispatch* dispatch; + const uint8_t* image; + size_t image_size; + const uint8_t* stack; + size_t stack_size; +}; +bool contains(const uint8_t* base, size_t size, uint64_t address, uint64_t count) { + uint64_t start = reinterpret_cast(base); + return address >= start && address - start <= size && count <= size - (address - start); +} +int64_t gateway(void* opaque, int number, const SyscallArgs* args) { + auto& context = *static_cast(opaque); + if (!args) + return -14; + if (number == linux_abi::kWrite) { + if (args->a[0] != 1 && args->a[0] != 2) + return -9; + if (!contains(context.image, context.image_size, args->a[1], args->a[2]) && + !contains(context.stack, context.stack_size, args->a[1], args->a[2])) + return -14; + } else if (number != linux_abi::kGetpid && number != linux_abi::kExitGroup) + return -38; + auto result = context.dispatch->invoke(number, *args); + return result.err ? -result.err : result.ret; +} +#endif +} // namespace +ElfRunResult run_cooperative_elf(const void* file, size_t size) { + ElfRunResult out; + auto info = BionicLoader::parse_header(file, size); + if (!info.valid) { + out.note = info.error; + return out; + } +#if !defined(__x86_64__) + out.note = "native x86_64 execution is unavailable in this host build"; + return out; +#else + auto fail = [&](const char* note) { + out.note = note; + return out; + }; + if (info.elf_type != 3) + return fail("cooperative runner requires position-independent ET_DYN"); + const size_t page = platform::page_size(); + constexpr uint64_t limit = 64 * 1024 * 1024; + uint64_t end = 0, phdr_address = 0; + size_t loads = 0; + for (const auto& p : info.phdrs) { + if (p.type == 2 || p.type == 3 || p.type == 7) + return fail("dynamic linking, PT_INTERP and TLS execution are not implemented"); + if (p.type != 1 || !p.memsz) + continue; + if ((p.flags & ~7u) || (p.flags & 3u) == 3u || p.vaddr % page || p.vaddr > limit || + p.memsz > limit - p.vaddr) + return fail("unsupported PT_LOAD permissions, alignment or image size"); + uint64_t segment_end = (p.vaddr + p.memsz + page - 1) / page * page; + for (const auto& other : info.phdrs) { + if (&other == &p || other.type != 1 || !other.memsz) + continue; + if (other.vaddr < segment_end && p.vaddr < other.vaddr + other.memsz) + return fail("overlapping PT_LOAD pages are not supported"); + } + end = std::max(end, segment_end); + ++loads; + uint64_t table_size = info.phdrs.size() * 56; + if (info.phdr_offset >= p.offset && info.phdr_offset - p.offset <= p.filesz && + table_size <= p.filesz - (info.phdr_offset - p.offset)) + phdr_address = p.vaddr + info.phdr_offset - p.offset; + // Conservative rejection, not instruction decoding or syscall interception. + if (p.flags & 1) { + const auto* bytes = static_cast(file) + p.offset; + for (size_t i = 1; i < p.filesz; ++i) + if (bytes[i - 1] == 0x0f && bytes[i] == 0x05) + return fail("raw Linux syscall bytes require a future interception backend"); + } + } + if (!loads || !end || !phdr_address) + return fail("PT_LOAD must include the program header table"); + auto release = [end](void* p) { + if (p) + platform::unmap(p, end); + }; + std::unique_ptr memory(platform::map_anonymous(end), release); + if (!memory) + return fail("cannot allocate ELF image"); + auto* image = static_cast(memory.get()); + for (const auto& p : info.phdrs) + if (p.type == 1 && p.filesz) + std::memcpy(image + p.vaddr, static_cast(file) + p.offset, p.filesz); + if (mprotect(image, end, PROT_NONE)) + return fail("cannot protect ELF image gaps"); + for (const auto& p : info.phdrs) + if (p.type == 1 && p.memsz) { + int prot = (p.flags & 4 ? PROT_READ : 0) | (p.flags & 2 ? PROT_WRITE : 0) | + (p.flags & 1 ? PROT_EXEC : 0); + size_t length = (p.memsz + page - 1) / page * page; + if (mprotect(image + p.vaddr, length, prot)) + return fail("cannot apply ELF segment protections"); + } + auto stack = BionicLoader::build_initial_stack(info, {"ps5droid-fixture"}, {}, 0, + reinterpret_cast(image) + phdr_address, + reinterpret_cast(image), page); + if (!stack.error.empty()) { + out.note = stack.error; + return out; + } + CompatMemory compat_memory; + SyscallDispatch dispatch(&compat_memory); + GatewayContext context{&dispatch, image, static_cast(end), stack.bytes.data(), + stack.bytes.size()}; + using Entry = int64_t (*)(void*, int64_t (*)(void*, int, const SyscallArgs*), const uint8_t*); + auto entry = reinterpret_cast(image + info.entry_point); + out.entry_result = entry(&context, gateway, stack.bytes.data()); + out.executed = true; + out.stop_requested = dispatch.stop_requested(); + out.note = + "cooperative ELF entry returned; unmodified bionic/Android startup remains unsupported"; + return out; +#endif +} +} // namespace compat +} // namespace ps5droid diff --git a/src/compat/elf_runner.h b/src/compat/elf_runner.h new file mode 100644 index 0000000..2b4d22f --- /dev/null +++ b/src/compat/elf_runner.h @@ -0,0 +1,20 @@ +// Trusted cooperative ELF execution experiment. Not an unmodified bionic loader. +#pragma once +#include +#include +#include + +namespace ps5droid { +namespace compat { +struct ElfRunResult { + bool executed = false; + bool stop_requested = false; + int64_t entry_result = 0; + std::string note; +}; +// Explicit opt-in only. Entry uses the C ABI documented in docs/elf-execution.md. +// Dynamic linking, relocations, TLS, raw syscalls and process isolation are absent. +ElfRunResult run_cooperative_elf(const void* file, size_t size); +bool probe_rx_memory(std::string* detail); +} // namespace compat +} // namespace ps5droid diff --git a/src/compat/fd_table.cpp b/src/compat/fd_table.cpp index 22f26b0..3e02343 100644 --- a/src/compat/fd_table.cpp +++ b/src/compat/fd_table.cpp @@ -1,336 +1,388 @@ -// PS5Droid - Guest File Descriptor Table and Epoll implementation. +// Linux guest descriptors. Native flags and errno never cross the guest ABI. #include "compat/fd_table.h" +#include "platform/platform.h" #include -#include +#include +#include +#include #include - -#include "platform/platform.h" +#include +#include +#include +#include namespace ps5droid { namespace compat { +struct FdSignal { + std::mutex mutex; + std::condition_variable changed; + uint64_t generation = 0; + void notify() { + { + std::lock_guard lock(mutex); + ++generation; + } + changed.notify_all(); + } +}; namespace { +int bad(int error) { + errno = error; + return -1; +} -class FileFdEntry : public FdEntry { +class NativeFd : public FdEntry { public: - FileFdEntry(const std::string& path, FILE* fp) : path_(path), fp_(fp) {} - ~FileFdEntry() override { close(); } - - FdType type() const override { return FdType::kFile; } - + NativeFd(int fd, bool owned, FdType type) : fd_(fd), owned_(owned), type_(type) {} + ~NativeFd() override { + if (owned_) + ::close(fd_); + } + FdType type() const override { return type_; } int64_t read(void* buf, size_t count, int64_t offset) override { - if (!fp_) - return -1; - if (offset >= 0) { - fseek(fp_, static_cast(offset), SEEK_SET); - } - size_t r = fread(buf, 1, count, fp_); - return static_cast(r); + if (count > static_cast(std::numeric_limits::max())) + return bad(EINVAL); + return offset < 0 ? ::read(fd_, buf, count) : ::pread(fd_, buf, count, offset); } - int64_t write(const void* buf, size_t count, int64_t offset) override { - if (!fp_) - return -1; - if (offset >= 0) { - fseek(fp_, static_cast(offset), SEEK_SET); - } - size_t w = fwrite(buf, 1, count, fp_); - fflush(fp_); - return static_cast(w); + if (count > static_cast(std::numeric_limits::max())) + return bad(EINVAL); + return offset < 0 ? ::write(fd_, buf, count) : ::pwrite(fd_, buf, count, offset); } - - int64_t lseek(int64_t offset, int whence) override { - if (!fp_) - return -1; - if (fseek(fp_, static_cast(offset), whence) != 0) { - return -1; + int64_t lseek(int64_t offset, int whence) override { return ::lseek(fd_, offset, whence); } + bool fstat(StatBuf* out) override { + if (!out) { + bad(EFAULT); + return false; } - return static_cast(ftell(fp_)); - } - - bool fstat(StatBuf* statbuf) override { - if (!statbuf || !fp_) + struct stat st{}; + if (::fstat(fd_, &st) != 0) return false; - memset(statbuf, 0, sizeof(*statbuf)); - long cur = ftell(fp_); - fseek(fp_, 0, SEEK_END); - long sz = ftell(fp_); - fseek(fp_, cur, SEEK_SET); - statbuf->st_size = sz; - statbuf->st_mode = 0100644; // S_IFREG + *out = {}; + out->st_dev = st.st_dev; + out->st_ino = st.st_ino; + out->st_nlink = st.st_nlink; + out->st_mode = st.st_mode; + out->st_uid = st.st_uid; + out->st_gid = st.st_gid; + out->st_rdev = st.st_rdev; + out->st_size = st.st_size; + out->st_blksize = st.st_blksize; + out->st_blocks = st.st_blocks; + out->st_atime_sec = st.st_atime; + out->st_mtime_sec = st.st_mtime; + out->st_ctime_sec = st.st_ctime; +#if defined(__APPLE__) + out->st_atime_nsec = st.st_atimespec.tv_nsec; + out->st_mtime_nsec = st.st_mtimespec.tv_nsec; + out->st_ctime_nsec = st.st_ctimespec.tv_nsec; +#else + out->st_atime_nsec = st.st_atim.tv_nsec; + out->st_mtime_nsec = st.st_mtim.tv_nsec; + out->st_ctime_nsec = st.st_ctim.tv_nsec; +#endif return true; } - - void close() override { - if (fp_) { - fclose(fp_); - fp_ = nullptr; - } - } + // Lifetime belongs to the shared open-file description, not one descriptor. + void close() override {} private: - std::string path_; - FILE* fp_; + int fd_; + bool owned_; + FdType type_; }; -class StreamFdEntry : public FdEntry { +class EventFd : public FdEntry { public: - explicit StreamFdEntry(FILE* stream) : stream_(stream) {} - FdType type() const override { return FdType::kStream; } - - int64_t read(void*, size_t, int64_t) override { return -1; } - int64_t write(const void* buf, size_t count, int64_t) override { - if (!stream_ || !buf) - return -1; - size_t w = fwrite(buf, 1, count, stream_); - fflush(stream_); - return static_cast(w); + EventFd(uint64_t value, int flags, std::shared_ptr signal) + : value_(value), flags_(flags), signal_(std::move(signal)) {} + FdType type() const override { return FdType::kEventFd; } + int64_t read(void* buf, size_t count, int64_t offset) override { + if (offset >= 0) + return bad(ESPIPE); + if (count < 8) + return bad(EINVAL); + if (!buf) + return bad(EFAULT); + std::unique_lock lock(mutex_); + if (!value_ && (flags_ & 0x800)) + return bad(EAGAIN); + changed_.wait(lock, [&] { return value_ != 0; }); + uint64_t value = (flags_ & 1) ? 1 : value_; + value_ -= value; + std::memcpy(buf, &value, 8); + lock.unlock(); + changed_.notify_all(); + signal_->notify(); + return 8; + } + int64_t write(const void* buf, size_t count, int64_t offset) override { + if (offset >= 0) + return bad(ESPIPE); + if (count != 8) + return bad(EINVAL); + if (!buf) + return bad(EFAULT); + uint64_t value; + std::memcpy(&value, buf, 8); + if (value == UINT64_MAX) + return bad(EINVAL); + std::unique_lock lock(mutex_); + auto fits = [&] { return value <= UINT64_MAX - 1 - value_; }; + if (!fits() && (flags_ & 0x800)) + return bad(EAGAIN); + changed_.wait(lock, fits); + value_ += value; + lock.unlock(); + changed_.notify_all(); + signal_->notify(); + return 8; + } + uint32_t ready() override { + std::lock_guard lock(mutex_); + return (value_ ? 1u : 0u) | (value_ < UINT64_MAX - 1 ? 4u : 0u); } - int64_t lseek(int64_t, int) override { return -1; } - bool fstat(StatBuf* statbuf) override { - if (!statbuf) + int64_t lseek(int64_t, int) override { return bad(ESPIPE); } + bool fstat(StatBuf* out) override { + if (!out) { + bad(EFAULT); return false; - memset(statbuf, 0, sizeof(*statbuf)); - statbuf->st_mode = 0020666; // S_IFCHR + } + *out = {}; + out->st_mode = 0600; return true; } - void close() override { stream_ = nullptr; } + void close() override {} private: - FILE* stream_; + std::mutex mutex_; + std::condition_variable changed_; + uint64_t value_; + int flags_; + std::shared_ptr signal_; }; -class EpollFdEntry : public FdEntry { +class EpollFd : public FdEntry { public: - EpollFdEntry() = default; + explicit EpollFd(std::shared_ptr signal) : signal_(std::move(signal)) {} FdType type() const override { return FdType::kEpoll; } - - int64_t read(void*, size_t, int64_t) override { return -1; } - int64_t write(const void*, size_t, int64_t) override { return -1; } - int64_t lseek(int64_t, int) override { return -1; } - bool fstat(StatBuf* statbuf) override { - if (!statbuf) + int64_t read(void*, size_t, int64_t) override { return bad(EINVAL); } + int64_t write(const void*, size_t, int64_t) override { return bad(EINVAL); } + int64_t lseek(int64_t, int) override { return bad(ESPIPE); } + bool fstat(StatBuf* out) override { + if (!out) { + bad(EFAULT); return false; - memset(statbuf, 0, sizeof(*statbuf)); + } + *out = {}; + out->st_mode = 0600; return true; } - void close() override { events_.clear(); } - - bool ctl(int op, int fd, const EpollEvent* event) { - if (op == 1 /* EPOLL_CTL_ADD */) { - if (!event) - return false; - events_[fd] = *event; - return true; - } else if (op == 2 /* EPOLL_CTL_DEL */) { - events_.erase(fd); - return true; - } else if (op == 3 /* EPOLL_CTL_MOD */) { - if (!event || events_.find(fd) == events_.end()) - return false; - events_[fd] = *event; - return true; + void close() override {} + bool ctl(int op, int fd, const std::shared_ptr& target, const EpollEvent* event) { + std::lock_guard lock(mutex_); + auto it = events_.find(fd); + if (it != events_.end() && it->second.target.expired()) { + events_.erase(it); + it = events_.end(); } - return false; - } - - int wait(EpollEvent* out_events, int maxevents, int timeout_ms) { - if (!out_events || maxevents <= 0) - return -1; - int count = 0; - for (const auto& kv : events_) { - if (count >= maxevents) - break; - out_events[count++] = kv.second; + if (op < 1 || op > 3) { + bad(EINVAL); + return false; } - if (count == 0 && timeout_ms > 0) { - platform::sleep_ns(static_cast(timeout_ms) * 1000000ull); + if (op != 2 && (!event || (event->events & ~0x1du))) { + bad(EINVAL); + return false; } - return count; - } - - private: - std::unordered_map events_; -}; - -class EventFdEntry : public FdEntry { - public: - explicit EventFdEntry(uint64_t initval) : counter_(initval) {} - FdType type() const override { return FdType::kEventFd; } - - int64_t read(void* buf, size_t count, int64_t) override { - if (count < sizeof(uint64_t) || !buf) - return -1; - uint64_t val = counter_; - counter_ = 0; - std::memcpy(buf, &val, sizeof(uint64_t)); - return sizeof(uint64_t); - } - - int64_t write(const void* buf, size_t count, int64_t) override { - if (count < sizeof(uint64_t) || !buf) - return -1; - uint64_t val = 0; - std::memcpy(&val, buf, sizeof(uint64_t)); - counter_ += val; - return sizeof(uint64_t); - } - - int64_t lseek(int64_t, int) override { return -1; } - bool fstat(StatBuf* statbuf) override { - if (!statbuf) + if (op == 1 && it != events_.end()) { + bad(EEXIST); + return false; + } + if (op != 1 && it == events_.end()) { + bad(ENOENT); return false; - memset(statbuf, 0, sizeof(*statbuf)); + } + if (op == 2) + events_.erase(it); + else + events_[fd] = Watch{target, *event}; + signal_->notify(); return true; } - void close() override { counter_ = 0; } + int wait(EpollEvent* out, int maxevents, int timeout_ms) { + if (!out) + return bad(EFAULT); + if (maxevents <= 0) + return bad(EINVAL); + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(std::max(timeout_ms, 0)); + for (;;) { + uint64_t generation; + { + std::lock_guard lock(signal_->mutex); + generation = signal_->generation; + } + int count = 0; + { + std::lock_guard lock(mutex_); + for (auto it = events_.begin(); it != events_.end();) { + auto target = it->second.target.lock(); + if (!target) { + it = events_.erase(it); + continue; + } + uint32_t ready = target->ready() & (it->second.event.events | 0x18u); + if (ready && count < maxevents) + out[count++] = {ready, it->second.event.data}; + ++it; + } + } + if (count || timeout_ms == 0) + return count; + std::unique_lock lock(signal_->mutex); + auto changed = [&] { return signal_->generation != generation; }; + if (timeout_ms < 0) + signal_->changed.wait(lock, changed); + else if (!signal_->changed.wait_until(lock, deadline, changed)) + return 0; + } + } private: - uint64_t counter_ = 0; + struct Watch { + std::weak_ptr target; + EpollEvent event; + }; + std::mutex mutex_; + std::unordered_map events_; + std::shared_ptr signal_; }; - } // namespace -CompatFdTable::CompatFdTable() { - table_[0] = std::make_shared(stdin); - table_[1] = std::make_shared(stdout); - table_[2] = std::make_shared(stderr); +CompatFdTable::CompatFdTable() : signal_(std::make_shared()) { + for (int fd = 0; fd < 3; ++fd) + table_[fd] = std::make_shared(fd, false, FdType::kStream); } - -CompatFdTable::~CompatFdTable() { - std::lock_guard lock(mutex_); - table_.clear(); -} - -int CompatFdTable::open_file(const std::string& path, int flags, int mode) { - (void)mode; +CompatFdTable::~CompatFdTable() = default; +int CompatFdTable::insert(std::shared_ptr entry) { std::lock_guard lock(mutex_); - const char* fmode = "r"; - if ((flags & 0x3) == 1) - fmode = "w"; - else if ((flags & 0x3) == 2) - fmode = "r+"; - if (flags & 0x200 /* O_CREAT */) { - if (flags & 0x400 /* O_TRUNC */) - fmode = "w+"; - else - fmode = "a+"; + int fd = 0; + while (table_.count(fd)) { + if (fd == INT32_MAX) + return bad(EMFILE); + ++fd; } - - FILE* fp = fopen(path.c_str(), fmode); - if (!fp) - return -1; - - int fd = next_fd_++; - table_[fd] = std::make_shared(path, fp); + table_[fd] = std::move(entry); return fd; } - -int CompatFdTable::create_epoll() { - std::lock_guard lock(mutex_); - int fd = next_fd_++; - table_[fd] = std::make_shared(); - return fd; +int CompatFdTable::open_file(const std::string& path, int flags, int mode) { + constexpr int allowed = + 3 | 0x40 | 0x80 | 0x100 | 0x200 | 0x400 | 0x800 | 0x8000 | 0x10000 | 0x20000 | 0x80000; + if ((flags & ~allowed) || (flags & 3) == 3) + return bad(EINVAL); + int native = (flags & 3) == 2 ? O_RDWR : (flags & 3) == 1 ? O_WRONLY : O_RDONLY; + const int guest[] = {0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x10000, 0x20000, 0x80000}; + const int host[] = {O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC, O_APPEND, + O_NONBLOCK, O_DIRECTORY, O_NOFOLLOW, O_CLOEXEC}; + for (size_t i = 0; i < sizeof(guest) / sizeof(guest[0]); ++i) + if (flags & guest[i]) + native |= host[i]; + int fd = ::open(path.c_str(), native, static_cast(mode & 07777)); + return fd < 0 ? -1 : insert(std::make_shared(fd, true, FdType::kFile)); +} +int CompatFdTable::create_epoll(int flags) { + if (flags & ~0x80000) + return bad(EINVAL); + return insert(std::make_shared(signal_)); } - int CompatFdTable::create_eventfd(uint64_t initval, int flags) { - (void)flags; - std::lock_guard lock(mutex_); - int fd = next_fd_++; - table_[fd] = std::make_shared(initval); - return fd; + if ((flags & ~(1 | 0x800 | 0x80000)) || initval > UINT32_MAX) + return bad(EINVAL); + return insert(std::make_shared(initval, flags, signal_)); } - bool CompatFdTable::epoll_ctl(int epfd, int op, int fd, const EpollEvent* event) { - auto entry = get(epfd); - if (!entry || entry->type() != FdType::kEpoll) + auto ep = get(epfd); + if (!ep) return false; - auto epoll = std::static_pointer_cast(entry); - return epoll->ctl(op, fd, event); + auto target = get(fd); + if (!target) + return false; + if (ep->type() != FdType::kEpoll || epfd == fd) { + bad(EINVAL); + return false; + } + // Only eventfd level-triggered readiness is implemented. Never fabricate file readiness. + if (target->type() != FdType::kEventFd) { + bad(EPERM); + return false; + } + return std::static_pointer_cast(ep)->ctl(op, fd, target, event); } - int CompatFdTable::epoll_wait(int epfd, EpollEvent* events, int maxevents, int timeout_ms) { - auto entry = get(epfd); - if (!entry || entry->type() != FdType::kEpoll) + auto ep = get(epfd); + if (!ep) return -1; - auto epoll = std::static_pointer_cast(entry); - return epoll->wait(events, maxevents, timeout_ms); + if (ep->type() != FdType::kEpoll) + return bad(EINVAL); + return std::static_pointer_cast(ep)->wait(events, maxevents, timeout_ms); } - int64_t CompatFdTable::read(int fd, void* buf, size_t count) { - auto entry = get(fd); - if (!entry) - return -1; - return entry->read(buf, count, -1); + auto e = get(fd); + return e ? e->read(buf, count) : -1; } - int64_t CompatFdTable::pread64(int fd, void* buf, size_t count, int64_t offset) { - auto entry = get(fd); - if (!entry) - return -1; - return entry->read(buf, count, offset); + if (offset < 0) + return bad(EINVAL); + auto e = get(fd); + return e ? e->read(buf, count, offset) : -1; } - int64_t CompatFdTable::write(int fd, const void* buf, size_t count) { - auto entry = get(fd); - if (!entry) - return -1; - return entry->write(buf, count, -1); + auto e = get(fd); + return e ? e->write(buf, count) : -1; } - int64_t CompatFdTable::lseek(int fd, int64_t offset, int whence) { - auto entry = get(fd); - if (!entry) - return -1; - return entry->lseek(offset, whence); + if (whence < 0 || whence > 2) + return bad(EINVAL); + auto e = get(fd); + return e ? e->lseek(offset, whence) : -1; } - -bool CompatFdTable::fstat(int fd, StatBuf* statbuf) { - auto entry = get(fd); - if (!entry) - return false; - return entry->fstat(statbuf); +bool CompatFdTable::fstat(int fd, StatBuf* out) { + auto e = get(fd); + return e && e->fstat(out); } - int CompatFdTable::dup(int oldfd) { - std::lock_guard lock(mutex_); - auto it = table_.find(oldfd); - if (it == table_.end()) - return -1; - int newfd = next_fd_++; - table_[newfd] = it->second; - return newfd; + auto e = get(oldfd); + return e ? insert(e) : -1; } - int CompatFdTable::dup2(int oldfd, int newfd) { std::lock_guard lock(mutex_); auto it = table_.find(oldfd); if (it == table_.end() || newfd < 0) - return -1; - table_[newfd] = it->second; - if (newfd >= next_fd_) - next_fd_ = newfd + 1; + return bad(EBADF); + auto entry = it->second; + table_[newfd] = std::move(entry); + signal_->notify(); return newfd; } - int CompatFdTable::close(int fd) { - std::lock_guard lock(mutex_); - auto it = table_.find(fd); - if (it == table_.end()) - return -1; - it->second->close(); - table_.erase(it); + { + std::lock_guard lock(mutex_); + if (!table_.erase(fd)) + return bad(EBADF); + } + signal_->notify(); return 0; } - std::shared_ptr CompatFdTable::get(int fd) { std::lock_guard lock(mutex_); auto it = table_.find(fd); - if (it == table_.end()) + if (it == table_.end()) { + bad(EBADF); return nullptr; + } return it->second; } - } // namespace compat } // namespace ps5droid diff --git a/src/compat/fd_table.h b/src/compat/fd_table.h index 9666e59..e6b54fb 100644 --- a/src/compat/fd_table.h +++ b/src/compat/fd_table.h @@ -1,8 +1,7 @@ // PS5Droid - Guest File Descriptor Table and Epoll abstraction. // -// Milestone 3: In-process file descriptor table managing simulated guest fds -// (files, streams, pipes, eventfds, epoll instances) and multiplexing epoll -// event loops over kqueue / host poll primitives. +// Native files, shared descriptor lifetimes and eventfd counters. Epoll currently +// supports level-triggered eventfd readiness only; other targets/flags fail explicitly. #pragma once #include @@ -30,20 +29,33 @@ struct StatBuf { uint32_t st_mode; uint32_t st_uid; uint32_t st_gid; + uint32_t padding; uint64_t st_rdev; int64_t st_size; int64_t st_blksize; int64_t st_blocks; int64_t st_atime_sec; + uint64_t st_atime_nsec; int64_t st_mtime_sec; + uint64_t st_mtime_nsec; int64_t st_ctime_sec; + uint64_t st_ctime_nsec; + int64_t reserved[3]; }; +static_assert(sizeof(StatBuf) == 144, "Linux x86_64 stat layout"); + +#pragma pack(push, 1) struct EpollEvent { uint32_t events; uint64_t data; }; +#pragma pack(pop) +static_assert(sizeof(EpollEvent) == 12, "Linux x86_64 epoll_event layout"); + +struct FdSignal; + class FdEntry { public: virtual ~FdEntry() = default; @@ -53,6 +65,7 @@ class FdEntry { virtual int64_t lseek(int64_t offset, int whence) = 0; virtual bool fstat(StatBuf* statbuf) = 0; virtual void close() = 0; + virtual uint32_t ready() { return 0; } }; class CompatFdTable { @@ -61,7 +74,7 @@ class CompatFdTable { ~CompatFdTable(); int open_file(const std::string& path, int flags, int mode); - int create_epoll(); + int create_epoll(int flags = 0); int create_eventfd(uint64_t initval, int flags); bool epoll_ctl(int epfd, int op, int fd, const EpollEvent* event); @@ -81,7 +94,8 @@ class CompatFdTable { private: std::mutex mutex_; - int next_fd_ = 3; // 0=stdin, 1=stdout, 2=stderr + int insert(std::shared_ptr entry); + std::shared_ptr signal_; std::unordered_map> table_; }; diff --git a/src/compat/linux_abi.cpp b/src/compat/linux_abi.cpp index a85250f..cd61ea3 100644 --- a/src/compat/linux_abi.cpp +++ b/src/compat/linux_abi.cpp @@ -9,12 +9,11 @@ namespace linux_abi { const SyscallInfo kSyscallTable[] = { // --- emulated, real in-process behavior ------------------------------- {kWrite, "write", kEmulated, "fd 1/2 passthrough to the process streams"}, - {kMmap, "mmap", kEmulated, "anonymous private mappings only (arena-backed)"}, + {kMmap, "mmap", kPartial, "anonymous private mappings only (arena-backed)"}, {kMunmap, "munmap", kPartial, "whole-mapping release only; partial interior ranges return EINVAL"}, {kMprotect, "mprotect", kPartial, - "R/W adjustments honored; PROT_EXEC is accepted but not granted " - "(no JIT path yet)"}, + "R/W adjustments honored; executable guest mappings rejected"}, {kBrk, "brk", kEmulated, "heap over an internal anonymous arena"}, {kSchedYield, "sched_yield", kEmulated, "maps to platform yield"}, {kNanosleep, "nanosleep", kEmulated, "maps to platform sleep"}, @@ -26,19 +25,23 @@ const SyscallInfo kSyscallTable[] = { {kExitGroup, "exit_group", kEmulated, "flags the emulation context as stopping"}, // --- guest fd table & stream / file operations ------------------------ - {kRead, "read", kEmulated, "reads from simulated guest fds"}, - {kOpen, "open", kEmulated, "opens files into in-process guest fd table"}, + {kRead, "read", kPartial, "reads from simulated guest fds"}, + {kOpen, "open", kPartial, "opens files into in-process guest fd table"}, {kClose, "close", kEmulated, "closes guest fds"}, - {kFstat, "fstat", kEmulated, "fstat on guest fds"}, - {kLseek, "lseek", kEmulated, "lseek on simulated guest fds"}, - {kPread64, "pread64", kEmulated, "positioned read on guest fds"}, + {kFstat, "fstat", kPartial, "fstat on guest fds"}, + {kLseek, "lseek", kPartial, "lseek on simulated guest fds"}, + {kPread64, "pread64", kPartial, "positioned read on guest fds"}, {kDup, "dup", kEmulated, "duplicates guest fds"}, {kDup2, "dup2", kEmulated, "duplicates guest fds to target index"}, - {kEpollWait, "epoll_wait", kEmulated, "wait on in-process epoll instances"}, - {kEpollCtl, "epoll_ctl", kEmulated, "control events on in-process epoll instances"}, - {kOpenat, "openat", kEmulated, "openat routed to in-process guest fd table"}, + {kEpollWait, "epoll_wait", kPartial, + "level-triggered eventfd readiness only; advanced modes rejected"}, + {kEpollCtl, "epoll_ctl", kPartial, + "eventfd targets only; files, sockets and nested epoll rejected"}, + {kOpenat, "openat", kPartial, + "absolute paths or AT_FDCWD only; other relative dirfds rejected"}, {kEventfd2, "eventfd2", kEmulated, "eventfd counter primitive in fd table"}, - {kEpollCreate1, "epoll_create1", kEmulated, "creates in-process epoll instance in fd table"}, + {kEpollCreate1, "epoll_create1", kPartial, + "creates limited eventfd readiness instance; flags validated"}, // --- honestly unsupported; these are the hard blockers ----------------- {kStat, "stat", kUnsupported, "guest path stat not routed"}, @@ -62,9 +65,9 @@ const SyscallInfo kSyscallTable[] = { {kWait4, "wait4", kUnsupported, "no child processes exist in the emulation model"}, {kKill, "kill", kUnsupported, "no signal delivery between processes"}, {kUname, "uname", kUnsupported, "would require synthesizing a fake kernel identity; refused"}, - {kFcntl, "fcntl", kUnsupported, "guest fd table not implemented"}, - {kFlock, "flock", kUnsupported, "guest fd table not implemented"}, - {kFsync, "fsync", kUnsupported, "guest fd table not implemented"}, + {kFcntl, "fcntl", kUnsupported, "operation not implemented in guest fd table"}, + {kFlock, "flock", kUnsupported, "operation not implemented in guest fd table"}, + {kFsync, "fsync", kUnsupported, "operation not implemented in guest fd table"}, {kGetcwd, "getcwd", kUnsupported, "guest path layer not implemented"}, {kChdir, "chdir", kUnsupported, "guest path layer not implemented"}, {kMkdir, "mkdir", kUnsupported, "guest path layer not implemented"}, @@ -90,8 +93,8 @@ const SyscallInfo kSyscallTable[] = { {kUnlinkat, "unlinkat", kUnsupported, "guest path layer missing"}, {kPpoll, "ppoll", kUnsupported, "poll layer not implemented"}, {kSetRobustList, "set_robust_list", kUnsupported, "not implemented"}, - {kDup3, "dup3", kUnsupported, "guest fd table not implemented"}, - {kPipe2, "pipe2", kUnsupported, "no guest fd table"}, + {kDup3, "dup3", kUnsupported, "operation not implemented in guest fd table"}, + {kPipe2, "pipe2", kUnsupported, "guest pipe descriptors not implemented"}, {kInotifyInit1, "inotify_init1", kUnsupported, "not implemented"}, {kMemfdCreate, "memfd_create", kUnsupported, "Linux memfd has no Orbis equivalent; unimplemented"}, diff --git a/src/compat/memory_compat.cpp b/src/compat/memory_compat.cpp index bbb421d..8518a81 100644 --- a/src/compat/memory_compat.cpp +++ b/src/compat/memory_compat.cpp @@ -2,6 +2,7 @@ #include "compat/memory_compat.h" #include +#include #include "platform/platform.h" @@ -14,7 +15,7 @@ constexpr size_t kHeapSize = 1024 * 1024; // 1 MiB brk arena size_t page_align_up_sz(size_t v) { size_t ps = platform::page_size(); - return (v + ps - 1) & ~(ps - 1); + return v > SIZE_MAX - (ps - 1) ? 0 : (v + ps - 1) & ~(ps - 1); } } // namespace @@ -49,14 +50,21 @@ MapResult CompatMemory::mmap(uintptr_t hint, size_t length, int prot, int flags, } (void)hint; // treated as a suggestion only; the allocator picks pages + if (prot & ~(linux_abi::kProtRead | linux_abi::kProtWrite)) + return {nullptr, linux_abi::kEinval, + "unsupported protection; executable guest mappings are unavailable"}; + if (flags != (linux_abi::kMapPrivate | linux_abi::kMapAnonymous)) + return {nullptr, linux_abi::kEinval, "unsupported mapping flags"}; size_t aligned = page_align_up_sz(length); + if (!aligned) + return {nullptr, linux_abi::kEnomem, "mapping length overflow"}; void* p = platform::map_anonymous(aligned); if (p == nullptr) { return {nullptr, linux_abi::kEnomem, "host map_anonymous failed"}; } uintptr_t addr = reinterpret_cast(p); - if (prot != (linux_abi::kProtRead | linux_abi::kProtWrite) && prot != linux_abi::kProtRead) { + if (prot != (linux_abi::kProtRead | linux_abi::kProtWrite)) { // Adjust to the requested protection (exec never granted). bool want_r = (prot & linux_abi::kProtRead) != 0; bool want_w = (prot & linux_abi::kProtWrite) != 0; @@ -74,6 +82,9 @@ MapResult CompatMemory::munmap(uintptr_t address, size_t length) { if (length == 0) { return {nullptr, linux_abi::kEinval, "munmap length is zero"}; } + length = page_align_up_sz(length); + if (!length) + return {nullptr, linux_abi::kEinval, "unmap length overflow"}; for (size_t i = 0; i < mappings_.size(); ++i) { const Mapping& m = mappings_[i]; if (address == m.addr && length == m.size) { @@ -94,11 +105,12 @@ MapResult CompatMemory::mprotect(uintptr_t address, size_t length, int prot) { if (length == 0) { return {nullptr, linux_abi::kEinval, "mprotect length is zero"}; } - if ((prot & ~(linux_abi::kProtRead | linux_abi::kProtWrite | linux_abi::kProtExec)) != 0) { + if ((prot & ~(linux_abi::kProtRead | linux_abi::kProtWrite)) != 0) { return {nullptr, linux_abi::kEinval, "unsupported prot bits"}; } for (const Mapping& m : mappings_) { - if (address >= m.addr && address + length <= m.addr + m.size) { + if (address >= m.addr && address - m.addr <= m.size && + length <= m.size - (address - m.addr)) { bool want_r = (prot & linux_abi::kProtRead) != 0; bool want_w = (prot & linux_abi::kProtWrite) != 0; if (platform::protect_memory(reinterpret_cast(address), length, want_r, @@ -148,10 +160,10 @@ BrkResult CompatMemory::brk(uintptr_t request) { bool CompatMemory::is_mapped(uintptr_t addr, size_t len) const { for (const Mapping& m : mappings_) { - if (addr >= m.addr && addr + len <= m.addr + m.size) + if (addr >= m.addr && addr - m.addr <= m.size && len <= m.size - (addr - m.addr)) return true; } - if (addr >= heap_start_ && addr + len <= heap_end_) + if (brk_ready_ && addr >= heap_start_ && addr <= heap_end_ && len <= heap_end_ - addr) return true; return false; } diff --git a/src/compat/syscall_dispatch.cpp b/src/compat/syscall_dispatch.cpp index f31f415..5ef774e 100644 --- a/src/compat/syscall_dispatch.cpp +++ b/src/compat/syscall_dispatch.cpp @@ -1,6 +1,8 @@ // PS5Droid - Linux syscall dispatch experiment (implementation). #include "compat/syscall_dispatch.h" +#include +#include #include #include @@ -10,6 +12,69 @@ namespace ps5droid { namespace compat { namespace { +std::atomic next_context{0x50534400ull}; + +// Translate host errno explicitly: FreeBSD/macOS values differ from Linux. +int linux_error() { + switch (errno) { + case EPERM: + return 1; + case ENOENT: + return 2; + case EINTR: + return 4; + case EIO: + return 5; + case EBADF: + return 9; + case EAGAIN: + return 11; + case ENOMEM: + return 12; + case EACCES: + return 13; + case EFAULT: + return 14; + case EBUSY: + return 16; + case EEXIST: + return 17; + case EXDEV: + return 18; + case ENODEV: + return 19; + case ENOTDIR: + return 20; + case EISDIR: + return 21; + case EINVAL: + return 22; + case ENFILE: + return 23; + case EMFILE: + return 24; + case EFBIG: + return 27; + case ENOSPC: + return 28; + case ESPIPE: + return 29; + case EROFS: + return 30; + case EPIPE: + return 32; + case ERANGE: + return 34; + case ENAMETOOLONG: + return 36; + case ENOSYS: + return 38; + case ELOOP: + return 40; + default: + return 5; + } +} struct TimespecView { // Linux/Orbis layout, 8+8 bytes on x86_64 int64_t tv_sec; @@ -20,7 +85,7 @@ struct TimespecView { // Linux/Orbis layout, 8+8 bytes on x86_64 SyscallDispatch::SyscallDispatch(CompatMemory* memory, CompatFdTable* fd_table) : memory_(memory), fd_table_(fd_table ? fd_table : &default_fd_table_), - context_id_(0x50534400ull | (platform::monotonic_ns() & 0xffffull)) {} + context_id_(next_context.fetch_add(1)) {} DispatchResult SyscallDispatch::ok(int64_t ret, const char* note) { return DispatchResult{ret, 0, true, note}; @@ -84,16 +149,18 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int mode = static_cast(linux_nr == kOpenat ? args.a[3] : args.a[2]); if (!path) return fail(kEfault, "path is null"); + if (linux_nr == kOpenat && path[0] != '/' && static_cast(args.a[0]) != -100) + return fail(kEnosys, "openat relative dirfd is not implemented"); int fd = fd_table_->open_file(path, flags, mode); if (fd < 0) - return fail(kEnoent, "open failed"); + return fail(linux_error(), "open failed"); return ok(fd, "fd_table file created"); } case kClose: { int fd = static_cast(static_cast(args.a[0])); if (fd_table_->close(fd) != 0) - return fail(kEbadf, "invalid fd"); + return fail(linux_error(), "invalid fd"); return ok(0, "fd closed"); } @@ -105,7 +172,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return fail(kEfault, "read buf is null"); int64_t r = fd_table_->read(fd, buf, count); if (r < 0) - return fail(kEbadf, "read failed"); + return fail(linux_error(), "read failed"); return ok(r, "fd read ok"); } @@ -118,7 +185,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return fail(kEfault, "buf is null"); int64_t r = fd_table_->pread64(fd, buf, count, off); if (r < 0) - return fail(kEbadf, "pread64 failed"); + return fail(linux_error(), "pread64 failed"); return ok(r, "pread64 ok"); } @@ -130,7 +197,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return fail(kEfault, "write buf is null"); int64_t n = fd_table_->write(fd, buf, count); if (n < 0) - return fail(kEbadf, "invalid fd"); + return fail(linux_error(), "invalid fd"); return ok(n, "stream/fd write ok"); } @@ -140,7 +207,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int whence = static_cast(args.a[2]); int64_t pos = fd_table_->lseek(fd, off, whence); if (pos < 0) - return fail(kEbadf, "lseek failed"); + return fail(linux_error(), "lseek failed"); return ok(pos, "lseek ok"); } @@ -150,7 +217,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { if (!st) return fail(kEfault, "statbuf is null"); if (!fd_table_->fstat(fd, st)) - return fail(kEbadf, "fstat failed"); + return fail(linux_error(), "fstat failed"); return ok(0, "fstat ok"); } @@ -158,7 +225,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int oldfd = static_cast(static_cast(args.a[0])); int newfd = fd_table_->dup(oldfd); if (newfd < 0) - return fail(kEbadf, "dup failed"); + return fail(linux_error(), "dup failed"); return ok(newfd, "dup ok"); } @@ -167,14 +234,14 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int newfd = static_cast(static_cast(args.a[1])); int res = fd_table_->dup2(oldfd, newfd); if (res < 0) - return fail(kEbadf, "dup2 failed"); + return fail(linux_error(), "dup2 failed"); return ok(res, "dup2 ok"); } case kEpollCreate1: { - int fd = fd_table_->create_epoll(); + int fd = fd_table_->create_epoll(static_cast(args.a[0])); if (fd < 0) - return fail(kEnomem, "epoll_create1 failed"); + return fail(linux_error(), "epoll_create1 failed"); return ok(fd, "epoll instance created"); } @@ -184,7 +251,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int target_fd = static_cast(args.a[2]); const EpollEvent* event = reinterpret_cast(args.a[3]); if (!fd_table_->epoll_ctl(epfd, op, target_fd, event)) { - return fail(kEinval, "epoll_ctl failed"); + return fail(linux_error(), "epoll_ctl failed"); } return ok(0, "epoll_ctl ok"); } @@ -196,7 +263,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int timeout = static_cast(args.a[3]); int n = fd_table_->epoll_wait(epfd, events, maxevents, timeout); if (n < 0) - return fail(kEinval, "epoll_wait failed"); + return fail(linux_error(), "epoll_wait failed"); return ok(n, "epoll_wait ok"); } @@ -205,7 +272,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int flags = static_cast(args.a[1]); int fd = fd_table_->create_eventfd(initval, flags); if (fd < 0) - return fail(kEnomem, "eventfd creation failed"); + return fail(linux_error(), "eventfd creation failed"); return ok(fd, "eventfd created"); } diff --git a/src/compat/syscall_dispatch.h b/src/compat/syscall_dispatch.h index df2df41..1f83999 100644 --- a/src/compat/syscall_dispatch.h +++ b/src/compat/syscall_dispatch.h @@ -26,7 +26,7 @@ struct SyscallArgs { }; struct DispatchResult { - int64_t ret; // syscall return value (negative => -errno) + int64_t ret; // operation result; -1 on failure (see err) int err; // linux errno when ret < 0, else 0 bool supported; // false => -ENOSYS was returned const char* note; // never nullptr; explains the outcome diff --git a/src/platform/ps5/display_ps5.cpp b/src/platform/ps5/display_ps5.cpp index bd1150f..0869f74 100644 --- a/src/platform/ps5/display_ps5.cpp +++ b/src/platform/ps5/display_ps5.cpp @@ -13,6 +13,7 @@ // SDL port), but never executed on a console. Treat as experimental until // a console run is documented. See docs/platform-constraints.md. #include "platform/display.h" +#include "platform/platform.h" #include "platform/ps5/sce_decls.h" #include @@ -58,6 +59,7 @@ class Ps5Display : public DisplayBackend { return false; } + allocated_ = true; void* vaddr = nullptr; if (ps5::sceKernelMapDirectMemory(&vaddr, kTotalSize, kMapProtReadWrite, 0, phys_addr_, kDirectAlign) != 0) { @@ -65,6 +67,7 @@ class Ps5Display : public DisplayBackend { return false; } + mapped_ = vaddr; buffers_[0].data = vaddr; buffers_[1].data = reinterpret_cast(vaddr) + kBufferSize; @@ -111,7 +114,9 @@ class Ps5Display : public DisplayBackend { } struct kevent evt; int count = 0; - if (ps5::sceKernelWaitEqueue(event_queue_, &evt, 1, &count, 0) != 0) { + uint32_t timeout_us = 1000000; + if (ps5::sceKernelWaitEqueue(event_queue_, &evt, 1, &count, &timeout_us) != 0 || + count != 1) { return false; } current_ ^= 1; @@ -132,9 +137,15 @@ class Ps5Display : public DisplayBackend { ps5::sceVideoOutClose(handle_); handle_ = -1; } - if (phys_addr_ != 0) { + frame_ = Framebuffer::wrap(nullptr, 0, 0); + if (mapped_) { + platform::unmap(mapped_, kTotalSize); + mapped_ = nullptr; + } + if (allocated_) { ps5::sceKernelReleaseDirectMemory(phys_addr_, kTotalSize); phys_addr_ = 0; + allocated_ = false; } inited_ = false; } @@ -144,6 +155,8 @@ class Ps5Display : public DisplayBackend { private: int handle_ = -1; intptr_t phys_addr_ = 0; + bool allocated_ = false; + void* mapped_ = nullptr; struct kevent* event_queue_ = nullptr; ps5::SceVideoOutBuffer buffers_[2]{}; ps5::SceVideoOutBufferAttribute attribute_{}; diff --git a/src/platform/ps5/input_ps5.cpp b/src/platform/ps5/input_ps5.cpp index 9f3031f..09479b7 100644 --- a/src/platform/ps5/input_ps5.cpp +++ b/src/platform/ps5/input_ps5.cpp @@ -5,6 +5,7 @@ // console. See docs/platform-constraints.md. #include "platform/display.h" #include "platform/ps5/sce_decls.h" +#include namespace ps5droid { namespace platform { @@ -12,6 +13,7 @@ namespace { class Ps5Input : public InputBackend { public: + ~Ps5Input() override { shutdown(); } bool init() override { if (inited_) return true; diff --git a/src/platform/ps5/sce_decls.h b/src/platform/ps5/sce_decls.h index 7c4b523..097e140 100644 --- a/src/platform/ps5/sce_decls.h +++ b/src/platform/ps5/sce_decls.h @@ -52,7 +52,7 @@ int sceKernelReleaseDirectMemory(intptr_t phys_addr, size_t size); // ps5-payload-sdk freebsd headers). int sceKernelCreateEqueue(struct kevent** queue_out, const char* name); int sceKernelWaitEqueue(struct kevent* queue, struct kevent* events_out, int num_events, - int* count_out, unsigned timeout_ms); + int* count_out, uint32_t* timeout_us); int sceKernelDeleteEqueue(struct kevent* queue); // System service: hide the splash screen once the payload is drawing. diff --git a/src/platform/threads.cpp b/src/platform/threads.cpp index 793fc5d..07d8afd 100644 --- a/src/platform/threads.cpp +++ b/src/platform/threads.cpp @@ -19,7 +19,73 @@ #include extern "C" { +#if defined(__APPLE__) +#include +#include +using thrd_t = pthread_t; +using mtx_t = pthread_mutex_t; +using cnd_t = pthread_cond_t; +constexpr int thrd_success = 0; +constexpr int mtx_plain = 0; +struct AppleThreadStart { + int (*fn)(void*); + void* arg; +}; +static void* apple_thread_start(void* p) { + auto ctx = *static_cast(p); + delete static_cast(p); + ctx.fn(ctx.arg); + return nullptr; +} +static int thrd_create(thrd_t* t, int (*fn)(void*), void* arg) { + auto* ctx = new AppleThreadStart{fn, arg}; + int result = pthread_create(t, nullptr, apple_thread_start, ctx); + if (result) + delete ctx; + return result; +} +static int thrd_join(thrd_t t, int*) { + return pthread_join(t, nullptr); +} +static thrd_t thrd_current() { + return pthread_self(); +} +static int thrd_sleep(const timespec* t, timespec* remain) { + return nanosleep(t, remain); +} +static void thrd_yield() { + sched_yield(); +} +static int mtx_init(mtx_t* m, int) { + return pthread_mutex_init(m, nullptr); +} +static int mtx_destroy(mtx_t* m) { + return pthread_mutex_destroy(m); +} +static int mtx_lock(mtx_t* m) { + return pthread_mutex_lock(m); +} +static int mtx_unlock(mtx_t* m) { + return pthread_mutex_unlock(m); +} +static int cnd_init(cnd_t* c) { + return pthread_cond_init(c, nullptr); +} +static int cnd_destroy(cnd_t* c) { + return pthread_cond_destroy(c); +} +static int cnd_wait(cnd_t* c, mtx_t* m) { + return pthread_cond_wait(c, m); +} +static int cnd_signal(cnd_t* c) { + return pthread_cond_signal(c); +} +static int cnd_broadcast(cnd_t* c) { + return pthread_cond_broadcast(c); +} +#else #include +#endif #include } diff --git a/tests/elf_fixture.h b/tests/elf_fixture.h new file mode 100644 index 0000000..27b5fd3 --- /dev/null +++ b/tests/elf_fixture.h @@ -0,0 +1,37 @@ +#pragma once +#include +#include +namespace fixture { +inline void put(std::vector& data, size_t at, uint64_t value, size_t count) { + for (size_t i = 0; i < count; ++i) + data[at + i] = static_cast(value >> (i * 8)); +} +inline std::vector elf() { + std::vector out(256, 0); + out[0] = 0x7f; + out[1] = 'E'; + out[2] = 'L'; + out[3] = 'F'; + out[4] = 2; + out[5] = 1; + out[6] = 1; + put(out, 16, 3, 2); + put(out, 18, 62, 2); + put(out, 20, 1, 4); + put(out, 24, 128, 8); + put(out, 32, 64, 8); + put(out, 52, 64, 2); + put(out, 54, 56, 2); + put(out, 56, 1, 2); + put(out, 64, 1, 4); + put(out, 68, 5, 4); + put(out, 96, 256, 8); + put(out, 104, 256, 8); + put(out, 112, 4096, 8); + // xor eax,eax; ret -- used only by inspection tests. + out[128] = 0x31; + out[129] = 0xc0; + out[130] = 0xc3; + return out; +} +} // namespace fixture diff --git a/tests/fixtures/AndroidManifest.xml b/tests/fixtures/AndroidManifest.xml new file mode 100644 index 0000000..2d88750 --- /dev/null +++ b/tests/fixtures/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/tests/fixtures/aapt2-manifest.apk b/tests/fixtures/aapt2-manifest.apk new file mode 100644 index 0000000000000000000000000000000000000000..c3cd52f06c72e1d4e6e2d1403cac4758e7faa07e GIT binary patch literal 575 zcmWIWW@cdk0uCTnWYDvo8>G(2z_5mifk7B3;+U6Gl%JX6o0ylGmRek*SCN}jI&rVx zVFQuY{>hiv7=zeUBv$DeC{FbA=-@Qm+<0SkP)6u1w~aR|73MX!KS+JBxlp0^#n!$z z)#v_x+!~x(<*%}M;hc$OU(>Iz{mgNvp*o<6{{!c@lah_hYqvP;yu5f?)dioeI%lk0 zo)^tJU~_o4t|7CM*A%JxgL-cdhO80)qnZ9)x_X)AJm=k)W~5$xekEEkHMB%abVc@- z!WG+7)^~0_c>m3eRxZ_h!5sw!?koO1W8E1hE?xTfh*+H)`}J8%7M+^nH`!q0`rlr2 z)>rWT`Eu``&#}`V+BywIC!8#mx&NE{ar6~t&Ob~4$p8ItugpSzlaF@YfqVRSr+iDk zm+Sp~+R;5KpY~4co5ru49(9NF`Ih4C%ci|AytOl0s@mk*ld|N0kN?J`owlxF4uFO$ zC~OrOxC6|DHGnJ-<^$rQ)Z+ZoqU6+Ky~Lv8WF`h4unbUwfssK52$29VHemb!Z$@Ce vfB^Q`g2=&0EOCc00Hg@hSum{(3=u$UQ5_lJ&B_LnX9B`nAiV~tf`I`5UQ59D literal 0 HcmV?d00001 diff --git a/tests/fixtures/cooperative_entry.c b/tests/fixtures/cooperative_entry.c new file mode 100644 index 0000000..bb22e95 --- /dev/null +++ b/tests/fixtures/cooperative_entry.c @@ -0,0 +1,25 @@ +/* Freestanding Android-target ELF fixture. No bionic or Android framework. + * The callback replaces syscall stubs explicitly; raw syscalls are not patched. */ +typedef unsigned long long u64; +typedef long long i64; +typedef i64 (*gateway_fn)(void*, int, const u64*); +__attribute__((visibility("hidden"))) i64 +ps5droid_fixture_entry(void* context, gateway_fn gateway, const unsigned char* initial_stack) { + u64 args[6] = {0}; + if (*(const u64*)initial_stack != 1) + return 10; + const char* name = (const char*)((const u64*)initial_stack)[1]; + if (name[0] != 'p') + return 11; + i64 pid = gateway(context, 39, args); + if (pid <= 0) + return 12; + static const char message[] = "PS5Droid cooperative ELF: entry -> write -> exit_group\n"; + args[0] = 1; + args[1] = (u64)message; + args[2] = sizeof(message) - 1; + if (gateway(context, 1, args) != (i64)(sizeof(message) - 1)) + return 13; + args[0] = 0; + return gateway(context, 231, args); +} diff --git a/tests/fixtures/cooperative_entry.ld b/tests/fixtures/cooperative_entry.ld new file mode 100644 index 0000000..22e8e95 --- /dev/null +++ b/tests/fixtures/cooperative_entry.ld @@ -0,0 +1,10 @@ +/* A single position-independent RX segment, aligned for PS5's larger pages. */ +OUTPUT_FORMAT(elf64-x86-64) +ENTRY(ps5droid_fixture_entry) +PHDRS { code PT_LOAD FILEHDR PHDRS FLAGS(5); } +SECTIONS { + . = SIZEOF_HEADERS; + .text : { *(.text*) } :code + .rodata : { *(.rodata*) } :code + /DISCARD/ : { *(.comment) *(.note*) *(.eh_frame*) *(.dynamic) *(.dynsym) *(.dynstr) *(.hash) *(.gnu.hash) } +} diff --git a/tests/fuzz_parsers.cpp b/tests/fuzz_parsers.cpp new file mode 100644 index 0000000..ef9cfa2 --- /dev/null +++ b/tests/fuzz_parsers.cpp @@ -0,0 +1,12 @@ +#include "android/image_manager.h" +#include "compat/bionic_loader.h" +#include +#include +#include +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + ps5droid::compat::BionicLoader::parse_header(data, size); + ps5droid::android::ImageManifest manifest; + ps5droid::android::parse_manifest(std::string(reinterpret_cast(data), size), + &manifest); + return 0; +} diff --git a/tests/test_apk_inspection.cpp b/tests/test_apk_inspection.cpp new file mode 100644 index 0000000..785915a --- /dev/null +++ b/tests/test_apk_inspection.cpp @@ -0,0 +1,59 @@ +#include "android/image_manager.h" +#include "platform/platform.h" +#include "test_framework.h" +#include +using namespace ps5droid::android; +#ifndef PS5DROID_TEST_FIXTURES +#define PS5DROID_TEST_FIXTURES "fixtures" +#endif +namespace { +std::string fixture(const std::string& name) { + return std::string(PS5DROID_TEST_FIXTURES) + "/" + name; +} +} // namespace +PS5DROID_TEST(apk_aapt2_manifest_reports_real_metadata) { + auto apk = inspect_apk(std::string(PS5DROID_SOURCE_FIXTURES) + "/aapt2-manifest.apk"); + CHECK_MSG(apk.is_apk, apk.failure_note); + CHECK(apk.package_name == "org.ps5droid.inspection"); + CHECK(apk.min_sdk == 28 && apk.target_sdk == 35); + CHECK(apk.has_manifest && !apk.has_native_libs && !apk.has_classes_dex); +} +PS5DROID_TEST(apk_stored_and_deflated_metadata_match) { + for (const auto* name : {"stored.apk", "deflated.apk"}) { + auto apk = inspect_apk(fixture(name)); + CHECK_MSG(apk.is_apk, apk.failure_note); + CHECK(apk.package_name == "org.ps5droid.inspection"); + CHECK(apk.file_count == 5); + CHECK(apk.dex_files == std::vector({"classes.dex", "classes2.dex"})); + CHECK(apk.native_abis == std::vector({"x86_64"})); + } +} +PS5DROID_TEST(apk_rejects_malformed_and_ambiguous_archives) { + for (const auto* name : + {"plain.zip", "bad-manifest.apk", "duplicate.apk", "large-manifest.apk", "bad-crc.apk", + "truncated.apk", "bad-chunk.apk", "bad-pool.apk", "bad-attributes.apk"}) { + auto apk = inspect_apk(fixture(name)); + CHECK_MSG(!apk.is_apk, name); + CHECK(!apk.failure_note.empty()); + } +} +PS5DROID_TEST(ext4_rejects_unbounded_shift) { + std::string path = "bad_ext4.img"; + std::vector data(2048, 0); + data[1024 + 0x38] = 0x53; + data[1024 + 0x39] = 0xef; + data[1024 + 0x18] = 0xff; + CHECK(ps5droid::platform::write_file(path, data.data(), data.size())); + auto result = probe_ext4(path); + ps5droid::platform::remove_file(path); + CHECK(!result.is_ext4 && !result.failure_note.empty()); +} + +PS5DROID_TEST(apk_utf8_and_utf16_string_pools_match) { + for (const auto* name : {"utf8.apk", "utf16.apk"}) { + auto apk = inspect_apk(fixture(name)); + CHECK_MSG(apk.is_apk, apk.failure_note); + CHECK(apk.package_name == "org.ps5droid.encoding"); + CHECK(apk.min_sdk == 28 && apk.target_sdk == 35); + } +} diff --git a/tests/test_binder_and_apk.cpp b/tests/test_binder_and_apk.cpp index 4a4bba1..3e4bdb9 100644 --- a/tests/test_binder_and_apk.cpp +++ b/tests/test_binder_and_apk.cpp @@ -27,14 +27,13 @@ PS5DROID_TEST(binder_engine_registration_and_tx) { CHECK_MSG(out == in, "reply mismatch"); } -PS5DROID_TEST(apk_inspection_basic) { - std::string path = "test_app.apk"; - const uint8_t zip_hdr[30] = {'P', 'K', 0x03, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +PS5DROID_TEST(apk_rejects_zip_magic_without_directory) { + std::string path = "test_invalid_app.apk"; + const uint8_t zip_hdr[30] = {'P', 'K', 0x03, 0x04}; ps5droid::platform::write_file(path, zip_hdr, sizeof(zip_hdr)); - ApkInspection apk = inspect_apk(path); - CHECK_MSG(apk.is_apk, "APK detection failed"); - ps5droid::platform::remove_file(path); + CHECK(!apk.is_apk); + CHECK(apk.package_name.empty()); + CHECK(!apk.failure_note.empty()); } diff --git a/tests/test_bionic_and_fd.cpp b/tests/test_bionic_and_fd.cpp index 1a366fd..64883e6 100644 --- a/tests/test_bionic_and_fd.cpp +++ b/tests/test_bionic_and_fd.cpp @@ -1,4 +1,5 @@ // PS5Droid - Milestone 3 & 4 unit tests. +#include "elf_fixture.h" #include "test_framework.h" #include @@ -12,7 +13,7 @@ using namespace ps5droid::compat; PS5DROID_TEST(fd_table_basic_rw_seek) { CompatFdTable table; std::string path = "test_fd_table.tmp"; - int fd = table.open_file(path, 0x200 | 0x400 | 0x2, 0644); + int fd = table.open_file(path, 0x40 | 0x200 | 0x2, 0644); CHECK_MSG(fd >= 3, "open_file failed"); const char* msg = "hello fd_table"; @@ -40,16 +41,8 @@ PS5DROID_TEST(fd_table_basic_rw_seek) { } PS5DROID_TEST(bionic_loader_hdr_and_stack) { - // Construct fake ELF64 header - uint8_t elf_bytes[128] = {0}; - elf_bytes[0] = 0x7f; - elf_bytes[1] = 'E'; - elf_bytes[2] = 'L'; - elf_bytes[3] = 'F'; - elf_bytes[4] = 2; // 64-bit - elf_bytes[18] = 62; // x86_64 - - BionicElfInfo info = BionicLoader::parse_header(elf_bytes, sizeof(elf_bytes)); + auto elf_bytes = fixture::elf(); + BionicElfInfo info = BionicLoader::parse_header(elf_bytes.data(), elf_bytes.size()); CHECK_MSG(info.valid, "ELF header parse failed"); auto stack = BionicLoader::setup_initial_stack(info, {"app"}, {"ENV=1"}); diff --git a/tests/test_compat_dispatch.cpp b/tests/test_compat_dispatch.cpp index 6c58466..d727399 100644 --- a/tests/test_compat_dispatch.cpp +++ b/tests/test_compat_dispatch.cpp @@ -196,7 +196,7 @@ PS5DROID_TEST(fd_table_and_epoll_dispatch) { std::string tmp = "ps5droid_fd_test.tmp"; SyscallArgs open_args{}; open_args.a[0] = reinterpret_cast(tmp.c_str()); - open_args.a[1] = 0x200 | 0x400 | 0x2; // O_CREAT|O_TRUNC|O_RDWR + open_args.a[1] = 0x40 | 0x200 | 0x2; // O_CREAT|O_TRUNC|O_RDWR DispatchResult r = d.invoke(kOpen, open_args); CHECK_MSG(r.ret >= 3, "open should return valid guest fd"); int fd = static_cast(r.ret); @@ -230,11 +230,13 @@ PS5DROID_TEST(fd_table_and_epoll_dispatch) { CHECK_MSG(r.ret >= 3, "epoll_create1 failed"); int epfd = static_cast(r.ret); + int eventfd = fdt.create_eventfd(1, 0x800); + CHECK(eventfd >= 3); EpollEvent ev{1 /* EPOLLIN */, 12345}; SyscallArgs ep_ctl{}; ep_ctl.a[0] = epfd; ep_ctl.a[1] = 1; // EPOLL_CTL_ADD - ep_ctl.a[2] = fd; + ep_ctl.a[2] = eventfd; ep_ctl.a[3] = reinterpret_cast(&ev); r = d.invoke(kEpollCtl, ep_ctl); CHECK_MSG(r.ret == 0, "epoll_ctl failed"); @@ -253,6 +255,7 @@ PS5DROID_TEST(fd_table_and_epoll_dispatch) { d.invoke(kClose, close_args); close_args.a[0] = epfd; d.invoke(kClose, close_args); + fdt.close(eventfd); ps5droid::platform::remove_file(tmp); } diff --git a/tests/test_elf_validation.cpp b/tests/test_elf_validation.cpp new file mode 100644 index 0000000..7f4f54b --- /dev/null +++ b/tests/test_elf_validation.cpp @@ -0,0 +1,83 @@ +#include "compat/bionic_loader.h" +#include "compat/elf_runner.h" +#include "compat/memory_compat.h" +#include "elf_fixture.h" +#include "test_framework.h" +#include +using namespace ps5droid::compat; +PS5DROID_TEST(elf_rejects_overflowing_table_and_invalid_layout) { + auto bytes = fixture::elf(); + fixture::put(bytes, 32, UINT64_MAX - 15, 8); + CHECK(!BionicLoader::parse_header(bytes.data(), bytes.size()).valid); + bytes = fixture::elf(); + fixture::put(bytes, 54, 1, 2); + CHECK(!BionicLoader::parse_header(bytes.data(), bytes.size()).valid); + bytes = fixture::elf(); + bytes[5] = 2; + CHECK(!BionicLoader::parse_header(bytes.data(), bytes.size()).valid); +} +PS5DROID_TEST(elf_rejects_invalid_segment_ranges_alignment_and_entry) { + auto bytes = fixture::elf(); + fixture::put(bytes, 72, UINT64_MAX, 8); + CHECK(!BionicLoader::parse_header(bytes.data(), bytes.size()).valid); + bytes = fixture::elf(); + fixture::put(bytes, 104, 100, 8); + CHECK(!BionicLoader::parse_header(bytes.data(), bytes.size()).valid); + bytes = fixture::elf(); + fixture::put(bytes, 112, 3, 8); + CHECK(!BionicLoader::parse_header(bytes.data(), bytes.size()).valid); + bytes = fixture::elf(); + fixture::put(bytes, 24, 1000, 8); + CHECK(!BionicLoader::parse_header(bytes.data(), bytes.size()).valid); +} +PS5DROID_TEST(elf_accepts_unaligned_input_without_casting_structs) { + auto bytes = fixture::elf(); + bytes.insert(bytes.begin(), 0); + CHECK(BionicLoader::parse_header(bytes.data() + 1, bytes.size() - 1).valid); +} +PS5DROID_TEST(initial_stack_contains_strings_valid_pointers_and_auxv) { + auto bytes = fixture::elf(); + auto info = BionicLoader::parse_header(bytes.data(), bytes.size()); + auto stack = BionicLoader::build_initial_stack(info, {"hello", "world"}, {"A=B"}, 0x100000, + 0x200040, 0x200000, 16384); + CHECK(stack.error.empty()); + CHECK(stack.stack_pointer % 16 == 0); + auto word = [&](size_t i) { + uint64_t x; + std::memcpy(&x, stack.bytes.data() + i * 8, 8); + return x; + }; + CHECK(word(0) == 2 && word(3) == 0 && word(5) == 0); + CHECK(std::string(reinterpret_cast(stack.bytes.data() + word(1) - 0x100000)) == "hello"); + CHECK(std::string(reinterpret_cast(stack.bytes.data() + word(4) - 0x100000)) == "A=B"); + CHECK(word(6) == 3 && word(7) == 0x200040); // AT_PHDR + CHECK(word(12) == 6 && word(13) == 16384); // AT_PAGESZ + CHECK(word(14) == 9 && word(15) == 0x200080); // AT_ENTRY + CHECK(word(16) == 0 && word(17) == 0); +} +PS5DROID_TEST(initial_stack_rejects_oversized_arguments_and_bad_addresses) { + auto bytes = fixture::elf(); + auto info = BionicLoader::parse_header(bytes.data(), bytes.size()); + auto make = [&](const std::vector& args, uint64_t base) { + return BionicLoader::build_initial_stack(info, args, {}, base, 0x200040, 0, 4096); + }; + CHECK(!make({std::string(1024 * 1024, 'x')}, 0x100000).error.empty()); + CHECK(!make(std::vector(4097, "x"), 0x100000).error.empty()); + CHECK(!make({std::string("a\0b", 3)}, 0x100000).error.empty()); + CHECK(!make({"a"}, UINT64_MAX - 15).error.empty()); + CHECK(!make({"a"}, 1).error.empty()); +} +PS5DROID_TEST(compat_memory_rounds_unmap_and_rejects_overflow_and_exec) { + CompatMemory memory; + auto mapped = memory.mmap(0, 8192, 3, 0x22, -1, 0); + CHECK(mapped.address); + CHECK(memory.munmap(reinterpret_cast(mapped.address), 8192).linux_errno == 0); + CHECK(!memory.mmap(0, SIZE_MAX, 3, 0x22, -1, 0).address); + CHECK(!memory.mmap(0, 4096, 5, 0x22, -1, 0).address); + CHECK(!memory.is_mapped(UINTPTR_MAX - 4, 100)); +} +PS5DROID_TEST(elf_runner_rejects_invalid_input) { + const char junk[] = "not an ELF"; + auto result = run_cooperative_elf(junk, sizeof(junk)); + CHECK(!result.executed && !result.note.empty()); +} diff --git a/tests/test_evidence_report.cpp b/tests/test_evidence_report.cpp new file mode 100644 index 0000000..e9ed69c --- /dev/null +++ b/tests/test_evidence_report.cpp @@ -0,0 +1,12 @@ +#include "android/evidence_report.h" +#include "test_framework.h" +PS5DROID_TEST(evidence_json_escapes_control_characters_and_preserves_unknowns) { + using namespace ps5droid::android; + CHECK(json_quote("a\"b\\c\n\t") == "\"a\\\"b\\\\c\\u000a\\u0009\""); + CapabilityReport report; + report.backend = "posix"; + auto text = evidence_json(report, {}); + CHECK(text.find("\"android_runtime\": \"blocked\"") != std::string::npos); + CHECK(text.find("\"firmware\": \"unrecorded\"") != std::string::npos); + CHECK(text.find("\"platform_probes_passed\": false") != std::string::npos); +} diff --git a/tests/test_fd_semantics.cpp b/tests/test_fd_semantics.cpp new file mode 100644 index 0000000..c9774dd --- /dev/null +++ b/tests/test_fd_semantics.cpp @@ -0,0 +1,205 @@ +#include "compat/syscall_dispatch.h" +#include "platform/platform.h" +#include "test_framework.h" +#include +#include +#include +#include +#if defined(__linux__) +#include +#include +#include +#include +#endif +using namespace ps5droid::compat; +namespace { +struct File { + const std::string path = "fd_semantics.tmp"; + File() { ps5droid::platform::write_file(path, "abcdef", 6); } + ~File() { ps5droid::platform::remove_file(path); } +}; +} // namespace +PS5DROID_TEST(fd_write_only_does_not_truncate) { + File f; + CompatFdTable t; + int fd = t.open_file(f.path, 1, 0); + CHECK(fd >= 3); + CHECK(t.write(fd, "X", 1) == 1); + CHECK(t.close(fd) == 0); + std::string text; + CHECK(ps5droid::platform::read_file(f.path, &text)); + CHECK(text == "Xbcdef"); +} +PS5DROID_TEST(fd_linux_create_truncate_append_and_exclusive) { + File f; + CompatFdTable t; + CHECK(t.open_file(f.path, 0x40 | 0x80 | 2, 0600) == -1); + CHECK(errno == EEXIST); + int fd = t.open_file(f.path, 0x40 | 0x200 | 2, 0600); + CHECK(fd >= 3); + StatBuf st{}; + CHECK(t.fstat(fd, &st)); + CHECK(st.st_size == 0); + CHECK(t.write(fd, "a", 1) == 1); + t.close(fd); + fd = t.open_file(f.path, 0x400 | 1, 0); + CHECK(fd >= 3); + CHECK(t.lseek(fd, 0, 0) == 0); + CHECK(t.write(fd, "b", 1) == 1); + t.close(fd); + std::string text; + CHECK(ps5droid::platform::read_file(f.path, &text)); + CHECK(text == "ab"); +} +PS5DROID_TEST(fd_dup_survives_close_and_shares_position) { + File f; + CompatFdTable t; + int fd = t.open_file(f.path, 2, 0); + CHECK(fd >= 3); + int copy = t.dup(fd); + CHECK(copy >= 3); + char c = 0; + CHECK(t.read(fd, &c, 1) == 1 && c == 'a'); + CHECK(t.read(copy, &c, 1) == 1 && c == 'b'); + CHECK(t.close(fd) == 0); + CHECK(t.read(copy, &c, 1) == 1 && c == 'c'); + CHECK(t.dup2(copy, copy) == copy); + CHECK(t.read(copy, &c, 1) == 1 && c == 'd'); +} +PS5DROID_TEST(fd_pread_preserves_offset_and_checks_negative_offset) { + File f; + CompatFdTable t; + int fd = t.open_file(f.path, 0, 0); + CHECK(fd >= 3); + CHECK(t.lseek(fd, 2, 0) == 2); + char c; + CHECK(t.pread64(fd, &c, 1, 0) == 1 && c == 'a'); + CHECK(t.lseek(fd, 0, 1) == 2); + CHECK(t.pread64(fd, &c, 1, -1) == -1); + CHECK(errno == EINVAL); +} +PS5DROID_TEST(fd_reuses_lowest_descriptor_and_dup2_replaces_target) { + File f; + CompatFdTable t; + int a = t.open_file(f.path, 0, 0), b = t.open_file(f.path, 0, 0); + CHECK(a == 3 && b == 4); + CHECK(t.lseek(a, 3, 0) == 3); + CHECK(t.dup2(a, b) == b); + char c; + CHECK(t.read(b, &c, 1) == 1 && c == 'd'); + CHECK(t.close(a) == 0); + CHECK(t.dup(b) == 3); +} +PS5DROID_TEST(fd_errors_are_translated_to_linux) { + CompatMemory mem; + SyscallDispatch d(&mem); + const char* missing = "ps5droid_missing_directory/file"; + SyscallArgs a{}; + a.a[0] = reinterpret_cast(missing); + auto r = d.invoke(ps5droid::linux_abi::kOpen, a); + CHECK(r.ret == -1 && r.err == 2); + a.a[0] = 0x80000000; + r = d.invoke(ps5droid::linux_abi::kEpollCreate1, a); + CHECK(r.ret == -1 && r.err == 22); + a = {}; + a.a[0] = 0; + a.a[1] = reinterpret_cast("relative"); + r = d.invoke(ps5droid::linux_abi::kOpenat, a); + CHECK(r.ret == -1 && r.err == 38); +} +PS5DROID_TEST(eventfd_nonblocking_semaphore_and_overflow) { + CompatFdTable t; + int fd = t.create_eventfd(2, 1 | 0x800); + CHECK(fd >= 3); + uint64_t value = 0; + CHECK(t.read(fd, &value, 8) == 8 && value == 1); + CHECK(t.read(fd, &value, 8) == 8 && value == 1); + CHECK(t.read(fd, &value, 8) == -1 && errno == EAGAIN); + value = UINT64_MAX; + CHECK(t.write(fd, &value, 8) == -1 && errno == EINVAL); + value = UINT64_MAX - 1; + CHECK(t.write(fd, &value, 8) == 8); + value = 1; + CHECK(t.write(fd, &value, 8) == -1 && errno == EAGAIN); + CHECK(t.create_eventfd(0, 0x400) == -1 && errno == EINVAL); +} +PS5DROID_TEST(epoll_reports_readiness_not_registration) { + CompatFdTable t; + int fd = t.create_eventfd(0, 0x800), ep = t.create_epoll(); + EpollEvent in{1, 0x123456789abcdef0ull}, out{}; + CHECK(t.epoll_ctl(ep, 1, fd, &in)); + CHECK(t.epoll_wait(ep, &out, 1, 0) == 0); + uint64_t value = 1; + CHECK(t.write(fd, &value, 8) == 8); + CHECK(t.epoll_wait(ep, &out, 1, 0) == 1 && out.events == 1 && out.data == in.data); + CHECK(t.read(fd, &value, 8) == 8); + CHECK(t.epoll_wait(ep, &out, 1, 0) == 0); + CHECK(!t.epoll_ctl(ep, 1, fd, &in) && errno == EEXIST); + in.events = 0x80000001u; + CHECK(!t.epoll_ctl(ep, 3, fd, &in) && errno == EINVAL); +} +PS5DROID_TEST(epoll_wait_wakes_after_eventfd_write) { + CompatFdTable t; + int fd = t.create_eventfd(0, 0x800), ep = t.create_epoll(); + EpollEvent in{1, 99}, out{}; + CHECK(t.epoll_ctl(ep, 1, fd, &in)); + std::atomic entered{false}; + int result = -1; + std::thread waiter([&] { + entered = true; + result = t.epoll_wait(ep, &out, 1, 2000); + }); + while (!entered) + std::this_thread::yield(); + uint64_t value = 1; + auto written = t.write(fd, &value, 8); + waiter.join(); + CHECK(written == 8); + CHECK(result == 1 && out.data == 99); +} +PS5DROID_TEST(epoll_last_descriptor_close_removes_watch) { + CompatFdTable t; + int fd = t.create_eventfd(1, 0x800), ep = t.create_epoll(); + EpollEvent event{1, 1}, out{}; + CHECK(t.epoll_ctl(ep, 1, fd, &event)); + int copy = t.dup(fd); + t.close(fd); + CHECK(t.epoll_wait(ep, &out, 1, 0) == 1); + t.close(copy); + CHECK(t.epoll_wait(ep, &out, 1, 0) == 0); +} +PS5DROID_TEST(epoll_rejects_regular_files) { + File f; + CompatFdTable t; + int fd = t.open_file(f.path, 0, 0), ep = t.create_epoll(); + EpollEvent event{1, 0}; + CHECK(!t.epoll_ctl(ep, 1, fd, &event)); + CHECK(errno == EPERM); +} +#if defined(__linux__) +PS5DROID_TEST(linux_differential_eventfd_and_epoll) { + CompatFdTable t; + int guest = t.create_eventfd(0, 0x800), gep = t.create_epoll(); + int native = eventfd(0, EFD_NONBLOCK), nep = epoll_create1(0); + CHECK(native >= 0 && nep >= 0); + EpollEvent g{1, 42}, gout{}; + epoll_event n{}; + n.events = EPOLLIN; + n.data.u64 = 42; + bool setup = t.epoll_ctl(gep, 1, guest, &g) && epoll_ctl(nep, EPOLL_CTL_ADD, native, &n) == 0; + int empty_guest = t.epoll_wait(gep, &gout, 1, 0), empty_native = epoll_wait(nep, &n, 1, 0); + uint64_t value = 7, gv = 0, nv = 0; + auto gw = t.write(guest, &value, 8); + auto nw = ::write(native, &value, 8); + int ready_guest = t.epoll_wait(gep, &gout, 1, 0), ready_native = epoll_wait(nep, &n, 1, 0); + auto gr = t.read(guest, &gv, 8); + auto nr = ::read(native, &nv, 8); + ::close(native); + ::close(nep); + CHECK(setup); + CHECK(empty_guest == empty_native && empty_guest == 0); + CHECK(gw == nw && gr == nr && gv == nv); + CHECK(ready_guest == ready_native && ready_guest == 1); + CHECK(gout.events == n.events && gout.data == n.data.u64); +} +#endif diff --git a/tests/test_image_manager.cpp b/tests/test_image_manager.cpp index 163eeb7..b7d5849 100644 --- a/tests/test_image_manager.cpp +++ b/tests/test_image_manager.cpp @@ -83,13 +83,14 @@ std::vector make_ext4_fixture() { } // namespace PS5DROID_TEST(manifest_parse_ok) { - const char* text = "# PS5Droid image manifest\n" - "system_image = images/system.img\n" - "vendor_image=images/vendor.img\n" - "android_api_level = 33\n" - "abi = x86_64\n" - "system_sha256 = deadbeef\n" - "description = test fixture\n"; + const char* text = + "# PS5Droid image manifest\n" + "system_image = images/system.img\n" + "vendor_image=images/vendor.img\n" + "android_api_level = 33\n" + "abi = x86_64\n" + "system_sha256 = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + "description = test fixture\n"; ImageManifest m; ParseStatus st = parse_manifest(text, &m); CHECK_MSG(st == ParseStatus::kOk, "parse failed"); @@ -97,7 +98,7 @@ PS5DROID_TEST(manifest_parse_ok) { CHECK_MSG(m.vendor_image == "images/vendor.img", "vendor_image"); CHECK_MSG(m.android_api_level == 33, "api level"); CHECK_MSG(m.abi == "x86_64", "abi"); - CHECK_MSG(m.system_sha256 == "deadbeef", "sha"); + CHECK_MSG(m.system_sha256 == std::string(64, 'a'), "sha"); } PS5DROID_TEST(manifest_parse_errors) { @@ -113,7 +114,7 @@ PS5DROID_TEST(manifest_parse_errors) { "vendor_image = b\n" "abi = x\n", &m2); - CHECK_MSG(st == ParseStatus::kMissingKeys, "zero api level rejected"); + CHECK_MSG(st == ParseStatus::kBadValue, "non-numeric api level rejected"); } PS5DROID_TEST(ext4_probe_detects_fixture) { diff --git a/tests/test_platform_threads.cpp b/tests/test_platform_threads.cpp index fcac2aa..0e9415c 100644 --- a/tests/test_platform_threads.cpp +++ b/tests/test_platform_threads.cpp @@ -102,20 +102,18 @@ PS5DROID_TEST(futex_wouldblock_and_wake) { } PS5DROID_TEST(futex_wake_waiter) { - // The main thread sleeps inside wait(); the waker thread changes the - // word after a generous delay (1s), guaranteeing the waiter is already - // enqueued, then wakes it. The 1s delay only bounds the worst case for - // a heavily preempted CI runner; the waiter enqueues within + // The main thread sleeps inside wait(); the waker thread wakes it after + // a generous delay (1s), without racing a write against the wait check. The 1s delay only + // bounds the worst case for a heavily preempted CI runner; the waiter enqueues within // microseconds in practice. static uint32_t word; word = 7; Thread waker; auto waker_fn = [](void*) { - ps5droid::platform::sleep_ns(1000000000ull); - word = 8; Futex f; - f.wake(&word, 4); + while (f.wake(&word, 1) == 0) + ps5droid::platform::yield_thread(); }; CHECK_MSG(waker.start(waker_fn, nullptr), "waker start failed"); @@ -124,7 +122,7 @@ PS5DROID_TEST(futex_wake_waiter) { CHECK_MSG(waker.join(), "waker join failed"); CHECK_MSG(wr == 0, "wait() must return 0 when woken"); - CHECK_MSG(word == 8, "waker must have changed the word"); + CHECK_MSG(word == 7, "wake does not modify the futex word"); } PS5DROID_TEST(thread_ids_differ) { diff --git a/tests/test_rpc_semantics.cpp b/tests/test_rpc_semantics.cpp new file mode 100644 index 0000000..472ead4 --- /dev/null +++ b/tests/test_rpc_semantics.cpp @@ -0,0 +1,85 @@ +#include "android/binder/binder_engine.h" +#include "test_framework.h" +#include +#include +#include +using namespace ps5droid::android; +namespace { +std::vector echo(uint32_t, const std::vector& in, void*) { + return in; +} +std::vector throwing(uint32_t, const std::vector&, void*) { + throw std::runtime_error("handler"); +} +struct Nested { + BinderEngine* engine; + uint32_t handle; + RpcStatus status; +}; +std::vector nested(uint32_t, const std::vector& in, void* p) { + auto& n = *static_cast(p); + auto r = n.engine->transact_checked(n.handle, 1, in); + n.status = r.status; + return r.reply; +} +} // namespace +PS5DROID_TEST(rpc_missing_and_reserved_handles_never_succeed) { + BinderEngine engine; + CHECK(engine.lookup_service("missing") == BinderEngine::kInvalidHandle); + CHECK(engine.lookup_service("servicemanager") == BinderEngine::kInvalidHandle); + std::vector output{1}; + CHECK(!engine.transact(0, 1, {}, &output)); + CHECK(output.empty()); + CHECK(engine.register_service("servicemanager", echo) == BinderEngine::kInvalidHandle); + CHECK(engine.register_service("", echo) == BinderEngine::kInvalidHandle); + CHECK(engine.register_service("null", nullptr) == BinderEngine::kInvalidHandle); +} +PS5DROID_TEST(rpc_rejects_payload_overflow_flags_and_allocation_failure) { + BinderEngine engine(1, 0); + uint32_t h = engine.register_service("echo", echo); + CHECK(engine.transact_checked(h, 1, {}).status == RpcStatus::kNoMemory); + CHECK(engine.transact_checked(h, 1, {}, 1).status == RpcStatus::kUnsupportedFlags); + CHECK(engine.transact_checked(h, 1, std::vector(257)).status == RpcStatus::kTooLarge); +} +PS5DROID_TEST(rpc_releases_buffers_after_handler_exception) { + BinderEngine engine(1, 256); + auto h = engine.register_service("throws", throwing); + CHECK(engine.transact_checked(h, 1, {}).status == RpcStatus::kHandlerError); + auto e = engine.register_service("echo", echo); + CHECK(engine.transact_checked(e, 1, {1, 2}).reply == std::vector({1, 2})); +} +PS5DROID_TEST(rpc_nested_calls_have_explicit_capacity_failure) { + BinderEngine engine(1, 256); + auto e = engine.register_service("echo", echo); + Nested n{&engine, e, RpcStatus::kOk}; + auto h = engine.register_service("nested", nested, &n); + CHECK(engine.transact_checked(h, 1, {1}).ok()); + CHECK(n.status == RpcStatus::kNoMemory); +} +PS5DROID_TEST(rpc_nested_calls_work_without_engine_lock_deadlock) { + BinderEngine engine(2, 512); + auto e = engine.register_service("echo", echo); + Nested n{&engine, e, RpcStatus::kNoMemory}; + auto h = engine.register_service("nested", nested, &n); + auto result = engine.transact_checked(h, 1, {7}); + CHECK(result.ok() && result.reply == std::vector({7})); + CHECK(n.status == RpcStatus::kOk); +} +PS5DROID_TEST(rpc_concurrent_calls_do_not_corrupt_buffers) { + BinderEngine engine(8, 8 * 256); + auto h = engine.register_service("echo", echo); + std::atomic errors{0}; + std::vector threads; + for (int i = 0; i < 8; ++i) + threads.emplace_back([&, i] { + std::vector input(256, static_cast(i)); + for (int j = 0; j < 100; ++j) { + auto r = engine.transact_checked(h, 1, input); + if (!r.ok() || r.reply != input) + ++errors; + } + }); + for (auto& thread : threads) + thread.join(); + CHECK(errors == 0); +} diff --git a/tools/annotate_console_report.py b/tools/annotate_console_report.py new file mode 100644 index 0000000..fff33c2 --- /dev/null +++ b/tools/annotate_console_report.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Attach tester-supplied console provenance without rewriting measurements.""" +import argparse +import hashlib +import json +from pathlib import Path +p = argparse.ArgumentParser(description=__doc__) +p.add_argument('report', type=Path) +p.add_argument('--firmware', required=True) +p.add_argument('--loader', required=True) +p.add_argument('--elf', type=Path, required=True) +p.add_argument('--run-id', required=True) +p.add_argument('--output', type=Path, required=True) +a = p.parse_args() +data = json.loads(a.report.read_text()) +if data.get('schema_version') != 1 or data.get('backend') != 'ps5': + p.error('requires a version 1 PS5 report; host evidence cannot be relabeled') +if a.output.resolve() == a.report.resolve(): + p.error('output must differ from the original report') +data['tester_annotations'] = { + 'firmware': a.firmware, 'loader': a.loader, 'run_id': a.run_id, + 'elf_sha256': hashlib.sha256(a.elf.read_bytes()).hexdigest(), + 'source_report_sha256': hashlib.sha256(a.report.read_bytes()).hexdigest(), + 'provenance': 'tester-supplied; original measurements preserved', +} +a.output.write_text(json.dumps(data, indent=2) + '\n') diff --git a/tools/build_elf_fixture.py b/tools/build_elf_fixture.py new file mode 100644 index 0000000..f8a747c --- /dev/null +++ b/tools/build_elf_fixture.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +"""Build the trusted cooperative fixture using upstream LLVM's Android target.""" +import argparse +from pathlib import Path +import subprocess +p = argparse.ArgumentParser(description=__doc__) +p.add_argument('--clang', default='clang') +p.add_argument('--linker', default='ld.lld') +p.add_argument('--output', type=Path, required=True) +a = p.parse_args() +root = Path(__file__).resolve().parents[1] +a.output.parent.mkdir(parents=True, exist_ok=True) +obj = a.output.with_suffix('.o') +subprocess.run([a.clang, '--target=x86_64-linux-android28', '-ffreestanding', '-fPIC', + '-fno-stack-protector', '-fno-unwind-tables', '-fno-asynchronous-unwind-tables', + '-O2', '-c', str(root / 'tests/fixtures/cooperative_entry.c'), '-o', str(obj)], check=True) +subprocess.run([a.linker, '-shared', '--build-id=none', '-z', 'max-page-size=16384', + '-T', str(root / 'tests/fixtures/cooperative_entry.ld'), str(obj), '-o', str(a.output)], check=True) diff --git a/tools/check_docs.py b/tools/check_docs.py new file mode 100644 index 0000000..ec9fc48 --- /dev/null +++ b/tools/check_docs.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""Validate repository Markdown links and capability documentation invariants.""" +from pathlib import Path +import re +import sys +root = Path(__file__).resolve().parents[1] +errors = [] +files = [root / 'README.md', root / 'THIRD_PARTY_NOTICES.md', *sorted((root / 'docs').glob('*.md'))] +for path in files: + text = path.read_text() + for target in re.findall(r'\]\(([^\s)]+)(?:\s+[^)]*)?\)', text): + if '://' in target or target.startswith(('#', 'mailto:')): + continue + target = target.split('#', 1)[0] + if target and not (path.parent / target).exists(): + errors.append(f'{path.relative_to(root)}: missing link {target}') +readme = (root / 'README.md').read_text() +for required in ['Android applications do not run yet', 'No verified console result', 'cooperative']: + if required not in readme: + errors.append(f'README is missing capability boundary: {required}') +if 'releases/latest' in (root / '.github/workflows/ci.yml').read_text(): + errors.append('CI must use an immutable SDK URL and checksum') +for error in errors: + print(error, file=sys.stderr) +sys.exit(bool(errors)) diff --git a/tools/check_reports.py b/tools/check_reports.py new file mode 100644 index 0000000..bf76186 --- /dev/null +++ b/tools/check_reports.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +"""Check CLI report contracts without promoting host results to console evidence.""" +import json +from pathlib import Path +import sys +report, apk = [json.loads(Path(path).read_text()) for path in sys.argv[1:]] +assert report['schema_version'] == 1 +assert report['backend'] == 'posix', report['backend'] +assert report['android_runtime'] == 'blocked' +assert report['platform_probes_passed'] and all(p['passed'] for p in report['probes']) +assert report['firmware'] == report['loader'] == 'unrecorded' +assert report['revision'] +assert apk['is_apk'] and apk['package_name'] == 'org.ps5droid.inspection' +assert apk['min_sdk'] == 28 and apk['target_sdk'] == 35 diff --git a/tools/make_test_fixtures.py b/tools/make_test_fixtures.py new file mode 100644 index 0000000..3c3ebb7 --- /dev/null +++ b/tools/make_test_fixtures.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Create reproducible ZIP/AXML edge cases; no downloaded inputs are needed.""" +import argparse +from pathlib import Path +import struct +import zipfile + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument('output', type=Path) +a = p.parse_args() +a.output.mkdir(parents=True, exist_ok=True) +source = Path(__file__).resolve().parents[1] / 'tests/fixtures/aapt2-manifest.apk' +with zipfile.ZipFile(source) as z: + manifest = z.read('AndroidManifest.xml') + +def apk(name, items, compression=zipfile.ZIP_STORED): + with zipfile.ZipFile(a.output / name, 'w', compression=compression) as z: + for key, value in items: + info = zipfile.ZipInfo(key, (2020, 1, 1, 0, 0, 0)) + info.compress_type = compression + z.writestr(info, value) + +files = [('AndroidManifest.xml', manifest), ('classes.dex', b'dex\n035\0'), + ('classes2.dex', b'dex\n035\0'), ('lib/x86_64/libsample.so', b'fixture'), + ('assets/message.txt', b'AndroidManifest.xml classes9.dex lib/other/libfake.so')] +apk('stored.apk', files) +apk('deflated.apk', files, zipfile.ZIP_DEFLATED) +apk('plain.zip', [('assets/message.txt', b'AndroidManifest.xml classes.dex')]) +apk('bad-manifest.apk', [('AndroidManifest.xml', b'not binary XML')]) +apk('duplicate.apk', [('AndroidManifest.xml', manifest), ('AndroidManifest.xml', manifest)]) +apk('large-manifest.apk', [('AndroidManifest.xml', b'x' * (4 * 1024 * 1024 + 1))], zipfile.ZIP_DEFLATED) +# CRC corruption: mutate the stored manifest without altering its advertised CRC. +data = bytearray((a.output / 'stored.apk').read_bytes()) +name_length, extra_length = struct.unpack_from(' Date: Thu, 22 Oct 2026 17:16:09 +0545 Subject: [PATCH 2/2] Record validated execution and cross-build evidence with seeded parser checks --- .github/workflows/ci.yml | 9 ++++-- CMakeLists.txt | 3 ++ README.md | 1 + cmake/build_info.h.in | 2 ++ docs/console-validation.md | 5 ++-- docs/development.md | 7 +++-- docs/validation.md | 49 +++++++++++++++++++++++++++++++ src/android/evidence_report.cpp | 29 +++++++++++++----- src/android/runtime_manager.cpp | 1 + src/android/runtime_manager.h | 1 + src/compat/linux_abi.cpp | 3 +- src/compat/memory_compat.cpp | 5 +--- src/compat/syscall_dispatch.cpp | 14 +++++---- tests/fixtures/image-manifest.txt | 4 +++ tests/test_compat_dispatch.cpp | 2 +- tests/test_elf_validation.cpp | 19 ++++++++++++ tests/test_fd_semantics.cpp | 25 ++++++++++++++++ tests/test_platform_threads.cpp | 6 ++-- tools/check_reports.py | 3 +- tools/make_test_fixtures.py | 9 ++++-- 20 files changed, 165 insertions(+), 32 deletions(-) create mode 100644 docs/validation.md create mode 100644 tests/fixtures/image-manifest.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77ed43b..4928cb1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -75,10 +75,15 @@ jobs: runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - - run: sudo apt-get update && sudo apt-get install -y clang cmake ninja-build zlib1g-dev + - run: sudo apt-get update && sudo apt-get install -y clang lld cmake ninja-build zlib1g-dev - run: CC=clang CXX=clang++ cmake -B build -G Ninja -DPS5DROID_BUILD_FUZZER=ON - run: cmake --build build --target ps5droid_fuzz - - run: ./build/ps5droid_fuzz -runs=10000 -max_len=65536 + - name: Seeded fuzz smoke + run: | + mkdir -p build/corpus + python3 tools/build_elf_fixture.py --output build/corpus/cooperative.elf + cp tests/fixtures/image-manifest.txt build/corpus/image-manifest.txt + ./build/ps5droid_fuzz build/corpus -runs=10000 -max_len=65536 ps5: name: PS5 cross-build (hardware execution unverified) runs-on: ubuntu-24.04 diff --git a/CMakeLists.txt b/CMakeLists.txt index 93082a2..a826b4c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,6 +62,9 @@ endif() # APK manifests use ZIP DEFLATE. Host builds use system zlib; console builds # build the same pinned upstream source with the PS5 toolchain. if(PROSPERO) + if(POLICY CMP0135) + cmake_policy(SET CMP0135 NEW) + endif() include(FetchContent) set(ZLIB_BUILD_SHARED OFF CACHE BOOL "" FORCE) set(ZLIB_INSTALL OFF CACHE BOOL "" FORCE) diff --git a/README.md b/README.md index 8a98070..9f82c65 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ The output is `build-ps5/ps5droid.elf`, an ELF payload. Follow the ## Development and evidence +- [Local validation record](docs/validation.md) - [Architecture and milestone boundaries](docs/architecture.md) - [Host builds, sanitizers, fuzzing and fixture provenance](docs/development.md) - [Linux ABI and PS5 platform constraints](docs/platform-constraints.md) diff --git a/cmake/build_info.h.in b/cmake/build_info.h.in index a4c284e..122afe6 100644 --- a/cmake/build_info.h.in +++ b/cmake/build_info.h.in @@ -1,3 +1,5 @@ #pragma once #define PS5DROID_BUILD_REVISION "@PS5DROID_BUILD_REVISION@" #define PS5DROID_SDK_VERSION "@PS5DROID_SDK_VERSION@" + +#define PS5DROID_BUILD_COMPILER "@CMAKE_CXX_COMPILER_ID@ @CMAKE_CXX_COMPILER_VERSION@" diff --git a/docs/console-validation.md b/docs/console-validation.md index a4b4c0d..dffc9e3 100644 --- a/docs/console-validation.md +++ b/docs/console-validation.md @@ -29,6 +29,7 @@ report is logged; it must not be mistaken for an empty successful report. | --- | --- | | `schema_version` | Report format version, currently 1 | | `backend` | Distinguishes host and console runs | +| `run_id`, `architecture`, `compiler` | Per-probe process/time identifier and actual build architecture/compiler | | `revision` | Configured source revision, with `-dirty` when applicable | | `sdk` | Explicit build pin, or `unrecorded` | | `firmware`, `loader` | `unrecorded` until supplied by the tester | @@ -51,8 +52,8 @@ The payload performs no kernel privilege changes or JIT permission workaround. Circle and Options; note disconnect/reconnect behavior separately. 3. Let multiple frames present, then exit through Options. 4. Retrieve the report with your existing console file-transfer tooling. A report - left from a previous process is not evidence for a new run; compare revision - and the externally recorded run identifier/time. + left from a previous process is not evidence for a new run; compare the embedded + `run_id`, revision and externally recorded run identifier/time. 5. Relaunch at least twice and verify that display and input initialize again. Observe available memory/resource diagnostics if your setup provides them. 6. Preserve logs, screenshots, failed operations and any missing observations. diff --git a/docs/development.md b/docs/development.md index 2e81934..8cdc97f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -35,10 +35,13 @@ ctest --test-dir build-tsan --output-on-failure CC=clang CXX=clang++ cmake -S . -B build-fuzz -G Ninja \ -DPS5DROID_BUILD_FUZZER=ON cmake --build build-fuzz --target ps5droid_fuzz -./build-fuzz/ps5droid_fuzz -runs=10000 -max_len=65536 +mkdir -p build-fuzz/corpus +python3 tools/build_elf_fixture.py --output build-fuzz/corpus/cooperative.elf +cp tests/fixtures/image-manifest.txt build-fuzz/corpus/image-manifest.txt +./build-fuzz/ps5droid_fuzz build-fuzz/corpus -runs=10000 -max_len=65536 ``` -Address/UndefinedBehaviorSanitizer and ThreadSanitizer run separately. The +Address/UndefinedBehaviorSanitizer and ThreadSanitizer run separately. Seeded fuzzing also requires upstream LLVM Clang and LLD. The libFuzzer target instruments ELF header and text image-manifest parsing. APK inspection has deterministic malformed-container/AXML regression tests; this harness does not claim APK fuzz coverage. Do not execute mutated ELF inputs. diff --git a/docs/validation.md b/docs/validation.md new file mode 100644 index 0000000..a0a85cc --- /dev/null +++ b/docs/validation.md @@ -0,0 +1,49 @@ +# Validation record — 2026-10-22 + +This is a **local development validation record**, separate from console evidence. +The machine was macOS on ARM64. The x86-64 host build ran as an x86-64 process +under Rosetta. No PS5 hardware was connected. + +| Check | Observed result | +| --- | --- | +| ARM64 host suite, Apple Clang 21 | 78/78 registered tests passed | +| x86-64 host suite, Apple Clang 21 | 78/78 registered tests passed | +| ARM64 AddressSanitizer + UndefinedBehaviorSanitizer | Suite passed; no reported sanitizer errors | +| ARM64 ThreadSanitizer | Suite passed; no reported data races | +| Trusted cooperative ELF | Entry executed, gateway write succeeded, exit requested, return value 0 | +| Seeded ELF/text-manifest fuzz smoke, LLVM 23.1.2 | 10,000 executions completed without a crash | +| AAPT2 fixture comparison | Actual package `org.ps5droid.inspection`, minimum SDK 28, target SDK 35 | +| Host JSON report contract | Schema/backend/architecture/compiler/revision/run identifier validated | +| Console report annotation guard | Host report rejected; original measurements preserved | +| PS5 cross-build | `ps5droid.elf` linked using SDK v0.45 and upstream Clang/LLD 23.1.2 | +| SDK archive | SHA-256 matched `.github/ps5-sdk.json` | +| Formatting and Markdown links | Checks passed | +| Linux native differential test / GCC build | Configured in CI; not executed locally | +| Fork GitHub Actions | [Jobs did not start](https://github.com/3z4k/PS5Droid/actions/runs/39769366161); no CI pass claimed | +| PS5 hardware | Pending; no verified console result | + +Architecture-dependent runner rejection tests execute in the x86-64 suite. The +Linux differential test is compiled only on Linux. These counts do not imply that +both cases ran on ARM64 macOS. + +The cross-build used the unmodified public SDK archive, its supplied CMake +toolchain/wrappers and pinned zlib 1.3.2 source. A local `LLVM_CONFIG` host-tool +selection supplied upstream Clang/LLD; no SDK declarations or success results were +substituted. CI's Ubuntu/Clang 18 configuration remains unexecuted while fork +runners are unavailable. + +## Cooperative execution output + +```text +PS5Droid cooperative ELF: entry -> write -> exit_group +executed=yes stop_requested=yes entry_result=0 +cooperative ELF entry returned; unmodified bionic/Android startup remains unsupported +``` + +This proves the cooperative entry/gateway path under the tested host configuration. +It does not establish unmodified bionic, Android app startup, Binder compatibility, +JIT/ART operation or execution on PS5 hardware. + +Reproduce using [development.md](development.md) and +[elf-execution.md](elf-execution.md). Hardware runs must follow the separate +[console procedure](console-validation.md) and preserve firmware/loader provenance. diff --git a/src/android/evidence_report.cpp b/src/android/evidence_report.cpp index 1484ec0..e7784b2 100644 --- a/src/android/evidence_report.cpp +++ b/src/android/evidence_report.cpp @@ -18,15 +18,30 @@ std::string json_quote(const std::string& text) { } return out + '"'; } +namespace { +const char* build_arch() { +#if defined(__x86_64__) + return "x86_64"; +#elif defined(__aarch64__) || defined(__arm64__) + return "arm64"; +#else + return "unrecorded"; +#endif +} +} // namespace std::string evidence_json(const CapabilityReport& report, const EvidenceMetadata& metadata, const std::vector& observations) { - std::string out = "{\n \"schema_version\": 1,\n \"backend\": " + json_quote(report.backend) + - ",\n \"revision\": " + json_quote(PS5DROID_BUILD_REVISION) + - ",\n \"sdk\": " + json_quote(PS5DROID_SDK_VERSION) + - ",\n \"firmware\": " + json_quote(metadata.firmware) + - ",\n \"loader\": " + json_quote(metadata.loader) + - ",\n \"android_runtime\": \"blocked\",\n \"platform_probes_passed\": " + - (report.all_passed ? "true" : "false") + ",\n \"probes\": ["; + std::string out = + "{\n \"schema_version\": 1,\n \"backend\": " + json_quote(report.backend) + + ",\n \"run_id\": " + json_quote(report.run_id.empty() ? "unrecorded" : report.run_id) + + ",\n \"architecture\": " + json_quote(build_arch()) + + ",\n \"compiler\": " + json_quote(PS5DROID_BUILD_COMPILER) + + ",\n \"revision\": " + json_quote(PS5DROID_BUILD_REVISION) + + ",\n \"sdk\": " + json_quote(PS5DROID_SDK_VERSION) + + ",\n \"firmware\": " + json_quote(metadata.firmware) + + ",\n \"loader\": " + json_quote(metadata.loader) + + ",\n \"android_runtime\": \"blocked\",\n \"platform_probes_passed\": " + + (report.all_passed ? "true" : "false") + ",\n \"probes\": ["; bool first = true; for (const auto& probe : report.results) { if (!first) diff --git a/src/android/runtime_manager.cpp b/src/android/runtime_manager.cpp index 245f8e1..8c12ebc 100644 --- a/src/android/runtime_manager.cpp +++ b/src/android/runtime_manager.cpp @@ -33,6 +33,7 @@ CapabilityReport RuntimeManager::probe(const std::string& writable_dir) { phase_ = RuntimePhase::kProbing; CapabilityReport report; report.backend = platform::backend_name(); + report.run_id = std::to_string(getpid()) + "-" + std::to_string(platform::monotonic_ns()); auto add = [&](const char* name, bool passed, const std::string& detail) { report.results.push_back(CapabilityResult{name, passed, detail}); diff --git a/src/android/runtime_manager.h b/src/android/runtime_manager.h index 7a4828a..4307e95 100644 --- a/src/android/runtime_manager.h +++ b/src/android/runtime_manager.h @@ -32,6 +32,7 @@ struct CapabilityReport { std::vector results; bool all_passed = false; const char* backend = ""; + std::string run_id; }; struct Blocker { diff --git a/src/compat/linux_abi.cpp b/src/compat/linux_abi.cpp index cd61ea3..55e27f3 100644 --- a/src/compat/linux_abi.cpp +++ b/src/compat/linux_abi.cpp @@ -21,7 +21,8 @@ const SyscallInfo kSyscallTable[] = { {kGettid, "gettid", kEmulated, "maps to the platform thread id"}, {kClockGettime, "clock_gettime", kEmulated, "CLOCK_MONOTONIC / CLOCK_REALTIME from platform clocks"}, - {kFutex, "futex", kPartial, "FUTEX_WAIT/WAKE with PRIVATE flag only, registry-based"}, + {kFutex, "futex", kPartial, + "private WAIT/WAKE only; timeouts rejected; mismatch returns EAGAIN"}, {kExitGroup, "exit_group", kEmulated, "flags the emulation context as stopping"}, // --- guest fd table & stream / file operations ------------------------ diff --git a/src/compat/memory_compat.cpp b/src/compat/memory_compat.cpp index 8518a81..bde5eba 100644 --- a/src/compat/memory_compat.cpp +++ b/src/compat/memory_compat.cpp @@ -115,10 +115,7 @@ MapResult CompatMemory::mprotect(uintptr_t address, size_t length, int prot) { bool want_w = (prot & linux_abi::kProtWrite) != 0; if (platform::protect_memory(reinterpret_cast(address), length, want_r, want_w)) { - return {reinterpret_cast(0), 0, - (prot & linux_abi::kProtExec) - ? "R/W applied; PROT_EXEC not granted (no JIT)" - : "protection applied"}; + return {nullptr, 0, "protection applied"}; } return {nullptr, linux_abi::kEinval, "host mprotect failed"}; } diff --git a/src/compat/syscall_dispatch.cpp b/src/compat/syscall_dispatch.cpp index 5ef774e..a4532de 100644 --- a/src/compat/syscall_dispatch.cpp +++ b/src/compat/syscall_dispatch.cpp @@ -149,7 +149,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int mode = static_cast(linux_nr == kOpenat ? args.a[3] : args.a[2]); if (!path) return fail(kEfault, "path is null"); - if (linux_nr == kOpenat && path[0] != '/' && static_cast(args.a[0]) != -100) + if (linux_nr == kOpenat && path[0] != '/' && static_cast(args.a[0]) != -100) return fail(kEnosys, "openat relative dirfd is not implemented"); int fd = fd_table_->open_file(path, flags, mode); if (fd < 0) @@ -168,7 +168,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int fd = static_cast(static_cast(args.a[0])); void* buf = reinterpret_cast(args.a[1]); size_t count = static_cast(args.a[2]); - if (!buf) + if (!buf && count) return fail(kEfault, "read buf is null"); int64_t r = fd_table_->read(fd, buf, count); if (r < 0) @@ -193,7 +193,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int fd = static_cast(static_cast(args.a[0])); const void* buf = reinterpret_cast(args.a[1]); size_t count = static_cast(args.a[2]); - if (buf == nullptr) + if (buf == nullptr && count) return fail(kEfault, "write buf is null"); int64_t n = fd_table_->write(fd, buf, count); if (n < 0) @@ -268,7 +268,7 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { } case kEventfd2: { - uint64_t initval = args.a[0]; + uint64_t initval = static_cast(args.a[0]); int flags = static_cast(args.a[1]); int fd = fd_table_->create_eventfd(initval, flags); if (fd < 0) @@ -329,9 +329,13 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return fail(kEfault, "uaddr is null"); uint32_t base = op & ~kFutexPrivateFlag; bool priv = (op & kFutexPrivateFlag) != 0; + if (reinterpret_cast(uaddr) % alignof(uint32_t)) + return fail(kEinval, "unaligned futex address"); if (base == kFutexWait && priv) { + if (args.a[3]) + return fail(kEinval, "futex timeouts are not implemented"); int r = platform::Futex().wait(uaddr, val); - return ok(r, r == 0 ? "woke" : "EWOULDBLOCK"); + return r == 0 ? ok(0, "woke") : fail(kEagain, "futex value mismatch"); } if (base == kFutexWake && priv) { int r = platform::Futex().wake(uaddr, val); diff --git a/tests/fixtures/image-manifest.txt b/tests/fixtures/image-manifest.txt new file mode 100644 index 0000000..2062ce1 --- /dev/null +++ b/tests/fixtures/image-manifest.txt @@ -0,0 +1,4 @@ +system_image = system.img +vendor_image = vendor.img +android_api_level = 35 +abi = x86_64 diff --git a/tests/test_compat_dispatch.cpp b/tests/test_compat_dispatch.cpp index d727399..bfe7acf 100644 --- a/tests/test_compat_dispatch.cpp +++ b/tests/test_compat_dispatch.cpp @@ -140,7 +140,7 @@ PS5DROID_TEST(futex_via_dispatch) { a.a[1] = kFutexWait | kFutexPrivateFlag; a.a[2] = 999; DispatchResult r = d.invoke(kFutex, a); - CHECK_MSG(r.ret == 1, "expected EWOULDBLOCK"); + CHECK_MSG(r.ret == -1 && r.err == kEagain, "expected EAGAIN"); // No-waiter wake returns 0 SyscallArgs b{}; diff --git a/tests/test_elf_validation.cpp b/tests/test_elf_validation.cpp index 7f4f54b..20a11a0 100644 --- a/tests/test_elf_validation.cpp +++ b/tests/test_elf_validation.cpp @@ -3,6 +3,7 @@ #include "compat/memory_compat.h" #include "elf_fixture.h" #include "test_framework.h" +#include #include using namespace ps5droid::compat; PS5DROID_TEST(elf_rejects_overflowing_table_and_invalid_layout) { @@ -81,3 +82,21 @@ PS5DROID_TEST(elf_runner_rejects_invalid_input) { auto result = run_cooperative_elf(junk, sizeof(junk)); CHECK(!result.executed && !result.note.empty()); } +PS5DROID_TEST(elf_runner_rejects_executable_contract_violations) { +#if defined(__x86_64__) + auto bytes = fixture::elf(); + fixture::put(bytes, 68, 7, 4); + CHECK(!run_cooperative_elf(bytes.data(), bytes.size()).executed); + bytes = fixture::elf(); + bytes[130] = 0x0f; + bytes[131] = 0x05; + auto raw = run_cooperative_elf(bytes.data(), bytes.size()); + CHECK(!raw.executed && raw.note.find("syscall") != std::string::npos); + bytes = fixture::elf(); + fixture::put(bytes, 56, 2, 2); + std::fill(bytes.begin() + 120, bytes.begin() + 176, 0); + fixture::put(bytes, 120, 2, 4); + auto dynamic = run_cooperative_elf(bytes.data(), bytes.size()); + CHECK(!dynamic.executed && dynamic.note.find("dynamic") != std::string::npos); +#endif +} diff --git a/tests/test_fd_semantics.cpp b/tests/test_fd_semantics.cpp index c9774dd..5136950 100644 --- a/tests/test_fd_semantics.cpp +++ b/tests/test_fd_semantics.cpp @@ -203,3 +203,28 @@ PS5DROID_TEST(linux_differential_eventfd_and_epoll) { CHECK(gout.events == n.events && gout.data == n.data.u64); } #endif +PS5DROID_TEST(openat_accepts_both_register_encodings_of_at_fdcwd) { + File file; + CompatMemory memory; + SyscallDispatch dispatch(&memory); + for (uint64_t dirfd : {uint64_t(0xffffffffffffff9cull), uint64_t(0xffffff9cull)}) { + SyscallArgs args{}; + args.a[0] = dirfd; + args.a[1] = reinterpret_cast(file.path.c_str()); + auto result = dispatch.invoke(ps5droid::linux_abi::kOpenat, args); + CHECK(result.ret >= 3); + CHECK(dispatch.fd_table()->close(static_cast(result.ret)) == 0); + } +} +PS5DROID_TEST(futex_rejects_unsupported_timeouts_without_waiting) { + CompatMemory memory; + SyscallDispatch dispatch(&memory); + uint32_t word = 1; + SyscallArgs args{}; + args.a[0] = reinterpret_cast(&word); + args.a[1] = 128; + args.a[2] = 1; + args.a[3] = 1; + auto result = dispatch.invoke(ps5droid::linux_abi::kFutex, args); + CHECK(result.ret == -1 && result.err == 22); +} diff --git a/tests/test_platform_threads.cpp b/tests/test_platform_threads.cpp index 0e9415c..4b5224e 100644 --- a/tests/test_platform_threads.cpp +++ b/tests/test_platform_threads.cpp @@ -102,10 +102,8 @@ PS5DROID_TEST(futex_wouldblock_and_wake) { } PS5DROID_TEST(futex_wake_waiter) { - // The main thread sleeps inside wait(); the waker thread wakes it after - // a generous delay (1s), without racing a write against the wait check. The 1s delay only - // bounds the worst case for a heavily preempted CI runner; the waiter enqueues within - // microseconds in practice. + // Keep attempting wake until the waiter has enqueued; no shared-word race + // or scheduler-dependent sleep is needed. CTest bounds a regression hang. static uint32_t word; word = 7; diff --git a/tools/check_reports.py b/tools/check_reports.py index bf76186..83cb69c 100644 --- a/tools/check_reports.py +++ b/tools/check_reports.py @@ -9,6 +9,7 @@ assert report['android_runtime'] == 'blocked' assert report['platform_probes_passed'] and all(p['passed'] for p in report['probes']) assert report['firmware'] == report['loader'] == 'unrecorded' -assert report['revision'] +assert report['revision'] and report['run_id'] != 'unrecorded' +assert report['architecture'] in {'x86_64', 'arm64'} and report['compiler'] assert apk['is_apk'] and apk['package_name'] == 'org.ps5droid.inspection' assert apk['min_sdk'] == 28 and apk['target_sdk'] == 35 diff --git a/tools/make_test_fixtures.py b/tools/make_test_fixtures.py index 3c3ebb7..82841c3 100644 --- a/tools/make_test_fixtures.py +++ b/tools/make_test_fixtures.py @@ -4,6 +4,7 @@ from pathlib import Path import struct import zipfile +import warnings p = argparse.ArgumentParser(description=__doc__) p.add_argument('output', type=Path) @@ -27,7 +28,9 @@ def apk(name, items, compression=zipfile.ZIP_STORED): apk('deflated.apk', files, zipfile.ZIP_DEFLATED) apk('plain.zip', [('assets/message.txt', b'AndroidManifest.xml classes.dex')]) apk('bad-manifest.apk', [('AndroidManifest.xml', b'not binary XML')]) -apk('duplicate.apk', [('AndroidManifest.xml', manifest), ('AndroidManifest.xml', manifest)]) +with warnings.catch_warnings(): + warnings.simplefilter('ignore', UserWarning) + apk('duplicate.apk', [('AndroidManifest.xml', manifest), ('AndroidManifest.xml', manifest)]) apk('large-manifest.apk', [('AndroidManifest.xml', b'x' * (4 * 1024 * 1024 + 1))], zipfile.ZIP_DEFLATED) # CRC corruption: mutate the stored manifest without altering its advertised CRC. data = bytearray((a.output / 'stored.apk').read_bytes()) @@ -35,8 +38,6 @@ def apk(name, items, compression=zipfile.ZIP_STORED): data[30 + name_length + extra_length + 10] ^= 0x10 (a.output / 'bad-crc.apk').write_bytes(data) (a.output / 'truncated.apk').write_bytes((a.output / 'stored.apk').read_bytes()[:-10]) -# A forged program header offset used by the deterministic malformed ELF corpus. -(a.output / 'stamp').write_text('ZIP fixtures generated\n') def binary_xml(utf8=True): @@ -87,3 +88,5 @@ def element(name, attrs): at += struct.unpack_from('