diff --git a/CHANGELOG.md b/CHANGELOG.md index f3e2cde..b65b360 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,71 @@ All notable changes to PS5Droid are documented here. The project follows its honesty policy (docs/development.md, section 6): nothing in these notes claims console execution that has not happened. +## [1.0.6] - 2026-11-21 + +### Added (Linux ABI surface, +15 syscalls) + +The emulated surface grew from 46 to 57 syscalls, partial support from 4 +to 8, and unsupported entries fell from 30 to 15 (80 tracked total): + +* **Emulated:** `madvise`, `chdir`, `personality`, `sched_setaffinity`, + `sched_getaffinity`, `set_robust_list`, `wait4`, `exit`, `flock`, + `getdents64`, `memfd_create`. +* **Partial:** `mremap` (in-place shrink and `MREMAP_MAYMOVE` grow), + `arch_prctl` (FS/GS values recorded; no real TLS switch), `ioctl` + (`FIONREAD` only), `ppoll` (no signal-mask semantics). + +### Added (Memory compatibility) + +* **`mremap`** supports in-place shrink, `MREMAP_MAYMOVE` grow with + content preservation, and rejects non-movable growth with `ENOMEM`. +* **`madvise`** accepts `MADV_NORMAL`/`MADV_DONTNEED`; `MADV_DONTNEED` + zeroes anonymous private pages. Unknown advice returns `EINVAL`. + +### Added (Guest fd table) + +* **Directory streams (`getdents64`)** over the guest fd table, including + `.`/`..`, `O_DIRECTORY` enforcement, and EOF reporting. +* **`flock`** advisory locks with shared/exclusive/`LOCK_NB` semantics, + per-path ownership, and automatic release on close. +* **`memfd_create`** with `MFD_CLOEXEC`/`MFD_ALLOW_SEALING` flag + validation and full read/write/seek/fstat behavior. +* **`ppoll`/`poll`** readiness reporting for pipes, eventfds, and + `POLLNVAL` for closed descriptors. +* **`FIONREAD` ioctl** on file and memory-backed descriptors. + +### Added (Guest filesystem view) + +* **Tracked guest cwd.** `chdir` updates a normalized guest cwd, and + relative `open`, `openat`, `stat`, `newfstatat`, `access`, `mkdir`, + `unlink`, `readlink`, and `unlinkat` resolve against it. + +### Fixed (APK inspection) + +* **Dynamic-Huffman DEFLATE blocks.** The ZIP inflater now builds + canonical Huffman trees for the code-length, literal/length, and + distance alphabets, so real-world `AndroidManifest.xml` entries that + zlib emits as `BTYPE=2` are decoded. STORED and fixed-Huffman remain + supported; truncated/oversubscribed streams fail cleanly. + +### Fixed (Bionic loader) + +* **Initial stack layout.** `setup_initial_stack` now emits a real Linux + x86_64 stack: argc, argv/envp pointers into the same buffer, NULL + terminators, and auxv. `AT_PHDR` is derived from the `PT_LOAD` segment + covering `e_phoff` instead of the hardcoded `0x400000`. + +### Changed (tests / docs / project) + +* Added `tests/test_compat_debt.cpp` (mremap/madvise, chdir, personality, + arch_prctl, affinity, flock, memfd, getdents64, ppoll) plus + dynamic-Huffman DEFLATE and dynamic-AXML APK tests and a real-stack + bionic test. 80/80 tests pass on host. +* Compatibility counts are pinned by + `matrix_counts_match_v1_0_6_release`; README, architecture, and + platform-constraints docs now report 57/8/15. +* Version bumped to 1.0.6. + ## [1.0.5] - 2026-10-22 ### Added (Linux ABI surface, +4 syscalls) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1eca7b9..cb215fd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,7 +16,7 @@ cmake_minimum_required(VERSION 3.16) project(ps5droid - VERSION 1.0.5 + VERSION 1.0.6 DESCRIPTION "PS5Droid - native Android runtime research for PS5" LANGUAGES C CXX) @@ -103,6 +103,7 @@ if(PS5DROID_BUILD_TESTS AND PS5DROID_BUILD_HOST AND NOT PROSPERO) tests/test_compat_dispatch.cpp tests/test_compat_matrix.cpp tests/test_compat_fs_syscalls.cpp + tests/test_compat_debt.cpp tests/test_ipc_ring.cpp tests/test_image_manager.cpp tests/test_runtime_manager.cpp diff --git a/README.md b/README.md index 665010b..9fac221 100644 --- a/README.md +++ b/README.md @@ -16,20 +16,20 @@ Waydroid is used as an *architectural reference* only (see 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 (v1.0.5) +## Current status (v1.0.6) | Area | Status | |---|---| | Portable platform layer (memory, threads, fs, IPC) | **Implemented and tested (host)** | -| Linux ABI dispatch experiment (guest fd table with Linux `O_*` flags, `fcntl`, `fsync`, readiness-based epoll/eventfd, guest pipes, mmap/brk/futex, path-stat family, writev, uname, prctl, getuid/getgid, getppid, set_tid_address, clock_nanosleep, getrandom) | **Implemented and tested (host)** | -| Compatibility matrix (80 syscalls: 46 emulated / 4 partial / 30 unsupported) | **Implemented and tested (host)** | +| Linux ABI dispatch experiment (guest fd table with Linux `O_*` flags, `fcntl`, `fsync`, readiness-based epoll/eventfd, guest pipes, mmap/brk/mremap/madvise, futex, path-stat family, guest cwd, directory streams, `flock`, `memfd_create`, `ppoll`, `FIONREAD`, writev, uname, prctl, getuid/getgid, getppid, set_tid_address, clock_nanosleep, getrandom) | **Implemented and tested (host)** | +| Compatibility matrix (80 syscalls: 57 emulated / 8 partial / 15 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 + build.prop parser | **Implemented and tested (host)** | -| APK inspection (binary AXML manifest parsing, ZIP entry extraction, native ABI detection, package name, app label, permissions & SDK levels) | **Implemented and tested (host)** | +| APK inspection (binary AXML manifest parsing, STORED/fixed/dynamic-Huffman DEFLATE, ZIP entry extraction, native ABI detection, package name, app label, permissions & SDK levels) | **Implemented and tested (host)** | | Launcher UI model + 8x8 framebuffer font + shared screen builders | **Implemented and tested (host)** | | Native PS5 payload (`ps5droid.elf`, video-out + pad + probe/status/matrix/about screens) | **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)** | +| Linux binary loading / bionic re-hosting (Milestone 4, real argv/envp/auxv stack layout) | **Implemented and tested (host)** | | Binder re-hosting (Milestone 5) | **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) | @@ -53,10 +53,13 @@ app/main.cpp (host CLI) app/ps5_main.cpp (PS5 payload) the PS5 backend uses ps5-payload-sdk facilities with hand-maintained, provenance-documented firmware declarations. * **compat/** — accepts Linux x86_64 syscall numbers and executes an - honestly classified subset (anonymous memory, clocks, futex wait/wake, - a guest fd table with Linux `O_*` flag values, `fcntl`, `fsync`, guest pipes, readiness-based - epoll/eventfd, path stat family, writev, uname, prctl, getuid/getgid, getppid, set_tid_address, clock_nanosleep, getrandom); everything else - returns `-ENOSYS` with an explanation. The verified + honestly classified subset (anonymous memory with `mremap`/`madvise`, + clocks, futex wait/wake, a guest fd table with Linux `O_*` flag values, + `fcntl`, `fsync`, `flock`, guest pipes, directory streams, `memfd_create`, + `ppoll`, readiness-based epoll/eventfd, path stat family with a tracked + guest cwd, writev, uname, prctl, identity syscalls, `arch_prctl` bookkeeping, + affinity, set_tid_address/set_robust_list, clock_nanosleep, getrandom); + 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 diff --git a/docs/architecture.md b/docs/architecture.md index d639a54..03ff35a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -33,15 +33,16 @@ src/ │ └── input_ps5.cpp scePad backend ├── compat/ Linux ABI experiment (Milestone 3+) │ ├── linux_abi.h/.cpp syscall constants + tables + verified FreeBSD mapping -│ ├── memory_compat.cpp Linux brk + anonymous MAP_PRIVATE mmap semantics +│ ├── memory_compat.cpp Linux brk + anonymous MAP_PRIVATE mmap/mremap/madvise semantics │ ├── fd_table.h/.cpp guest fd table: Linux O_* flags, lowest-free fds, guest pipes, -│ │ readiness-based epoll, eventfd (EFD_SEMAPHORE/overflow) +│ │ directory streams, memfd, flock, poll, readiness-based +│ │ epoll, eventfd (EFD_SEMAPHORE/overflow) │ ├── syscall_dispatch.cpp Linux syscall number -> emulated op dispatch -│ ├── bionic_loader.cpp x86_64 ELF inspection + auxv/initial-stack builder +│ ├── bionic_loader.cpp x86_64 ELF inspection + real argv/envp/auxv stack builder │ └── ipc_compat.cpp SPSC ring + Binder-style block allocator ├── android/ │ ├── sha256.cpp FIPS 180-4 (clean-room) -│ ├── image_manager.cpp manifest parsing + ext4 superblock + AXML parser + ZIP + build.prop +│ ├── image_manager.cpp manifest + ext4 probe + AXML + ZIP/DEFLATE (dynamic Huffman) + build.prop │ ├── runtime_manager.cpp capability probes + honest start attempts │ └── binder/ │ ├── binder_engine.h/.cpp in-process Binder RPC engine (Milestone 5) @@ -101,24 +102,33 @@ numbers and executes a curated subset: * `futex` WAIT/WAKE (private) over `platform::Futex` (registry-based, wake-atomicity mirrors Linux's kernel-side check-and-enqueue); * a **guest fd table** (`compat::CompatFdTable`) with Linux `O_*` flag - values, descriptor and status flag management via `fcntl`, `fsync` buffer synchronization, lowest-free fd allocation, `dup`/`dup2`/`dup3`, in-process guest pipes (`pipe2`), + values, descriptor and status flag management via `fcntl`, `fsync` buffer + synchronization, lowest-free fd allocation, `dup`/`dup2`/`dup3`, + in-process guest pipes (`pipe2`), directory streams (`getdents64`), + `memfd_create`, advisory `flock`, `poll`/`ppoll`, `FIONREAD` ioctl, positioned `pread64` that never moves the shared offset, eventfd counters honoring `EFD_SEMAPHORE` and the overflow ceiling, and `writev` gather output; * **readiness-based epoll**: `epoll_ctl` enforces Linux `EEXIST`/ `ENOENT` semantics and `epoll_wait` reports only entries whose target fd is currently ready (eventfd counters and pipes drive readiness); * the path family `stat`/`newfstatat`/`unlinkat` (AT_FDCWD only), `access`, - `mkdir`, `unlink`, `readlink`, `getcwd` over host stat/stdio/symlink calls; + `mkdir`, `unlink`, `readlink`, `getcwd`, and `chdir` over host + stat/stdio/symlink calls, with a tracked guest cwd for relative paths; * `uname` and `prctl` (process/thread naming); -* user and group identity (`getuid`, `getgid`, `geteuid`, `getegid`, `getppid` returning single-process guest identity) and thread id tracking (`set_tid_address`); +* user and group identity (`getuid`, `getgid`, `geteuid`, `getegid`, `getppid` returning single-process guest identity), thread id tracking (`set_tid_address`), `personality`, and `set_robust_list` registration; +* `arch_prctl` FS/GS bookkeeping (PARTIAL: no real TLS base switch) and + single-CPU `sched_setaffinity`/`sched_getaffinity`; +* `mremap` (PARTIAL: in-place shrink and MAYMOVE grow) and `madvise` + (`MADV_DONTNEED` zeroes anonymous private pages); +* `exit`/`wait4` under the no-child model (`wait4` returns `ECHILD`); * high-resolution sleep (`nanosleep`, `clock_nanosleep`); * `getrandom` (PARTIAL) from the host `/dev/urandom`; * `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 (46 emulated / 4 partial / -30 unsupported = 80 tracked at the v1.0.5 release) is data, not prose: +sourced from the syscall table. The matrix (57 emulated / 8 partial / +15 unsupported = 80 tracked at the v1.0.6 release) is data, not prose: `ps5droid-host --matrix` prints it, tests pin the counts, and the release documents repeat them. @@ -175,17 +185,23 @@ documented in `development.md`; CI cross-builds the ELF on every push. 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 mostly done (v1.0.5)** — anonymous-memory subset, guest fd - table with Linux flag semantics, `fcntl`, `fsync`, guest pipes (`pipe2`), readiness-based - epoll/eventfd, `uname`, `prctl`, user/group/parent IDs (`getppid`), thread tracking (`set_tid_address`), `clock_nanosleep`, and path-stat family demonstrated end-to-end; - remaining: sockets, signals, directory streams, kqueue-backed poll on Orbis. -4. **M4 done at feasibility level** — bionic ELF inspection + auxv/ - initial-stack construction tested on host; full dynamic linker - namespaces remain un-hosted. +3. **M3 mostly done (v1.0.6)** — anonymous-memory subset with + `mremap`/`madvise`, guest fd table with Linux flag semantics, `fcntl`, + `fsync`, `flock`, guest pipes (`pipe2`), directory streams + (`getdents64`), `memfd_create`, `poll`/`ppoll`, readiness-based + epoll/eventfd, `uname`, `prctl`, identity and affinity calls, thread + tracking (`set_tid_address`/`set_robust_list`), `clock_nanosleep`, and + the path-stat family plus `chdir` demonstrated end-to-end; remaining: + sockets, signals, and a kqueue-backed poll implementation on Orbis. +4. **M4 done at feasibility level** — bionic ELF inspection + real + argv/envp/auxv initial-stack construction (AT_PHDR derived from + PT_LOAD) tested on host; full dynamic linker namespaces remain + un-hosted. 5. **M5 done at engine level** — in-process Binder RPC engine (handles, transactions, block-allocated buffers) tested on host; not wire-compatible with the kernel protocol and never claiming to be. -6. **M6 done at inspection level (v1.0.5)** — APK structure probing (ZIP - extraction, binary AXML AndroidManifest parsing for package name, app label, permissions, SDK - levels, native library ABI extraction, DEX/native-lib presence); launch research waits on M4/M5 runtime - evidence. +6. **M6 done at inspection level (v1.0.6)** — APK structure probing (ZIP + extraction, STORED/fixed/dynamic-Huffman DEFLATE, binary AXML + AndroidManifest parsing for package name, app label, permissions, SDK + levels, native library ABI extraction, DEX/native-lib presence); launch + research waits on M4/M5 runtime evidence. diff --git a/docs/development.md b/docs/development.md index e095faa..89a634b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,6 +1,6 @@ # Development Guide -Current release: **v1.0.5** (see `CHANGELOG.md` and `src/version.h`). +Current release: **v1.0.6** (see `CHANGELOG.md` and `src/version.h`). ## 1. Repository layout diff --git a/docs/platform-constraints.md b/docs/platform-constraints.md index 9150996..7caceed 100644 --- a/docs/platform-constraints.md +++ b/docs/platform-constraints.md @@ -120,31 +120,41 @@ Consequences (all encoded in `src/compat/linux_abi.h` and tested in paths are a known risk. The compat layer returns `-ENOSYS` for the signal family. -## 6. Linux ABI compatibility matrix (v1.0.5) +## 6. Linux ABI compatibility matrix (v1.0.6) Authoritative live output: `./build/ps5droid-host --matrix`. Summary of the 80 tracked syscalls: -* **EMULATED (46)** — real in-process behavior, unit tested: - memory (`mmap`, `brk`), clocks (`clock_gettime`, `clock_getres`, - `gettimeofday`, `nanosleep`, `clock_nanosleep`, `sched_yield`), identity - (`getpid`, `gettid`, `getuid`, `getgid`, `geteuid`, `getegid`, `getppid`), system & process (`uname`, `prctl`, `set_tid_address`), the guest fd table family (`read`, `write`, - `writev`, `open`, `openat`, `close`, `lseek`, `pread64`, `fstat`, - `dup`, `dup2`, `dup3`, `pipe2`, `fcntl`, `fsync`, `epoll_create1`, `epoll_ctl`, `epoll_wait`, - `eventfd2`), the path family (`stat`, `newfstatat`, `unlinkat`, `access`, `readlink`, - `mkdir`, `unlink`, `getcwd`), and `exit_group` -* **PARTIAL (4)** — implemented with documented restrictions: +* **EMULATED (57)** — real in-process behavior, unit tested: + memory (`mmap`, `brk`, `madvise`), clocks (`clock_gettime`, + `clock_getres`, `gettimeofday`, `nanosleep`, `clock_nanosleep`, + `sched_yield`), identity (`getpid`, `gettid`, `getuid`, `getgid`, + `geteuid`, `getegid`, `getppid`), system & process (`uname`, `prctl`, + `personality`, `set_tid_address`, `set_robust_list`, + `sched_setaffinity`, `sched_getaffinity`, `wait4`, `exit`, + `exit_group`), the guest fd table family (`read`, `write`, `writev`, + `open`, `openat`, `close`, `lseek`, `pread64`, `fstat`, `dup`, `dup2`, + `dup3`, `pipe2`, `fcntl`, `fsync`, `flock`, `getdents64`, + `memfd_create`, `epoll_create1`, `epoll_ctl`, `epoll_wait`, + `eventfd2`), the path family (`stat`, `newfstatat`, `unlinkat`, + `access`, `readlink`, `mkdir`, `unlink`, `getcwd`, `chdir`) +* **PARTIAL (8)** — implemented with documented restrictions: `munmap` (whole mappings only), `mprotect` (R/W only; PROT_EXEC not - granted), `futex` (WAIT/WAKE + PRIVATE flag only), `getrandom` - (host `/dev/urandom`; pool distinction not modeled) -* **UNSUPPORTED (30)** — return `-ENOSYS` with an explanatory note. The - hard blockers remain `clone/fork/vfork/execve` (no process creation - for payloads), the socket and signal families, and directory streams. + granted), `mremap` (in-place shrink and `MREMAP_MAYMOVE` grow only), + `futex` (WAIT/WAKE + PRIVATE flag only), `getrandom` (host + `/dev/urandom`; pool distinction not modeled), `arch_prctl` (FS/GS + values recorded; no real TLS base switch), `ioctl` (`FIONREAD` only), + `ppoll` (readiness polling; no signal mask semantics) +* **UNSUPPORTED (15)** — return `-ENOSYS` with an explanatory note. The + hard blockers remain `clone/fork/vfork/execve` (no process creation for + payloads), the socket family (`socket`, `connect`, `accept`, `bind`, + `listen`), the signal family (`rt_sigaction`, `rt_sigprocmask`, `kill`, + `sigaltstack`, `tgkill`), and `inotify_init1`. `getpid` returns the emulation-context id and `gettid` the platform thread id — single-process model, documented in `src/compat/syscall_dispatch.h`. The counts are pinned by -`tests/test_compat_matrix.cpp` (`matrix_counts_match_v1_0_5_release`) +`tests/test_compat_matrix.cpp` (`matrix_counts_match_v1_0_6_release`) so docs and code cannot drift silently. ## 7. Filesystem diff --git a/src/android/image_manager.cpp b/src/android/image_manager.cpp index a1727f5..56fb036 100644 --- a/src/android/image_manager.cpp +++ b/src/android/image_manager.cpp @@ -27,13 +27,16 @@ struct BitReader { const uint8_t* data; size_t size; size_t bit_off = 0; + bool failed = false; uint32_t read_bits(size_t count) { uint32_t val = 0; for (size_t i = 0; i < count; ++i) { size_t byte_idx = bit_off / 8; - if (byte_idx >= size) + if (byte_idx >= size) { + failed = true; break; + } size_t bit_idx = bit_off % 8; uint32_t bit = (data[byte_idx] >> bit_idx) & 1; val |= (bit << i); @@ -49,21 +52,194 @@ struct BitReader { } }; -// Inflates DEFLATE payload (STORED and FIXED Huffman blocks). -bool inflate_deflate(const uint8_t* in, size_t in_size, std::vector* out, - size_t expected_out_size) { +// Canonical Huffman tree for DEFLATE lit/len, distance and code-length +// alphabets. Codes are inserted MSB-first, matching DEFLATE bit order. +class HuffmanTree { + public: + bool build(const std::vector& lengths, int max_bits) { + nodes_.clear(); + nodes_.push_back(Node{}); + + int count[16] = {0}; + for (uint8_t len : lengths) { + if (len > max_bits) + return false; + if (len > 0) + ++count[len]; + } + + int left = 1; + for (int bits = 1; bits <= max_bits; ++bits) { + left = (left << 1) - count[bits]; + if (left < 0) + return false; // over-subscribed + } + + int next_code[16] = {0}; + int code = 0; + for (int bits = 1; bits <= max_bits; ++bits) { + code = (code + count[bits - 1]) << 1; + next_code[bits] = code; + } + + for (size_t symbol = 0; symbol < lengths.size(); ++symbol) { + int len = lengths[symbol]; + if (len == 0) + continue; + int current = next_code[len]++; + int node = 0; + for (int i = len - 1; i >= 0; --i) { + int bit = (current >> i) & 1; + int next = nodes_[static_cast(node)].child[bit]; + if (next < 0) { + nodes_.push_back(Node{}); + next = static_cast(nodes_.size()) - 1; + nodes_[static_cast(node)].child[bit] = next; + } + node = next; + } + if (nodes_[static_cast(node)].symbol >= 0) + return false; // duplicate code + nodes_[static_cast(node)].symbol = static_cast(symbol); + } + return true; + } + + int decode(BitReader& br) const { + int node = 0; + for (int depth = 0; depth < 16; ++depth) { + uint32_t bit = br.read_bits(1); + if (br.failed) + return -1; + int next = nodes_[static_cast(node)].child[bit]; + if (next < 0) + return -1; + node = next; + int symbol = nodes_[static_cast(node)].symbol; + if (symbol >= 0) + return symbol; + } + return -1; + } + + private: + struct Node { + int child[2] = {-1, -1}; + int symbol = -1; + }; + std::vector nodes_; +}; + +const uint16_t kLengthBase[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, + 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; +const uint8_t kLengthBits[] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, + 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; +const uint16_t kDistBase[] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, + 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, + 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; +const uint8_t kDistBits[] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, + 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + +bool inflate_dynamic_block(BitReader& br, std::vector* out) { + uint32_t hlit = br.read_bits(5) + 257; + uint32_t hdist = br.read_bits(5) + 1; + uint32_t hclen = br.read_bits(4) + 4; + if (br.failed || hlit > 286 || hdist > 32) + return false; + + static const uint8_t kCodeLengthOrder[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, + 11, 4, 12, 3, 13, 2, 14, 1, 15}; + std::vector code_lengths(19, 0); + for (uint32_t i = 0; i < hclen; ++i) + code_lengths[kCodeLengthOrder[i]] = static_cast(br.read_bits(3)); + if (br.failed) + return false; + + HuffmanTree code_tree; + if (!code_tree.build(code_lengths, 7)) + return false; + + std::vector lengths; + lengths.reserve(hlit + hdist); + while (lengths.size() < hlit + hdist) { + int symbol = code_tree.decode(br); + if (symbol < 0) + return false; + if (symbol <= 15) { + lengths.push_back(static_cast(symbol)); + } else if (symbol == 16) { + if (lengths.empty()) + return false; + uint8_t previous = lengths.back(); + uint32_t repeat = 3 + br.read_bits(2); + for (uint32_t i = 0; i < repeat; ++i) + lengths.push_back(previous); + } else if (symbol == 17) { + uint32_t repeat = 3 + br.read_bits(3); + for (uint32_t i = 0; i < repeat; ++i) + lengths.push_back(0); + } else if (symbol == 18) { + uint32_t repeat = 11 + br.read_bits(7); + for (uint32_t i = 0; i < repeat; ++i) + lengths.push_back(0); + } else { + return false; + } + if (br.failed || lengths.size() > hlit + hdist) + return false; + } + + std::vector lit_lengths(lengths.begin(), lengths.begin() + hlit); + std::vector dist_lengths(lengths.begin() + hlit, lengths.end()); + HuffmanTree lit_tree; + HuffmanTree dist_tree; + if (!lit_tree.build(lit_lengths, 15) || !dist_tree.build(dist_lengths, 15)) + return false; + + while (true) { + int symbol = lit_tree.decode(br); + if (symbol < 0) + return false; + if (symbol == 256) + break; + if (symbol < 256) { + out->push_back(static_cast(symbol)); + continue; + } + if (symbol > 285) + return false; + uint32_t index = static_cast(symbol - 257); + uint32_t match_len = kLengthBase[index] + br.read_bits(kLengthBits[index]); + int dist_symbol = dist_tree.decode(br); + if (br.failed || dist_symbol < 0 || dist_symbol >= 30) + return false; + uint32_t match_dist = kDistBase[dist_symbol] + br.read_bits(kDistBits[dist_symbol]); + if (br.failed || match_dist == 0 || match_dist > out->size()) + return false; + size_t start_pos = out->size() - match_dist; + for (uint32_t m = 0; m < match_len; ++m) + out->push_back((*out)[start_pos + m]); + } + return !br.failed; +} + +// Inflates DEFLATE payload (STORED, FIXED and DYNAMIC Huffman blocks). +bool inflate_deflate_impl(const uint8_t* in, size_t in_size, std::vector* out, + size_t expected_out_size) { if (!in || in_size == 0 || !out) return false; out->clear(); out->reserve(expected_out_size > 0 ? expected_out_size : 4096); - BitReader br{in, in_size, 0}; + BitReader br{in, in_size, 0, false}; bool last = false; while (!last) { uint32_t bfinal = br.read_bits(1); uint32_t btype = br.read_bits(2); last = (bfinal != 0); + if (br.failed) + return false; if (btype == 0) { // STORED br.align_byte(); @@ -116,7 +292,7 @@ bool inflate_deflate(const uint8_t* in, size_t in_size, std::vector* ou } } - if (!found) + if (br.failed || !found) return false; if (code == 256) break; // End of block @@ -124,50 +300,45 @@ bool inflate_deflate(const uint8_t* in, size_t in_size, std::vector* ou if (code < 256) { out->push_back(static_cast(code)); } else if (code <= 285) { - // Length code - static const uint16_t len_base[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, - 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, - 67, 83, 99, 115, 131, 163, 195, 227, 258}; - static const uint8_t len_bits[] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, - 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; uint32_t idx = code - 257; if (idx >= 29) return false; - uint32_t match_len = len_base[idx] + br.read_bits(len_bits[idx]); + uint32_t match_len = kLengthBase[idx] + br.read_bits(kLengthBits[idx]); // Distance code (5 fixed bits for fixed huffman) uint32_t dist_code = 0; for (int d = 0; d < 5; ++d) { dist_code = (dist_code << 1) | br.read_bits(1); } - static const uint16_t dist_base[] = { - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, - 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, - 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; - static const uint8_t dist_bits[] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, - 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, - 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; - if (dist_code >= 30) + if (br.failed || dist_code >= 30) return false; - uint32_t match_dist = dist_base[dist_code] + br.read_bits(dist_bits[dist_code]); + uint32_t match_dist = kDistBase[dist_code] + br.read_bits(kDistBits[dist_code]); - if (match_dist > out->size()) + if (match_dist == 0 || match_dist > out->size()) return false; size_t start_pos = out->size() - match_dist; - for (size_t m = 0; m < match_len; ++m) { + for (uint32_t m = 0; m < match_len; ++m) { out->push_back((*out)[start_pos + m]); } } } + } else if (btype == 2) { // DYNAMIC HUFFMAN + if (!inflate_dynamic_block(br, out)) + return false; } else { - return false; // Dynamic Huffman or reserved + return false; // reserved block type } } - return true; + return !br.failed; } } // namespace +bool inflate_deflate(const uint8_t* in, size_t in_size, std::vector* out, + size_t expected_out_size) { + return inflate_deflate_impl(in, in_size, out, expected_out_size); +} + ParseStatus parse_manifest(const std::string& text, ImageManifest* out) { if (out == nullptr) return ParseStatus::kBadValue; @@ -604,8 +775,8 @@ ApkInspection inspect_apk(const std::string& apk_path) { axml_ptr = manifest_bytes.data(); axml_sz = manifest_bytes.size(); } else if (manifest_method == 8) { // DEFLATE - if (inflate_deflate(manifest_bytes.data(), manifest_bytes.size(), &decompressed, - manifest_uncompressed_size)) { + if (inflate_deflate_impl(manifest_bytes.data(), manifest_bytes.size(), &decompressed, + manifest_uncompressed_size)) { axml_ptr = decompressed.data(); axml_sz = decompressed.size(); } diff --git a/src/android/image_manager.h b/src/android/image_manager.h index 3520688..7a8af4c 100644 --- a/src/android/image_manager.h +++ b/src/android/image_manager.h @@ -112,5 +112,11 @@ struct BuildProp { BuildProp parse_build_prop(const std::string& text); +// Inflates a raw DEFLATE stream (the payload of a ZIP method-8 entry). +// Supports STORED, FIXED and DYNAMIC Huffman blocks. Exposed so the APK +// inspector and the unit tests exercise the same decoder. +bool inflate_deflate(const uint8_t* in, size_t in_size, std::vector* out, + size_t expected_out_size = 0); + } // namespace android } // namespace ps5droid diff --git a/src/compat/bionic_loader.cpp b/src/compat/bionic_loader.cpp index 3965448..6fcc369 100644 --- a/src/compat/bionic_loader.cpp +++ b/src/compat/bionic_loader.cpp @@ -36,6 +36,7 @@ struct RawElf64Phdr { uint64_t p_align; }; +constexpr uint32_t PT_LOAD = 1; constexpr uint32_t PT_INTERP = 3; constexpr uint32_t PT_TLS = 7; @@ -110,6 +111,16 @@ BionicElfInfo BionicLoader::parse_header(const void* data, size_t size) { } } + // Program headers live inside a PT_LOAD segment; translate e_phoff to + // the virtual address the dynamic linker sees at AT_PHDR. + for (const Elf64PhdrInfo& phdr : res.phdrs) { + if (phdr.type == PT_LOAD && ehdr->e_phoff >= phdr.offset && + ehdr->e_phoff < phdr.offset + phdr.filesz) { + res.phdr_addr = phdr.vaddr + (ehdr->e_phoff - phdr.offset); + break; + } + } + return res; } @@ -127,29 +138,44 @@ std::vector BionicLoader::build_auxv(uint64_t entry, uint64_t phdr, u 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); + const std::vector& env, + uint64_t stack_base) { + const uint64_t phdr = info.phdr_addr != 0 ? info.phdr_addr : 0x400000; + auto auxv = build_auxv(info.entry_point, phdr, info.phdrs.size()); + + // Linux x86_64 initial stack: argc, argv[], NULL, envp[], NULL, auxv[], + // then the argument/environment strings themselves. Pointers are + // expressed relative to `stack_base` so the caller can place the buffer. + size_t words = 1 + args.size() + 1 + env.size() + 1 + auxv.size() * 2; + size_t strings_offset = (words * sizeof(uint64_t) + 7) & ~static_cast(7); + size_t total = strings_offset; + for (const std::string& arg : args) + total += arg.size() + 1; + for (const std::string& entry : env) + total += entry.size() + 1; + + std::vector stack(total, 0); uint64_t* ptr = reinterpret_cast(stack.data()); - *ptr++ = argc; - for (size_t i = 0; i < args.size(); ++i) { - *ptr++ = 0x7fffffffe000 + i * 32; + *ptr++ = static_cast(args.size()); + size_t cursor = strings_offset; + for (const std::string& arg : args) { + *ptr++ = stack_base + cursor; + std::memcpy(stack.data() + cursor, arg.c_str(), arg.size() + 1); + cursor += arg.size() + 1; } *ptr++ = 0; // NULL argv terminator - for (size_t i = 0; i < env.size(); ++i) { - *ptr++ = 0x7fffffffe800 + i * 32; + for (const std::string& entry : env) { + *ptr++ = stack_base + cursor; + std::memcpy(stack.data() + cursor, entry.c_str(), entry.size() + 1); + cursor += entry.size() + 1; } *ptr++ = 0; // NULL env terminator - for (const auto& a : auxv) { - *ptr++ = a.type; - *ptr++ = a.val; + for (const AuxvEntry& entry : auxv) { + *ptr++ = entry.type; + *ptr++ = entry.val; } return stack; diff --git a/src/compat/bionic_loader.h b/src/compat/bionic_loader.h index 046a030..8dd14ef 100644 --- a/src/compat/bionic_loader.h +++ b/src/compat/bionic_loader.h @@ -27,6 +27,7 @@ struct Elf64PhdrInfo { struct BionicElfInfo { bool valid = false; uint64_t entry_point = 0; + uint64_t phdr_addr = 0; // in-memory address of the program headers (from PT_LOAD) std::string interp; bool is_bionic = false; uint64_t tls_filesz = 0; @@ -48,7 +49,8 @@ class BionicLoader { uint64_t pagesz = 4096); static std::vector setup_initial_stack(const BionicElfInfo& info, const std::vector& args, - const std::vector& env); + const std::vector& env, + uint64_t stack_base = 0x7fffffffe000ull); }; } // namespace compat diff --git a/src/compat/fd_table.cpp b/src/compat/fd_table.cpp index 22922b4..651e1ff 100644 --- a/src/compat/fd_table.cpp +++ b/src/compat/fd_table.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "platform/platform.h" @@ -117,6 +118,30 @@ class FileFdEntry : public FdEntry { return 0; } + int ioctl(unsigned long request, void* arg, int* err) override { + if (request != linux_abi::kFionread) + return FdEntry::ioctl(request, arg, err); + if (!arg) { + set_err(err, linux_abi::kEfault); + return -1; + } + if (!fp_) { + set_err(err, linux_abi::kEbadf); + return -1; + } + long cur = ftell(fp_); + if (cur < 0 || fseek(fp_, 0, SEEK_END) != 0) { + set_err(err, linux_abi::kEio); + return -1; + } + long end = ftell(fp_); + fseek(fp_, cur, SEEK_SET); + *static_cast(arg) = end > cur ? static_cast(end - cur) : 0; + return 0; + } + + const std::string* lock_path() const override { return &path_; } + void close() override { if (fp_) { fclose(fp_); @@ -176,6 +201,18 @@ class StreamFdEntry : public FdEntry { } return 0; } + + int ioctl(unsigned long request, void* arg, int* err) override { + if (request != linux_abi::kFionread) + return FdEntry::ioctl(request, arg, err); + if (!arg) { + set_err(err, linux_abi::kEfault); + return -1; + } + *static_cast(arg) = 0; + return 0; + } + void close() override { stream_ = nullptr; } uint32_t readiness() const override { return linux_abi::kEpollOut; } @@ -425,6 +462,18 @@ class PipeFdEntry : public FdEntry { return true; } + int ioctl(unsigned long request, void* arg, int* err) override { + if (request != linux_abi::kFionread) + return FdEntry::ioctl(request, arg, err); + if (!arg) { + set_err(err, linux_abi::kEfault); + return -1; + } + std::lock_guard lock(state_->mutex); + *static_cast(arg) = static_cast(state_->buffer.size()); + return 0; + } + void close() override { std::lock_guard lock(state_->mutex); if (is_writer_) { @@ -453,6 +502,197 @@ class PipeFdEntry : public FdEntry { bool is_writer_; }; +// --------------------------------------------------------------------------- +// Directory stream (getdents64). Names come from the portable platform +// directory listing; inode numbers are synthetic and d_type is DT_UNKNOWN +// because the platform layer does not expose either. +// --------------------------------------------------------------------------- +class DirFdEntry : public FdEntry { + public: + explicit DirFdEntry(const std::string& path) : path_(path) { + names_.push_back("."); + names_.push_back(".."); + for (const std::string& name : platform::list_dir(path)) + names_.push_back(name); + } + + FdType type() const override { return FdType::kDirectory; } + + int64_t read(void*, size_t, int64_t, int* err) override { + set_err(err, linux_abi::kEisdir); + return -1; + } + int64_t write(const void*, size_t, int64_t, int* err) override { + set_err(err, linux_abi::kEisdir); + return -1; + } + int64_t lseek(int64_t offset, int whence, int* err) override { + if (offset == 0 && whence == 0) { + std::lock_guard lock(mutex_); + index_ = 0; + return 0; + } + set_err(err, linux_abi::kEinval); + return -1; + } + bool fstat(StatBuf* statbuf) override { + if (!statbuf) + return false; + memset(statbuf, 0, sizeof(*statbuf)); + statbuf->st_mode = 0040755; // S_IFDIR | 0755 + return true; + } + void close() override { + std::lock_guard lock(mutex_); + names_.clear(); + index_ = 0; + } + + int64_t getdents64(void* buf, size_t count, int* err) override { + if (!buf) { + set_err(err, linux_abi::kEfault); + return -1; + } + std::lock_guard lock(mutex_); + size_t written = 0; + while (index_ < names_.size()) { + const std::string& name = names_[index_]; + size_t reclen = (19 + name.size() + 1 + 7) & ~static_cast(7); + if (reclen > count - written) { + if (written == 0) { + set_err(err, linux_abi::kEinval); + return -1; + } + break; + } + uint8_t* rec = static_cast(buf) + written; + memset(rec, 0, reclen); + uint64_t ino = static_cast(index_ + 1); + int64_t off = static_cast(index_ + 1); + memcpy(rec + 0, &ino, sizeof(ino)); + memcpy(rec + 8, &off, sizeof(off)); + uint16_t rl = static_cast(reclen); + memcpy(rec + 16, &rl, sizeof(rl)); + rec[18] = 0; // DT_UNKNOWN + memcpy(rec + 19, name.c_str(), name.size() + 1); + written += reclen; + ++index_; + } + return static_cast(written); + } + + const std::string* lock_path() const override { return &path_; } + + uint32_t readiness() const override { return linux_abi::kEpollIn; } + + private: + std::string path_; + std::vector names_; + size_t index_ = 0; + mutable std::mutex mutex_; +}; + +// --------------------------------------------------------------------------- +// In-process memory file (memfd_create). +// --------------------------------------------------------------------------- +class MemFdEntry : public FdEntry { + public: + explicit MemFdEntry(std::string name) : name_(std::move(name)) {} + + FdType type() const override { return FdType::kMemFd; } + + int64_t read(void* buf, size_t count, int64_t offset, int* err) override { + if (!buf && count > 0) { + set_err(err, linux_abi::kEfault); + return -1; + } + std::lock_guard lock(mutex_); + size_t pos = offset >= 0 ? static_cast(offset) : offset_; + if (pos >= data_.size()) + return 0; + size_t n = std::min(count, data_.size() - pos); + memcpy(buf, data_.data() + pos, n); + if (offset < 0) + offset_ = pos + n; + return static_cast(n); + } + + int64_t write(const void* buf, size_t count, int64_t offset, int* err) override { + if (!buf && count > 0) { + set_err(err, linux_abi::kEfault); + return -1; + } + std::lock_guard lock(mutex_); + size_t pos = offset >= 0 ? static_cast(offset) : offset_; + if (pos + count > data_.size()) + data_.resize(pos + count, 0); + memcpy(data_.data() + pos, buf, count); + if (offset < 0) + offset_ = pos + count; + return static_cast(count); + } + + int64_t lseek(int64_t offset, int whence, int* err) override { + std::lock_guard lock(mutex_); + int64_t base; + if (whence == 0) { + base = 0; + } else if (whence == 1) { + base = static_cast(offset_); + } else if (whence == 2) { + base = static_cast(data_.size()); + } else { + set_err(err, linux_abi::kEinval); + return -1; + } + int64_t next = base + offset; + if (next < 0) { + set_err(err, linux_abi::kEinval); + return -1; + } + offset_ = static_cast(next); + return next; + } + + bool fstat(StatBuf* statbuf) override { + if (!statbuf) + return false; + std::lock_guard lock(mutex_); + memset(statbuf, 0, sizeof(*statbuf)); + statbuf->st_mode = 0100666; // S_IFREG | 0666 + statbuf->st_size = static_cast(data_.size()); + statbuf->st_nlink = 1; + return true; + } + + void close() override { + std::lock_guard lock(mutex_); + data_.clear(); + offset_ = 0; + } + + int ioctl(unsigned long request, void* arg, int* err) override { + if (request != linux_abi::kFionread) + return FdEntry::ioctl(request, arg, err); + if (!arg) { + set_err(err, linux_abi::kEfault); + return -1; + } + std::lock_guard lock(mutex_); + size_t remaining = offset_ < data_.size() ? data_.size() - offset_ : 0; + *static_cast(arg) = static_cast(remaining); + return 0; + } + + uint32_t readiness() const override { return linux_abi::kEpollIn | linux_abi::kEpollOut; } + + private: + std::string name_; + std::vector data_; + size_t offset_ = 0; + mutable std::mutex mutex_; +}; + } // namespace int EpollFdEntry::wait(EpollEvent* out_events, int maxevents, int timeout_ms) { @@ -509,16 +749,41 @@ int CompatFdTable::open_file(const std::string& path, int flags, int mode) { const bool excl = (flags & kOExcl) != 0; const bool trunc = (flags & kOTrunc) != 0; const bool append = (flags & kOAppend) != 0; + const bool directory = (flags & kODirectory) != 0; const int access = flags & kOAccmode; if (access != kORdonly && access != kOWronly && access != kORdwr) return -kEinval; const bool exists = platform::file_exists(path); + const bool is_dir = exists && platform::is_directory(path); + + if (directory) { + if (!exists) + return -kEnoent; + if (!is_dir) + return -kEnotdir; + if (access != kORdonly) + return -kEisdir; + } else if (is_dir && access != kORdonly) { + return -kEisdir; + } + if (is_dir && (cread || trunc)) + return -kEisdir; + if (excl && cread && exists) return -kEexist; if (!cread && !exists) return -kEnoent; + if (is_dir) { + std::lock_guard lock(mutex_); + int fd = allocate_fd_locked(); + auto entry = std::make_shared(path); + entry->set_status_flags(flags); + table_[fd] = TableSlot{entry, 0}; + return fd; + } + if (cread && !exists) { FILE* creator = fopen(path.c_str(), "ab"); if (creator == nullptr) @@ -567,6 +832,19 @@ int CompatFdTable::create_eventfd(uint64_t initval, int flags) { return fd; } +int CompatFdTable::create_memfd(const std::string& name, int flags) { + using namespace linux_abi; + if ((flags & ~(kMemfdCloexec | kMemfdAllowSealing)) != 0) + return -kEinval; + + std::lock_guard lock(mutex_); + int fd = allocate_fd_locked(); + auto entry = std::make_shared(name); + int fd_flags = (flags & kMemfdCloexec) ? kFdCloexec : 0; + table_[fd] = TableSlot{entry, fd_flags}; + return fd; +} + int CompatFdTable::create_pipe(int pipefds[2], int flags) { (void)flags; if (!pipefds) @@ -646,6 +924,150 @@ bool CompatFdTable::fstat(int fd, StatBuf* statbuf) { return entry->fstat(statbuf); } +int64_t CompatFdTable::getdents64(int fd, void* buf, size_t count, int* err) { + auto entry = get(fd); + if (!entry) { + set_table_err(err, linux_abi::kEbadf); + return -1; + } + return entry->getdents64(buf, count, err); +} + +int CompatFdTable::ioctl(int fd, unsigned long request, void* arg, int* err) { + auto entry = get(fd); + if (!entry) { + set_table_err(err, linux_abi::kEbadf); + return -1; + } + return entry->ioctl(request, arg, err); +} + +int CompatFdTable::poll(PollFd* fds, int nfds, int timeout_ms, int* err) { + using namespace linux_abi; + if (nfds < 0 || (nfds > 0 && fds == nullptr)) { + set_table_err(err, nfds < 0 ? kEinval : kEfault); + return -1; + } + + int64_t deadline_ns = -1; + if (timeout_ms > 0) + deadline_ns = static_cast(platform::monotonic_ns()) + + static_cast(timeout_ms) * 1000000; + + while (true) { + int ready = 0; + for (int i = 0; i < nfds; ++i) { + fds[i].revents = 0; + auto entry = get(fds[i].fd); + if (!entry) { + fds[i].revents = static_cast(kPollNval); + ++ready; + continue; + } + uint32_t mask = entry->readiness(); + int16_t re = 0; + if ((mask & kEpollIn) != 0 && (fds[i].events & kPollIn) != 0) + re = static_cast(re | kPollIn); + if ((mask & kEpollOut) != 0 && (fds[i].events & kPollOut) != 0) + re = static_cast(re | kPollOut); + fds[i].revents = re; + if (re != 0) + ++ready; + } + if (ready > 0) + return ready; + if (timeout_ms == 0) + return 0; + if (deadline_ns >= 0 && static_cast(platform::monotonic_ns()) >= deadline_ns) + return 0; + platform::sleep_ns(1000000); + } +} + +bool CompatFdTable::try_flock_locked(const std::string& key, FdEntry* owner, int op) { + using namespace linux_abi; + const int base = op & ~kFlockNb; + auto it = flocks_.find(key); + + if (base == kFlockUn) { + if (it == flocks_.end()) + return true; + it->second.shared.erase(owner); + if (it->second.exclusive == owner) + it->second.exclusive = nullptr; + if (it->second.exclusive == nullptr && it->second.shared.empty()) + flocks_.erase(it); + return true; + } + if (base != kFlockSh && base != kFlockEx) + return false; + + if (it == flocks_.end()) + it = flocks_.emplace(key, FlockState{}).first; + FlockState& state = it->second; + + if (base == kFlockSh) { + if (state.exclusive != nullptr && state.exclusive != owner) + return false; + state.shared[owner] = 1; + return true; + } + + if (state.exclusive != nullptr && state.exclusive != owner) + return false; + for (const auto& entry : state.shared) { + if (entry.first != owner) + return false; + } + state.shared.erase(owner); + state.exclusive = owner; + return true; +} + +void CompatFdTable::release_locks_locked(FdEntry* entry) { + for (auto it = flocks_.begin(); it != flocks_.end();) { + it->second.shared.erase(entry); + if (it->second.exclusive == entry) + it->second.exclusive = nullptr; + if (it->second.exclusive == nullptr && it->second.shared.empty()) { + it = flocks_.erase(it); + } else { + ++it; + } + } +} + +int CompatFdTable::flock(int fd, int op, int* err) { + using namespace linux_abi; + auto entry = get(fd); + if (!entry) { + set_table_err(err, kEbadf); + return -1; + } + const std::string* path = entry->lock_path(); + std::string key = + path ? *path : "entry:" + std::to_string(reinterpret_cast(entry.get())); + const bool nonblock = (op & kFlockNb) != 0; + const int base = op & ~kFlockNb; + if (base != kFlockSh && base != kFlockEx && base != kFlockUn) { + set_table_err(err, kEinval); + return -1; + } + + while (true) { + { + std::lock_guard lock(mutex_); + if (try_flock_locked(key, entry.get(), op)) + return 0; + } + if (nonblock) { + set_table_err(err, kEagain); + return -1; + } + platform::sleep_ns(1000000); + } +} + int CompatFdTable::dup(int oldfd) { return dup_minfd(oldfd, 0, false); } @@ -657,7 +1079,14 @@ int CompatFdTable::dup2(int oldfd, int newfd) { return -1; if (oldfd == newfd) return newfd; - table_[newfd] = TableSlot{it->second.entry, 0}; + auto existing = table_.find(newfd); + if (existing != table_.end()) { + if (existing->second.entry.use_count() == 1) + release_locks_locked(existing->second.entry.get()); + existing->second.entry->close(); + } + auto entry = it->second.entry; + table_[newfd] = TableSlot{entry, 0}; return newfd; } @@ -721,6 +1150,10 @@ int CompatFdTable::close(int fd) { auto it = table_.find(fd); if (it == table_.end()) return -1; + // flock locks belong to the open file description: dup'ed fds share it, + // so release only when the last descriptor referencing the entry closes. + if (it->second.entry.use_count() == 1) + release_locks_locked(it->second.entry.get()); it->second.entry->close(); table_.erase(it); return 0; diff --git a/src/compat/fd_table.h b/src/compat/fd_table.h index bac5c1a..b3ce080 100644 --- a/src/compat/fd_table.h +++ b/src/compat/fd_table.h @@ -33,6 +33,8 @@ enum class FdType { kEpoll, kEventFd, kPipe, + kDirectory, + kMemFd, }; struct StatBuf { @@ -56,6 +58,13 @@ struct EpollEvent { uint64_t data; }; +// Linux x86_64 struct pollfd (short fields + int fd). +struct PollFd { + int fd; + int16_t events; + int16_t revents; +}; + class CompatFdTable; class FdEntry { @@ -76,6 +85,25 @@ class FdEntry { } virtual void close() = 0; + // getdents64 for directory entries; non-directories report EISDIR. + virtual int64_t getdents64(void* buf, size_t count, int* err) { + (void)buf; + (void)count; + set_err(err, linux_abi::kEnotdir); + return -1; + } + + // ioctl subset (FIONREAD); default reports ENOTTY. + virtual int ioctl(unsigned long request, void* arg, int* err) { + (void)request; + (void)arg; + set_err(err, linux_abi::kEnotty); + return -1; + } + + // Identity used by flock: files share a path; other entries are unique. + virtual const std::string* lock_path() const { return nullptr; } + // Event mask currently reported to epoll (linux_abi::LinuxEpollEventBit). // Default: always ready for read and write (regular files/streams). virtual uint32_t readiness() const { return linux_abi::kEpollIn | linux_abi::kEpollOut; } @@ -103,6 +131,7 @@ class CompatFdTable { ~CompatFdTable(); // Opens a file with LINUX x86_64 O_* flag values (linux_abi::LinuxOpenFlag). + // Directories are opened as guest directory streams (getdents64). // Returns the new fd, or a negative Linux errno (-ENOENT, -EEXIST, ...). int open_file(const std::string& path, int flags, int mode); @@ -110,6 +139,9 @@ class CompatFdTable { // Returns the new fd, or -EINVAL for initval above the kernel ceiling. int create_eventfd(uint64_t initval, int flags); + // Creates an in-process memory file (memfd_create). + int create_memfd(const std::string& name, int flags); + // Creates an in-process guest pipe. int create_pipe(int pipefds[2], int flags); @@ -117,11 +149,20 @@ class CompatFdTable { int epoll_ctl(int epfd, int op, int fd, const EpollEvent* event); int epoll_wait(int epfd, EpollEvent* events, int maxevents, int timeout_ms); + // poll(2) over guest fds. Returns the number of ready descriptors, 0 on + // timeout, or -1 with *err set. + int poll(PollFd* fds, int nfds, int timeout_ms, int* err = nullptr); + + // flock(2) advisory locking (SH/EX/UN, LOCK_NB). + int flock(int fd, int op, int* err = nullptr); + // All return -1 with *err set to the Linux errno on failure. int64_t read(int fd, void* buf, size_t count, int* err = nullptr); int64_t pread64(int fd, void* buf, size_t count, int64_t offset, int* err = nullptr); int64_t write(int fd, const void* buf, size_t count, int* err = nullptr); int64_t lseek(int fd, int64_t offset, int whence, int* err = nullptr); + int64_t getdents64(int fd, void* buf, size_t count, int* err = nullptr); + int ioctl(int fd, unsigned long request, void* arg, int* err = nullptr); bool fstat(int fd, StatBuf* statbuf); int dup(int oldfd); @@ -134,11 +175,19 @@ class CompatFdTable { std::shared_ptr get(int fd); private: + struct FlockState { + FdEntry* exclusive = nullptr; + std::unordered_map shared; + }; + int allocate_fd_locked(int minfd = 0); int dup_minfd_locked(int oldfd, int minfd, bool cloexec); + void release_locks_locked(FdEntry* entry); + bool try_flock_locked(const std::string& key, FdEntry* owner, int op); std::mutex mutex_; std::unordered_map table_; + std::unordered_map flocks_; }; } // namespace compat diff --git a/src/compat/linux_abi.cpp b/src/compat/linux_abi.cpp index 21d140e..6cde89b 100644 --- a/src/compat/linux_abi.cpp +++ b/src/compat/linux_abi.cpp @@ -52,6 +52,35 @@ const SyscallInfo kSyscallTable[] = { "fcntl F_GETFD/F_SETFD (FD_CLOEXEC), F_GETFL/F_SETFL, F_DUPFD/_CLOEXEC in guest fd table"}, {kFsync, "fsync", kEmulated, "synchronizes file and stream buffers in guest fd table"}, + // --- v1.0.6 technical-debt cleanup: previously unsupported calls ------ + {kMremap, "mremap", kPartial, + "in-place shrink and MREMAP_MAYMOVE grow over tracked mappings; " + "MREMAP_FIXED/DONTUNMAP not modeled"}, + {kMadvise, "madvise", kEmulated, + "advice validated; MADV_DONTNEED zeroes anonymous private pages, " + "other advice is a documented no-op"}, + {kFlock, "flock", kEmulated, + "in-process advisory locks per file path (SH/EX/UN, LOCK_NB) over guest fds"}, + {kChdir, "chdir", kEmulated, + "guest cwd tracked by the dispatch; relative paths resolve against it"}, + {kPersonality, "personality", kEmulated, "single Linux persona (PER_LINUX) reported"}, + {kArchPrctl, "arch_prctl", kPartial, + "ARCH_SET/GET_FS/GS values recorded per context; no real TLS base switch"}, + {kSchedSetaffinity, "sched_setaffinity", kEmulated, + "single-CPU affinity model; non-empty masks accepted for the context"}, + {kSchedGetaffinity, "sched_getaffinity", kEmulated, "reports an affinity mask with CPU 0 set"}, + {kGetdents64, "getdents64", kEmulated, + "directory streams opened as guest fds; Linux dirent64 records emitted"}, + {kPpoll, "ppoll", kPartial, + "readiness poll over guest fds; signal mask argument is ignored (signals unsupported)"}, + {kSetRobustList, "set_robust_list", kEmulated, + "registration recorded; futex robust-list processing not modeled"}, + {kMemfdCreate, "memfd_create", kEmulated, + "in-process anonymous memory file with read/write/seek/pread semantics"}, + {kIoctl, "ioctl", kPartial, "FIONREAD only; all other requests return ENOTTY"}, + {kExit, "exit", kEmulated, "flags the emulation context as stopping (thread exit)"}, + {kWait4, "wait4", kEmulated, "no child processes exist; always returns ECHILD"}, + // --- path / filesystem family (host stat/stdio backed) ----------------- {kStat, "stat", kEmulated, "guest path stat via host stat(2); StatBuf is the guest layout"}, {kAccess, "access", kEmulated, "F_OK/R_OK/W_OK/X_OK via host access(2)"}, @@ -84,9 +113,6 @@ const SyscallInfo kSyscallTable[] = { // --- honestly unsupported; these are the hard blockers ----------------- {kRtSigaction, "rt_sigaction", kUnsupported, "Linux signal ABI not implemented on Orbis"}, {kRtSigprocmask, "rt_sigprocmask", kUnsupported, "Linux signal ABI not implemented on Orbis"}, - {kIoctl, "ioctl", kUnsupported, "Linux ioctl subsys vary wildly; none wired"}, - {kMremap, "mremap", kUnsupported, "not implemented"}, - {kMadvise, "madvise", kUnsupported, "not implemented"}, {kSocket, "socket", kUnsupported, "BSD socket domains/families differ from Linux; not wired"}, {kConnect, "connect", kUnsupported, "socket layer not implemented"}, {kAccept, "accept", kUnsupported, "socket layer not implemented"}, @@ -97,24 +123,11 @@ const SyscallInfo kSyscallTable[] = { {kFork, "fork", kUnsupported, "HARD BLOCKER: no process creation API for Orbis payloads"}, {kVfork, "vfork", kUnsupported, "HARD BLOCKER: see fork"}, {kExecve, "execve", kUnsupported, "HARD BLOCKER: no ELF exec loader exposed to payloads"}, - {kExit, "exit", kUnsupported, "thread exit path not implemented"}, - {kWait4, "wait4", kUnsupported, "no child processes exist in the emulation model"}, {kKill, "kill", kUnsupported, "no signal delivery between processes"}, - {kFlock, "flock", kUnsupported, "advisory locks not implemented"}, - {kChdir, "chdir", kUnsupported, "would change the host process cwd; side-effectful, refused"}, {kSigaltstack, "sigaltstack", kUnsupported, "signal ABI not implemented"}, - {kPersonality, "personality", kUnsupported, "not implemented"}, - {kArchPrctl, "arch_prctl", kUnsupported, "not implemented"}, - {kSchedSetaffinity, "sched_setaffinity", kUnsupported, "not implemented"}, - {kSchedGetaffinity, "sched_getaffinity", kUnsupported, "not implemented"}, - {kGetdents64, "getdents64", kUnsupported, - "directory streams not in the fd table; Linux dirent layout not emitted"}, {kTgkill, "tgkill", kUnsupported, "signal ABI not implemented"}, - {kPpoll, "ppoll", kUnsupported, "poll layer not implemented"}, - {kSetRobustList, "set_robust_list", kUnsupported, "not implemented"}, - {kInotifyInit1, "inotify_init1", kUnsupported, "not implemented"}, - {kMemfdCreate, "memfd_create", kUnsupported, - "Linux memfd has no Orbis equivalent; unimplemented"}, + {kInotifyInit1, "inotify_init1", kUnsupported, + "no inotify watch layer in the guest fd table; events would never be delivered"}, }; const int kSyscallTableSize = static_cast(sizeof(kSyscallTable) / sizeof(kSyscallTable[0])); diff --git a/src/compat/linux_abi.h b/src/compat/linux_abi.h index 596d61c..ab596d2 100644 --- a/src/compat/linux_abi.h +++ b/src/compat/linux_abi.h @@ -36,9 +36,11 @@ namespace linux_abi { enum LinuxErrno : int { kEperm = 1, kEnoent = 2, + kEsrch = 3, kEintr = 4, kEio = 5, kEbadf = 9, + kEchild = 10, kEagain = 11, kEnomem = 12, kEaccess = 13, @@ -46,13 +48,17 @@ enum LinuxErrno : int { kEbusy = 16, kEexist = 17, kEnodev = 19, + kEnotdir = 20, + kEisdir = 21, kEinval = 22, kEnfile = 23, kEmfile = 24, + kEnotty = 25, kEnospc = 28, kEpipe = 32, kErange = 34, kEnosys = 38, + kEopnotsupp = 95, kEtimedout = 110, }; @@ -116,8 +122,67 @@ enum LinuxOpenFlag : int { kOTrunc = 0x200, // 01000 kOAppend = 0x400, // 02000 kONonblock = 0x800, // 020000 + kODirectory = 0x10000, }; +// mremap(2) flags (Linux x86_64 UAPI). +enum LinuxMremapFlag : int { + kMremapMaymove = 1, + kMremapFixed = 2, + kMremapDontunmap = 4, +}; + +// madvise(2) advice values (Linux x86_64 UAPI). +enum LinuxMadvise : int { + kMadvNormal = 0, + kMadvRandom = 1, + kMadvSequential = 2, + kMadvWillneed = 3, + kMadvDontneed = 4, + kMadvFree = 8, + kMadvDontfork = 10, + kMadvDontdump = 16, + kMadvDodump = 17, +}; + +// flock(2) operations. +enum LinuxFlockOp : int { + kFlockSh = 1, + kFlockEx = 2, + kFlockNb = 4, + kFlockUn = 8, +}; + +// personality(2) and arch_prctl(2) values. +enum LinuxPersonality : int { + kPerLinux = 0, +}; + +enum LinuxArchPrctl : int { + kArchSetGs = 0x1001, + kArchSetFs = 0x1002, + kArchGetFs = 0x1003, + kArchGetGs = 0x1004, +}; + +// poll(2) event bits and memfd flags. +enum LinuxPollBit : uint32_t { + kPollIn = 0x1, + kPollOut = 0x4, + kPollErr = 0x8, + kPollHup = 0x10, + kPollNval = 0x20, +}; + +enum LinuxMemfdFlag : int { + kMemfdCloexec = 0x1, + kMemfdAllowSealing = 0x2, +}; + +// ioctl(2) requests supported by the guest fd table. +constexpr unsigned long kFionread = 0x541B; +constexpr unsigned long kTiocgwinsz = 0x5413; + // openat/newfstatat/unlinkat dirfd special values and flags (Linux x86_64 UAPI). enum LinuxAtFlag : int { kAtFdcwd = -100, diff --git a/src/compat/memory_compat.cpp b/src/compat/memory_compat.cpp index 86bd0d5..d5b9061 100644 --- a/src/compat/memory_compat.cpp +++ b/src/compat/memory_compat.cpp @@ -93,6 +93,90 @@ MapResult CompatMemory::munmap(uintptr_t address, size_t length) { "experiment"}; } +MapResult CompatMemory::mremap(uintptr_t address, size_t old_length, size_t new_length, int flags) { + if (new_length == 0) { + return {nullptr, linux_abi::kEinval, "mremap new length is zero"}; + } + if ((flags & ~(linux_abi::kMremapMaymove)) != 0) { + return {nullptr, linux_abi::kEinval, + "only MREMAP_MAYMOVE is supported (MREMAP_FIXED/DONTUNMAP refused)"}; + } + for (size_t i = 0; i < mappings_.size(); ++i) { + Mapping& m = mappings_[i]; + if (address != m.addr) + continue; + if (old_length != m.size) { + return {nullptr, linux_abi::kEinval, "old_size must match the tracked mapping size"}; + } + + size_t new_aligned = page_align_up_sz(new_length); + if (new_aligned <= m.size) { + size_t tail = m.size - new_aligned; + if (tail > 0 && + !platform::unmap(reinterpret_cast(address + new_aligned), tail)) { + return {nullptr, linux_abi::kEnomem, "host unmap of the shrink tail failed"}; + } + m.size = new_aligned; + return {reinterpret_cast(address), 0, "mapping shrunk in place"}; + } + + if ((flags & linux_abi::kMremapMaymove) == 0) { + return {nullptr, linux_abi::kEnomem, + "growing requires MREMAP_MAYMOVE (no adjacent free-space tracking)"}; + } + + void* fresh = platform::map_anonymous(new_aligned); + if (fresh == nullptr) { + return {nullptr, linux_abi::kEnomem, "host map_anonymous failed for mremap grow"}; + } + std::memcpy(fresh, reinterpret_cast(address), m.size); + if (!platform::unmap(reinterpret_cast(address), m.size)) { + platform::unmap(fresh, new_aligned); + return {nullptr, linux_abi::kEnomem, "host unmap of the old mapping failed"}; + } + m.addr = reinterpret_cast(fresh); + m.size = new_aligned; + return {fresh, 0, "mapping moved and grown"}; + } + return {nullptr, linux_abi::kEinval, "address is not the start of a tracked mapping"}; +} + +MapResult CompatMemory::madvise(uintptr_t address, size_t length, int advice) { + if (length == 0) { + return {nullptr, linux_abi::kEinval, "madvise length is zero"}; + } + switch (advice) { + case linux_abi::kMadvNormal: + case linux_abi::kMadvRandom: + case linux_abi::kMadvSequential: + case linux_abi::kMadvWillneed: + case linux_abi::kMadvFree: + case linux_abi::kMadvDontfork: + case linux_abi::kMadvDontdump: + case linux_abi::kMadvDodump: + break; + case linux_abi::kMadvDontneed: + for (const Mapping& m : mappings_) { + if (address >= m.addr && address + length <= m.addr + m.size) { + // Anonymous private memory: Linux discards the pages and later + // faults return zeroes. Zeroing is the observable equivalent here. + std::memset(reinterpret_cast(address), 0, length); + return {reinterpret_cast(address), 0, + "MADV_DONTNEED zeroed the anonymous private range"}; + } + } + return {nullptr, linux_abi::kEnomem, "range is not a tracked mapping"}; + default: + return {nullptr, linux_abi::kEinval, "unsupported madvise advice"}; + } + for (const Mapping& m : mappings_) { + if (address >= m.addr && address + length <= m.addr + m.size) { + return {reinterpret_cast(address), 0, "madvise advice accepted (no-op)"}; + } + } + return {nullptr, linux_abi::kEnomem, "range is not a tracked mapping"}; +} + MapResult CompatMemory::mprotect(uintptr_t address, size_t length, int prot) { if (length == 0) { return {nullptr, linux_abi::kEinval, "mprotect length is zero"}; diff --git a/src/compat/memory_compat.h b/src/compat/memory_compat.h index e9784c6..a8ec22f 100644 --- a/src/compat/memory_compat.h +++ b/src/compat/memory_compat.h @@ -48,6 +48,14 @@ class CompatMemory { // Linux mprotect: R/W honored; PROT_EXEC recorded but not granted. MapResult mprotect(uintptr_t address, size_t length, int prot); + // Linux mremap: in-place shrink and MREMAP_MAYMOVE grow of a tracked + // anonymous mapping. MREMAP_FIXED / MREMAP_DONTUNMAP are refused. + MapResult mremap(uintptr_t address, size_t old_length, size_t new_length, int flags); + + // Linux madvise over tracked anonymous private memory. MADV_DONTNEED + // zeroes the range; other accepted advice values are documented no-ops. + MapResult madvise(uintptr_t address, size_t length, int advice); + // Linux brk: brk(0) -> current break; brk(addr) -> new break or the // unchanged current break when the request cannot be honored. BrkResult brk(uintptr_t request); @@ -67,7 +75,6 @@ class CompatMemory { size_t size; int prot; }; - bool commit_pages(uintptr_t addr, size_t len); // Heap (brk) arena diff --git a/src/compat/syscall_dispatch.cpp b/src/compat/syscall_dispatch.cpp index 3237af6..3498c5c 100644 --- a/src/compat/syscall_dispatch.cpp +++ b/src/compat/syscall_dispatch.cpp @@ -58,11 +58,58 @@ int host_errno_to_linux() { return errno; } +std::string normalize_path(const std::string& in) { + bool absolute = !in.empty() && in[0] == '/'; + std::vector parts; + size_t start = 0; + while (start <= in.size()) { + size_t slash = in.find('/', start); + std::string part = + in.substr(start, slash == std::string::npos ? std::string::npos : slash - start); + if (!part.empty() && part != ".") { + if (part == "..") { + if (!parts.empty()) + parts.pop_back(); + } else { + parts.push_back(part); + } + } + if (slash == std::string::npos) + break; + start = slash + 1; + } + + std::string out = absolute ? "/" : ""; + for (size_t i = 0; i < parts.size(); ++i) { + if (i > 0) + out += "/"; + out += parts[i]; + } + if (out.empty()) + return absolute ? "/" : "."; + return out; +} + } // namespace 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_(0x50534400ull | (platform::monotonic_ns() & 0xffffull)) { + char cwd[4096]; + if (::getcwd(cwd, sizeof(cwd)) != nullptr) + guest_cwd_ = normalize_path(cwd); + else + guest_cwd_ = "/"; +} + +std::string SyscallDispatch::resolve_path(const char* path) const { + if (path == nullptr) + return {}; + std::string p(path); + if (p.empty() || p[0] != '/') + p = guest_cwd_ + "/" + p; + return normalize_path(p); +} DispatchResult SyscallDispatch::ok(int64_t ret, const char* note) { return DispatchResult{ret, 0, true, note}; @@ -112,6 +159,27 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return ok(0, r.note); } + case kMremap: { + uintptr_t addr = static_cast(args.a[0]); + size_t old_len = static_cast(args.a[1]); + size_t new_len = static_cast(args.a[2]); + int flags = static_cast(args.a[3]); + MapResult r = memory_->mremap(addr, old_len, new_len, flags); + if (r.address == nullptr) + return fail(r.linux_errno, r.note); + return ok(reinterpret_cast(r.address), r.note); + } + + case kMadvise: { + uintptr_t addr = static_cast(args.a[0]); + size_t len = static_cast(args.a[1]); + int advice = static_cast(args.a[2]); + MapResult r = memory_->madvise(addr, len, advice); + if (r.address == nullptr) + return fail(r.linux_errno, r.note); + return ok(0, r.note); + } + case kBrk: { uintptr_t req = static_cast(args.a[0]); BrkResult r = memory_->brk(req); @@ -131,7 +199,8 @@ 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"); - int fd = fd_table_->open_file(path, flags, mode); + std::string resolved = resolve_path(path); + int fd = fd_table_->open_file(resolved, flags, mode); if (fd < 0) return fail(-fd, "open failed with guest errno"); return ok(fd, "guest fd allocated (Linux O_* flags)"); @@ -250,13 +319,14 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return fail(kEfault, "path is null"); if (!st) return fail(kEfault, "statbuf is null"); + std::string resolved = resolve_path(path); struct stat host_st; int rc; if (linux_nr == kNewfstatat && (static_cast(static_cast(args.a[3])) & kAtSymlinkNofollow) != 0) { - rc = ::lstat(path, &host_st); + rc = ::lstat(resolved.c_str(), &host_st); } else { - rc = ::stat(path, &host_st); + rc = ::stat(resolved.c_str(), &host_st); } if (rc != 0) { int he = host_errno_to_linux(); @@ -274,7 +344,8 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { if (mode != kFOk && mode != kROk && mode != kWOk && mode != kXOk && mode != (kROk | kWOk) && mode != (kROk | kXOk) && mode != (kWOk | kXOk) && mode != (kROk | kWOk | kXOk)) return fail(kEinval, "invalid access mode"); - if (::access(path, mode) != 0) { + std::string resolved = resolve_path(path); + if (::access(resolved.c_str(), mode) != 0) { int he = host_errno_to_linux(); return fail(he == 0 ? kEaccess : he, "access failed"); } @@ -286,7 +357,8 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { int mode = static_cast(args.a[1]); if (!path) return fail(kEfault, "path is null"); - if (::mkdir(path, static_cast(mode)) != 0) { + std::string resolved = resolve_path(path); + if (::mkdir(resolved.c_str(), static_cast(mode)) != 0) { int he = host_errno_to_linux(); return fail(he == 0 ? kEio : he, "mkdir failed"); } @@ -297,7 +369,8 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { const char* path = reinterpret_cast(args.a[0]); if (!path) return fail(kEfault, "path is null"); - if (::unlink(path) != 0) { + std::string resolved = resolve_path(path); + if (::unlink(resolved.c_str()) != 0) { int he = host_errno_to_linux(); return fail(he == 0 ? kEnoent : he, "unlink failed"); } @@ -312,14 +385,15 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return fail(kEfault, "null argument"); if (bufsiz == 0) return fail(kEinval, "bufsiz must be positive"); - if (std::strcmp(path, "/proc/self/exe") == 0) { + std::string resolved = resolve_path(path); + if (resolved == "/proc/self/exe") { const char* self = "ps5droid"; size_t len = std::strlen(self); size_t copy_len = std::min(bufsiz, len); std::memcpy(buf, self, copy_len); return ok(static_cast(copy_len), "/proc/self/exe simulated link"); } - ssize_t rc = ::readlink(path, buf, bufsiz); + ssize_t rc = ::readlink(resolved.c_str(), buf, bufsiz); if (rc < 0) { int he = host_errno_to_linux(); return fail(he == 0 ? kEnoent : he, "readlink failed"); @@ -327,6 +401,22 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return ok(static_cast(rc), "host readlink ok"); } + case kChdir: { + const char* path = reinterpret_cast(args.a[0]); + if (!path) + return fail(kEfault, "path is null"); + std::string resolved = resolve_path(path); + struct stat host_st; + if (::stat(resolved.c_str(), &host_st) != 0) { + int he = host_errno_to_linux(); + return fail(he == 0 ? kEnoent : he, "chdir path does not exist"); + } + if (!S_ISDIR(host_st.st_mode)) + return fail(kEnotdir, "chdir target is not a directory"); + guest_cwd_ = resolved; + return ok(0, "guest cwd updated"); + } + case kGetcwd: { char* buf = reinterpret_cast(args.a[0]); size_t size = static_cast(args.a[1]); @@ -334,12 +424,10 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return fail(kEfault, "buffer is null"); if (size == 0) return fail(kEinval, "size must be positive"); - if (::getcwd(buf, size) == nullptr) { - int he = host_errno_to_linux(); - return fail(he == kErange ? kErange : (he == 0 ? kErange : he), - "cwd does not fit the buffer"); - } - return ok(static_cast(strlen(buf)), "host process cwd"); + if (size <= guest_cwd_.size()) + return fail(kErange, "cwd does not fit the buffer"); + std::memcpy(buf, guest_cwd_.c_str(), guest_cwd_.size() + 1); + return ok(static_cast(guest_cwd_.size()), "guest cwd"); } case kGettimeofday: { @@ -515,6 +603,84 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return ok(static_cast(platform::current_thread_id()), "set_tid_address ok"); } + case kPersonality: { + unsigned long persona = static_cast(args.a[0]); + if (persona == 0xfffffffful) + return ok(kPerLinux, "current persona is PER_LINUX"); + if (persona != kPerLinux) + return fail(kEinval, "only PER_LINUX persona is supported"); + return ok(kPerLinux, "previous persona was PER_LINUX"); + } + + case kArchPrctl: { + int code = static_cast(args.a[0]); + uint64_t addr = args.a[1]; + if (code == kArchSetFs) { + fs_base_ = addr; + return ok(0, "ARCH_SET_FS value recorded (no real TLS switch)"); + } + if (code == kArchSetGs) { + gs_base_ = addr; + return ok(0, "ARCH_SET_GS value recorded (no real TLS switch)"); + } + if (code == kArchGetFs || code == kArchGetGs) { + if (addr == 0) + return fail(kEfault, "arch_prctl result pointer is null"); + *reinterpret_cast(addr) = code == kArchGetFs ? fs_base_ : gs_base_; + return ok(0, "arch_prctl base value returned"); + } + return fail(kEinval, "unsupported arch_prctl code"); + } + + case kSchedSetaffinity: { + int pid = static_cast(static_cast(args.a[0])); + size_t len = static_cast(args.a[1]); + const void* mask = reinterpret_cast(args.a[2]); + if (pid != 0 && static_cast(pid) != context_id_) + return fail(kEsrch, "no such process in the single-process model"); + if (len < sizeof(uint64_t)) + return fail(kEinval, "affinity mask is smaller than one CPU word"); + if (!mask) + return fail(kEfault, "affinity mask is null"); + bool any = false; + const uint8_t* bytes = static_cast(mask); + for (size_t i = 0; i < len; ++i) + any = any || bytes[i] != 0; + if (!any) + return fail(kEinval, "affinity mask selects no CPU"); + return ok(0, "single-CPU affinity accepted"); + } + + case kSchedGetaffinity: { + int pid = static_cast(static_cast(args.a[0])); + size_t len = static_cast(args.a[1]); + void* mask = reinterpret_cast(args.a[2]); + if (pid != 0 && static_cast(pid) != context_id_) + return fail(kEsrch, "no such process in the single-process model"); + if (len < sizeof(uint64_t)) + return fail(kEinval, "affinity mask is smaller than one CPU word"); + if (!mask) + return fail(kEfault, "affinity mask is null"); + std::memset(mask, 0, len); + *static_cast(mask) = 1; // CPU 0 + return ok(0, "affinity mask reports CPU 0"); + } + + case kSetRobustList: { + robust_list_ = args.a[0]; + robust_list_len_ = static_cast(args.a[1]); + return ok(0, "robust futex list registered (processing not modeled)"); + } + + case kWait4: { + return fail(kEchild, "no child processes exist in the emulation model"); + } + + case kExit: { + stop_requested_ = true; + return ok(0, "thread exit requested"); + } + case kFsync: { if (!fd_table_) return fail(kEbadf, "no fd table"); @@ -536,6 +702,66 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { return ok(rc, "fcntl ok"); } + case kFlock: { + int fd = static_cast(static_cast(args.a[0])); + int op = static_cast(args.a[1]); + int err = 0; + if (fd_table_->flock(fd, op, &err) != 0) + return fail(err != 0 ? err : kEbadf, "flock failed"); + return ok(0, "flock ok"); + } + + case kGetdents64: { + int fd = static_cast(static_cast(args.a[0])); + void* buf = reinterpret_cast(args.a[1]); + size_t count = static_cast(args.a[2]); + int err = 0; + int64_t n = fd_table_->getdents64(fd, buf, count, &err); + if (n < 0) + return fail(err != 0 ? err : kEbadf, "getdents64 failed"); + return ok(n, "directory entries emitted"); + } + + case kIoctl: { + int fd = static_cast(static_cast(args.a[0])); + unsigned long request = static_cast(args.a[1]); + void* arg = reinterpret_cast(args.a[2]); + int err = 0; + if (fd_table_->ioctl(fd, request, arg, &err) != 0) + return fail(err != 0 ? err : kEnotty, "ioctl failed"); + return ok(0, "ioctl ok"); + } + + case kPpoll: { + PollFd* fds = reinterpret_cast(args.a[0]); + int nfds = static_cast(static_cast(args.a[1])); + const TimespecView* timeout = reinterpret_cast(args.a[2]); + int timeout_ms = -1; + if (timeout != nullptr) { + if (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec > 999999999) + return fail(kEinval, "invalid ppoll timespec"); + uint64_t ns = static_cast(timeout->tv_sec) * 1000000000ull + + static_cast(timeout->tv_nsec); + timeout_ms = static_cast((ns + 999999ull) / 1000000ull); + } + int err = 0; + int n = fd_table_->poll(fds, nfds, timeout_ms, &err); + if (n < 0) + return fail(err != 0 ? err : kEinval, "ppoll failed"); + return ok(n, n > 0 ? "ready descriptors reported" : "ppoll timed out"); + } + + case kMemfdCreate: { + const char* name = reinterpret_cast(args.a[0]); + int flags = static_cast(args.a[1]); + if (!name) + return fail(kEfault, "memfd name is null"); + int fd = fd_table_->create_memfd(name, flags); + if (fd < 0) + return fail(-fd, "memfd_create failed"); + return ok(fd, "in-process memory file created"); + } + case kUnlinkat: { int dirfd = static_cast(static_cast(args.a[0])); const char* path = reinterpret_cast(args.a[1]); @@ -547,11 +773,12 @@ DispatchResult SyscallDispatch::invoke(int linux_nr, const SyscallArgs& args) { if ((flags & ~kAtRemovedir) != 0) return fail(kEinval, "unsupported unlinkat flags"); + std::string resolved = resolve_path(path); int rc; if ((flags & kAtRemovedir) != 0) { - rc = ::rmdir(path); + rc = ::rmdir(resolved.c_str()); } else { - rc = ::unlink(path); + rc = ::unlink(resolved.c_str()); } if (rc != 0) { int he = host_errno_to_linux(); diff --git a/src/compat/syscall_dispatch.h b/src/compat/syscall_dispatch.h index df2df41..8d42e4c 100644 --- a/src/compat/syscall_dispatch.h +++ b/src/compat/syscall_dispatch.h @@ -60,11 +60,18 @@ class SyscallDispatch { DispatchResult fail(int err, const char* note); DispatchResult nosys(const char* note); + std::string resolve_path(const char* path) const; + CompatMemory* memory_; CompatFdTable* fd_table_; CompatFdTable default_fd_table_; uint64_t context_id_; bool stop_requested_ = false; + std::string guest_cwd_; + uint64_t fs_base_ = 0; + uint64_t gs_base_ = 0; + uint64_t robust_list_ = 0; + size_t robust_list_len_ = 0; }; } // namespace compat diff --git a/src/platform/filesystem.cpp b/src/platform/filesystem.cpp index 9b4b000..54f41c0 100644 --- a/src/platform/filesystem.cpp +++ b/src/platform/filesystem.cpp @@ -52,6 +52,11 @@ bool file_exists(const std::string& path) { return stat(path.c_str(), &st) == 0; } +bool is_directory(const std::string& path) { + struct stat st; + return stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode); +} + bool remove_file(const std::string& path) { return remove(path.c_str()) == 0; } diff --git a/src/platform/platform.h b/src/platform/platform.h index 7bc7ff6..1d18386 100644 --- a/src/platform/platform.h +++ b/src/platform/platform.h @@ -155,6 +155,7 @@ class Futex { bool read_file(const std::string& path, std::string* out); bool write_file(const std::string& path, const void* data, size_t len); bool file_exists(const std::string& path); +bool is_directory(const std::string& path); bool remove_file(const std::string& path); bool make_dir(const std::string& path, int mode); std::vector list_dir(const std::string& path); diff --git a/src/version.h b/src/version.h index 212931c..325889a 100644 --- a/src/version.h +++ b/src/version.h @@ -7,6 +7,6 @@ namespace ps5droid { -inline constexpr const char* kVersion = "1.0.5"; +inline constexpr const char* kVersion = "1.0.6"; } // namespace ps5droid diff --git a/tests/test_binder_and_apk.cpp b/tests/test_binder_and_apk.cpp index 318f60d..bf5db6d 100644 --- a/tests/test_binder_and_apk.cpp +++ b/tests/test_binder_and_apk.cpp @@ -306,6 +306,139 @@ PS5DROID_TEST(apk_inspection_basic) { ps5droid::platform::remove_file(path); } +PS5DROID_TEST(apk_inspection_deflated_manifest) { + // AndroidManifest.xml compressed with a DYNAMIC Huffman block (zlib + // level 6, wbits=-15). Real APKs use this block type; v1.0.5 could not + // read them. + static const uint8_t kCompressedManifest[] = { + 237, 150, 193, 74, 195, 64, 16, 134, 255, 164, 105, 154, 26, 67, 114, 168, 32, 212, + 139, 224, 81, 115, 19, 189, 10, 22, 17, 164, 136, 22, 15, 222, 214, 100, 45, 75, + 154, 100, 201, 70, 161, 120, 237, 51, 120, 243, 89, 117, 182, 93, 105, 136, 250, 2, + 146, 9, 31, 187, 204, 254, 255, 36, 153, 203, 108, 15, 30, 194, 33, 96, 225, 0, + 190, 5, 4, 48, 65, 251, 91, 108, 195, 39, 246, 136, 99, 226, 140, 184, 34, 30, + 9, 78, 40, 226, 141, 88, 17, 239, 196, 7, 225, 121, 57, 43, 196, 51, 87, 53, + 6, 3, 201, 146, 140, 205, 57, 70, 163, 178, 154, 199, 82, 157, 166, 85, 41, 210, + 56, 93, 22, 44, 23, 9, 105, 95, 20, 87, 39, 42, 205, 16, 4, 185, 40, 238, + 211, 236, 129, 87, 74, 148, 5, 162, 168, 102, 213, 156, 215, 141, 148, 231, 177, 164, + 22, 175, 162, 94, 194, 247, 153, 148, 11, 145, 176, 90, 31, 244, 251, 11, 246, 196, + 23, 112, 221, 203, 101, 113, 33, 37, 194, 112, 93, 87, 242, 42, 23, 106, 237, 117, + 28, 122, 35, 199, 120, 204, 138, 205, 39, 108, 207, 226, 235, 233, 108, 114, 55, 157, + 204, 96, 91, 17, 206, 55, 29, 192, 167, 9, 221, 130, 17, 61, 150, 105, 135, 206, + 233, 189, 173, 127, 21, 232, 233, 85, 251, 110, 90, 190, 158, 241, 217, 13, 159, 99, + 86, 242, 69, 251, 102, 223, 111, 228, 14, 77, 173, 163, 86, 45, 215, 212, 250, 142, + 78, 211, 105, 58, 77, 167, 233, 52, 157, 230, 63, 107, 218, 179, 120, 128, 159, 179, + 152, 230, 38, 232, 22, 179, 158, 197, 195, 63, 124, 59, 191, 248, 244, 181, 102, 215, + 248, 244, 250, 5}; + const uint32_t kUncompressedSize = 2319; + + CHECK_MSG(((kCompressedManifest[0] >> 1) & 3) == 2, "fixture must use a dynamic Huffman block"); + + std::vector zip; + auto push16 = [&](uint16_t v) { + zip.push_back(static_cast(v & 0xFF)); + zip.push_back(static_cast((v >> 8) & 0xFF)); + }; + auto push32 = [&](uint32_t v) { + zip.push_back(static_cast(v & 0xFF)); + zip.push_back(static_cast((v >> 8) & 0xFF)); + zip.push_back(static_cast((v >> 16) & 0xFF)); + zip.push_back(static_cast((v >> 24) & 0xFF)); + }; + + push32(0x04034b50); + push16(20); + push16(0); + push16(8); // DEFLATE + push16(0); + push16(0); + push32(0); + push32(static_cast(sizeof(kCompressedManifest))); + push32(kUncompressedSize); + const std::string fn = "AndroidManifest.xml"; + push16(static_cast(fn.size())); + push16(0); + zip.insert(zip.end(), fn.begin(), fn.end()); + zip.insert(zip.end(), kCompressedManifest, kCompressedManifest + sizeof(kCompressedManifest)); + + const std::string dex = "classes.dex"; + const std::string dex_data = "dex\n035\0"; + push32(0x04034b50); + push16(20); + push16(0); + push16(0); + push16(0); + push16(0); + push32(0); + push32(static_cast(dex_data.size())); + push32(static_cast(dex_data.size())); + push16(static_cast(dex.size())); + push16(0); + zip.insert(zip.end(), dex.begin(), dex.end()); + zip.insert(zip.end(), dex_data.begin(), dex_data.end()); + + std::string path = "test_dynamic_manifest.apk"; + CHECK_MSG(ps5droid::platform::write_file(path, zip.data(), zip.size()), "fixture write failed"); + + ApkInspection apk = inspect_apk(path); + CHECK_MSG(apk.is_apk, "APK detection failed"); + CHECK_MSG(apk.has_manifest, "manifest entry must be detected"); + CHECK_MSG(apk.has_classes_dex, "classes.dex must be detected"); + CHECK_MSG(apk.package_name == "org.ps5droid.dynamic", "dynamic manifest package mismatch"); + CHECK_MSG(apk.min_sdk_version == 24, "dynamic manifest minSdk mismatch"); + CHECK_MSG(apk.target_sdk_version == 33, "dynamic manifest targetSdk mismatch"); + CHECK_MSG(apk.activity_count == 50, "dynamic manifest activity count mismatch"); + CHECK_MSG(apk.app_label == "DynApp", "dynamic manifest label mismatch"); + CHECK_MSG(apk.permissions.size() == 1 && apk.permissions[0] == "android.permission.INTERNET", + "dynamic manifest permission mismatch"); + CHECK_MSG(apk.package_note.find("parsed binary AXML") != std::string::npos, + "package note must report AXML success"); + + ps5droid::platform::remove_file(path); +} + +PS5DROID_TEST(deflate_dynamic_huffman_block) { + // Raw DEFLATE stream produced by zlib level 6 (wbits=-15) for the + // payload reconstructed below. Its first block is BTYPE=2 (dynamic + // Huffman), which the v1.0.5 decoder rejected. + static const uint8_t kDynamic[] = { + 237, 214, 61, 14, 130, 64, 16, 134, 225, 171, 16, 122, 151, 202, 198, 172, 116, + 20, 22, 82, 24, 46, 48, 129, 149, 76, 12, 11, 97, 209, 132, 219, 75, 252, + 137, 71, 96, 13, 111, 253, 204, 219, 78, 62, 219, 137, 215, 171, 11, 83, 50, + 72, 125, 147, 214, 29, 211, 126, 108, 205, 16, 246, 205, 216, 107, 99, 154, 217, + 75, 167, 117, 154, 91, 169, 39, 125, 232, 52, 39, 226, 95, 116, 88, 96, 185, + 62, 139, 250, 52, 131, 97, 24, 254, 67, 190, 7, 23, 118, 131, 27, 59, 13, + 65, 123, 159, 188, 245, 115, 107, 126, 96, 78, 101, 85, 92, 202, 162, 34, 34, + 34, 218, 84, 148, 125, 87, 82, 110, 217, 75, 48, 12, 111, 150, 35, 127, 213, + 68, 68, 68, 236, 37, 24, 134, 225, 213, 57, 242, 87, 77, 68, 68, 196, 94, + 130, 97, 24, 94, 157, 35, 127, 213, 68, 68, 68, 209, 236, 165, 39}; + + std::string payload; + const std::string manifest = ""; + const std::string activity = ""; + const std::string permission = ""; + for (int i = 0; i < 4; ++i) { + payload += manifest; + for (int j = 0; j < 40; ++j) + payload += activity; + for (int j = 0; j < 20; ++j) + payload += permission; + payload += ""; + } + + CHECK_MSG(((kDynamic[0] >> 1) & 3) == 2, "test vector must be a dynamic block"); + + std::vector out; + CHECK_MSG(inflate_deflate(kDynamic, sizeof(kDynamic), &out, payload.size()), + "dynamic Huffman inflate failed"); + CHECK_MSG(out.size() == payload.size(), "inflated size mismatch"); + CHECK_MSG(memcmp(out.data(), payload.data(), payload.size()) == 0, "inflated bytes mismatch"); + + // Truncated input must fail cleanly instead of reading past the buffer. + std::vector truncated; + CHECK_MSG(!inflate_deflate(kDynamic, 40, &truncated, payload.size()), + "truncated dynamic stream must be rejected"); +} + PS5DROID_TEST(build_prop_parsing) { std::string content = "# Android build properties\n" "ro.build.version.release=11\n" diff --git a/tests/test_bionic_and_fd.cpp b/tests/test_bionic_and_fd.cpp index 18ac737..eb520ac 100644 --- a/tests/test_bionic_and_fd.cpp +++ b/tests/test_bionic_and_fd.cpp @@ -112,7 +112,7 @@ PS5DROID_TEST(fd_table_fcntl_and_flags) { } PS5DROID_TEST(bionic_loader_hdr_and_stack) { - // Construct fake ELF64 header + // Construct fake ELF64 header with one PT_LOAD covering the headers. uint8_t elf_bytes[128] = {0}; elf_bytes[0] = 0x7f; elf_bytes[1] = 'E'; @@ -121,9 +121,53 @@ PS5DROID_TEST(bionic_loader_hdr_and_stack) { elf_bytes[4] = 2; // 64-bit elf_bytes[18] = 62; // x86_64 + // e_phoff = 64, e_phentsize = 56, e_phnum = 1 + uint64_t phoff = 64; + memcpy(elf_bytes + 32, &phoff, sizeof(phoff)); + uint16_t phentsize = 56; + memcpy(elf_bytes + 54, &phentsize, sizeof(phentsize)); + uint16_t phnum = 1; + memcpy(elf_bytes + 56, &phnum, sizeof(phnum)); + + // RawElf64Phdr at offset 64: PT_LOAD, offset 0, vaddr 0x400000, filesz 200 + uint8_t* ph = elf_bytes + 64; + uint32_t p_type = 1; + uint32_t p_flags = 5; + uint64_t p_offset = 0; + uint64_t p_vaddr = 0x400000; + uint64_t p_filesz = 200; + memcpy(ph + 0, &p_type, sizeof(p_type)); + memcpy(ph + 4, &p_flags, sizeof(p_flags)); + memcpy(ph + 8, &p_offset, sizeof(p_offset)); + memcpy(ph + 16, &p_vaddr, sizeof(p_vaddr)); + memcpy(ph + 32, &p_filesz, sizeof(p_filesz)); + BionicElfInfo info = BionicLoader::parse_header(elf_bytes, sizeof(elf_bytes)); CHECK_MSG(info.valid, "ELF header parse failed"); + CHECK_MSG(info.phdr_addr == 0x400000 + 64, "AT_PHDR address must come from PT_LOAD"); - auto stack = BionicLoader::setup_initial_stack(info, {"app"}, {"ENV=1"}); + const uint64_t base = 0x1000; + auto stack = BionicLoader::setup_initial_stack(info, {"app", "--flag"}, {"ENV=1"}, base); CHECK_MSG(!stack.empty(), "stack setup failed"); + + const uint64_t* words = reinterpret_cast(stack.data()); + CHECK_MSG(words[0] == 2, "argc must be 2"); + + auto string_at = [&](uint64_t pointer) -> const char* { + if (pointer < base || pointer - base >= stack.size()) + return nullptr; + return reinterpret_cast(stack.data() + (pointer - base)); + }; + CHECK_MSG(string_at(words[1]) != nullptr && strcmp(string_at(words[1]), "app") == 0, + "argv[0] must point at real bytes"); + CHECK_MSG(string_at(words[2]) != nullptr && strcmp(string_at(words[2]), "--flag") == 0, + "argv[1] must point at real bytes"); + CHECK_MSG(words[3] == 0, "argv must be NULL-terminated"); + CHECK_MSG(string_at(words[4]) != nullptr && strcmp(string_at(words[4]), "ENV=1") == 0, + "envp[0] must point at real bytes"); + CHECK_MSG(words[5] == 0, "envp must be NULL-terminated"); + + // auxv starts after envp; AT_PHDR must carry the derived address. + CHECK_MSG(words[6] == 3, "AT_PHDR must be the first auxv entry"); + CHECK_MSG(words[7] == 0x400000 + 64, "AT_PHDR value must match phdr_addr"); } diff --git a/tests/test_compat_debt.cpp b/tests/test_compat_debt.cpp new file mode 100644 index 0000000..5e4f589 --- /dev/null +++ b/tests/test_compat_debt.cpp @@ -0,0 +1,494 @@ +// PS5Droid - v1.0.6 technical-debt cleanup syscall tests. +// +// Every syscall exercised here moved out of the UNSUPPORTED column in +// v1.0.6. The tests prove real behavior (or the documented partial +// semantics) rather than stubs. +#include "test_framework.h" + +#include +#include +#include + +#include + +#include "compat/memory_compat.h" +#include "compat/syscall_dispatch.h" +#include "platform/platform.h" + +using namespace ps5droid::compat; +using namespace ps5droid::linux_abi; + +namespace { + +struct GuestTimespec { + int64_t tv_sec; + int64_t tv_nsec; +}; + +void* map_anon(SyscallDispatch* d, size_t len) { + SyscallArgs a{}; + a.a[1] = len; + a.a[2] = kProtRead | kProtWrite; + a.a[3] = kMapPrivate | kMapAnonymous; + a.a[4] = static_cast(-1); + DispatchResult r = d->invoke(kMmap, a); + return r.ret > 0 ? reinterpret_cast(r.ret) : nullptr; +} + +} // namespace + +PS5DROID_TEST(mremap_and_madvise) { + CompatMemory mem; + SyscallDispatch d(&mem); + + uint8_t* p = static_cast(map_anon(&d, 4096)); + CHECK_MSG(p != nullptr, "initial mmap failed"); + memset(p, 0x5A, 4096); + + // Grow with MREMAP_MAYMOVE: contents preserved, address may move. + SyscallArgs grow{}; + grow.a[0] = reinterpret_cast(p); + grow.a[1] = 4096; + grow.a[2] = 8192; + grow.a[3] = kMremapMaymove; + DispatchResult g = d.invoke(kMremap, grow); + CHECK_MSG(g.ret > 0, "mremap MAYMOVE grow failed"); + uint8_t* grown = reinterpret_cast(g.ret); + CHECK_MSG(grown[0] == 0x5A && grown[4095] == 0x5A, "mremap grow lost data"); + memset(grown + 4096, 0xA5, 4096); + + // Grow without MAYMOVE is refused. + SyscallArgs no_move{}; + no_move.a[0] = reinterpret_cast(grown); + no_move.a[1] = 8192; + no_move.a[2] = 16384; + no_move.a[3] = 0; + DispatchResult nm = d.invoke(kMremap, no_move); + CHECK_MSG(nm.ret == -1 && nm.err == kEnomem, "grow without MAYMOVE must ENOMEM"); + + // Shrink in place. + SyscallArgs shrink{}; + shrink.a[0] = reinterpret_cast(grown); + shrink.a[1] = 8192; + shrink.a[2] = 4096; + shrink.a[3] = 0; + DispatchResult s = d.invoke(kMremap, shrink); + CHECK_MSG(s.ret == static_cast(reinterpret_cast(grown)), + "shrink must keep the address"); + + // MADV_DONTNEED zeroes the anonymous private range. + SyscallArgs adv{}; + adv.a[0] = reinterpret_cast(grown); + adv.a[1] = 4096; + adv.a[2] = kMadvDontneed; + CHECK_MSG(d.invoke(kMadvise, adv).ret == 0, "MADV_DONTNEED failed"); + CHECK_MSG(grown[0] == 0 && grown[4095] == 0, "MADV_DONTNEED must zero pages"); + + SyscallArgs normal{}; + normal.a[0] = reinterpret_cast(grown); + normal.a[1] = 4096; + normal.a[2] = kMadvNormal; + CHECK_MSG(d.invoke(kMadvise, normal).ret == 0, "MADV_NORMAL failed"); + + SyscallArgs bad{}; + bad.a[0] = reinterpret_cast(grown); + bad.a[1] = 4096; + bad.a[2] = 12345; + DispatchResult br = d.invoke(kMadvise, bad); + CHECK_MSG(br.ret == -1 && br.err == kEinval, "unknown advice must EINVAL"); + + SyscallArgs unmap{}; + unmap.a[0] = reinterpret_cast(grown); + unmap.a[1] = 4096; + CHECK_MSG(d.invoke(kMunmap, unmap).ret == 0, "munmap failed"); +} + +PS5DROID_TEST(chdir_tracks_guest_cwd) { + CompatMemory mem; + SyscallDispatch d(&mem); + + const std::string dir = "ps5droid_cwd_probe.dir"; + const std::string inner = dir + "/inner.tmp"; + ps5droid::platform::remove_file(inner); + ps5droid::platform::make_dir(dir, 0755); + + char original[512] = {0}; + SyscallArgs cwd{}; + cwd.a[0] = reinterpret_cast(original); + cwd.a[1] = sizeof(original); + CHECK_MSG(d.invoke(kGetcwd, cwd).ret > 0, "getcwd before chdir failed"); + + SyscallArgs ch{}; + ch.a[0] = reinterpret_cast(dir.c_str()); + CHECK_MSG(d.invoke(kChdir, ch).ret == 0, "chdir into temp dir failed"); + + char after[512] = {0}; + cwd.a[0] = reinterpret_cast(after); + cwd.a[1] = sizeof(after); + CHECK_MSG(d.invoke(kGetcwd, cwd).ret > 0, "getcwd after chdir failed"); + CHECK_MSG(std::string(after).find(dir) != std::string::npos, + "guest cwd must include the new directory"); + + // Relative open/stat resolve against the guest cwd. + SyscallArgs open{}; + open.a[0] = reinterpret_cast("inner.tmp"); + open.a[1] = kOCreat | kOTrunc | kORdwr; + DispatchResult orr = d.invoke(kOpen, open); + CHECK_MSG(orr.ret >= 3, "relative open failed"); + + StatBuf st{}; + SyscallArgs stat_args{}; + stat_args.a[0] = reinterpret_cast("inner.tmp"); + stat_args.a[1] = reinterpret_cast(&st); + CHECK_MSG(d.invoke(kStat, stat_args).ret == 0, "relative stat failed"); + CHECK_MSG(st.st_size == 0, "new file size must be zero"); + + SyscallArgs close_args{}; + close_args.a[0] = static_cast(orr.ret); + d.invoke(kClose, close_args); + + // Missing target and non-directory target report the Linux errno. + SyscallArgs missing{}; + missing.a[0] = reinterpret_cast("no_such_dir_ps5droid"); + DispatchResult mr = d.invoke(kChdir, missing); + CHECK_MSG(mr.ret == -1 && mr.err == kEnoent, "missing chdir target must ENOENT"); + + SyscallArgs file_target{}; + file_target.a[0] = reinterpret_cast("inner.tmp"); + DispatchResult fr = d.invoke(kChdir, file_target); + CHECK_MSG(fr.ret == -1 && fr.err == kEnotdir, "file chdir target must ENOTDIR"); + + // Return to the original directory with an absolute path. + SyscallArgs back{}; + back.a[0] = reinterpret_cast(original); + CHECK_MSG(d.invoke(kChdir, back).ret == 0, "chdir back failed"); + + ps5droid::platform::remove_file(inner); + rmdir(dir.c_str()); +} + +PS5DROID_TEST(personality_arch_prctl_affinity_robust_wait_exit) { + CompatMemory mem; + SyscallDispatch d(&mem); + + SyscallArgs persona{}; + CHECK_MSG(d.invoke(kPersonality, persona).ret == kPerLinux, + "personality must report PER_LINUX"); + persona.a[0] = 0xffffffffull; + CHECK_MSG(d.invoke(kPersonality, persona).ret == kPerLinux, "personality query failed"); + persona.a[0] = 1; + CHECK_MSG(d.invoke(kPersonality, persona).ret == -1, "unknown persona must fail"); + + uint64_t fs_value = 0; + SyscallArgs set_fs{}; + set_fs.a[0] = kArchSetFs; + set_fs.a[1] = 0xdeadbeefull; + CHECK_MSG(d.invoke(kArchPrctl, set_fs).ret == 0, "ARCH_SET_FS failed"); + SyscallArgs get_fs{}; + get_fs.a[0] = kArchGetFs; + get_fs.a[1] = reinterpret_cast(&fs_value); + CHECK_MSG(d.invoke(kArchPrctl, get_fs).ret == 0, "ARCH_GET_FS failed"); + CHECK_MSG(fs_value == 0xdeadbeefull, "ARCH_GET_FS value mismatch"); + get_fs.a[0] = 999; + CHECK_MSG(d.invoke(kArchPrctl, get_fs).ret == -1, "unknown arch_prctl must fail"); + + uint64_t mask = 1; + SyscallArgs set_aff{}; + set_aff.a[0] = 0; + set_aff.a[1] = sizeof(mask); + set_aff.a[2] = reinterpret_cast(&mask); + CHECK_MSG(d.invoke(kSchedSetaffinity, set_aff).ret == 0, "sched_setaffinity failed"); + + uint64_t got_mask = 0; + SyscallArgs get_aff{}; + get_aff.a[0] = 0; + get_aff.a[1] = sizeof(got_mask); + get_aff.a[2] = reinterpret_cast(&got_mask); + CHECK_MSG(d.invoke(kSchedGetaffinity, get_aff).ret == 0, "sched_getaffinity failed"); + CHECK_MSG(got_mask == 1, "affinity must report CPU 0"); + + uint64_t empty_mask = 0; + set_aff.a[2] = reinterpret_cast(&empty_mask); + CHECK_MSG(d.invoke(kSchedSetaffinity, set_aff).ret == -1, "empty affinity mask must fail"); + + SyscallArgs robust{}; + robust.a[0] = 0x1234; + robust.a[1] = 24; + CHECK_MSG(d.invoke(kSetRobustList, robust).ret == 0, "set_robust_list failed"); + + DispatchResult wr = d.invoke(kWait4, {}); + CHECK_MSG(wr.ret == -1 && wr.err == kEchild, "wait4 must ECHILD"); + + CHECK_MSG(!d.stop_requested(), "context must start running"); + CHECK_MSG(d.invoke(kExit, {}).ret == 0, "exit must return 0"); + CHECK_MSG(d.stop_requested(), "exit must flag the context"); +} + +PS5DROID_TEST(flock_advisory_locks) { + CompatMemory mem; + CompatFdTable fdt; + SyscallDispatch d(&mem, &fdt); + + const std::string path = "ps5droid_flock_probe.tmp"; + SyscallArgs open{}; + open.a[0] = reinterpret_cast(path.c_str()); + open.a[1] = kOCreat | kOTrunc | kORdwr; + int fd1 = static_cast(d.invoke(kOpen, open).ret); + int fd2 = static_cast(d.invoke(kOpen, open).ret); + CHECK_MSG(fd1 >= 3 && fd2 >= 3 && fd1 != fd2, "two opens failed"); + + SyscallArgs lk{}; + lk.a[0] = static_cast(fd1); + lk.a[1] = kFlockEx | kFlockNb; + CHECK_MSG(d.invoke(kFlock, lk).ret == 0, "exclusive lock failed"); + + lk.a[0] = static_cast(fd2); + DispatchResult conflict = d.invoke(kFlock, lk); + CHECK_MSG(conflict.ret == -1 && conflict.err == kEagain, + "conflicting exclusive lock must EAGAIN"); + + lk.a[1] = kFlockSh | kFlockNb; + conflict = d.invoke(kFlock, lk); + CHECK_MSG(conflict.ret == -1 && conflict.err == kEagain, + "shared lock must conflict with exclusive"); + + lk.a[0] = static_cast(fd1); + lk.a[1] = kFlockUn; + CHECK_MSG(d.invoke(kFlock, lk).ret == 0, "unlock failed"); + + lk.a[0] = static_cast(fd2); + lk.a[1] = kFlockSh | kFlockNb; + CHECK_MSG(d.invoke(kFlock, lk).ret == 0, "shared lock after unlock failed"); + + lk.a[0] = static_cast(fd1); + lk.a[1] = kFlockEx | kFlockNb; + conflict = d.invoke(kFlock, lk); + CHECK_MSG(conflict.ret == -1 && conflict.err == kEagain, + "exclusive lock must conflict with shared"); + + lk.a[0] = static_cast(fd2); + lk.a[1] = kFlockUn; + CHECK_MSG(d.invoke(kFlock, lk).ret == 0, "shared unlock failed"); + + lk.a[0] = static_cast(fd1); + lk.a[1] = kFlockEx | kFlockNb; + CHECK_MSG(d.invoke(kFlock, lk).ret == 0, "exclusive lock after shared unlock failed"); + + // dup shares the open file description: closing one fd keeps the lock + // until the last descriptor is gone. + SyscallArgs dup_args{}; + dup_args.a[0] = static_cast(fd1); + DispatchResult dup_res = d.invoke(kDup, dup_args); + CHECK_MSG(dup_res.ret >= 3, "dup failed"); + int dup_fd = static_cast(dup_res.ret); + + SyscallArgs cl{}; + cl.a[0] = static_cast(fd1); + d.invoke(kClose, cl); + + lk.a[0] = static_cast(fd2); + conflict = d.invoke(kFlock, lk); + CHECK_MSG(conflict.ret == -1 && conflict.err == kEagain, + "lock must survive closing one dup'ed descriptor"); + + lk.a[0] = static_cast(dup_fd); + CHECK_MSG(d.invoke(kFlock, lk).ret == 0, "dup'ed descriptor shares the lock"); + + cl.a[0] = static_cast(dup_fd); + d.invoke(kClose, cl); + lk.a[0] = static_cast(fd2); + CHECK_MSG(d.invoke(kFlock, lk).ret == 0, "last close must release the lock"); + + cl.a[0] = static_cast(fd2); + d.invoke(kClose, cl); + ps5droid::platform::remove_file(path); +} + +PS5DROID_TEST(memfd_and_fionread) { + CompatMemory mem; + CompatFdTable fdt; + SyscallDispatch d(&mem, &fdt); + + SyscallArgs create{}; + create.a[0] = reinterpret_cast("ps5droid-memfd"); + create.a[1] = kMemfdCloexec; + DispatchResult cr = d.invoke(kMemfdCreate, create); + CHECK_MSG(cr.ret >= 3, "memfd_create failed"); + int fd = static_cast(cr.ret); + + const char* text = "memfd payload"; + SyscallArgs wr{}; + wr.a[0] = static_cast(fd); + wr.a[1] = reinterpret_cast(text); + wr.a[2] = strlen(text); + CHECK_MSG(d.invoke(kWrite, wr).ret == static_cast(strlen(text)), "memfd write failed"); + + SyscallArgs seek{}; + seek.a[0] = static_cast(fd); + seek.a[1] = 0; + seek.a[2] = 0; + CHECK_MSG(d.invoke(kLseek, seek).ret == 0, "memfd seek failed"); + + int available = 0; + SyscallArgs ioctl_args{}; + ioctl_args.a[0] = static_cast(fd); + ioctl_args.a[1] = kFionread; + ioctl_args.a[2] = reinterpret_cast(&available); + CHECK_MSG(d.invoke(kIoctl, ioctl_args).ret == 0, "FIONREAD failed"); + CHECK_MSG(available == static_cast(strlen(text)), "FIONREAD count mismatch"); + + char buf[32] = {0}; + SyscallArgs rd{}; + rd.a[0] = static_cast(fd); + rd.a[1] = reinterpret_cast(buf); + rd.a[2] = sizeof(buf); + CHECK_MSG(d.invoke(kRead, rd).ret == static_cast(strlen(text)), "memfd read failed"); + CHECK_MSG(strcmp(buf, text) == 0, "memfd data mismatch"); + + StatBuf st{}; + SyscallArgs fst{}; + fst.a[0] = static_cast(fd); + fst.a[1] = reinterpret_cast(&st); + CHECK_MSG(d.invoke(kFstat, fst).ret == 0, "memfd fstat failed"); + CHECK_MSG(st.st_size == static_cast(strlen(text)), "memfd size mismatch"); + + ioctl_args.a[1] = kTiocgwinsz; + DispatchResult notty = d.invoke(kIoctl, ioctl_args); + CHECK_MSG(notty.ret == -1 && notty.err == kEnotty, "unsupported ioctl must ENOTTY"); + + create.a[1] = 0x4000; + DispatchResult bad_flags = d.invoke(kMemfdCreate, create); + CHECK_MSG(bad_flags.ret == -1 && bad_flags.err == kEinval, "unknown memfd flags must EINVAL"); + + SyscallArgs cl{}; + cl.a[0] = static_cast(fd); + d.invoke(kClose, cl); +} + +PS5DROID_TEST(getdents64_directory_stream) { + CompatMemory mem; + CompatFdTable fdt; + SyscallDispatch d(&mem, &fdt); + + const std::string dir = "ps5droid_dents_probe.dir"; + ps5droid::platform::make_dir(dir, 0755); + ps5droid::platform::write_file(dir + "/alpha", "a", 1); + ps5droid::platform::write_file(dir + "/beta", "b", 1); + + SyscallArgs open{}; + open.a[0] = reinterpret_cast(dir.c_str()); + open.a[1] = kORdonly | kODirectory; + DispatchResult orr = d.invoke(kOpen, open); + CHECK_MSG(orr.ret >= 3, "directory open failed"); + int fd = static_cast(orr.ret); + + uint8_t buffer[512]; + SyscallArgs gd{}; + gd.a[0] = static_cast(fd); + gd.a[1] = reinterpret_cast(buffer); + gd.a[2] = sizeof(buffer); + DispatchResult r = d.invoke(kGetdents64, gd); + CHECK_MSG(r.ret > 0, "getdents64 returned no records"); + + std::vector names; + size_t offset = 0; + while (offset + 19 <= static_cast(r.ret)) { + uint16_t reclen = 0; + memcpy(&reclen, buffer + offset + 16, sizeof(reclen)); + CHECK_MSG(reclen >= 19 && offset + reclen <= static_cast(r.ret), + "invalid dirent64 record length"); + names.emplace_back(reinterpret_cast(buffer + offset + 19)); + offset += reclen; + } + CHECK_MSG(names.size() == 4, "expected . .. alpha beta"); + CHECK_MSG(names[0] == "." && names[1] == "..", "dot entries must come first"); + CHECK_MSG(names[2] == "alpha" && names[3] == "beta", "directory names mismatch"); + + DispatchResult eof = d.invoke(kGetdents64, gd); + CHECK_MSG(eof.ret == 0, "second getdents64 must report EOF"); + + // O_DIRECTORY on a regular file is ENOTDIR. + const std::string file = dir + "/alpha"; + open.a[0] = reinterpret_cast(file.c_str()); + DispatchResult notdir = d.invoke(kOpen, open); + CHECK_MSG(notdir.ret == -1 && notdir.err == kEnotdir, "O_DIRECTORY on file must ENOTDIR"); + + // getdents64 on a regular fd is ENOTDIR. + open.a[0] = reinterpret_cast(file.c_str()); + open.a[1] = kORdonly; + int file_fd = static_cast(d.invoke(kOpen, open).ret); + gd.a[0] = static_cast(file_fd); + DispatchResult not_dir = d.invoke(kGetdents64, gd); + CHECK_MSG(not_dir.ret == -1 && not_dir.err == kEnotdir, + "getdents64 on regular file must ENOTDIR"); + + SyscallArgs cl{}; + cl.a[0] = static_cast(fd); + d.invoke(kClose, cl); + cl.a[0] = static_cast(file_fd); + d.invoke(kClose, cl); + + ps5droid::platform::remove_file(file); + ps5droid::platform::remove_file(dir + "/beta"); + rmdir(dir.c_str()); +} + +PS5DROID_TEST(ppoll_readiness_and_nval) { + CompatMemory mem; + CompatFdTable fdt; + SyscallDispatch d(&mem, &fdt); + + int pipefds[2] = {-1, -1}; + SyscallArgs pipe_args{}; + pipe_args.a[0] = reinterpret_cast(pipefds); + CHECK_MSG(d.invoke(kPipe2, pipe_args).ret == 0, "pipe2 failed"); + + const char* msg = "ready"; + SyscallArgs wr{}; + wr.a[0] = static_cast(pipefds[1]); + wr.a[1] = reinterpret_cast(msg); + wr.a[2] = strlen(msg); + CHECK_MSG(d.invoke(kWrite, wr).ret == static_cast(strlen(msg)), "pipe write failed"); + + PollFd pollfd{}; + pollfd.fd = pipefds[0]; + pollfd.events = kPollIn; + GuestTimespec zero{0, 0}; + SyscallArgs pp{}; + pp.a[0] = reinterpret_cast(&pollfd); + pp.a[1] = 1; + pp.a[2] = reinterpret_cast(&zero); + DispatchResult r = d.invoke(kPpoll, pp); + CHECK_MSG(r.ret == 1 && pollfd.revents == kPollIn, "ppoll must report POLLIN"); + + // Invalid fd is reported as POLLNVAL. + PollFd bad{}; + bad.fd = 999; + bad.events = kPollIn; + pp.a[0] = reinterpret_cast(&bad); + r = d.invoke(kPpoll, pp); + CHECK_MSG(r.ret == 1 && bad.revents == kPollNval, "invalid fd must report POLLNVAL"); + + // Drain the pipe and wait briefly: no readiness, timeout returns 0. + char drain[16]; + SyscallArgs rd{}; + rd.a[0] = static_cast(pipefds[0]); + rd.a[1] = reinterpret_cast(drain); + rd.a[2] = sizeof(drain); + d.invoke(kRead, rd); + + PollFd empty{}; + empty.fd = pipefds[0]; + empty.events = kPollIn; + GuestTimespec short_wait{0, 2000000}; // 2 ms + pp.a[0] = reinterpret_cast(&empty); + pp.a[2] = reinterpret_cast(&short_wait); + r = d.invoke(kPpoll, pp); + CHECK_MSG(r.ret == 0 && empty.revents == 0, "ppoll must time out with no readiness"); + + SyscallArgs cl{}; + cl.a[0] = static_cast(pipefds[0]); + d.invoke(kClose, cl); + cl.a[0] = static_cast(pipefds[1]); + d.invoke(kClose, cl); +} diff --git a/tests/test_compat_dispatch.cpp b/tests/test_compat_dispatch.cpp index d9b25e9..50d553e 100644 --- a/tests/test_compat_dispatch.cpp +++ b/tests/test_compat_dispatch.cpp @@ -171,7 +171,7 @@ PS5DROID_TEST(write_passthrough) { PS5DROID_TEST(honest_enosys_for_blockers) { CompatMemory mem; SyscallDispatch d(&mem); - const int blocked[] = {kClone, kFork, kExecve, kSocket, kChdir}; + const int blocked[] = {kClone, kFork, kExecve, kSocket, kRtSigaction}; for (int nr : blocked) { SyscallArgs a{}; DispatchResult r = d.invoke(nr, a); diff --git a/tests/test_compat_matrix.cpp b/tests/test_compat_matrix.cpp index 384395e..83536ea 100644 --- a/tests/test_compat_matrix.cpp +++ b/tests/test_compat_matrix.cpp @@ -19,7 +19,7 @@ PS5DROID_TEST(table_entries_valid) { CHECK_MSG(kSyscallTableSize >= 70, "table suspiciously small"); } -PS5DROID_TEST(matrix_counts_match_v1_0_5_release) { +PS5DROID_TEST(matrix_counts_match_v1_0_6_release) { int emulated = 0, partial = 0, unsupported = 0; for (int i = 0; i < kSyscallTableSize; ++i) { switch (kSyscallTable[i].support) { @@ -34,10 +34,10 @@ PS5DROID_TEST(matrix_counts_match_v1_0_5_release) { break; } } - CHECK_MSG(emulated == 46, "46 emulated syscalls in v1.0.5"); - CHECK_MSG(partial == 4, "4 partial syscalls in v1.0.5"); - CHECK_MSG(unsupported == 30, "30 unsupported syscalls in v1.0.5"); - CHECK_MSG(kSyscallTableSize == 80, "80 tracked syscalls in v1.0.5"); + CHECK_MSG(emulated == 57, "57 emulated syscalls in v1.0.6"); + CHECK_MSG(partial == 8, "8 partial syscalls in v1.0.6"); + CHECK_MSG(unsupported == 15, "15 unsupported syscalls in v1.0.6"); + CHECK_MSG(kSyscallTableSize == 80, "80 tracked syscalls in v1.0.6"); } PS5DROID_TEST(names_resolve) { diff --git a/tests/test_screens.cpp b/tests/test_screens.cpp index 6e05202..966dd6e 100644 --- a/tests/test_screens.cpp +++ b/tests/test_screens.cpp @@ -64,7 +64,7 @@ PS5DROID_TEST(matrix_screen_pages_and_counts) { CHECK_MSG(p0.page_count > 1, "matrix must be paged for a small budget"); CHECK_MSG(p0.page == 0, "requested page echoed"); CHECK_MSG(p0.lines.size() <= 6, "page respects the line budget"); - CHECK_MSG(p0.lines[1].text.find("EMU 46") != std::string::npos, + CHECK_MSG(p0.lines[1].text.find("EMU 57") != std::string::npos, "summary must cite the release counts"); ui::MatrixPage last = ui::matrix_screen_lines(matrix, 9999, 6);