+
+
**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
+
+- [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)
+- [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..122afe6
--- /dev/null
+++ b/cmake/build_info.h.in
@@ -0,0 +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/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 @@
+
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..dffc9e3
--- /dev/null
+++ b/docs/console-validation.md
@@ -0,0 +1,83 @@
+# 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 |
+| `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 |
+| `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 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.
+
+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..8cdc97f 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -1,108 +1,101 @@
-# 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
+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
```
-Sanitizer run (recommended before commits; caught real bugs in this
-repo):
+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.
+
+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/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/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..e7784b2
--- /dev/null
+++ b/src/android/evidence_report.cpp
@@ -0,0 +1,67 @@
+#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 + '"';
+}
+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 \"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)
+ 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..8c12ebc 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,10 +29,11 @@ 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();
+ 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});
@@ -76,9 +79,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 +98,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 +224,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 +236,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..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 {
@@ -50,7 +51,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..55e27f3 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"},
@@ -22,23 +21,28 @@ 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 ------------------------
- {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 +66,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 +94,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..bde5eba 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,19 +105,17 @@ 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,
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"};
}
@@ -148,10 +157,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..a4532de 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");
}
@@ -101,11 +168,11 @@ 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)
- 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");
}
@@ -126,11 +193,11 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) {
int fd = static_cast