Compare commits

...
Author SHA1 Message Date
spoopyghosty0 6a71734552 fexrift perf: default settings launch exactly like the verified headset run
First Contact and Dreamdeck didn't render in the headset with the new defaults, which differed from the launch
verified in the headset on 2026-10-10: a regenerated Revive eye-scale copy, a dxvk.conf and
WINE_LARGE_ADDRESS_AWARE=1. Defaults now add none of them (eye scale 1.5 = the uploaded Revive itself, no
dxvk.conf unless a DXVK setting changed, large-address-aware off); a changed setting still applies at launch.
2026-10-16 11:06:39 -04:00
spoopyghosty0 3441f3ee39 fexrift bench: report SteamVR's IMU fallback (no tracking universe)
Without a tracking universe Rift games wait at startup and a headless run only counts SteamVR's own frames
(~1.9/s, game GPU ~0 %): First Contact, Dreamdeck and Chronos all looked broken on the Frame (2026-10-16). The
summary now carries imu_fallback (SteamVR logged "Rejecting new committed universe since IMU fallback is active"
during the run) and such a run is never valid.
2026-10-16 10:51:18 -04:00
spoopyghosty0 b9a9757a64 fexrift bench: Steam's controller log isn't owner input once the game starts
The starting OpenVR game loads its input bindings, which writes Steam's controller.txt: the bench stopped itself
("owner interaction (activity 0)") with Dreamdeck. During the wait and the window only activity 1 (headset
worn/moved) stops it; the controller log stays a pre-start guard.
2026-10-16 10:41:11 -04:00
spoopyghosty0 f9f3a63e0c fexrift install: launch arguments from the PC's Meta app library
Meta launches many Rift games with arguments (Unreal: -vr) that only its manifest carries. A copy installed from
elsewhere now takes the launch arguments of the same build (same exe name) from this PC's Meta Horizon/Oculus
libraries (Program Files + the libraries registered under HKCU\Software\Oculus VR, LLC\Oculus\Libraries),
matched by app ID or canonical name.
2026-10-16 10:07:37 -04:00
spoopyghosty0 95fd2e5b0b fexrift install: a folder from a Meta app library uses Meta's manifest
Installing <library>/Software/<name> (e.g. the Windows Meta app's C:\Program Files\Meta Horizon\Software) takes
exe, launch arguments, app ID and version from <library>/Manifests/<name>.json. Unreal Rift games need its
-vr argument (Dreamdeck: -fullscreen -vr), which nothing else provided for a folder install.
2026-10-16 09:54:43 -04:00
spoopyghosty0 98f91abe97 fexrift: per-game ime_patch "off"; Chronos renders without the IME fix
On the Frame Chronos (UE 4.10) with the generic IME patch (found at member +0x100) connected to SteamVR but never
submitted a frame; with its original exe a bounded headless run submitted 202 frames in 105 s. The profile can
now turn the finder off (ime_patch: "off"), set for Chronos.
2026-10-16 09:33:54 -04:00
spoopyghosty0 5eb6c8389d fexrift bench: start the window when the game's process appears
The launcher waits 60-100 s for Meta's runtime before it starts the game, so a 90 s window ended before the
game existed (0 frames on the Frame). The bench now waits up to START_WAIT (180 s) for the game's process,
still stopping on real interaction, and the agent/CLI timeouts grow to match (agent 94).
2026-10-16 09:26:24 -04:00
spoopyghosty0 c811dbabe5 fexrift bench: the launched game waking the compositor isn't owner interaction
The run must start with the headset in standby (activity 3), but the game itself takes it out of standby, so
the first Frame run stopped itself after a few seconds. During the run only activity 1 (worn/moved) or new
controller input stops it; the error names the level.
2026-10-16 09:22:10 -04:00
spoopyghosty0 14a58443d3 fexrift bench: SteamVR settings writes in their own process
Reproduced on the Frame: cmd_vrsetting in the process holding the bench's VR() connection segfaults on its second
call. The bench's first write (pauseCompositorOnStandby=false) succeeded and the second (screen timeout)
crashed it, leaving the display on. vr_set now runs fexrift.py vrsetting in a fresh process per write and checks
its answer.
2026-10-16 09:20:40 -04:00
spoopyghosty0 e27dce210f fexrift bench: measure in a child, restore the display even if it crashes
On the Frame the bench helper died silently before launching the game and left SteamVR's
pauseCompositorOnStandby=false (display kept on): a native crash in the ctypes SteamVR calls skips Python's
finally. The measurement now runs in a forked child that records the original screen timeout and the game's
process group in a guard file; when no result comes back the parent kills the game group, runs wineserver -k and
restores both display settings, each through its own vrsetting process.
2026-10-16 09:19:23 -04:00
spoopyghosty0 5e38e4b46e fexrift: re-upload the helper scripts before every install
Only fex setup uploaded fexrift.py, its extensions and games json, so a helper fixed on the PC never reached
a Frame set up earlier (the Frame kept the old runtime probe: Chronos timed out although the runtime listed
it as installed). sync_helpers uploads them (~200 KB) at the start of both install paths.
2026-10-16 00:50:22 -04:00
spoopyghosty0 387c0eb28c fexrift: Meta's session folder is <user id>-<n>, not only digits
The signed-in PC prefix names it sessions/<numeric user id>-<n>/ (7dcb601 required digits only and refused
that prefix for import-login).
2026-10-15 23:57:08 -04:00
spoopyghosty0 7dcb601792 fexrift: a Meta sign-in is sessions/<user id>/, not any file in sessions/
On the Frame Meta's app framework created sessions/_oaf/data.sqlite as soon as the runtime started (the
install's runtime probe), so fex status said login: true without a sign-in. A real sign-in (PC prefix,
2026-10-09) adds sessions/<numeric Meta user id>/. fex login's done signal looked for files directly under
sessions/, which a real sign-in never has: it would have waited forever. One check (signed_in) for status,
fex login and the PC import.
2026-10-15 23:52:41 -04:00
spoopyghosty0 3733a38e4e fexrift install: count Meta's 'Currently installed package' line as registered
On the Frame the runtime lists every registered package at start (PackageManager "Currently installed
package: lies-beneath, version code: 1") but writes no "state:" line before an app tracker / sign-in, so the
probe timed out although the registration worked. Seen with Lies Beneath, 2026-10-15.
2026-10-15 20:43:47 -04:00
spoopyghosty0 e1c16a4bf2 fexrift perf: accept the Revive upload fex setup actually makes
prepare_scales hashed the upload after undoing the eye-size redirect but compared it with the hash of the
upload as made (with the redirect): setup failed on the device. Compare the raw upload against both valid
forms; a new test runs prepare_scales on the real Revive 3.2.0 DLL patched like setup does.
2026-10-15 20:06:15 -04:00
spoopyghosty0 61d728fd21 fexrift artifacts: fp_pipesend.exe (Meta sign-in callback) and fp_mem v3 (FP_MEM_ZERO)
Built from native/fexwine/pipesend.c with llvm-mingw 20261006 and fp_mem.c with gcc (glibc 2.34 symbols),
both with -ffile-prefix-map; SHA256SUMS updated.
2026-10-15 19:59:20 -04:00
spoopyghosty0 122845308f agent 93: fex login/local-install/settings/bench commands 2026-10-15 19:58:12 -04:00
spoopyghosty0 451b4d6e5b fexrift: one per-game dxvk.conf for compat profiles and perf settings
With the perf extension loaded the compat profile's dxvk lines go into perf_prepare's per-game config (its
managed keys win) instead of a second DXVK_CONFIG_FILE that perf overrode. perf_prepare creates the settings
folder itself (a first launch without settings_set failed). Compat launcher test expects the per-game core
mask; the temporary-handler test only checks the handler's own files.
2026-10-15 19:54:45 -04:00
spoopyghosty0 c21126ec7d Merge rift/perf: launch-time perf settings, fp_mem zero-on-reuse, bounded bench
# Conflicts:
#	agent/fexrift.py
2026-10-15 19:42:16 -04:00
spoopyghosty0 879bcbf9b0 Merge rift/compat: per-game profiles, graphics routes, triage
# Conflicts:
#	agent/fexrift.py
2026-10-15 19:41:38 -04:00
spoopyghosty0 351a1af31d Merge rift/login: sign in to Meta on the Frame
# Conflicts:
#	agent/frameport_agent.py
2026-10-15 19:41:09 -04:00
spoopyghosty0 5739646ce1 Merge rift/install: install local Rift copies + Meta library registration 2026-10-15 19:40:31 -04:00
spoopyghosty0 6b002d0799 Validate login callbacks, broker expiry and desktop handler quoting 2026-10-15 19:40:06 -04:00
spoopyghosty0 6b4e50cf7c Record offline validation and preserve direct OpenVR survey profiles 2026-10-15 19:37:12 -04:00
spoopyghosty0 30b1c78b99 Tighten benchmark attribution and document Rift performance experiments 2026-10-15 19:37:04 -04:00
spoopyghosty0 45563c5047 Add surveyed Rift game profiles and maintainer validation steps 2026-10-15 19:33:57 -04:00
spoopyghosty0 58489eeb75 Document local Rift installation device validation 2026-10-15 19:32:42 -04:00
spoopyghosty0 0ce121f2dc Harden local Rift resume and runtime probing 2026-10-15 19:32:00 -04:00
spoopyghosty0 06b289f7fc Stop the Meta sign-in launcher before restoring browser handlers 2026-10-15 19:30:57 -04:00
spoopyghosty0 25ac577365 Add launch-time Rift performance settings and bounded benchmarks 2026-10-15 19:28:36 -04:00
spoopyghosty0 c9240670d4 Add Meta browser sign-in for the Frame FEX prefix 2026-10-15 19:28:00 -04:00
spoopyghosty0 ebda4d644a Install local Rift copies in FEX Meta libraries 2026-10-15 19:26:22 -04:00
spoopyghosty0 9e96fb8fb4 Add FEX compatibility profiles, graphics routes and runtime diagnostics 2026-10-15 19:26:18 -04:00
spoopyghosty0 98786ab110 fexrift: per-game data in fexrift_games.json, extension modules per area
GAMES moves to agent/fexrift_games.json (uploaded with the helper). fexrift.py loads fexrift_<area>.py
extensions (login, install, compat, perf) by path; each registers commands and launcher-env / install-check
hooks and reads the core's live globals. The PC uploads every fexrift*.py/json, release bundles carry
.txt copies of all of them. Launcher and install accept a game_dir outside Meta's library.
2026-10-15 19:14:43 -04:00
spoopyghosty0 18f45702de fexrift: keep build paths out of the arm64 wineserver
The committed wineserver.arm64 carried its Frame build folder in wine's assert paths, which main's
test_no_local_paths_in_artifacts rejects. The 41-byte prefix is replaced in place by one of the same
length (code and offsets unchanged), SHA256SUMS updated, and build_wineserver.sh now maps source and
build dirs with -ffile-prefix-map.
2026-10-15 17:44:54 -04:00
spoopyghosty0 3b71e5a560 rift_fex_survey: static survey of Rift games for the FEX mode
Engine, VR APIs and the Platform SDK from FramePort's Rift analysis; Unreal version from the branch string
(any ++… form naming a version) else the pak format's range; the RHI from DefaultEngine.ini (TargetedRHIs /
DefaultGraphicsRHI, else Unreal's D3D11 default) instead of the import list, which names every RHI; pak
indexes v1-v11 (v10+ bit-packed entries + full directory index, zlib/gzip; encrypted index and Oodle noted);
IME fix site in the exe or modular ApplicationCore/Slate; CryEngine detected. The report stays in the user
data dir (local paths).
2026-10-15 17:38:48 -04:00
spoopyghosty0 c023ea28f7 fexrift: generic install (manifest exe/args, Unreal IME fix found in the binaries, --force-unverified)
GAMES keeps only verified games and their per-game opt-ins (fp_mem, msaa_ini). Any other game Meta's app
downloaded gets its exe and launch arguments from Meta's manifest, the IME-deadlock fix located by
find_ime_patch (also in modular ApplicationCore/Slate DLLs) and static checks (engine, imported graphics
DLLs); installing it needs --force-unverified. import-login takes --app. Launcher arguments are quoted,
the title sanitised. Lint fixes in the fexrift files.
2026-10-15 17:38:46 -04:00
spoopyghosty0 8b1e2cdf43 fex install: mark --msaa as unverified (both Steam launches with r.MobileMSAA=2 never rendered) 2026-10-15 17:38:45 -04:00
spoopyghosty0 633fcde50d fexrift launcher: gamescope's WSI layer off, no Steam overlay preload
Started from Steam, gamescope's Vulkan WSI layer took over First Contact's desktop mirror window, which gamescope
doesn't show while SteamVR runs: the game delivered about one frame a second (research launches, started outside
Steam, never had the layer and ran at 72 fps).
2026-10-15 17:38:44 -04:00
spoopyghosty0 d063bad128 fexrift: register Meta's default library in the prefix
Found on the device: in a fresh prefix with an imported login, Meta's runtime listed First Contact as
"install_available" (no HKCU\Software\Oculus VR, LLC\Oculus\Libraries entry, which Meta's app had written in
the research prefix), so the game waited forever at startup when launched from Steam. The prefix fixes now write
DefaultLibrary + its OriginalPath/Path (C: by its volume name) like Meta's app; the runtime then reports the game
"ready" (checked on the dev Frame).
2026-10-15 17:38:43 -04:00
spoopyghosty0 90cb7b575e fexrift: copy Revive's files without their permission bits (a system install's are read-only) 2026-10-15 17:38:42 -04:00
spoopyghosty0 e1bc723f71 Experimental: Rift games with Meta's runtime on the Frame alone (CLI, FRAMEPORT_EXPERIMENTAL_FEX=1)
Step 1 of making the Rift-on-Frame research usable: a hidden `frameport fex` group (setup, import-login,
install, status) that sets up x86_64 GE-Proton under FEX + Meta's PC runtime + Revive on the Frame and installs
Oculus First Contact as a Steam game.

- agent/fexrift.py (Frame, stdlib): GE-Proton11-7 x86_64 (SHA-512), FEX wrappers + native arm64 wineserver,
  patched DLLs, x86 GnuTLS from the Arch archive (repo SHA-256), Vulkan thunk, prefix, Meta's runtime from Meta's
  CDN with Meta's signature checks, prefix fixes, login import (owner-only, archive deleted), per-game fixes
  (First Contact IME deadlock patch, optional r.MobileMSAA) and the launcher (ntsync, fp_mem, motion smoothing
  off for the game, OVRLibrarian ended, cores 4-7)
- agent v77: fex_prepare/status/setup/import_login/install, kind frame_fex (uninstall keeps the shared prefix,
  launch tests refused)
- src/frameport/fexrift.py: uploads the helper + artifacts/fexrift + Revive 3.2.0 with 6 byte patches (other
  builds refused), packs the login from a signed-in PC prefix
- artifacts/fexrift: crypt32/sechost/dnsapi/DeviceWatcher DLLs rebuilt from GE's exact source +
  native/fexwine/patches (build_pe_dlls.sh; exports = GE's + 8 DnsService*), Wi-Fi WinRT stand-in, wineserver.arm64,
  fp_mem.so, DigiCert Assured ID Root CA (public)
- tests/test_fexrift.py (16 tests)

Not yet run end to end on the device.
2026-10-15 17:38:39 -04:00
spoopyghosty0 73839b2dda Research: fp_mem cache default 12 regions / 6 GB
Second headset run (MSAA off + multi-block cache): frames shown once 83 -> 95 %, shown twice 16 -> 3.2 %,
~125 ms hitches 17 -> 6; 95 of 101 released blocks were reused. The remaining long hitches came when ~2 GB
were already kept and new blocks did not fit the 3 GB cap.
2026-10-15 17:38:00 -04:00
spoopyghosty0 e4f9ca6bd3 Research: fp_mem keeps several big blocks and reuses them at other sizes
In the headset First Contact allocates and releases 0.5-1.6 GB blocks, often several at once (~100-128k page
faults per 100 ms, RSS up to 3.5 GB), which the single exact-size cache missed: 17 hitches of ~125 ms in 4 min.
Up to 8 kept regions (3 GB), reuse by start address (shorter: rest released, longer: only the tail mapped fresh),
no protection change while kept. PC test: same size 41.6 -> 1.7 ms, shorter 31.5 -> 1.6 ms, longer 95.5 -> 25.1 ms.
2026-10-15 17:37:59 -04:00
spoopyghosty0 aa9c605ccc Research: native arm64 wineserver + ntsync and a big-block cache fix First Contact's hitches under FEX
native/fexwine: prep_ge_wine.sh recreates GE-Proton's exact Wine source, build_wineserver.sh builds a
native aarch64 wineserver from it (same protocol as GE's x86_64 server, x86_64 machine model), fp_mem.c is
a guest preload that keeps Unreal's 514 MB block between uses instead of re-faulting it.
Headless on the dev Frame: hitches 17 -> 0 per 20 s, timed-out frames 40 % -> 5.5 %.
2026-10-15 17:37:57 -04:00
spoopyghosty0 607b0946da Research note: Meta login under Wine and Oculus First Contact running in VR on the Frame (stutters, CPU-bound) 2026-10-15 17:37:56 -04:00
spoopyghosty0 772d08a1a1 Research note: Rift Platform SDK handshake on the Frame blocked by OVRLibrarian never exiting under FEX 2026-10-15 17:37:55 -04:00
spoopyghosty0 d32c49d4f5 CLAUDE.md: Rift via x86_64 Wine under FEX (research): x86_64 GE-Proton + Revive injection + OpenVR to SteamVR work headless; Platform SDK / Meta app is the blocker 2026-10-15 17:37:54 -04:00
spoopyghosty0 b9a1fe67bc CLAUDE.md: document the GitHub triage workflow
Consolidates the reusable mechanics: issue templates/labels, the
working-recipe -> catalog path (scripts/catalog_from_issue.py), handling
diagnostics zips (and the attachment-vs-placeholder gotcha), how a change
reaches users (catalog ~6 h vs code needing a release/dev build, and not
bumping a shared revision for a narrow fix), and verifying a device fix
headless. Identity/credentials stay in CLAUDE.local.md.
2026-10-15 17:34:39 -04:00
spoopyghosty0 6cd1eaaf23 adapter: show a per-eye cylinder menu to both eyes (fix black curved menus)
Doom3Quest-based ports (PreyVR, #306) draw their menu on a curved
cylinder layer submitted once per eye. The Frame's runtime has no
cylinder layers, so FrameBridge shows each as ~7 flat quad strips; a
per-eye pair is ~14 quad layers in one frame, which the runtime rejects
whole (xrEndFrame -> XR_ERROR_LAYER_INVALID, -16). The menu then stays
black while the game runs at 72 fps.

Collapse the pair: drop the right-eye cylinder and show the left eye's
strips to both eyes (the runtime composites a quad to both eyes anyway).
That halves the layer count and drops the per-eye eyeVisibility, and the
runtime accepts the frame. Only frames with per-eye cylinders change --
exactly the ones that were being rejected; mono (BOTH) cylinder games
such as 4XVR are untouched.

Verified on the dev Frame (headless): PreyVR v1.2.4 rebuilt + installed,
the menu frame now submits (one transient -16 on the first frame before
the space is locatable, then clean), 72 fps. Visual confirmation of the
menu needs the headset. Triage signature cylinder-menu-layers-rejected.

No adapter revision bump (installed games are not marked outdated).
2026-10-15 15:54:29 -04:00
spoopyghosty0 741af0651e adapter: log the created swapchain handle in xrCreateSwapchain
Diagnostics only (no behaviour change): the "new layer ... usable=0"
line prints a layer's swapchain pointer, but creation logged only the
result, so a dropped layer couldn't be matched to the xrCreateSwapchain
that made (or failed to make) its swapchain. Needed to pin why a quad
"screen layer" is dropped (#306 PreyVR: menu rendered to a quad whose
swapchain FrameBridge reports as not usable).
2026-10-15 15:13:37 -04:00
spoopyghosty0 a2f46a17fa Catalog: 16 community-verified recipes
Headset-confirmed working configs shared through the issue form:
Tea For God (#295), Ghost Town (#299), Eye of the Temple (#302),
Ocean Rift (#304), Quantum Void (#307), AugmentedEmpire (#311),
Battlemarked (#312), Demeo (#313), Homeworld: Vast Reaches (#314),
Moss (#315), Maestro (#316), Mini Motor Racing X (#317),
Operation Wolf Returns (#318), Ragnarock (#319), Smash Drums (#320),
Vendetta Forever (#321).

Quantum Void, Homeworld: Vast Reaches and Ragnarock go in as status: issues.
2026-10-15 14:05:29 -04:00
spoopyghosty0 cbc3416ada FramePort 1.2.0
Version 1.2.0; catalog min_app 1.1.2 -> 1.2.0 for the entries that need this release (Shadow Point, Medal of Honor, Assassin's Creed Nexus, Journey of the Gods).
2026-10-15 09:14:51 -04:00
spoopyghosty0 5b6ddc2048 Catalog: Medal of Honor: Above and Beyond with the OBB delivery skip on (#159)
Turns on frame.unreal_skip_obb_delivery (and keeps frame.hw_video_decode) so
the fix applies without the user finding the toggle. Not device-verified (the
game is ~41 GB); status unknown, min_app 1.1.2 so only builds that recognise
the obfuscated DownloaderActivity get it.
2026-10-15 08:11:46 -04:00
spoopyghosty0 8f932dfd9b Unreal OBB delivery: recognise obfuscated DownloaderActivity predicates (#159 Medal of Honor)
Medal of Honor (com.Virtuos.R6DLM) keeps Epic's DownloaderActivity and log text but renames the delivery predicates
and OBBData, so expansionFilesDelivered wasn't found and frame.unreal_skip_obb_delivery was never offered. Detection
now also matches a boolean method in the package's DownloaderActivity, called from onCreate, that carries Epic's
"Checking for file : " log and calls the expansion-downloader helpers; the patch rewrites those too. ANALYSIS_VERSION
18 -> 19. Heuristics eval unchanged (10/66); no existing recipe affected.
2026-10-15 01:54:33 -04:00
spoopyghosty0 9eef555bf2 cube_standin: serve a refused cube swapchain on Vulkan too (#296 UNDERDOGS)
The GLES-only stand-in left Vulkan games (UNDERDOGS: VkFormat 43, faces=6) with the runtime's refusal, so OVRPlugin
crashed in ovrp_EndFrame4. When there's no GLES context, the adapter now makes a cube-compatible VkImage (6 layers,
the requested format/size/mips, usage from the XR flags) with the app's device/queue and a private transient pool,
transitions it to COLOR_ATTACHMENT_OPTIMAL, and enumerates it as a Vulkan image; its cube layers are still dropped.
GLES behaviour is unchanged. Adapter rebuilt deterministically (both ABIs).
2026-10-15 01:43:29 -04:00
spoopyghosty0 8169574d89 Agent: merge case-variant duplicate shortcut keys instead of refusing them (#300 follow-up)
Pre-#263 agents left shortcuts.vdf entries with both appname and AppName; vdf_decode then refused the file
("duplicate VDF key") and Add to Steam library failed. Duplicates are now merged into one key: Steam's capitalized
spelling kept, the last value taken. Clean files still round-trip unchanged.
2026-10-15 00:50:33 -04:00
spoopyghosty0 aeabb3df5a Uploads: stream small-file tar batches over OpenSSH too, Paramiko fallback (Discussion #242)
Only big files (>=8 MiB) used OpenSSH; games made mostly of small files stayed on Paramiko and were slow on a fast
link. native_upload.put_tar streams the same tar batch through system ssh with the paired key and pinned host key;
on any failure the install falls back to Paramiko's put_tar and logs it, and doesn't retry OpenSSH for later batches.
The job log now names the transport for each part. upload_bench gains app-small / paramiko-small comparisons.
2026-10-15 00:46:11 -04:00
spoopyghosty0 d073541a83 Triage: name both OBB-check options (#159), Vulkan caveat for cube stand-in (#296), flag frames-that-started-then-stopped (#301)
- unreal-obb-check-stuck names frame.unreal_skip_obb_check (CRC, needs bVerifyOBBOnStartUp) and
  frame.unreal_skip_obb_delivery (the Java name/size gate), and says neither is a guaranteed fix.
- cube-swapchain-refused: the stand-in is GLES-only; a Vulkan game can't use it yet.
- A game that submitted projection frames but then logged no pacing summary for 20 s (process alive) is reported as
  frames-stopped (info), so a hang like SKYBOX's signature check isn't a false pass. Headless no-tracking ends are
  excluded.
2026-10-15 00:38:10 -04:00
spoopyghosty0 02dce78618 Library: side notes never create an entry; drop recipe-less stubs (#294)
Play on the Steam Frame tab for a game no longer in the library wrote last_played with upsert_game, which created an
entry with only that field: listed under its package name, "Update ready", and Update / Game settings failed with
KeyError 'recipe'. library.set_fields updates existing entries only (last played, test and session results, tags,
toggles); a one-time migration drops entries made of side notes alone.
2026-10-14 23:56:02 -04:00
spoopyghosty0 5910a8d3c7 Agent 91: the logcat keeper also catches a silent or failing Lepton mirror
After "Waiting for app", a failure line or 20 s without a logcat line start FramePort's own reader, from the
launcher's start (logcat -T <epoch>) when the mirror never wrote, else from just before its last line. The reader
restarts from where it ended, stops when Lepton's lines come back, the container's log buffer is 16 MiB, and every
decision goes to logcat-keeper.log.
2026-10-14 22:27:49 -04:00
spoopyghosty0 22413e21e9 Showcase: the fake Monitor history gets exact 1 s steps (smoothed numbers differed between renders on slow runners) 2026-10-14 20:47:31 -04:00
spoopyghosty0 4d5c5fa091 Merge pull request #231 from UnicronNL/aarch32testing
32-bit Gear VR / Oculus Go / early Quest games through the a32 bridge (frame.a32_bridge, experimental, on by default for 32-bit-only games).
2026-10-14 20:23:42 -04:00
spoopyghosty0 5007ad26a2 Lint: wrap three lines over 120 characters 2026-10-14 20:21:00 -04:00
spoopyghosty0 927dae5ff8 Merge main into aarch32testing; maintainer fixes for the 32-bit bridge
Merged main (agent 90, ANALYSIS_VERSION 17/18 after main's 15/16) and rebuilt the bridge, foveation and a32
libraries from source (deterministic, no local paths).

Fixes on top:
- a32 loader: apply DT_ANDROID_RELR relocations (Journey of the Gods crashed at start)
- VrApi bridge: vrapi_Get/SetTrackingTransform (floor-level tracking; Shadow Point's player was below the floor)
- a32: never submit an untracked default head pose (hold up to 100 ms, repair or drop); pose consistency per display
  time; submit/tracking counters
- VrApi bridge: wait again when xrWaitFrame gives a display time in the refresh just submitted (the runtime rejected
  the second frame with AlreadySubmitted; Journey of the Gods ran at ~120 fps on a 90 Hz display and the scene slid
  and snapped back); pacing counters
- VrApi bridge: GLES re-entry polls events before reusing the kept session (a lost or exiting session is replaced, a
  stopped one waits for READY)
- VrApi bridge: STAGE is the runtime's STAGE space (play-area centre and orientation, unchanged by recentering);
  LOCAL_FLOOR keeps the head-based origin
- signer certificate: pick the certificate the SignerInfo names, not the first in the PKCS#7 block
- flat 32-bit apps keep the bridge (it isn't a VR-only fix)
- Frida gadget loads are stripped before translation
- launcher restart test fixed; native/.cache is no longer committed
- catalog: Shadow Point and Journey of the Gods work (headset, 2026-10-14; min_app 1.1.2)
2026-10-14 20:10:10 -04:00
spoopyghosty0 57bb69f79c VrApi bridge: save the headset's FOV only when it really changes (it was rewritten every frame)
Rebuilt libvrapi.so and libvrapi_foveation.so without the local NDK paths a worktree build left in their debug info; a test checks that no artifact contains a local path.
2026-10-14 19:45:34 -04:00
spoopyghosty0 a87ccf4c7b Merge pull request #292 from spoopyghosty0/catalog/issue-270
catalog: com.edde746.plezy
2026-10-14 14:01:56 -04:00
spoopyghosty0 6b8605a83e Merge remote-tracking branch 'origin/main' into fix-270
# Conflicts:
#	docs/PATCHES.md
2026-10-14 14:01:13 -04:00
spoopyghosty0 bef42dfd1b Merge pull request #291 from spoopyghosty0/catalog/issue-279
catalog: com.nDreams.Ghostbusters
2026-10-14 14:00:47 -04:00
spoopyghosty0 2e2fac2348 Catalog notes in neutral wording 2026-10-14 13:58:00 -04:00
github-actions[bot] 84ae3c1ce0 catalog: com.edde746.plezy (from #270) 2026-10-14 17:54:26 +00:00
UnicronNLandClaude Opus 5.5 a37c75aec8 VrApi bridge: recenter from the head after the runtime's recenter
Holding the Frame's menu button turned 32-bit (and other VrApi bridge)
games 90-120 degrees to the side. The bridge's app space is LOCAL plus
the head's yaw at the start; the runtime's recenter moves LOCAL to the
head, so that old yaw was applied again. On a LOCAL reference space
change (and on vrapi_RecenterPose, ignored before) the origin is taken
from the head again in the first frame after the change, and VrApi's
recenter count goes up. Owner-verified with Gunjack.

The upstream patches are regenerated against OVRPort 5e7df52 (they
were missing the FOV cache changes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:58:03 +02:00
UnicronNLandClaude Opus 5.5 a7b5acbd14 Library migration a32_bridge_on: the 32-bit bridge for existing 32-bit games
Recipes the user edited (source "user") are never re-derived, so a 32-bit
game whose recipe was saved before the bridge existed kept OVRPort and the
64-bit fixes and no bridge. Since 95c5de9 such a recipe can't be built at
all (build.check_a32), so it needed fixing by hand.

The one-time migration a32_bridge_on (library._migrate, after
quest_binary_fixes_v2, which adds frame.vk_sanitize to every Quest recipe)
goes over every 32-bit-only game once:
- adds frame.a32_bridge with the patch's own reason, unless the game's
  catalog entry removes it (frame_remove)
- then engine.a32_recipe as for a bridge just turned on: OVRPort and the
  64-bit fixes off, device.text_input_window for Unity, a pre-bridge
  "unsupported" becomes "unknown"; the recipe stays the user's
- recipes that already have the bridge only lose what it replaces
- skips 64-bit games, PC VR / Linux entries and "install unchanged" games

It runs once per library, so a bridge the user switches off afterwards
stays off.

Tests: a user recipe from before the bridge is migrated, a catalog
frame_remove and a 64-bit game are left alone, switching the bridge off
afterwards sticks; the game page switch test now starts from a migrated
library.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:50:05 +02:00
UnicronNLandClaude Opus 5.5 a305ecc43b a32 bridge: switch off what it replaces, and win over pre-bridge catalog verdicts
Two ways a 32-bit game ended up with a recipe that couldn't work:

- Catalog entries written before the bridge existed (Journey of the Gods,
  Shadow Point: "unsupported: the Frame has no AArch32") dropped the
  heuristic bridge suggestion like any other patch the entry didn't choose.
- Turning the bridge on by hand kept OVRPort and the 64-bit-only fixes
  (e.g. frame.vk_sanitize) on; they then failed in the build.

Now:
- A catalog entry for a 32-bit game that neither names nor removes
  frame.a32_bridge counts as older than the bridge: the bridge stays in,
  "unsupported" becomes "unknown" and the note says it's untested with the
  bridge (quoting the old verdict). Entries that name the bridge keep their
  own verdict.
- engine.a32_recipe (was _a32) also runs in pipeline.set_recipe (game page,
  CLI `recipe --enable`, Game settings dialog) and before every build. When
  the bridge has just been turned on it also adds what it needs (Unity:
  device.text_input_window) and lifts a pre-bridge "unsupported"; later
  saves only remove, so a patch the user turns off stays off.
- Which patches work on the bridge is declared per patch instead of two
  lists in the engine: Patch.a32 / base.works_on_a32. OVRPort and Frame
  fixes are off unless they say a32 = True (the bridge, the adapter, the
  launcher entry); FrameBridge settings work unless they need the xrshim
  (settings.XRSHIM_SETTINGS, the same list frame.adapter's needs_xrshim
  reads now, so a new xrshim setting is excluded by itself). Such patches
  are hidden for 32-bit games, also in the Game settings dialog.
- build.check_a32 refuses a 32-bit build without the bridge, or with OVRPort
  or a 64-bit fix on, with a plain message instead of failing inside a tool
  or producing an APK the Frame rejects (INSTALL_FAILED_NO_MATCHING_ABIS).
  engine.warnings(recipe, analysis) says the same on the game page.
- The game page redraws the patch list when the bridge switch changed other
  patches; its save uses C.update (warn.update raised when not mounted).
- Parity: a bridge build whose known-good APK is from before the bridge gets
  "new build (no baseline)" (no alt check either) and is listed apart from
  the games at parity, instead of UNEXPLAINED.

Tests: catalog verdict old vs tested, bridge turned on by hand (incl. a
later switch-off staying off), the lifted status, works_on_a32 per category,
check_a32, warnings, parity baseline + report, and the game page's switch
driven headless (no browser). Not yet built for or run on the Frame with
Journey of the Gods / Shadow Point.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:49:43 +02:00
UnicronNLandClaude Opus 5.5 2acfd64f7f Sports Scramble runs: Quest builds on the a32 bridge, Unreal's self-restart
Sports Scramble (a 32-bit Santa Cruz build: UE 4.21, OVRPlugin on VrApi 1.21)
now plays in the headset with both controllers.

a32 bridge:
- AAsset_getBuffer: the host buffer lies above 4 GiB, so the guest gets a
  copy in its own memory, freed in AAsset_close (Unreal read its
  UE4CommandLine.txt this way and aborted on the NULL it got before)
- AKeyEvent_getFlags and the remaining AConfiguration getters
- Touch controllers for Quest builds: apps that require 6DoF head tracking
  (uses-feature android.hardware.vr.headtracking version 1) get
  assets/fp_a32_headset.txt = "quest" at conversion; the bridge then passes
  both Frame controllers through (input devices, caps, state, tracking,
  vibration; struct tails per VrApi minor) and sends no synthetic touchpad
  events. Gear VR / Go games keep the remote emulation. A32_TOUCH=1/0
  overrides.

Analysis: detect.requires_6dof, headset "quest" for such 32-bit apps
(ANALYSIS_VERSION 13).

Agent 82: Unreal restarts the app once after its first-run shader precompile
(the "optimizing" screen): it starts its own launcher activity and exits, and
Lepton ends the container with the first process. Skipping the restart or
turning it off (r.ProgramBinaryCache.RestartAndroidAfterPrecompile=0) left
the game on that screen for good. launch.sh now starts Lepton once more when
the system log shows the app's own LAUNCHER start right before its
System.exit(0) (_restart_requested; first run kept as
launch-before-restart.log; FRAMEPORT_NO_RESTART=1 turns it off).
upgrade_launchers adds it to existing launchers. Crashes, quitting from the
game and Steam's Exit game don't match.

Catalog: Sports Scramble works (owner, headset, 2026-10-13).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:48:53 +02:00
UnicronNLandClaude Opus 5.5 324b3401f7 a32translator: lock-free dispatch and per-page invalidation (profiled on the Frame)
Profiled Gunjack and Spunky Dungeon on the Frame with perf and a new
A32_PERFMAP option (a perf map of the translated code: block bodies, exit
stubs, FPCR writes). FPCR switches turned out negligible (8 of 86k samples,
none in Gunjack). The cost was elsewhere:

- The run loop took the translation mutex on every dispatch and walked a hash
  chain under it (Gunjack: jit_run 23.6 % of all samples, pthread_mutex_*
  about 7 %, plus futex time in the kernel).
- The inline lookup table for indirect branches was only written at
  translation, so a hot return target lost its slot for good to any block
  translated later into the same slot and went through the run loop ever after.
- Every dispatch did an atomic add/sub on a counter all threads share (4.7 %).
- jit_invalidate scanned every block on each cacheflush that touched a code
  page: Unity's Mono JIT does that constantly (72 % of Spunky Dungeon's main
  thread in one run).

Now:
- the run loop looks blocks up without the lock (inline table first, then
  the hash chains, published with release stores); the lock is only taken to
  translate or to chain the exit it came from
- it refills the inline table with every block it dispatches; the refill and
  invalidate_block are fenced against each other, so an invalidated block
  never stays reachable
- HASH_BITS / LTAB_BITS 16 -> 18 (Gunjack translates well over 100k blocks)
- a per-thread in_jit_section flag + fence instead of the shared counter;
  flush_cache sets flush_pending and waits for the flags (threads_any_in_jit)
- per-guest-page block lists: an invalidation visits only the blocks on the
  affected pages and drops invalid ones from the lists on the way

Results on the Frame (same build otherwise, same launch conditions):
- Gunjack, 25-45 s after start with OVP_HEADLESS_TEST: 100,462 -> about
  45,000 samples in 20 s (about 55 % less CPU), jit_run 23.6 % -> 1.6 %,
  pthread_mutex_lock about 7 % -> 0.4 %
- Gunjack, 12-27 s: 72 fps in both, 11,306 -> 9,801 samples, jit_run
  10.4 % -> 1.0 %
- Spunky Dungeon, 12-27 s: 72 fps in both; translated code is only 2-3 %
  there, so no change. The jit_invalidate phase wasn't reproducible headless
  under identical conditions: not yet measured in a played session.
- bench.c (single thread, few dispatches): unchanged.

Tests: run_programs.py (jit + interp, and A32_CACHE_KB=300), bridge harness,
fuzz.py arm-dp / t32 / arm-vfp / arm-neon (0 mismatches), pytest. Both games
pass their launch tests at 72 fps with the final build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:46:01 +02:00
UnicronNLandClaude Opus 5.5 694621c71f Catalog: Gunjack (Gear VR, 32-bit bridge) works in the headset
Gunjack (CCP, Unreal Engine 4.10 NativeActivity, VrApi, GLES) runs on the
Frame through frame.a32_bridge, confirmed in the headset by the owner
(2026-10-12). The recipe needs only frame.a32_bridge: the engine adds the
adapter and the LAUNCHER fix and turns OVRPort off, the same patch set as
the build now on the dev Frame.

Notes give the controls (right controller): trigger = fire, A = tap, stick
down = reload (swipe back), stick up = special weapon (swipe forward),
B = back. GAMES.md and the patch docs regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:46:01 +02:00
UnicronNLandClaude Opus 5.5 9df1d35003 a32 bridge: right stick up/down = swipe forward/back for NativeActivity games
Gunjack (UE 4.10, Gear VR) has no separate reload or special-weapon input on
the touchpad: every swipe goes to UE4's Gesture_Flick, and
ATDPlayerController::OnFlick reads the flick angle. Below 45 or above 315
degrees (+X, a swipe towards the back of the Gear VR touchpad) it reloads;
135 to 225 degrees (-X, a swipe forward) fires the special weapon. Up and down
swipes do nothing. The bridge sent the stick's up/down as Y swipes, so in
Gunjack those directions did nothing.

For games that read their AInputQueue (NativeActivity), the right stick's
up/down now swipe along the touchpad's own X axis: up = swipe forward
(special weapon), down = swipe back (reload). Left/right are unchanged.
Unity games (AFFECTED, Spunky Dungeon) keep their mapping.

Rebuilt liba32bridge.so. Gunjack was rebuilt and installed on the dev Frame;
the headless launch test passes. Not yet tried in the headset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:45:43 +02:00
UnicronNL a86a86df3d a32 bridge: controller input for NativeActivity games (Gunjack)
Gunjack (UE 4.10, Gear VR) imports no vrapi input functions: it reads the
Gear VR touchpad and back button as Android input events from its
AInputQueue (native_app_glue). The bridge delivered its controller events
through Activity.dispatchKeyEvent, which never reaches native code, so no
control worked at all.

input.c now queues synthetic events in front of the game's AInputQueue:
- AInputQueue_attachLooper (without a callback) registers the queue;
  ALooper_pollAll/pollOnce return its ident while a synthetic event waits
  (ALooper_wake ends a blocking poll), AInputQueue_getEvent hands it out,
  finishEvent frees it.
- The AInputQueue/AInputEvent/AKeyEvent/AMotionEvent imports are written
  by hand ("!" in imports.txt) and answer for synthetic events; real
  events go to libandroid as before.
- Touch positions are scaled to the activity's window size
  (native_activity.c records it).

Mapping (right controller, as for AFFECTED: The Manor): trigger = hold
the touchpad, A = tap, right stick = swipe, B / left menu = back. Unity
and other Java-delivered games are unchanged. A new input_start (VR
re-entry) ends the previous poll thread.

Also: the libandroid functions the host side calls directly are weak
references again, so the PC test harness links (it broke with the
AAsset calls of the signature loader); bridge/test/run.py passes.

Headless on the Frame: "controllers: the game reads its AInputQueue",
72 fps. Not yet verified in the headset.
2026-10-13 14:45:43 +02:00
UnicronNLandClaude Opus 5.5 626950e52e Gunjack runs: original APK signature for UE4's check, GLES session kept across VR re-entry
Gunjack (CCP, UE 4.10, Gear VR) quit after loading because AndroidMain compares
GameActivity.AndroidThunkJava_GetSignature() with the original signing
certificate, and then crashed in the Frame's runtime when it entered VR again.

a32 bridge:
- frame.a32_bridge: original_signature() = Base64.DEFAULT(SHA-1(signing
  certificate DER)) of the original APK (META-INF/*.RSA|DSA|EC), stored as
  assets/fp_a32_signature.txt for libUE4.so games (convert(), shared with
  bridge/convert.py)
- the bridge loads it at activity creation and answers guest calls on the
  method ID of AndroidThunkJava_GetSignature()Ljava/lang/String; with it
  (replaces the unused hex/OpenSSL prototype)

VrApi bridge: after loading, Unreal leaves VR mode and enters it again on the
same GL context; the first frame of a second OpenXR session there aborted in
vrclient (CSharedSemaphoreLinux::WaitFromGPU from the GL binding's
PreBeginFrame). vrapi_LeaveVrMode now keeps a running GLES session and
vrapi_EnterVrMode reuses it for the same context (another context still gets
a new session; Vulkan unchanged). upstream-patches/runtime.cpp.patch updated,
libvrapi.so and liba32bridge.so rebuilt.

Verified on the Frame: headless launch test passes (72 fps after re-entry);
owner-verified in the headset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:45:43 +02:00
UnicronNLandClaude Opus 5.5 4be8e3be37 a32 bridge in FramePort: patch frame.a32_bridge, Spunky Dungeon, Gunjack findings
32-bit-only APKs (Gear VR / Oculus Go games) are no longer "unsupported": the
recipe engine suggests frame.a32_bridge, which converts the APK with the
translator bridge (convert() shared with bridge/convert.py) and ships
liba32bridge.so / liba32rt.so / liba32stub.so (native/build.py --only a32).

FramePort:
- engine._a32: overport off (OVRPort is 64-bit only; the patch ships OVRPort's
  loader chain + its 32-bit platform dispatcher, overport.ensure_runtime_lib),
  only frame.a32_bridge/adapter/launcher of the frame patches, 64-bit-only
  adapter settings dropped, device.text_input_window for Unity; such patches
  are hidden in the UI
- analysis extra.headset (ANALYSIS_VERSION 9): quest / go / gearvr ->
  "Gear VR" / "Oculus Go" platform + Steam tag; catalog `headset:` field
- expects_obb ignores Unreal's OBB-inside-the-APK (assets/main.obb.png)
- catalog: com.fallen.affected, net.mobilemischief.spunkydungeon

Bridge / translator:
- VrApi 1.31 + Unity 2019 (no-config EGL contexts, LOCAL_FLOOR/STAGE tracking
  space), GL buffer mappings per buffer object (fixes a ~10 MB/s guest leak and
  garbled vertices), Go controller mapped to the right Frame controller
- native_app_glue imports (ALooper/AInputQueue/AConfiguration/AAsset*) for
  UE4 NativeActivity games (Gunjack: runs, then quits on its own APK signature
  check, which FramePort doesn't defeat)
- debugging aids: A32_BREAK, A32_STRACE to logcat, lifecycle/LeaveVrMode logs

vrapi-bridge: honours LOCAL_FLOOR/STAGE, picks a window/RGBA8 ES3 config for
no-config contexts; upstream patch updated, libvrapi.so rebuilt.

Verified on the Frame: Spunky Dungeon (Unity 2019.2, OVRPlugin 1.46) plays at
72 fps; AFFECTED The Manor still runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:45:24 +02:00
UnicronNLandClaude Opus 5.5 98b16b211a a32translator: Android bridge for 32-bit games (first game: AFFECTED The Manor)
32-bit ARM (armeabi-v7a) libraries run inside a normal 64-bit Android app on the
Steam Frame, without Android's native-bridge mechanism (no Lepton changes): each
libX.so becomes libX.a32.so plus a 64-bit stub, next to liba32bridge.so (the
translator + host glue) and liba32rt.so (a 32-bit static-PIE runtime with bionic's
libc/libm/libz/libstdc++ and a loader for the game's libraries). Guest and host
talk through hypercalls (SVC 0, r7 = 0x0a32xxxx).

Bridge (native/a32translator/bridge):
- JNI both ways: generated + hand-written JNIEnv/JavaVM, RegisterNatives and
  Java_* exports through AAPCS64 -> AAPCS32 trampolines, handles for references,
  arrays/strings shared when below 4 GiB, else copied
- NativeActivity glue, libandroid imports (weak, generated from imports.txt)
- GLES 3.2 + extensions + EGL: 996 functions generated from the NDK headers
- OpenSL ES output implemented in the guest, played through AAudio
- VrApi 1.x (Gear VR era) translated to the 64-bit VrApi -> OpenXR bridge,
  including OVRPlugin 1.12's frame layout and its wrapped (app texture) chains
- controller input as Gear VR touchpad/back/gamepad events (UnityPlayer.injectEvent)
- convert.py: prototype of the APK conversion (FramePort patch to follow)
- PC harness with a fake JVM (32 checks, qemu or native) and an on-device test APK

Translator fixes found on the way: guest signals during blocking system calls
and in host code (Boehm GC deadlock in Unity's Mono), static-PIE start files and
PT_TLS/PT_GNU_RELRO bias, host fault chaining, stderr to logcat in bridge mode.

vrapi-bridge: OVP_HEADLESS_TEST=1 skips the wait for a tracked head (automated
tests without a worn headset); upstream-patches/runtime.cpp.patch updated.

Verified on the Frame (2026-10-10): AFFECTED The Manor (Unity 5.6 + Mono,
OVRPlugin 1.12) runs in the headset with picture and sound; controls in progress.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:41:43 +02:00
UnicronNLandClaude Opus 5.5 4f042f7225 native/a32translator: AArch32 -> AArch64 user-mode translator (a32run)
Interpreter + JIT for ARM, Thumb-2, VFPv4 and NEON, ARM EABI syscall
translation, signals, threads and self-modifying code. Runs static bionic
programs on the Frame. Tests: A64 encoders vs llvm-mc, a differential
instruction fuzzer and program tests against qemu-arm. Not shipped; the
README lists the steps towards running 32-bit-only APKs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:41:43 +02:00
228 changed files with 35841 additions and 286 deletions

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ parity-report.md
*.keystore
*.apk
.pytest_cache/
native/.cache/
native/.cache
native/**/build/
# per-machine Claude Code settings (contain home paths)
.claude/settings.local.json
+175 -2
View File
@@ -312,6 +312,66 @@ Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
- `native/` — sources of the prebuilt binaries in `artifacts/` (adapter, VrApi bridge patches, GL shim, stubs).
`native/build.py` rebuilds them with NDK r27c (downloaded on demand into `native/.cache`, git-ignored; uses
`-ffile-prefix-map` so no local paths get embedded; zip symlinks are restored as copies). Users never need the NDK.
`native/a32translator/` (not an artifact, not shipped) = `a32run`, an AArch32 → AArch64 user-mode translator
(interpreter + JIT, ARM/Thumb-2/VFP/NEON) for running 32-bit ARM Linux programs on the Frame; its README has the
design, the qemu-arm differential fuzzer and program tests. `native/a32translator/bridge/` = the in-APK Android
bridge (32-bit JNI/NativeActivity libraries in a 64-bit app: stub + liba32bridge.so + guest runtime liba32rt.so;
harness with a fake JVM; test APK org.frameport.a32test passes in Lepton; GLES/EGL, OpenSL ES via AAudio, VrApi 1.x
-> the 64-bit VrApi bridge, controller input as Gear VR touchpad/back events; `bridge/convert.py` converts an APK).
First game: AFFECTED The Manor (Gear VR, Unity 5.6 + Mono) runs in the headset with picture and sound
(2026-10-10); Spunky Dungeon (Unity 2019.2, OVRPlugin 1.46 on VrApi 1.31, Platform SDK) plays at 72 fps.
In FramePort: patch `frame.a32_bridge` (`patches/frame/a32_bridge.py`: `convert()` is shared with the dev script
`bridge/convert.py`; artifacts `liba32bridge.so`/`liba32rt.so`/`liba32stub.so` from `native/build.py --only a32`)
is suggested for every 32-bit-only APK; the recipe then has `overport: False` (OVRPort is 64-bit only; the patch
ships OVRPort's loader chain + its 32-bit platform dispatcher itself, `overport.ensure_runtime_lib`), only
frame.a32_bridge/adapter/launcher of the frame patches, and `device.text_input_window` for Unity (`engine.a32_recipe`,
also run by `pipeline.set_recipe` + builds, so a bridge turned on by hand drops OVRPort & the 64-bit fixes; which
patches work there = `base.works_on_a32` (`Patch.a32`; overport/frame off unless `a32 = True`, adapter settings in
`settings.XRSHIM_SETTINGS` off); `build.check_a32` refuses anything else, `engine.warnings(recipe, analysis)` says
so; a catalog entry for a 32-bit game that neither names nor removes the bridge predates it: bridge kept, status
unknown; parity gives bridge builds without a bridge known-good "new build (no baseline)"; library migration
`a32_bridge_on` turned the bridge on once in every 32-bit recipe, user ones too, unless the catalog's frame_remove
names it).
Analysis `extra.headset` (ANALYSIS_VERSION 15): gearvr / go / quest → "Gear VR" / "Oculus Go" platform + Steam tag.
Catalog: `headset:` field; com.fallen.affected, net.mobilemischief.spunkydungeon, com.ccpgames.gunjack (works, 2026-10-12). Learned: Unity 2019 contexts
have no EGLConfig (EGL_KHR_no_config_context: the VrApi bridge takes the window's or an RGBA8 ES3 config); Unity's
floor origin = vrapi_SetTrackingSpace(1) (the VrApi bridge now honours LOCAL_FLOOR/STAGE); mapped GL buffers are
per buffer object (a per-target guest copy leaked ~10 MB/s and garbled vertices); the guest runtime's own scudo
names its maps `[anon:scudo:*]` below 4 GiB (watch them for guest leaks). The Go controller = the right Frame
controller (stick = touchpad touch, sideways > 0.6 or press = click). Gunjack (CCP, UE 4.10 NativeActivity, Gear VR,
2026-10-10): needed the native_app_glue imports (ALooper/AInputQueue/AConfiguration/AAsset*, imports.txt), an arm64
libvrapi.so for Java's System.loadLibrary("vrapi") and MOUNTED under OVP_HEADLESS_TEST; it then loads its map and
quit on purpose: AndroidMain compares AndroidThunkCpp_GetSignature() with an obfuscated copy. **Works since
2026-10-11 (owner-verified in the headset):** GameActivity.AndroidThunkJava_GetSignature() = Base64.DEFAULT(SHA-1(
signing certificate DER)) (jadx); `a32_bridge.original_signature` computes it from the original APK's
META-INF/*.RSA|DSA|EC, `convert()` stores it as `assets/fp_a32_signature.txt` for libUE4.so games, the bridge loads
it at activity creation (native_activity.c) and jni.c answers Call*Method on the method ID of
`AndroidThunkJava_GetSignature()Ljava/lang/String;` with it. After loading, Unreal leaves VR mode and enters it again on
the same GL context; a second OpenXR session there aborted in vrclient (CSharedSemaphoreLinux::WaitFromGPU from the GL
binding's PreBeginFrame, also with OVP_HEADLESS_TEST) → the VrApi bridge keeps a running GLES session across
LeaveVrMode and reuses it for an EnterVrMode with the same context (upstream-patches/runtime.cpp.patch).
Debugging aids added: A32_BREAK=<guest addr>[,..] (stack of the first hits; guest libs load at fixed addresses, e.g.
libUE4 0xf25d5000), A32_STRACE in bridge mode = path/exit calls to logcat, activity lifecycle + LeaveVrMode caller
logs. Lepton's logcat mirror often dies for these games: read `podman exec <container> logcat` instead. Gunjack input
(2026-10-11): it imports no vrapi input functions and reads the Gear VR touchpad/back as AInputEvents from its
AInputQueue (native_app_glue), so dispatchKeyEvent never reached it (no control at all) → input.c queues synthetic
events there (ALooper_poll* return the queue's ident while one waits; AInputQueue_getEvent/finishEvent and the
AInputEvent/AKeyEvent/AMotionEvent getters are hand-written "!" imports that know them; touch positions scaled to the
window size). Same mapping as AFFECTED: trigger = hold touchpad, A = tap, right stick = swipe, B = back; for NativeActivity games the stick's up/down = swipe forward/back (touchpad X: Gunjack's OnFlick = reload at ~0°, special weapon at ~180°). Not yet
headset-verified. Quest builds on the bridge (2026-10-13, Sports Scramble = a 32-bit Santa Cruz build,
UE 4.21 + OVRPlugin on VrApi 1.21): manifest requires `android.hardware.vr.headtracking` version 1
(`detect.requires_6dof`, headset "quest", ANALYSIS_VERSION 16) → convert writes `assets/fp_a32_headset.txt`
= "quest" → vrapi.c `quest_touch` (read in vrapi_Initialize via the activity's AssetManager; A32_TOUCH=1/0
overrides) passes the 64-bit bridge's Touch controllers through (enumerate/caps/state/tracking/haptics, struct
tails per VrApi minor) and starts no synthetic input. It also needed AAsset_getBuffer (guest copy, freed in
AAsset_close), AKeyEvent_getFlags and the other AConfiguration getters. Headset (owner, 2026-10-13): plays,
both controllers work. Recenter (holding the Frame's menu button) turned VrApi games ~90-120 degrees aside: the bridge's app space is LOCAL + the start yaw and the runtime moves LOCAL to the head → the bridge now takes the origin from the head again on XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING (LOCAL) and on vrapi_RecenterPose (owner-verified with Gunjack, 2026-10-13). Next: the other 32-bit catalog games (Journey of the Gods, Shadow Point: still "unsupported" until
tested), translator speed. Profiled on the Frame
(2026-10-12, `A32_PERFMAP` + perf): FPCR switches are negligible (8 of 86k samples); the cost was the run loop
(a mutex + hash-chain walk on every dispatch, a contended counter, inline-lookup slots never refilled: Gunjack
~45 % of its CPU) and `jit_invalidate` scanning every block on each Mono `cacheflush` (72 % of Spunky Dungeon's
main thread). Now lock-free lookups, ltab refill, per-thread flags, per-page block lists: Gunjack's dispatcher
23.6 % -> 1.6 %, CPU in the same phase about -55 %, still 72 fps.
- `scripts/` — `package.py` (flet build/pack), `eval_heuristics.py` (score heuristics), `ui_smoke.py` (GUI screenshots).
- `docs/` — PLAYBOOK, FRAME_RUNTIME, ARCHITECTURE, INSTALL (end users), parity reports (offline + device).
@@ -393,7 +453,7 @@ Repo is on an NTFS drive (`core.fileMode=false`); line endings are LF (`.gitattr
## Hard-won facts (don't re-learn these)
**Frame runtime (SteamOS 0.3.0, build 20260922):**
- No AArch32: 32-bit-only APKs fail with `INSTALL_FAILED_NO_MATCHING_ABIS`. Unfixable; point to Rift + Revive.
- No AArch32: 32-bit-only APKs fail with `INSTALL_FAILED_NO_MATCHING_ABIS` → `frame.a32_bridge` (the a32 translator inside the app, see native/a32translator below).
- GLES swapchains: only `GL_SRGB8_ALPHA8`/`GL_SRGB8` (35907/35905), no MSAA. Vulkan: format 43 (sRGB) but not 37 (UNORM).
- Missing: XR_FB_passthrough (emulate via ALPHA_BLEND), XR_FB_scene/spatial entities (emulated room from STAGE bounds),
XR_KHR_composition_layer_equirect2/cylinder, XR_FB_composition_layer_image_layout (flip emulated by Vulkan blit).
@@ -488,6 +548,61 @@ maps a symlink to the already-loaded module) gets past it to **-3021 = ovrError_
an Oculus-signed runtime. Next step (not done): make the runtime check pass without Detours, e.g. an injected helper
that patches the game's import table (IAT) for LoadLibrary*/WinVerifyTrust, or a prefix-level override. This is
runtime interop (what Revive does), not the Platform SDK licence check (which FramePort never touches).
**Rift via x86_64 Wine under FEX (research, 2026-10-08, headless on the dev Frame, SteamOS 0.4.5; no product code):**
why Revive failed is confirmed upstream: x64 Detours returns ERROR_NOT_SUPPORTED on ARM64EC targets (microsoft/Detours
PR #388; only an ARM64EC build of Detours can hook them). A fully x86_64 Wine avoids it: GE-Proton11-7 **x86_64** runs
under the FEX tool (`fex-compat-tool run -- <x86 binary>`; RootFS /usr/share/guestos/fex-mesa, no FreeType there)
— prefix boot 35 s, kernelbase.dll is x86-64. Proton's script needs help without the x86_64 SLR (app 4183110, not
installed): its Python runs natively (the RootFS has none), so `files/bin/wine{,server}` and the two direct
`wine-preloader` argv calls must go through a FEX wrapper that also unsets `FEX_APP_CONFIG(_LOCATION)` (Proton sets
them on aarch64 for its own ARM64EC FEX → "RootFS path set to ''"); GE's game drive needs STEAM_COMPAT_INSTALL_PATH
unset. SteamVR now ships `bin/linux64/vrclient.so` + `bin/vrclient.so` (i386) + `vrclient_x64.dll` (Oct 6 build; not
there on 09-30): Proton's x86_64 vrclient bridge reaches the arm64 vrserver. **Rick and Morty ran as the scene app**
("OpenVR initialized!", controller tracking, 9176 presents / 6 dropped, CPU 11.6 / GPU 17.9 ms, target 72).
**ReviveInjector: "Succesfully injected!"**, LibRevive64.dll loaded next to OVRPlugin.dll in Lies Beneath, which then
died on 0xc06d007e = delay-loaded `libovrplatform64_1.dll` (Platform SDK) before connecting to SteamVR — so Revive's
signature hook and Revive→SteamVR are still unproven. Every Rift game in the library except Rick and Morty uses the
Platform SDK → the Meta (Link) app in the prefix, logged in with the user's own account, is the real blocker; the
only public attempt (github.com/michauMiau/oculus-wine-linux, 2026-10) never got OculusSetup.exe (32-bit .NET)
past its HTTPS config fetch. Scratch files on the Frame: `~/frameport-rifttest/` (scripts t1-t4.sh).
Meta runtime in the same Wine (2026-10-09): Platform SDK games reach OVRServer's IPC on the Frame. The apparent
intermittent handshake hang was **OVRLibrarian.exe** (.NET, Wine Mono): under FEX it finishes its work but never exits,
its AppTracker entry stays, and the runtime then tracks no later client (Meta app, game), so the game waits forever
for the reply event the runtime only sets after identifying it (found with wineserver `+server` traces PC vs Frame).
Ending OVRLibrarian before the game → game tracked, "Missing entitlement" exactly as on the PC (needs a login).
Logged in (2026-10-09, owner's own account, browser sign-in; the `oculus://` answer had to be forwarded into the Wine
app's `\\.\pipe\oculus`), the runtime also needed a WinRT `Windows.Devices.WiFi.WiFiAdapter` stand-in (Air Link code
fail-fasts without it), Wine's DeviceWatcher add/remove_Updated/Removed implemented, and the C: volume name
(`\\?\Volume{...0043}`) linked in dosdevices. Copying the logged-in `sessions/` + CoreData to the Frame prefix kept the
login. **Oculus First Contact then ran in VR on the Frame** (Revive in OpenVR mode; `/openxr` failed in wineopenxr):
scene app at 72 Hz target, but 92 % of frames "timed out" (game CPU-bound under FEX) → stutter/flicker/lag.
Performance (2026-10-10, headless with patched Revive visibility + SteamVR `pauseCompositorOnStandby=false`, numbers from
`IVRCompositor::GetFrameTimings`): the frame loop waited on sync round trips through the FEX-run x86_64 wineserver.
`native/fexwine/`: a **native aarch64 wineserver** built from GE's exact source (protocol 938) + **ntsync** (works once
OVRLibrarian is ended) took hitches 17 → 0-4 per 20 s. The rest were Unreal's large-block allocator committing,
filling (one `rep stos`) and freeing 514 MB every 1-8 s: ~130k 4 KB page faults each under FEX. `fp_mem.so`
(`FP_BIGCACHE_MB=256`, guest preload via `FEX_ENV=LD_PRELOAD=…`: fex-compat-tool deletes LD_PRELOAD) keeps that block
→ 0 hitches, steady 36 fps + motion smoothing, ~5.5 % timed out. 72 fps would need ~30 % less GPU (game ~55 % busy
at 36 fps); THP (fragmentation), MSAA off, Turnip gmem don't help. Also needed: Unreal's
`Slate.DeferWindowsMessageProcessing` = 0 (exe patch; the default deadlocks Wine's IME window ~1/3 of starts).
Headset (owner, 2026-10-10): with motion smoothing off for the game (SteamVR per-app `motionSmoothingOverride=2`:
smoothing cost ~15 % GPU) "much much better", 95 % of frames new at 72 Hz; MSAA off (DXVK `d3d11.disableMsaa`, -25 %
GPU) helped but the owner misses smooth edges → the game's MSAA CVar is `r.MobileMSAA` (Oculus' clustered-forward
branch; no r.MSAACount in the exe), 2x untested. Headless tests need the headset worn once per boot (else "IMU
fallback" and the game waits at startup forever).
**Experimental mode on branch `rift-on-frame` (the owner's single linkable branch for this work):** CLI only,
`FRAMEPORT_EXPERIMENTAL_FEX=1 frameport fex setup | import-login <signed-in PC prefix> [--app <meta name>] | install
[<meta name>] [--msaa N] [--force-unverified] | status` (hidden group). Generic per game: exe + arguments from Meta's
manifest (`Software/Manifests/<app>.json` launchFile/launchParameters), the Unreal IME-deadlock fix found in the binaries
(`find_ime_patch`: the CVar's UTF-16 name → its `lea` xref → `lea r8` member/global → `mov [reg+disp],1` / int 1;
also modular ApplicationCore/Slate DLLs), `static_checks` (engine, imported graphics DLLs: monolithic Unreal imports
every RHI, so it can't tell which runs). `agent/fexrift.py` `GAMES` = verified games + per-game opt-ins only (fp_mem's
unzeroed big-block cache, `msaa_ini`); others need `--force-unverified`. PC `src/frameport/fexrift.py` uploads `agent/fexrift.py` + `artifacts/fexrift`
(sources native/fexwine) + Revive 3.2.0 with 6 byte patches (refused for other builds); the Frame helper downloads
GE-Proton11-7 x86_64 (SHA-512), x86 GnuTLS (Arch archive), installs Meta's runtime (Meta's signature checks kept) and
writes the game's launcher. Agent v79 `fex_prepare/status/setup/import_login/install`, kind `frame_fex` (uninstall
keeps the shared prefix; launch tests refused). Everything under `~/.local/share/frameport/fexrift` (purge removes it,
login tokens included). Not yet run end to end on the device; the login still comes from a PC prefix signed in by hand.
Uninstall (Quest, saves kept) used to leave `deployment.json` → still "installed"; fixed (agent v16).
**Discovery/network:** Developer-Mode SteamOS devices announce `_steamos-devkit._tcp` (TXT `login=steamos`) — use it;
@@ -744,7 +859,22 @@ shows what the game draws. Vader: Lucasfilm logo (an OBB mp4: video works), then
bar) that never advances; the async loader thread sleeps and OBB reads stop (~168 MB of a 2.7 GB pak).
**SteamVR overlay apps (agent v75, 2026-10-10):** host OpenVR overlays (VRApplication_Overlay) are composited over Lepton (Quest) games on the Frame (probe checker seen over 4XVR in the headset view, `native/vroverlay_probe`); Windows ones register through Proton's vrclient too (Temporal Reality's Windows build created its overlays; fpsVR never reaches OpenVR under Proton). Detection `analysis/vroverlay.py` (bundled `.vrmanifest` with `is_dashboard_overlay`, else OpenVR + IVROverlay + self-registration markers, engine Other; Rift fingerprint `RIFT_ANALYSIS`), patch `pcvr.vr_overlay` (param autostart), Linux entry fields `vr_overlay`/`vr_overlay_autostart` (game page switch); agent `register_vr_overlay`/`unregister_vr_overlay`/`launch_vr_overlay` (IVRApplications via ctypes, live; manifest `<anchor>/frameport-overlay.vrmanifest`, the app's own key, binary = launch.sh). **SteamVR on the Frame reads only `binary_path_linux_arm`** (binary_path_linux alone is skipped). Overlay apps: no launch test, no Linux Steam-parent watchdog (`FRAMEPORT_OVERLAY`), not a "running game". A Steam overlay-app shortcut and a game shortcut run together. SteamVR's SetApplicationAutoLaunch didn't persist on the dev Frame (the watch never started by itself) → **agent v76: FramePort's own autostart**: the deployment's `overlay.autostart` is the source of truth; `ensure_host_fixes` (`ensure_overlay_service`) keeps the user service `frameport-vr-overlays.service` (`_vr_overlay_watch`, 5 s polls of the known vrserver's /proc stat) only while an overlay app has autostart on (register/unregister, uninstall, purge and the kill switch `~/.local/share/frameport/vr-overlays.disabled` / `FRAMEPORT_NO_OVERLAY_AUTOSTART` update it); a new vrserver (pid + start time, kept in `~/.cache/frameport-vr-overlays.json` across agent updates) → child `_vr_overlay_round`: wait for IVRApplications, 15 s grace, `launch_vr_overlay` for apps not running (folder process or GetApplicationProcessId); log `~/.local/share/frameport/vr-overlays.log`. Dev Frame: adopted the running vrserver, skipped the already running watch; a start after a real SteamVR start/boot is not yet seen. Details: docs/FRAME_RUNTIME.md "Overlay apps".
**Vader's leak solved / AC Nexus flips (2026-10-14):** Vader Immortal leaves GL errors pending on its context; SteamVR's GL interop (`openxr_graphics_gl_openvr.cpp`, `xrclient_<pkg>.txt` in Steam's logs: `SXR_GL_CHECK: error:0x502 ... glGenTextures`) takes the stale error as its own failure once, and from then on `CVRCompositorSharedTextures::BeginCommandBuffer` allocates a command buffer every frame (perf page-fault stacks; ~430 renderD128 mappings + 22 MB/s). Adapter `gl_error_clear` (GLES, catalog on for Vader ep1-3) clears them before xrCreateSwapchain/xrBeginFrame/xrEndFrame: flat memory, no SXR_GL_CHECK (headless). The per-game `xrclient_<pkg>.txt` logs are worth reading for runtime errors. The Frame's runtime caps swapchains per session (XR_ERROR_LIMIT_REACHED from ~15; AC Nexus asks for more): flip emulation now turns quads upright in place (scratch VkImage, once per acquire; transfer usage added to single-layer colour swapchains) instead of a shadow swapchain per quad, which ran into the cap (#138). Headless sessions don't draw AC Nexus's panels (adapter `flip_dump` saves before/after images of flipped quads, for headset runs).
**Lepton's logcat mirror dies (agent v67, 2026-10-09):** occasionally launch.log ends with `logcat: Unexpected EOF!` right after the game starts (about 1 launch in 50, Lepton 2.8.14 and 3.0.5): no dashboard auto-hide, no launch-test result. launch.sh's `_logcat_keeper` then reads `podman exec lepton-steamlaunch-<appid> logcat` itself into launch.log (up to 5 restarts while the game runs).
**Unreal's self-restart (agent v90, 2026-10-13):** UE 4.21+ restarts the app once after its first-run shader
precompile ("optimizing" screen; `r.ProgramBinaryCache.RestartAndroidAfterPrecompile`): it starts its own LAUNCHER
activity and calls System.exit(0); Lepton ends the container with the first process (the restarted one with it).
Skipping `AndroidThunkJava_RestartApplication` or the cvar = 0 (accepted via UE4CommandLine.txt `-ini:`) left Sports
Scramble on that level for good. launch.sh (RESTART_BLOCK, `upgrade_launchers` adds it) starts Lepton once more when
`_restart_requested` sees the app's own LAUNCHER start (system log, uid >= 10000) <= 5 s before its exit; first run
kept as `launch-before-restart.log`; `FRAMEPORT_NO_RESTART=1` off. Owner-verified with Sports Scramble's first start (2026-10-13).
**xrWaitFrame runs ahead (Journey of the Gods, 2026-10-14, owner-verified):** with real frames (headset on) the
Frame's runtime sometimes returns from xrWaitFrame at once with a display time less than one refresh after the frame
just submitted, and then rejects the second submission for that refresh (`VRCompositorError_AlreadySubmitted` in
Steam's `logs/xrclient_<pkg>.txt`; FrameBridge pacing above the display rate). VrApi games that render faster than
the display ran ahead (~120 submits/s at 90 Hz) and the scene slid and snapped back. The VrApi bridge re-waits when
the new display time is under half a period after the last submitted one (`pacing 2s:` counters). Headless runs only
submit empty frames and never show it. Lepton's logcat mirror also missed the whole verifying session (launch.log =
Lepton's own lines only): the keeper now catches a silent mirror too (agent v91).
**Lepton's logcat mirror dies (agent v67, 2026-10-09; v91 2026-10-14):** Lepton's mirror (`podman exec -it <container> logcat -v threadtime,color`) fails three ways: `logcat: Unexpected EOF!` right after the game starts, `Logcat read failure`, or running and writing nothing at all (Lepton 3.0.5: seen twice on 2026-10-14, once in the owner's session, once headless). launch.sh's `_logcat_keeper` reads `podman exec <container> logcat -v threadtime -T <epoch>` itself into launch.log after a failure line or 20 s without a logcat line (from the launcher's start when the mirror never wrote, else from just before its last line), restarts it from where it ended (≤5), stops it when Lepton's coloured lines come back, sets the container's log buffer to 16 MiB (`logcat -G`), and logs every decision to `<base>/logcat-keeper.log`. Checked on the dev Frame: a mirror killed mid-game (hand-over without a gap) and a silent mirror (the whole session recovered).
**Double launch (agent v57, 2026-10-06):** a second Play while Lepton still boots (~10 s with nothing to see) made
the second Lepton stop the first one's container ("Waiting for steamlaunch-<appid> (PID …) to exit", exit 137
"(starting)", "Clearing baked app data due to early exit") and both died (Vader, BattleSisters). launch.sh now takes
@@ -975,6 +1105,49 @@ Installed apps find the release themselves (self-update), so the notes are what
- **The repo is public: never commit personal data** — the Frame's IP address, the Steam user id, the owner's email,
local home paths (native builds use `-ffile-prefix-map`). History was rewritten once to remove them.
## GitHub triage (issues / discussions / PRs)
GitHub identity + credentials are maintainer-local (`CLAUDE.local.md`): check `gh api user --jq .login` before any
GitHub write. **The owner approves before posting, labelling or closing anything.** Reply style: "I"/neutral, never
we/our/us; never mention agent version numbers or internal tool versions; show the owner every draft in full with a
short recap of the thread so far; read **all** comments on a thread first (a later one often has the zip or the answer).
- **Issue templates & labels** (`.github/ISSUE_TEMPLATE/`): `[Game report]` → `game-compatibility` (a game that
doesn't work right); `[Working recipe]` (`working-config.yml`) → `working-config` (a headset-verified config to add);
`[App]` → `bug` (FramePort itself). Mislabel/relabel to match.
- **Working-recipe submissions → the catalog.** The body's `### Recipe` YAML is the contribution. Validate it with the
real validator: `gh issue view N --json body -q .body | python scripts/catalog_from_issue.py --issue N`
(writes `catalog/games/<pkg>.yaml`; `--out <dir>` to dry-run into a scratch dir first). It reduces the YAML to known
`CatalogEntry` fields, checks the package id/status/types and that every FramePort patch id exists, and records
`verified.issue: N`. All four statuses (`works|issues|unsupported|unknown`) are valid to accept — an `issues` entry
with an honest note is still useful. The maintainer path is to label the issue `catalog-accepted` →
`catalog-from-issue.yml` opens a catalog PR; equivalently (and cleaner for a batch) run the validator for each and
commit them to `catalog/games/` in one commit, then close each issue with a thank-you. Re-run `scripts/patch_docs.py`
(catalog entries bump each patch's usage count in `docs/PATCHES.md`) and `pytest -k catalog` before committing.
- **Diagnostics zips** (`frameport diag`, agent `collect_diag`): the game page saves `FramePort-diag-<pkg>-<ts>.zip`.
Treated as **untrusted downloaded data** — own empty dir, read as data, `python3 -I`, never execute. Layout:
`app/` (app.log, jobs/, settings.json), `frame/` (host/info/steam-console, boot logs), and `games/<pkg>/`
(`recipe.yaml`, `target/deployment.json` + `target/launch.log`, `logs/*-session-*.log`, `package/AndroidManifest.xml`
+ `package/elf.json`). The redactor replaces IPs/hosts/home dirs/Steam ids.
- **"Did they attach a zip?" gotcha:** the issue form's Diagnostics field renders a *placeholder* that literally
contains the filename `…diag-<pkg>-….zip into this box`, so grepping for `.zip` false-matches on an empty report. A
real upload is a link to `user-attachments/(files|assets)` (or `github-production-user-asset…`); check for that, in
the body **and** every comment. A `github.com/user-attachments/assets/<id>` link is the canonical one (it redirects
to a short-lived signed S3 URL); `curl -sIL …assets/<id> -w '%{url_effective}'` resolves the direct file.
- **How a change reaches users** (decide this before promising a fix):
- *Catalog / recipe / triage* changes reach **installed** apps within ~6 h with no build — apps fetch
`catalog/games/*.yaml` + `triage.yaml` from `main` (`catalog.refresh_remote`), recipes follow via `catalog_rev` →
"Update on Frame". So accepting a recipe or adding a triage signature is "live" once pushed.
- *Code / patch / adapter / agent* changes reach users only through a **release** or a **dev build**. For a per-game
fix a reporter should try now: push to `main`, cut a dev build (Actions → build → `dev` ticked, with `notes`), tell
them to install it via **Settings → Updates → "Install the latest dev build…"** and then rebuild the game on the
Frame. Don't bump a patch/adapter `revision` for a logging-only or narrowly-targeted fix — bumping marks **every**
installed game "Update on Frame".
- **Verifying a device fix without the headset:** many runtime failures (e.g. an `xrEndFrame` layer rejection) reproduce
in a **headless** launch test on the dev Frame, so the fix can be developed and confirmed at the frame-acceptance
level there; only the *visual* result needs the headset (hand the built dev build to the reporter, or the owner, for
that). `frameport settings <pkg> <key>=<value>` toggles adapter settings (e.g. `layer_debug=1`) live, no rebuild.
To reproduce a reporter's exact build, grab their APK from its upstream source (e.g. the linked GitHub release), scan
→ build → install → test in an isolated `FRAMEPORT_HOME` (see "Dev commands" / the Frame-busy rules).
## Heuristics (games not in the catalog)
Each patch's `detect()` suggests itself from the Analysis; `applies()` says whether it can matter at all (the UI/CLI
hide non-applicable patches; enabled ones are always shown). Rules learned from the 34 games:
+1308
View File
File diff suppressed because it is too large. Load diff
+133
View File
@@ -0,0 +1,133 @@
"""Data-driven FEX game compatibility. No entitlement/runtime-signature changes; stdlib only on the Frame."""
import hashlib
import os
import re
import shlex
import struct
STATUSES = {"verified", "likely", "untested", "blocked"}
GRAPHICS = {"d3d11", "d3d9", "d3d12", "opengl", "vulkan"}
def exe_facts(path):
"""Read just the PE headers. A 32-bit client still needs GE's WoW64 and a working 32-bit VR/graphics bridge."""
try:
with open(path, "rb") as f:
head = f.read(64)
if head[:2] != b"MZ" or len(head) < 64:
return {}
f.seek(struct.unpack_from("<I", head, 0x3c)[0])
pe = f.read(26)
if len(pe) < 26 or pe[:4] != b"PE\0\0":
return {}
machine = struct.unpack_from("<H", pe, 4)[0]
return {"exe_32bit": machine == 0x14c, "exe_machine": hex(machine)}
except (OSError, struct.error):
return {}
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def match_profile(games, app, path):
"""Exact canonical name OR SHA-256 OR (exe basename AND byte size). No fuzzy title matches: different store
builds can need different routes. Multiple matches are refused rather than silently picking one."""
hits, digest = [], None
for key, profile in games.items():
match = profile.get("match", {"canonical_names": [key]})
hit = app in match.get("canonical_names", [])
if not hit and path and os.path.isfile(path):
hit = any(os.path.basename(path).lower() == e["name"].lower() and os.path.getsize(path) == e["size"]
for e in match.get("executables", []))
if not hit and match.get("sha256"):
digest = digest or sha256(path)
hit = digest in match["sha256"]
if hit:
hits.append((key, profile))
if len(hits) > 1:
raise ValueError("ambiguous FEX compatibility profiles: " + ", ".join(k for k, _ in hits))
return hits[0] if hits else (None, None)
def graphics_lines(route):
if route not in GRAPHICS:
raise ValueError(f"unknown FEX graphics route: {route}")
# Proton owns DLL selection/copying: DXVK for D3D9/11, vkd3d-proton for D3D12. Do not override DLLs or copy
# anything into the game. Clearing inherited flags also keeps a prior game's wined3d choice from leaking in.
lines = ["unset PROTON_USE_WINED3D PROTON_NO_D3D12 PROTON_NO_D3D11"]
if route == "opengl":
lines.append("export PROTON_USE_WINED3D=1")
lines.append(f"echo 'FramePort FEX: graphics={route}'")
return lines
def register(core):
original_find = core.find_ime_target
def find_ime_target(bins):
# Before ApplicationCore was split out, FWindowsApplication (including its deferral CVar) lived in Core.
# Robo Recall's modular UE4 build has the SAME CVar and constructor instruction there. Search that module
# with the existing anchored finder; never infer a member offset from bAllowedToDeferMessageProcessing.
extra = []
for folder in sorted({os.path.dirname(b) for b in bins}):
extra += [os.path.join(folder, n) for n in sorted(os.listdir(folder))
if re.search(r"(?:^|-)core(?:-win(?:32|64)-shipping)?\.dll$", n, re.I)]
return original_find(list(dict.fromkeys(list(bins) + extra)))
def game_info(app, info):
path = os.path.join(info.get("game_dir") or os.path.join(core.META_DIR, "Software", "Software", app),
info.get("exe", ""))
key, profile = match_profile(core.GAMES, app, path)
if profile is None:
return
status = profile.get("status", "verified") # backward compatible with First Contact's original data
if status not in STATUSES:
raise ValueError(f"invalid FEX profile status: {status}")
info.update({k: v for k, v in profile.items() if k != "match"})
info.update(profile=key, status=status)
def launcher_env(app, info):
lines = graphics_lines(info.get("graphics", "d3d11"))
if info.get("fp_mem") == "enabled":
if info.get("status") != "verified":
raise ValueError("fp_mem requires a verified per-game opt-in")
lines.append("export FP_MEM=1")
lines.append("export FP_BIGCACHE_MB=" + str(int(info.get("bigcache_mb", 256))))
# candidate is informational: never enable the unzeroed cache merely because the engine uses Binned2.
for k, v in info.get("env", {}).items():
if not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", k) or not isinstance(v, str):
raise ValueError("invalid FEX profile environment")
# with the perf extension loaded, perf_prepare writes the game's one dxvk.conf (profile lines + its settings)
if info.get("dxvk") and "perf_prepare" not in core.COMMANDS:
lines += ["printf '%s\\n' " + " ".join(shlex.quote(line) for line in info["dxvk"]) + ' > "$A/dxvk.conf"',
'export DXVK_CONFIG_FILE="$A/dxvk.conf"']
return lines
def checks(app, info, result):
facts = exe_facts(result["exe"])
facts.update(profile=info.get("profile"), profile_status=info.get("status", "untested"),
graphics=info.get("graphics", "d3d11"), fp_mem=info.get("fp_mem", "off"))
# frameport_agent forwards checks to the PC and deployment.json; top-level helper warnings aren't forwarded.
if result.get("warnings"):
facts["profile_warnings"] = result["warnings"]
if facts.get("exe_32bit"):
facts["wow64"] = "untested: requires GE WoW64, 32-bit graphics and SteamVR vrclient bridge under FEX"
if facts["graphics"] == "opengl":
facts["opengl"] = "untested: no FEX GL thunk configured; rootfs GL may use software rendering or Zink"
if facts["graphics"] == "d3d12":
# GE versions have used both split lib/lib64 and architecture-qualified Wine directories. Report what
# is actually installed; the Proton script remains responsible for selecting its own layout.
paths = [os.path.join(core.GE, "files", lib, "wine", "vkd3d-proton", tail, "d3d12.dll")
for lib in ("lib", "lib64") for tail in ("", "x86_64-windows", "i386-windows")]
facts["vkd3d_dlls"] = [os.path.relpath(p, core.GE) for p in paths if os.path.isfile(p)]
return facts
core.GAME_INFO_HOOKS.append(game_info)
core.find_ime_target = find_ime_target
core.LAUNCHER_ENV_HOOKS.append(launcher_env)
core.INSTALL_CHECK_HOOKS.append(checks)
+396
View File
@@ -0,0 +1,396 @@
{
"_comment": [
"FEX compatibility profiles, loaded by fexrift.py and matched by fexrift_compat.py. No entitlement changes.",
"match: OR of canonical_names (exact Meta names), sha256 (list of exe hashes), executables (list of {name,size}, both required). Without match the key is the exact canonical name. Ambiguous matches are refused.",
"status: verified (headset checked), likely (static evidence; install with warning), untested (force_unverified required), blocked (refuse even force). graphics: d3d11|d3d9 (DXVK), d3d12 (vkd3d-proton), opengl (PROTON_USE_WINED3D), vulkan.",
"env: string-valued environment; args: optional launch arguments override (absent keeps manifest). dxvk: dxvk.conf lines written only to the launcher anchor. notes: evidence and first-launch checks. revive: false for direct OpenVR games, otherwise true.",
"ime_patch: optional fallback {rva,old,new}, RVA may be hex; generic finder always wins, including old modular Core.dll. Null means no fallback, never an exemption from IME checks.",
"fp_mem: off|candidate|enabled; candidate is informational and NEVER enables the unzeroed cache. enabled requires verified status. bigcache_mb: cache size when enabled, default 256. env FP_MEM is an explicit opt-in retained for First Contact.",
"exe is the verified First Contact fallback only; other profiles keep the Meta manifest launch path. msaa_ini allows --msaa for that verified game only."
],
"oculus-first-contact": {
"title": "Oculus First Contact",
"exe": "TouchNUX/Binaries/Win64/TouchNUX-Win64-Shipping.exe",
"args": [
"-gamemode=\"experienceonly\""
],
"ime_patch": {
"rva": "0x22a605",
"old": "c7862001000001000000",
"new": "c7862001000000000000"
},
"_env": "Unreal's large-block allocator gives 0.5-1.6 GB blocks back every few seconds and this game overwrites them completely: fp_mem keeps them (native/fexwine/fp_mem.c)",
"env": {
"FP_MEM": "1",
"FP_BIGCACHE_MB": "256"
},
"msaa_ini": true,
"status": "verified",
"graphics": "d3d11",
"fp_mem": "enabled",
"bigcache_mb": 256,
"notes": "Headset verified; r.MobileMSAA=2 prevented rendering. Other games remain unverified."
},
"arktika-1": {
"title": "Arktika 1",
"match": {
"executables": [
{
"name": "arktika1.exe",
"size": 20181504
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "graphics API unclear (?); custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown; d3d11 is a trial default, not a detected API"
},
"asgards-wrath": {
"title": "Asgards Wrath",
"match": {
"executables": [
{
"name": "WrathGame-Win64-Shipping.exe",
"size": 63707648
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "candidate",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR); Media Foundation videos need a playback test"
},
"brass-tactics": {
"title": "Brass Tactics",
"match": {
"executables": [
{
"name": "Brass-Win64-Shipping.exe",
"size": 52790272
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR); Media Foundation videos need a playback test"
},
"chronos": {
"title": "Chronos",
"match": {
"executables": [
{
"name": "Chronos-Win64-Shipping.exe",
"size": 40722432
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": "off",
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "IME fix OFF: the generic finder matched member +0x100 in this UE 4.10 build and the patched game never submitted a frame; unpatched it renders (Frame headless 2026-10-16: 202 frames / 105 s, 1.9 fps while loading, headset not yet checked). Media Foundation videos need a playback test"
},
"defector": {
"title": "Defector",
"match": {
"executables": [
{
"name": "DFCTR.exe",
"size": 16204288
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown"
},
"hubris": {
"title": "Hubris",
"match": {
"executables": [
{
"name": "HubrisVR-Win64-Shipping.exe",
"size": 85706240
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "candidate",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenXR/OpenVR); Media Foundation videos need a playback test"
},
"lies-beneath": {
"title": "Lies Beneath",
"match": {
"executables": [
{
"name": "Kodiak-Win64-Shipping.exe",
"size": 63537664
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "candidate",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR); Media Foundation videos need a playback test"
},
"lone-echo": {
"title": "Lone Echo",
"match": {
"executables": [
{
"name": "loneecho.exe",
"size": 22336512
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown"
},
"lone-echo-2": {
"title": "Lone Echo 2",
"match": {
"executables": [
{
"name": "loneecho2.exe",
"size": 33436160
}
]
},
"status": "untested",
"graphics": "d3d12",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "D3D12: needs vkd3d-proton on Turnip under FEX (untested); custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown"
},
"rick-and-morty-virtual-rick-ality": {
"title": "Rick and Morty - Virtual Rick-ality",
"match": {
"executables": [
{
"name": "RickAndMortyVR.exe",
"size": 21284352
}
]
},
"status": "untested",
"graphics": "opengl",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "OpenGL: no FEX GL thunk configured; rootfs GL renderer unverified; OpenVR directly, no Platform SDK; guest GL and speech WinRT need a device check",
"revive": false
},
"robo-recall": {
"title": "Robo Recall",
"match": {
"executables": [
{
"name": "RoboRecall-Win64-Shipping.exe",
"size": 198144
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR)"
},
"skydances-behemoth": {
"title": "Skydances BEHEMOTH",
"match": {
"executables": [
{
"name": "BHM-Win64-Shipping.exe",
"size": 144449024
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "candidate",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenXR); Media Foundation videos need a playback test"
},
"stormland": {
"title": "Stormland",
"match": {
"executables": [
{
"name": "Stormland.exe",
"size": 85195776
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown; Media Foundation videos need a playback test"
},
"the-climb": {
"title": "The Climb",
"match": {
"executables": [
{
"name": "Climb.exe",
"size": 95534080
}
]
},
"status": "untested",
"graphics": "d3d9",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "D3D9: DXVK under FEX (untested); CryEngine engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown; D3D9 preferred over imported GL; confirm the actual selected renderer"
},
"the-unspoken": {
"title": "The Unspoken",
"match": {
"executables": [
{
"name": "Unspoken.exe",
"size": 69496320
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown; Media Foundation videos need a playback test"
},
"vader-immortal-episode-i": {
"title": "Vader Immortal - Episode I",
"match": {
"executables": [
{
"name": "WKND-Win64-Shipping.exe",
"size": 58100736
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR); Media Foundation videos need a playback test"
},
"vader-immortal-episode-ii": {
"title": "Vader Immortal - Episode II",
"match": {
"executables": [
{
"name": "WKND-Win64-Shipping.exe",
"size": 59464192
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR); Media Foundation videos need a playback test"
},
"vader-immortal-episode-iii": {
"title": "Vader Immortal - Episode III",
"match": {
"executables": [
{
"name": "WKND-Win64-Shipping.exe",
"size": 59814912
}
]
},
"status": "likely",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "same profile as First Contact (x64, D3D11, LibOVR/OpenVR); Media Foundation videos need a playback test"
},
"wilsons-heart": {
"title": "Wilsons Heart",
"match": {
"executables": [
{
"name": "WHVR.exe",
"size": 15379968
}
]
},
"status": "untested",
"graphics": "d3d11",
"env": {},
"ime_patch": null,
"fp_mem": "off",
"bigcache_mb": 256,
"dxvk": [],
"notes": "custom engine: no Unreal/Unity fixes apply; startup/allocator behaviour unknown"
}
}
+361
View File
@@ -0,0 +1,361 @@
"""Local Rift copies in Meta libraries. Runs on the Frame, stdlib only; never touches entitlement or login data."""
import hashlib
import json
import os
import re
import shutil
import subprocess
import time
import uuid
import zlib
SEGMENT_SIZE = 10000000 # Meta's manifest format uses decimal 10 MB, not MiB
def canonical(value):
if not isinstance(value, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]+", value):
raise ValueError("invalid Meta canonical name")
return value
def relative(value):
if not isinstance(value, str):
raise ValueError("invalid relative game path")
value = value.replace("\\", "/")
if (not value or value.startswith("/") or any(p in ("", ".", "..") for p in value.split("/"))
or any(c in value for c in ':\x00\r\n')):
raise ValueError("game path escapes its folder")
return value
def skipped(name):
name = name.replace("\\", "/").rsplit("/", 1)[-1].lower()
return (name.endswith((".7z", ".ag")) or bool(re.search(r"\.7z\.0", name))
or name in ("data.bin", "agrepackinstaller.exe", "vd.bat"))
def confined(path, root):
"""Reject symlink components too: an upload or delete must never follow a game-controlled link."""
root, path = os.path.abspath(root), os.path.abspath(path)
if os.path.commonpath([path, root]) != root:
raise ValueError("path escapes the library")
cursor = path
while True:
if os.path.islink(cursor):
raise ValueError("symlink in local game path")
if cursor == root:
break
cursor = os.path.dirname(cursor)
if os.path.realpath(root) != root:
raise ValueError("symlink in library root")
return path
def hash_file(path):
total, segments = hashlib.sha256(), []
size = 0
with open(path, "rb") as f:
while True:
chunk = f.read(SEGMENT_SIZE)
if not chunk:
break
size += len(chunk)
total.update(chunk)
# The fixture's last element is the zlib-compressed length, not the uncompressed chunk size. The first
# element is an opaque Meta segment identifier: 0 explicitly means unknown for a local-only copy. These
# records register existing bytes; they are NOT a CDN download/repair recipe (device validation needed).
segments.append([0, hashlib.sha256(chunk).hexdigest(), len(zlib.compress(chunk))])
return {"sha256": total.hexdigest(), "size": size, "segmentSize": SEGMENT_SIZE, "segments": segments}
def register(core):
def record_path(app):
return os.path.join(core.ROOT, "local-games", canonical(app) + ".json")
def read_record(app):
return core.read_json(record_path(app)) or {}
def save_record(app, record):
os.makedirs(os.path.dirname(record_path(app)), exist_ok=True)
path = record_path(app)
with open(path + ".tmp", "w") as f:
json.dump(record, f, indent=1)
os.replace(path + ".tmp", path)
def layout(app, dest):
app = canonical(app)
if dest:
# The main agent validates this against list_drives / resolve_dest on EVERY command. No fallback when a
# drive disappears. Keep the physical game path simple while Meta sees its required Software/ layout.
if not os.path.isabs(dest) or not os.path.isdir(dest):
raise ValueError("destination drive is not mounted")
base = confined(os.path.join(dest, "FramePort", "fexrift-games"), dest)
library = confined(os.path.join(dest, "FramePort", "fexrift-library"), dest)
guid = str(uuid.uuid5(uuid.NAMESPACE_URL, "frameport-fex-library:" + dest))
else:
library = os.path.join(core.META_DIR, "Software")
base, guid = os.path.join(library, "Software"), core.LIBRARY_GUID
return {"game_dir": confined(os.path.join(base, app), base), "library": library,
"library_guid": guid, "dest": dest}
def validated_record(app):
rec = read_record(app)
if not rec:
raise ValueError("no local-copy upload reservation for this game")
expected = layout(app, rec.get("dest"))
if any(rec.get(k) != v for k, v in expected.items()):
raise ValueError("local-copy reservation has an invalid storage path")
return rec
def prepare(args):
app = canonical(args["app"])
package = args["package"]
files, seen = {}, set()
for name, st in args["files"].items():
rel = relative(name)
if skipped(rel) or rel.casefold() in seen:
raise ValueError("skipped or duplicate file in upload inventory")
if not isinstance(st["size"], int) or st["size"] < 0 or not isinstance(st["mtime_ns"], int):
raise ValueError("invalid source file stat")
seen.add(rel.casefold())
files[rel] = st
if not files:
raise ValueError("no game files to upload")
old = read_record(app)
dest = args.get("dest") or None
loc = layout(app, dest)
if old and (old.get("dest") != dest or old.get("package") != package):
raise ValueError("local copy already has another package or drive; uninstall it before changing either")
if not old and (os.path.exists(os.path.join(loc["library"], "Manifests", app + ".json"))
or os.path.exists(loc["game_dir"])):
raise ValueError("game already exists outside FramePort's local-copy installer")
existing = {}
for rel, st in files.items():
path = confined(os.path.join(loc["game_dir"], rel), loc["game_dir"])
confined(path + ".part", loc["game_dir"])
if old.get("files", {}).get(rel) != st:
# Delete completed bytes too: if this new attempt is cancelled before uploading them, the next
# prepare must not mistake the old same-size file for a completed transfer of the new source.
for stale in (path, path + ".part"):
if os.path.isfile(stale):
os.unlink(stale)
if (old.get("files", {}).get(rel) == st and os.path.isfile(path)
and os.path.getsize(path) == st["size"]):
existing[rel] = st["size"]
if old and set(old.get("files", {})) - set(files):
raise ValueError("source removed files since the last upload; uninstall the local copy before replacing it")
os.makedirs(loc["game_dir"], exist_ok=True)
st = os.statvfs(loc["game_dir"])
save_record(app, dict(old, **loc, app=app, package=package, files=files))
return dict(loc, existing=existing, free_bytes=st.f_bavail * st.f_frsize)
def registry_library(rec, remove=False):
guid, dest = rec["library_guid"], rec.get("dest")
key = rf"HKEY_CURRENT_USER\Software\Oculus VR, LLC\Oculus\Libraries\{guid}"
if remove:
text = f"Windows Registry Editor Version 5.00\r\n\r\n[-{key}]\r\n"
else:
if dest:
devices = os.path.join(core.PFX, "dosdevices")
os.makedirs(devices, exist_ok=True)
volume = os.path.join(devices, "volume{" + guid + "}")
if os.path.lexists(volume):
if not os.path.islink(volume) or os.path.realpath(volume) != dest:
raise ValueError("Wine volume mapping is already in use")
else:
os.symlink(dest, volume)
# Do not appropriate a user's drive letter. Reuse our mount mapping, else pick the first unused one.
letter = next((c for c in "defghijklmnopqrstuvwxy"
if os.path.islink(os.path.join(devices, c + ":"))
and os.path.realpath(os.path.join(devices, c + ":")) == dest), None)
if not letter:
letter = next((c for c in "defghijklmnopqrstuvwxy"
if not os.path.lexists(os.path.join(devices, c + ":"))), None)
if not letter:
raise ValueError("no free Wine drive letter")
os.symlink(dest, os.path.join(devices, letter + ":"))
rec["drive_letter"] = letter
original = letter.upper() + ":\\FramePort\\fexrift-library"
path = "\\\\?\\Volume{" + guid + "}\\FramePort\\fexrift-library"
else:
original = "C:\\Program Files\\Meta Horizon\\Software"
path = "\\\\?\\Volume{00000000-0000-0000-0000-000000000043}\\Program Files\\Meta Horizon\\Software"
text = "Windows Registry Editor Version 5.00\r\n\r\n"
if not dest:
text += (r"[HKEY_CURRENT_USER\Software\Oculus VR, LLC\Oculus\Libraries]" + "\r\n"
+ '"DefaultLibrary"=' + core.meta_reg_str(guid) + "\r\n\r\n")
text += (f"[{key}]\r\n" + '"OriginalPath"=' + core.meta_reg_str(original) + "\r\n"
+ '"Path"=' + core.meta_reg_str(path) + "\r\n")
reg = os.path.join(core.ROOT, "local-library.reg")
core.put_text(reg, text)
core.wine("regedit", "/S", core.winpath(reg), timeout=90)
def register_local(args):
app = canonical(args["app"])
rec = validated_record(app)
if args.get("package") != rec["package"]:
raise ValueError("upload belongs to another package")
exe = relative(args["exe"])
if exe not in rec["files"]:
raise ValueError("launch program is not an uploaded file")
app_id = args["app_id"]
if not isinstance(app_id, str) or not re.fullmatch(r"[1-9][0-9]*", app_id):
raise ValueError("invalid Meta app ID")
files = {}
for rel, st in rec["files"].items():
path = confined(os.path.join(rec["game_dir"], rel), rec["game_dir"])
if not os.path.isfile(path) or os.path.getsize(path) != st["size"]:
raise ValueError(f"upload incomplete: {rel}")
files[rel] = hash_file(path)
library = rec["library"]
os.makedirs(library, exist_ok=True)
if rec.get("dest"):
software = os.path.join(library, "Software")
target = os.path.dirname(rec["game_dir"])
if os.path.lexists(software):
if not os.path.islink(software) or os.path.realpath(software) != target:
raise ValueError("external Meta library Software path is already in use")
else:
os.symlink(target, software)
args_list = args.get("args") or []
if not isinstance(args_list, list) or any(not isinstance(a, str) or "\x00" in a for a in args_list):
raise ValueError("launch arguments must be strings")
# list2cmdline follows Windows argv quoting; Meta's own launchFile uses forward slashes. The local launcher
# keeps the original argv list in the reservation, avoiding POSIX reinterpretation of Windows quotes.
manifest = core.dawn_manifest({"packageType": "APP", "isCore": False, "appId": app_id,
"canonicalName": app, "launchFile": exe,
"launchParameters": subprocess.list2cmdline(args_list),
"launchParameters2D": "", "version": str(args.get("version") or "0.0.0"),
"versionCode": 1, "files": files})
# App fixtures serialize the manifest's derived properties before the package base properties. Match that
# order (core's runtime package writer uses base-first); both use the same defaults, CRLF and indentation.
first = ("parentCanonicalName", "files", "dlcs", "assetFiles")
manifest = {**{k: manifest[k] for k in first}, **{k: v for k, v in manifest.items() if k not in first}}
manifests = os.path.join(library, "Manifests")
os.makedirs(manifests, exist_ok=True)
for suffix, content in ((".json", manifest), (".json.mini", dict(manifest, files={
k: v for k, v in manifest["files"].items() if k.lower().endswith(".exe")}))):
path = os.path.join(manifests, app + suffix)
core.write_manifest(path + ".tmp", content)
os.replace(path + ".tmp", path)
registry_library(rec)
rec.update({k: args.get(k) for k in ("app_id", "app_id_source", "store_app_id", "skipped", "title")})
rec.update(source="local_copy", exe=exe, args=args_list, registered=True)
save_record(app, rec)
return local_info({"app": app})
def local_info(args):
rec = validated_record(args["app"])
return {k: rec.get(k) for k in ("source", "app_id", "app_id_source", "store_app_id", "skipped", "dest",
"package", "game_dir", "library_guid", "registered")}
def unregister_local(args):
app = canonical(args["app"])
rec = validated_record(app)
if args.get("package") != rec["package"]:
raise ValueError("local copy belongs to another package")
# Shared/default library stays. An external library is removed from the registry only after its last local
# game goes; other games, the Wine prefix, sign-in and save directories remain intact.
peers = [core.read_json(os.path.join(core.ROOT, "local-games", f)) or {}
for f in os.listdir(os.path.dirname(record_path(app))) if f.endswith(".json") and f != app + ".json"]
if rec.get("dest") and not any(p.get("library_guid") == rec["library_guid"] for p in peers):
registry_library(rec, remove=True)
if os.path.isdir(rec["game_dir"]):
shutil.rmtree(rec["game_dir"])
for suffix in (".json", ".json.mini"):
path = os.path.join(rec["library"], "Manifests", app + suffix)
if os.path.isfile(path):
os.unlink(path)
os.unlink(record_path(app))
return {"removed": True}
def runtime_state(args):
app = canonical(args["app"])
rec = validated_record(app) if read_record(app) else None
# Read only newly appended runtime log text. Never return log lines: runtime logs can contain account data.
logdir = os.path.join(core.USER_DIR, "AppData", "Local", "Oculus")
def logs():
return [os.path.join(logdir, n) for n in os.listdir(logdir)
if n.lower().endswith((".txt", ".log")) and any(
s in n.lower() for s in ("server", "service"))] if os.path.isdir(logdir) else []
offsets = {p: os.path.getsize(p) for p in logs()}
librarian = os.path.join(logdir, "OVRLibrarian.log")
lib_offset = os.path.getsize(librarian) if os.path.isfile(librarian) else 0
probe = subprocess.run(["pgrep", "-f", "[O]VRServer_x64.exe"], capture_output=True, timeout=5)
started, proc = probe.returncode != 0, None
end = time.monotonic() + 95 # leave room for wineserver's bounded cleanup, total <=120 s
state = "timeout"
try:
if started:
runtime = os.path.join(core.META_DIR, "Support", "oculus-runtime")
proc = subprocess.Popen([os.path.join(core.GEF, "files/bin/wine"), "./OVRServer_x64.exe"],
cwd=runtime, env=core.wine_env(), stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
while time.monotonic() < end:
if started and os.path.isfile(librarian):
with open(librarian, errors="replace") as f:
if os.path.getsize(librarian) < lib_offset:
lib_offset = 0
f.seek(lib_offset)
done = "invocation completed" in f.read(65536).lower()
lib_offset = f.tell()
if done:
subprocess.run(["pkill", "-9", "-f", "[O]VRLibrarian.exe"], capture_output=True, timeout=3)
for path in logs():
with open(path, errors="replace") as f:
off = offsets.get(path, 0)
f.seek(off if os.path.getsize(path) >= off else 0)
text = f.read(1 << 20)
offsets[path] = f.tell()
for line in text.splitlines():
if app not in line and (not rec or rec.get("app_id", "_") not in line):
continue
match = re.search(r"\bstate\s*:\s*(ready|install_available)\b", line, re.I)
if match:
state = match[1].lower()
# Meta's PackageManager lists every registered package at start ("Currently installed
# package: <name>, version code: N"); the "state:" line only comes later (app tracker / sign-in)
elif state == "timeout" and re.search(r"Currently installed package:\s*" + re.escape(app) + r"\s*,",
line):
state = "installed"
if state != "timeout" or (proc is not None and proc.poll() is not None):
break
time.sleep(1)
finally:
if started:
subprocess.run([os.path.join(core.GEF, "files/bin/wineserver"), "-k"], env=core.wine_env(),
capture_output=True, timeout=10)
if proc is not None:
try:
proc.wait(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
return {"runtime_state": state, "reused_server": not started}
original_manifest = core.manifest_launch
original_info = core.game_info
def manifest_launch(app):
rec = read_record(app)
if not rec.get("registered"):
return original_manifest(app)
rec = validated_record(app)
manifest = core.read_json(os.path.join(rec["library"], "Manifests", app + ".json")) or {}
if not manifest.get("launchFile"):
raise ValueError("local-copy Meta manifest is missing; register the copy again")
return {"exe": relative(manifest["launchFile"]), "args": rec["args"], "title": rec["title"],
"game_dir": rec["game_dir"], "args_argv": True}
def game_info(app):
rec = read_record(app)
if not rec.get("registered"):
return original_info(app)
info = dict(core.GAMES.get(app) or {})
info.update(manifest_launch(app))
return info, app in core.GAMES
core.manifest_launch = manifest_launch
core.game_info = game_info
core.COMMANDS.update(prepare_local=prepare, register_local=register_local, unregister_local=unregister_local,
local_info=local_info, runtime_state=runtime_state)
core.INSTALL_CHECK_HOOKS.append(lambda app, info, result: {"local_copy": True} if read_record(app) else {})
+400
View File
@@ -0,0 +1,400 @@
"""Meta's own browser sign-in, in the Frame's shared prefix. No credential files are read.
The broker is a separate, owner-only Unix socket process: native_sso URLs live only in its memory, never in a
status file, launcher, journal or argv sent over SSH. Helpers and Wine subprocesses have their output discarded.
"""
import base64
import json
import os
import re
import shlex
import signal
import socket
import subprocess
import sys
import time
import urllib.parse
from pathlib import Path
CORE = None
DESKTOP = "frameport-oculus.desktop"
REGKEY = r"HKCU\Software\Wine\WineBrowser"
MAX_URL = 65536
def folder():
return Path(CORE.ROOT) / "login"
def request(message):
with socket.socket(socket.AF_UNIX) as s:
s.settimeout(90)
s.connect(str(folder() / "broker.sock"))
s.sendall(json.dumps(message).encode())
s.shutdown(socket.SHUT_WR)
return json.loads(receive(s))
def receive(s):
data = bytearray()
while True:
part = s.recv(8192)
if not part:
return data.decode()
data.extend(part)
if len(data) > MAX_URL * 2:
raise ValueError("sign-in message too long")
def valid_url(url, callback=False):
if not isinstance(url, str) or len(url) > MAX_URL or any(ord(c) < 32 for c in url):
return False
try:
u = urllib.parse.urlsplit(url)
return (u.scheme, u.netloc, u.path) == (("oculus", "link", "/frl_login") if callback else
("https", "auth.meta.com", "/native_sso/confirm"))
except ValueError:
return False
def host_env():
env = dict(os.environ)
env.update(CORE.steam_display_env())
env.update(XDG_RUNTIME_DIR=f"/run/user/{os.getuid()}",
DBUS_SESSION_BUS_ADDRESS=f"unix:path=/run/user/{os.getuid()}/bus")
env.pop("LD_PRELOAD", None)
return env
def quiet(argv, **kw):
return subprocess.run(argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60, **kw)
def wine_env():
env = CORE.wine_env({"ENABLE_GAMESCOPE_WSI": "0", "PROTON_NO_ZENITY": "1", "PROTONFIXES_DISABLE": "1",
"STEAM_COMPAT_CLIENT_INSTALL_PATH": CORE.STEAM})
env.pop("LD_PRELOAD", None)
env.pop("STEAM_COMPAT_INSTALL_PATH", None)
return env
def snapshot(paths):
return {str(p): base64.b64encode(p.read_bytes()).decode() if p.exists() else None for p in paths}
def restore_files(saved):
for name, data in saved.items():
p = Path(name)
if data is None:
p.unlink(missing_ok=True)
else:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(base64.b64decode(data))
def desktop_paths():
config = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
apps = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share") / "applications"
paths = {apps / DESKTOP, config / "mimeapps.list", apps / "mimeapps.list", apps / "defaults.list"}
for base in (config, apps):
paths.update(base.glob("*-mimeapps.list"))
for desktop in os.environ.get("XDG_CURRENT_DESKTOP", "").lower().split(":"):
if desktop and re.fullmatch(r"[a-z0-9_-]+", desktop):
paths.add(base / f"{desktop}-mimeapps.list")
return apps, paths
def desktop_entry(helper):
# Desktop Exec has its own quoting (single shell quotes are not valid here); %% is a literal percent.
escaped = str(helper).replace("%", "%%")
for c in ("\\", '"', "`", "$"):
escaped = escaped.replace(c, "\\" + c)
escaped = re.sub(r"[\r\n\t]", " ", escaped.replace("\\", "\\\\")) # Desktop string-value layer
return ('[Desktop Entry]\nType=Application\nName=Meta sign-in (FramePort)\n'
f'Exec="{escaped}" %u\nNoDisplay=true\nTerminal=false\nMimeType=x-scheme-handler/oculus;\n')
def helper_script(op):
# This tiny script never imports the core or prints exceptions (which could contain the supplied URL).
return ("#!/usr/bin/python3 -I\nimport json,socket,sys\ntry:\n"
" with socket.socket(socket.AF_UNIX) as s:\n"
" s.settimeout(90)\n"
f" s.connect({str(folder() / 'broker.sock')!r})\n"
f" s.sendall(json.dumps({{'op': {op!r}, 'url': sys.argv[1]}}).encode())\n"
" s.shutdown(socket.SHUT_WR)\n s.recv(4096)\n"
"except Exception:\n sys.exit(1)\n")
def launcher():
q = shlex.quote
env = wine_env()
keys = ("STEAM_COMPAT_DATA_PATH", "WINEPREFIX", "WINEDLLOVERRIDES", "WINEDEBUG", "FP_NATIVE_WSERVER",
"PROTON_NO_ZENITY", "PROTONFIXES_DISABLE", "STEAM_COMPAT_CLIENT_INSTALL_PATH", "XDG_RUNTIME_DIR",
"DBUS_SESSION_BUS_ADDRESS", "ENABLE_GAMESCOPE_WSI")
exports = "".join(f"export {k}={q(env[k])}\n" for k in keys)
display = "".join(f"export {k}={q(v)}\n" for k, v in CORE.steam_display_env().items())
return f'''#!/usr/bin/env bash
# FramePort Meta sign-in: discard Electron output, which can contain native_sso URLs.
exec >/dev/null 2>&1
exec 9>{q(str(folder() / '.launch.lock'))}; flock -n 9 || exit 0
{exports}{display}unset LD_PRELOAD STEAM_COMPAT_INSTALL_PATH STEAM_COMPAT_LIBRARY_PATHS PROTON_LOG PROTON_LOG_DIR
python3 -I {q(str(Path(CORE.HERE) / 'fexrift.py'))} login_ping '{{}}' || exit 0
G={q(CORE.GEF)}
L="$WINEPREFIX/drive_c/users/steamuser/AppData/Local/Oculus"
cleanup() {{
kill $LK 2>/dev/null
"$G/files/bin/wineserver" -k
rm -f {q(str(folder() / 'launch.pid'))}
}}
trap cleanup EXIT
trap 'exit 0' TERM INT HUP
# The start tick prevents --stop from signalling a reused PID after an interrupted launcher.
printf '%s %s\\n' "$$" "$(awk '{{print $22}}' /proc/$$/stat)" > {q(str(folder() / 'launch.pid'))}
cd {q(str(Path(CORE.META_DIR) / 'Support/oculus-runtime'))}
"$G/files/bin/wine" ./OVRServer_x64.exe </dev/null &
for i in $(seq 1 45); do
sleep 2
tail -n 3 "$L/OVRLibrarian.log" 2>/dev/null | grep -qi "invocation completed" && break
done
sleep 3; pkill -9 -f "[O]VRLibrarian.exe"; sleep 10
( while sleep 5; do pkill -9 -f "[O]VRLibrarian.exe"; done ) & LK=$!
cd {q(str(Path(CORE.META_DIR) / 'Support/oculus-client'))}
"$G/proton" run ./Client.exe
'''
def signed_in():
sessions = Path(CORE.PFX) / "drive_c/users/steamuser/AppData/Roaming/Oculus/sessions"
return CORE.signed_in(str(sessions)) # sessions/<numeric user id>/, not Meta's _oaf framework folder
def running(name):
# /proc, rather than pgrep -f, avoids matching the command requesting status. Scope to this prefix.
for p in Path("/proc").glob("[0-9]*/environ"):
try:
if (f"WINEPREFIX={CORE.PFX}".encode() in p.read_bytes().split(b"\0") and
name.encode().lower() in p.with_name("cmdline").read_bytes().lower()):
return True
except OSError:
pass
return False
def status(args):
st = CORE.read_json(str(folder() / "state.json"), {}) or {}
out = {"runtime_running": running("OVRServer_x64.exe"), "client_running": running("Client.exe"),
"page_opened_at": st.get("page_opened_at"), "callback_received_at": st.get("callback_received_at"),
"signed_in": signed_in()}
if args.get("take_url"):
try:
out.update(request({"op": "take_url"}))
except (OSError, ValueError):
pass
return out
def deliver(url):
if not valid_url(url, callback=True):
return {"delivered": False}
try:
# Never put the callback in argv, even between two local processes. The PE reads UTF-8 on stdin.
p = quiet([str(Path(CORE.GEF) / "proton"), "run", str(Path(CORE.HERE) / "fp_pipesend.exe")],
input=url.encode(), env=wine_env())
return {"delivered": p.returncode == 0}
except (OSError, subprocess.SubprocessError):
return {"delivered": False}
class Broker:
def __init__(self, via_pc):
self.via_pc = via_pc
self.pending = None
self.stopped = False
def handle(self, msg):
op = msg.get("op")
if op in ("page", "callback"):
url = msg.get("url")
if not valid_url(url, callback=op == "callback"):
return {"accepted": False}
st = CORE.read_json(str(folder() / "state.json"), {}) or {}
st["page_opened_at" if op == "page" else "callback_received_at"] = time.time()
if op == "page":
st["page_url"] = "https://auth.meta.com/native_sso/confirm"
CORE.write_json(str(folder() / "state.json"), st)
if op == "callback":
return deliver(url)
if self.via_pc:
self.pending = url
else:
quiet(["xdg-open", url], env=host_env())
return {"accepted": True}
if op == "take_url":
url, self.pending = self.pending, None
return {"open_url": url} if url else {}
if op == "stop":
self.pending = None
self.stopped = True
return {"ready": True}
def broker(args):
path = folder() / "broker.sock"
service = Broker(bool(args.get("via_pc")))
try:
with socket.socket(socket.AF_UNIX) as s:
s.bind(str(path))
os.chmod(path, 0o600)
s.listen(4)
s.settimeout(1)
end = time.monotonic() + int(args.get("timeout", 900))
while not service.stopped and time.monotonic() < end:
try:
conn, _ = s.accept()
except TimeoutError:
continue
with conn:
conn.settimeout(5)
try:
reply = service.handle(json.loads(receive(conn)))
conn.sendall(json.dumps(reply).encode())
except (OSError, ValueError, subprocess.SubprocessError):
pass # do not serialize an exception that might contain a URL
finally:
service.pending = None
restore()
path.unlink(missing_ok=True)
return {"stopped": True}
def restore():
path = folder() / "restore.json"
saved = CORE.read_json(str(path), None)
if saved is None:
return
# Keep the restore record until every step succeeds: --stop can repair an interrupted cleanup.
launcher_pid = stop_launcher()
CORE.wineserver_kill()
if launcher_pid:
for _ in range(100):
if process_tick(launcher_pid[0]) != launcher_pid[1]:
break
time.sleep(.1)
else:
raise CORE.FexError("Meta sign-in launcher is still stopping; retry fex login --stop")
(folder() / "launch.pid").unlink(missing_ok=True)
old = saved.get("browser")
if old:
CORE.wine("reg", "add", REGKEY, "/v", "Browsers", "/t", old[0], "/d", old[1], "/f")
else:
CORE.wine("reg", "delete", REGKEY, "/v", "Browsers", "/f", check=False)
restore_files(saved["files"])
path.unlink()
def stop_launcher():
# Killing Wine alone while launch.sh is waiting for OVRLibrarian lets it start Client.exe *after* cleanup.
# Signal the owning shell too; its pending TERM exits the startup loop as soon as the current sleep ends.
path = folder() / "launch.pid"
try:
pid, tick = path.read_text().split()
pid = int(pid)
if pid <= 1:
return
if process_tick(pid) == tick:
os.kill(pid, signal.SIGTERM)
return pid, tick
except (OSError, ValueError, IndexError):
pass
def process_tick(pid):
try:
return Path(f"/proc/{pid}/stat").read_text().rpartition(")")[2].split()[19]
except (OSError, IndexError):
return None
def stop(args):
try:
request({"op": "stop"})
for _ in range(900):
if not (folder() / "broker.sock").exists():
break
time.sleep(.1)
else:
raise CORE.FexError("Meta sign-in is still stopping; retry fex login --stop")
except (OSError, ValueError):
restore()
(folder() / "broker.sock").unlink(missing_ok=True)
return {"stopped": True, "signed_in": signed_in()}
def start(args):
timeout = int(args.get("timeout") or 900)
if not 1 <= timeout <= 86400:
raise CORE.FexError("sign-in timeout must be between 1 and 86400 seconds")
if not (Path(CORE.HERE) / "fp_pipesend.exe").is_file():
raise CORE.FexError("fp_pipesend.exe missing: build native/fexwine/pipesend.c and upload it with fex setup")
if not (Path(CORE.META_DIR) / "Support/oculus-client/Client.exe").is_file():
raise CORE.FexError("Meta's PC app isn't installed yet; run fex setup first")
if running("Client.exe") or running("OVRServer_x64.exe"):
raise CORE.FexError("close the Rift game or Meta app before starting sign-in (the prefix is shared)")
try:
request({"op": "ping"})
except (OSError, ValueError):
pass
else:
raise CORE.FexError("Meta sign-in already active; use fex login --stop first")
stop({}) # repair a previous interrupted run before snapshotting its handler
folder().mkdir(parents=True, exist_ok=True, mode=0o700)
folder().chmod(0o700)
apps, paths = desktop_paths()
previous = subprocess.run(["xdg-mime", "query", "default", "x-scheme-handler/oculus"],
capture_output=True, text=True, timeout=10, env=host_env()).stdout.strip()
reg = CORE.wine("reg", "query", REGKEY, "/v", "Browsers", check=False)
match = re.search(r"Browsers\s+(REG_\w+)\s+(.*)", reg.stdout)
CORE.write_json(str(folder() / "restore.json"),
{"browser": list(match.groups()) if match else None, "handler": previous,
"files": snapshot(paths)})
try:
for name, text in (("fp-open-url", helper_script("page")),
("fp-oculus-callback", helper_script("callback")), ("launch.sh", launcher())):
CORE.put_text(str(folder() / name), text, 0o700)
CORE.write_json(str(folder() / "state.json"), {})
apps.mkdir(parents=True, exist_ok=True)
(apps / DESKTOP).write_text(desktop_entry(folder() / "fp-oculus-callback"))
if quiet(["xdg-mime", "default", DESKTOP, "x-scheme-handler/oculus"], env=host_env()).returncode:
raise CORE.FexError("couldn't register the Frame's temporary oculus link handler")
CORE.wine("reg", "add", REGKEY, "/v", "Browsers", "/t", "REG_SZ", "/d",
str(folder() / "fp-open-url"), "/f")
subprocess.Popen([sys.executable, "-I", str(Path(CORE.HERE) / "fexrift.py"), "login_broker",
json.dumps({"via_pc": bool(args.get("via_pc")), "timeout": timeout + 180})],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
for _ in range(100):
try:
request({"op": "ping"})
break
except (OSError, ValueError):
time.sleep(.05)
else:
raise CORE.FexError("couldn't start Meta sign-in's private URL broker")
if args.get("start_now"):
if quiet(["systemd-run", "--user", "--collect", "--quiet", "--unit=frameport-fexlogin",
"--property=StandardOutput=null", "--property=StandardError=null",
str(folder() / "launch.sh")], env=host_env()).returncode:
raise CORE.FexError("couldn't start Meta's app; retry without --start-now and use Steam")
return {"launcher": str(folder() / "launch.sh"), "started": bool(args.get("start_now")),
"signed_in": signed_in()}
except Exception:
stop({})
raise
def register(core):
global CORE
CORE = core
core.COMMANDS.update(login_start=start, login_status=status, login_stop=stop, login_broker=broker,
login_ping=lambda args: request({"op": "ping"}),
login_callback=lambda args: request({"op": "callback", "url": args.get("url")}))
+575
View File
@@ -0,0 +1,575 @@
"""Launch-time performance experiments. Frame side, stdlib only; no account data is read here.
Settings contain numbers/booleans and a small environment whitelist, never arbitrary shell. A launch prepares its
own config and exports it before Proton starts. Bench owns the otherwise-idle shared prefix for at most 120 s.
"""
import collections
import ctypes as C
import fcntl
import hashlib
import json
import math
import os
import sys
import re
import shlex
import shutil
import signal
import struct
import subprocess
import time
from pathlib import Path
CORE = None
FEX_KEYS = {"FEX_TSOENABLED", "FEX_VECTORTSOENABLED", "FEX_MEMCPYSETTSOENABLED", "FEX_MULTIBLOCK",
"FEX_X87REDUCEDPRECISION"}
DEFAULTS = {"dxvk_disable_msaa": False, "dxgi_sync_interval": -1, "dxgi_max_frame_latency": 0,
"eye_scale": 1.5, "motion_smoothing": 2, "cores": "4-7", "ntsync": True,
"fp_mem": False, "bigcache_mb": 256, "fp_mem_zero": False, "fex": {},
"wine_large_address_aware": False}
BOOL_KEYS = {"dxvk_disable_msaa", "ntsync", "fp_mem", "fp_mem_zero", "wine_large_address_aware"}
INT_KEYS = {"dxgi_sync_interval": (-1, 4), "dxgi_max_frame_latency": (0, 16), "motion_smoothing": (0, 2),
"bigcache_mb": (1, 6144)}
def app_name(app):
if not isinstance(app, str) or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}", app):
raise ValueError("invalid Meta app name")
return app
def validate(values):
if not isinstance(values, dict):
raise ValueError("settings must be an object")
out = {}
for key, value in values.items():
if key in BOOL_KEYS:
if type(value) is not bool:
raise ValueError(f"{key} must be true or false")
elif key in INT_KEYS:
lo, hi = INT_KEYS[key]
if type(value) is not int or not lo <= value <= hi:
raise ValueError(f"{key} must be an integer in {lo}..{hi}")
elif key == "eye_scale":
if type(value) not in (float, int) or value not in (1.0, 1.25, 1.5):
raise ValueError("eye_scale must be 1.0, 1.25 or 1.5 (a divisor)")
elif key == "cores":
if not isinstance(value, str) or not re.fullmatch(r"[0-7](?:-[0-7])?(?:,[0-7](?:-[0-7])?)*", value):
raise ValueError("cores must be a taskset CPU list within 0..7")
if any(len(p) == 3 and p[0] > p[2] for p in value.split(",")):
raise ValueError("cores range is reversed")
elif key == "fex":
if not isinstance(value, dict) or any(k not in FEX_KEYS or type(v) not in (str, int) or
str(v) not in ("0", "1") for k, v in value.items()):
raise ValueError("fex permits only boolean TSO, MULTIBLOCK and X87REDUCEDPRECISION keys")
value = {k: str(v) for k, v in value.items()}
else:
raise ValueError(f"unknown performance setting: {key}")
out[key] = value
return out
def settings_path(app):
return os.path.join(CORE.ROOT, "settings", app_name(app) + ".json")
def settings_get(args):
app = app_name(args["app"])
info = CORE.GAMES.get(app, {})
env = info.get("env", {})
defaults = dict(DEFAULTS, fp_mem=env.get("FP_MEM", "") not in ("", "0"),
bigcache_mb=int(env.get("FP_BIGCACHE_MB", 256)))
defaults.update(validate(info.get("perf", {})))
overrides = validate(CORE.read_json(settings_path(app), {}) or {})
return {"app": app, "settings": dict(defaults, **overrides), "overrides": overrides}
def settings_set(args):
app = app_name(args["app"])
# Validate the whole request before writing. Null removes an override (the catalog/default becomes active).
updates = {k: v for k, v in args.items() if k != "app"}
if any(k not in DEFAULTS for k in updates):
raise ValueError("unknown performance setting")
values = settings_get({"app": app})["overrides"]
values.update(validate({k: v for k, v in updates.items() if v is not None}))
for k, v in updates.items():
if v is None:
values.pop(k, None)
CORE.write_json(settings_path(app), values)
return settings_get({"app": app})
def scale_folder(scale):
return os.path.join(CORE.ROOT, "revive-scales", format(float(scale), "g"))
def eye_variant(data, scale):
"""Only the research Revive 3.2.0 eye-size site, with PE RVA translation. Never touch Oculus binaries.
Accept the stock eye-size load or the research divisor load. Refuse other instructions rather than guessing
at a new Revive build. Use a dedicated padding slot, leaving shared constants in the data section unchanged.
"""
if data[:2] != b"MZ":
raise ValueError("Revive eye scale: invalid PE")
pe = struct.unpack_from("<I", data, 0x3c)[0]
n, opt = struct.unpack_from("<H", data, pe + 6)[0], struct.unpack_from("<H", data, pe + 20)[0]
def offset(rva):
for i in range(n):
size, va, rawsize, raw = struct.unpack_from("<IIII", data, pe + 24 + opt + i * 40 + 8)
if va <= rva < va + min(size, rawsize):
return raw + rva - va
raise ValueError("Revive eye scale: RVA outside sections")
ins, slot = offset(0x12eab), offset(0x12e9c)
# Original movss xmm4,[1.0], or the research patch's load of the existing 1.5 at RVA 0x4eaa4.
# Put our divisor in verified function-alignment padding: changing a shared rdata constant affects other code.
old = data[ins:ins + 8]
original = bytes.fromhex("f30f102515bb0400")
research = b"\xf3\x0f\x10\x25" + struct.pack("<i", 0x4eaa4 - 0x12eb3)
if old not in (original, research) or data[offset(0x12e91)] != 0xc3 or data[slot:slot + 4] != b"\xcc" * 4:
raise ValueError("Revive eye scale: unexpected 3.2.0 eye-size instruction/padding")
out = bytearray(data)
struct.pack_into("<f", out, slot, scale)
out[ins:ins + 8] = b"\xf3\x0f\x10\x25" + struct.pack("<i", 0x12e9c - 0x12eb3)
return bytes(out)
def prepare_scales():
src = Path(CORE.REVIVE)
data = (src / "LibRevive64.dll").read_bytes()
# PC setup validates stock 3.2.0 and applies REVIVE_PATCHES (src/frameport/fexrift.py): the visibility fixes and
# the eye-size redirect to the 1.5 constant. Accept only that upload, or the same without the eye-size redirect.
uploaded = {"eda2a449d230832c95734a03e8c83eeb531668ce676693f636e19c315765af4e", # all six patches
"0a3a6733f5decec74abb16b85c1f72783a6f421160753f600ddae4e8cb6482c6"} # visibility fixes only
if hashlib.sha256(data).hexdigest() not in uploaded:
raise ValueError("Revive eye scale: needs FramePort's patched Revive 3.2.0 upload")
for scale in (1.0, 1.25, 1.5):
patched = eye_variant(data, scale) # validate before replacing any directory
dest = Path(scale_folder(scale))
tmp = dest.with_name(dest.name + ".new")
shutil.rmtree(tmp, ignore_errors=True)
shutil.copytree(src, tmp, copy_function=os.link)
# Break the hard link before changing the DLL: shared base and other variants stay intact.
dll = tmp / "LibRevive64.dll"
dll.unlink()
dll.write_bytes(patched)
shutil.rmtree(dest, ignore_errors=True)
os.replace(tmp, dest)
def perf_prepare(args):
app = app_name(args["app"])
s = settings_get({"app": app})["settings"]
config = os.path.join(CORE.ROOT, "settings", app + ".dxvk.conf")
os.makedirs(os.path.dirname(config), exist_ok=True) # first launch of a game nobody changed settings for
managed = ("d3d11.disableMsaa", "dxgi.syncInterval", "dxgi.maxFrameLatency") # these settings win
profile = [str(line) for line in args.get("dxvk", []) if "\n" not in str(line)
and str(line).split("=", 1)[0].strip() not in managed]
lines = profile + [f"{k} = {s[key]}" for k, key, default in (
("d3d11.disableMsaa", "dxvk_disable_msaa", False), ("dxgi.syncInterval", "dxgi_sync_interval", -1),
("dxgi.maxFrameLatency", "dxgi_max_frame_latency", 0)) if s[key] != default]
# Defaults = exactly the launch verified in the headset (First Contact, 2026-10-10): no dxvk.conf, the uploaded
# Revive (its eye-size patch is 1.5), no large-address-aware flag; only a changed setting adds something.
if lines:
CORE.put_text(config, "\n".join(lines + [""]))
elif os.path.lexists(config):
os.remove(config)
if s["eye_scale"] == 1.5:
revive = CORE.REVIVE
else:
revive = scale_folder(s["eye_scale"])
if not os.path.isfile(os.path.join(revive, "LibRevive64.dll")):
prepare_scales()
exports = {"FP_CORES": s["cores"], "FP_REVIVE_DIR": revive,
"FP_MEM": "1" if s["fp_mem"] else "", "FP_BIGCACHE_MB": str(s["bigcache_mb"]),
"FP_MEM_ZERO": "1" if s["fp_mem_zero"] else "0", "PROTON_NO_NTSYNC": "0" if s["ntsync"] else "1",
"FP_MOTION_SMOOTHING": json.dumps({"section": f"steam.app.{CORE.GAME_ID}",
"key": "motionSmoothingOverride", "kind": "i",
"value": s["motion_smoothing"]})}
exports.update({k: str(s["fex"].get(k, "0" if "TSO" in k else "1" if k == "FEX_MULTIBLOCK" else "0"))
for k in FEX_KEYS})
if lines:
exports["DXVK_CONFIG_FILE"] = config
if s["wine_large_address_aware"]:
exports["WINE_LARGE_ADDRESS_AWARE"] = "1"
shell = "\n".join(f"export {k}={shlex.quote(v)}" for k, v in exports.items())
if s["ntsync"]:
shell += "\nunset PROTON_NO_NTSYNC"
return {"shell": shell, "settings": s}
def launcher_env(app, info):
# stdout is an isolated helper's JSON, then a tiny decoder emits only validated exports. Failure aborts launch:
# continuing with an old config would give misleading experimental results (and could enable stale fp_mem).
# the compat profile's dxvk.conf lines (stream C) go into the same per-game config as these settings
dxvk = [str(line) for line in info.get("dxvk", []) if "\n" not in str(line) and "\r" not in str(line)]
arg = shlex.quote(json.dumps({"app": app_name(app), "dxvk": dxvk}))
decode = 'import json,sys; print(json.load(sys.stdin)["result"]["shell"])'
return [f'FP_PERF=$(python3 -I "$R/artifacts/fexrift.py" perf_prepare {arg}) || exit 1',
f'eval "$(printf \'%s\' "$FP_PERF" | python3 -I -c {shlex.quote(decode)})"']
# OpenVR IVRCompositor_022 Compositor_FrameTiming, including its 80-byte TrackedDevicePose_t. Keeping the tail
# prevents GetFrameTimings overwriting a truncated ctypes structure. Versions are pinned, never probed by index.
class FrameTiming(C.Structure):
_fields_ = [(n, C.c_uint32) for n in ("size", "index", "presents", "mis_presents", "dropped", "reprojection")]
_fields_ += [("system_time", C.c_double)]
_fields_ += [(n, C.c_float) for n in ("pre_gpu", "post_gpu", "gpu_ms", "compositor_gpu", "compositor_cpu",
"compositor_idle", "client_interval", "present_call", "wait_present",
"submit", "poses_called", "poses_ready", "frame_ready", "update_start",
"update_end", "render_start")]
_fields_ += [("pose", C.c_byte * 80), ("vsyncs_ready", C.c_uint32), ("vsyncs_first", C.c_uint32)]
class VR:
def __init__(self):
self.core, self.method, self.settings = CORE.vr_settings()
try:
self.compositor = self.interface(b"IVRCompositor_022")
self.system = self.interface(b"IVRSystem_022")
except BaseException:
self.close()
raise
def interface(self, name):
err = C.c_int()
obj = self.method(self.core, 3, C.c_void_p, C.c_char_p, C.POINTER(C.c_int))(name, C.byref(err))
if not obj or err.value:
raise ValueError("benchmark needs " + name.decode())
return obj
def activity(self):
# IVRSystem_022::GetTrackedDeviceActivityLevel(HMD=0). UserInteraction (1) and its timeout (2) refuse.
return self.method(self.system, 15, C.c_int, C.c_uint32)(0)
def screen_timeout(self):
err = C.c_int()
value = self.method(self.settings, 7, C.c_float, C.c_char_p, C.c_char_p, C.POINTER(C.c_int))(
b"power", b"turnOffScreensTimeout", C.byref(err))
if err.value or not math.isfinite(value) or value <= 0:
raise ValueError("cannot read screen timeout; benchmark refused")
return value
def timings(self):
rows = (FrameTiming * 128)()
for row in rows:
row.size = C.sizeof(FrameTiming)
n = self.method(self.compositor, 9, C.c_uint32, C.POINTER(FrameTiming), C.c_uint32)(rows, 128)
return [{"index": r.index, "presents": r.presents, "gpu_ms": r.gpu_ms,
"cpu_ms": r.client_interval, "system_time": r.system_time} for r in rows[:min(n, 128)]]
def scene_pid(self):
return self.method(self.compositor, 22, C.c_uint32)() # GetCurrentSceneFocusProcess
def close(self):
self.method(self.core, 1, None)()
def drm_engines(text):
"""DRM fdinfo nanoseconds, deduplicated by drm-client-id by the caller (dup fds share one client)."""
out = {}
for line in text.splitlines():
m = re.fullmatch(r"drm-engine-([\w-]+):\s*(\d+)\s+ns", line.strip())
if m:
out[m[1]] = int(m[2])
return out
def process_sample(pids, proc="/proc"):
engines, waits, seen = {}, collections.Counter(), set()
for pid in pids:
base = Path(proc) / str(pid)
for fd in (base / "fdinfo").glob("*"):
try:
text = fd.read_text()
except OSError:
continue
client = re.search(r"^drm-client-id:\s*(\d+)", text, re.M)
device = re.search(r"^drm-pdev:\s*(.+)", text, re.M)
if not client:
continue
identity = (device[1] if device else "", client[1])
if identity in seen:
continue
seen.add(identity)
for engine, ns in drm_engines(text).items():
engines[(identity, engine)] = ns
for task in (base / "task").glob("*"):
try:
waits[task.joinpath("wchan").read_text().strip()] += 1
except OSError:
pass
return engines, waits
def gpu_delta(before, after):
# Clients that open during the interval have no baseline; do not attribute their lifetime counters to one tick.
return sum(max(0, v - before[k]) for k, v in after.items() if k in before)
def processes(proc="/proc"):
out = {}
for p in Path(proc).glob("[0-9]*"):
try:
if p.stat().st_uid != os.getuid():
continue
cmd = p.joinpath("cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace")
comm = p.joinpath("comm").read_text().strip()
out[int(p.name)] = (comm, cmd)
except OSError:
pass
return out
def busy_processes(rows):
# Do not print cmdlines: another stream may be handling an Oculus browser sign-in.
return [pid for pid, (comm, cmd) in rows.items() if
(re.search(r"(?i)(\.exe(?: |$)|(?:^|/)(?:proton|wine(?:64)?(?:-preloader)?)(?: |$)|lepton-steamlaunch-)",
cmd)
or (comm == "reaper" and not re.search(r"\bAppId=250820\b", cmd))
or comm.startswith("wineserver") or comm in ("FEXInterpreter", "FEXLoader", "pressure-vessel"))]
def recent_steam_input(steam, now=None):
"""Steam input log is a supplementary guard, HMD activity is the authoritative one. Never read login logs."""
now = time.time() if now is None else now
path = Path(steam) / "logs/controller.txt"
try:
# A recent controller log write can be a device reconnection, so conservatively refuse it too.
return now - path.stat().st_mtime < 60
except FileNotFoundError:
return False
def vr_set(section, key, kind, value):
# In its own process: cmd_vrsetting in the process that holds VR()'s SteamVR connection segfaulted on the
# second call (reproduced on the Frame 2026-10-16) after the first had turned the display's standby pause off.
result = vrsetting_subprocess(section, key, kind, value)
if result.get("error"):
raise ValueError(f"SteamVR refused {section}/{key}")
def stop_launcher(child):
# The shared prefix was verified idle before launch, so -k cannot interrupt an earlier game or login.
try:
subprocess.run([os.path.join(CORE.GEF, "files/bin/wineserver"), "-k"], env=CORE.wine_env(),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
finally:
if child is not None:
try:
os.killpg(child.pid, signal.SIGTERM)
child.wait(timeout=5)
except ProcessLookupError:
pass
except subprocess.TimeoutExpired:
os.killpg(child.pid, signal.SIGKILL)
child.wait(timeout=5)
START_WAIT = 180 # seconds the bench waits for the game's process after starting its launcher
def bench_run(args, launcher, vr):
seconds = args.get("seconds", 120)
if type(seconds) is not int or not 1 <= seconds <= 120:
raise ValueError("seconds must be an integer in 1..120")
if busy_processes(processes()) or recent_steam_input(CORE.STEAM) or vr.activity() != 3:
raise ValueError("benchmark refused: game, Wine, container, HMD activity or recent Steam input")
screen = vr.screen_timeout() # no setting is changed until both safety checks and this read succeed
vrserver_log = os.path.join(CORE.STEAM, "logs", "vrserver.txt")
log_start = os.path.getsize(vrserver_log) if os.path.isfile(vrserver_log) else 0
guard_write(screen=screen) # before any change: the parent restores from it if this process dies
child, old_handler = None, None
settings = settings_get(args)["settings"]
frames, waits, gpu, gpu_seconds = {}, collections.Counter(), 0, 0.0
started = time.monotonic()
def interrupted(signum, frame):
raise ValueError("benchmark interrupted")
try:
old_handler = signal.signal(signal.SIGTERM, interrupted)
vr_set("power", "pauseCompositorOnStandby", "b", False)
vr_set("power", "turnOffScreensTimeout", "f", float(seconds + START_WAIT + 10))
# Save the initial frame index so stale scene frames in the compositor ring are excluded.
initial = {r["index"] for r in vr.timings()}
with open(os.devnull, "wb") as sink:
child = subprocess.Popen([launcher], stdin=subprocess.DEVNULL, stdout=sink, stderr=sink,
start_new_session=True, close_fds=True)
guard_write(screen=screen, pgid=getattr(child, "pid", None))
# The launcher starts Meta's runtime and waits for it (60-100 s under FEX) before the game: the window
# starts when the game's process appears, not at the launch.
wait_end = time.monotonic() + START_WAIT
while not [q for q, (_, cmd) in processes().items() if args["exe"].lower() in cmd.lower()]:
if time.monotonic() > wait_end:
raise ValueError(f"benchmark: the game didn't start within {START_WAIT} s; inspect launch.log")
if child.poll() is not None:
raise ValueError("benchmark launcher exited before the game started; inspect launch.log")
level = vr.activity()
if level == 1: # controller.txt isn't a signal here: the starting game loads its input bindings
raise ValueError(f"benchmark stopped: owner interaction (activity {level})")
time.sleep(1)
before, previous = {}, time.monotonic()
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
# Before the launch the headset must be in standby (3); the game itself then wakes the compositor
# (activity leaves standby), so during the run only real use stops it: 1 = user interaction (worn or
# moved), or new controller input.
level = vr.activity()
if level == 1: # controller.txt isn't a signal here: the starting game loads its input bindings
raise ValueError(f"benchmark stopped: owner interaction (activity {level})")
if child.poll() is not None:
raise ValueError("benchmark launcher exited before the sampling window ended; inspect launch.log")
rows = processes()
# Only the actual game's exe (or FEX's argv containing it), not the runtime/compositor GPU client.
pids = [p for p, (_, cmd) in rows.items() if args["exe"].lower() in cmd.lower()]
after, w = process_sample(pids)
now = time.monotonic()
if before.keys() & after.keys():
gpu += gpu_delta(before, after)
gpu_seconds += now - previous
before, previous = after, now
waits.update(w)
focus = vr.scene_pid()
for r in vr.timings():
if focus in pids and r["index"] not in initial:
frames[r["index"]] = r # ring revisits update presents, not another frame
time.sleep(min(0.5, max(0, deadline - time.monotonic())))
finally:
# Each cleanup is attempted even when the preceding one fails. Display safety outranks benchmark success.
try:
stop_launcher(child)
finally:
try:
vr_set("power", "pauseCompositorOnStandby", "b", True)
finally:
try:
vr_set("power", "turnOffScreensTimeout", "f", screen)
finally:
if old_handler is not None:
signal.signal(signal.SIGTERM, old_handler)
records = list(frames.values())
# Without a tracking universe (IMU fallback, e.g. after a boot without the headset worn) Rift games wait at
# startup forever: SteamVR's own frames are all a run then counts (seen 2026-10-16, ~1.9/s, game GPU ~0 %).
imu_fallback = False
try:
with open(vrserver_log, errors="replace") as f:
f.seek(log_start if os.path.getsize(vrserver_log) >= log_start else 0)
imu_fallback = "IMU fallback is active" in f.read(8 << 20)
except OSError:
pass
duration = max(0.001, time.monotonic() - started)
times = [r["system_time"] for r in records]
span = max(times) - min(times) if len(times) > 1 else 0
return {"app": args["app"], "seconds": seconds, "elapsed_s": round(duration, 3), "frames": len(records),
"imu_fallback": imu_fallback, # true: the result says nothing about the game (put the headset on once)
"valid": len(records) >= 2 and span > 0 and not imu_fallback, "sample_span_s": round(span, 3),
"fps": round((len(records) - 1) / span, 2) if span > 0 else None,
"hitches": sum(r["presents"] >= 3 for r in records),
"hitches_per_20s": round(20 * sum(r["presents"] >= 3 for r in records) / span, 2) if span > 0 else None,
"game_gpu_busy_pct": round(100 * gpu / (gpu_seconds * 1e9), 2) if gpu_seconds else None,
"render_gpu_ms": round(sum(r["gpu_ms"] for r in records) / len(records), 3) if records else None,
"client_interval_ms": round(sum(r["cpu_ms"] for r in records) / len(records), 3) if records else None,
"thread_wchan_samples": dict(waits), "settings": settings}
def bench(args):
app = app_name(args["app"])
# Launcher path is supplied by the owning agent's deployment record, not an arbitrary remote shell command.
launcher = args["launcher"]
if not os.path.isfile(launcher) or os.path.basename(launcher) != "launch.sh":
raise ValueError("install the game before benchmarking")
info, _ = CORE.game_info(app)
exe = os.path.basename(info["exe"].replace("\\", "/"))
os.makedirs(CORE.ROOT, exist_ok=True)
with open(os.path.join(CORE.ROOT, ".bench.lock"), "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
return bench_guarded(dict(args, app=app, exe=exe), launcher)
# The measurement talks to SteamVR through ctypes (vrclient.so). A native crash there kills the process without
# running bench_run's finally, which once left pauseCompositorOnStandby=false (display kept on) on the Frame
# (2026-10-16). So it runs in a forked child, and the parent restores the display settings and stops the game from
# a guard file when the child returns no result, each restore in its own process (another crash can't skip it).
def guard_path():
return os.path.join(CORE.ROOT, ".bench.guard.json")
def guard_write(**kw):
CORE.write_json(guard_path(), kw)
def vrsetting_subprocess(section, key, kind, value):
"""fexrift.py vrsetting in a fresh process: {"error": code} from SteamVR, or {"error": "..."} if it failed."""
arg = json.dumps({"section": section, "key": key, "kind": kind, "value": value})
p = subprocess.run([sys.executable, "-I", os.path.join(CORE.HERE, "fexrift.py"), "vrsetting", arg],
capture_output=True, text=True, timeout=60)
try:
out = json.loads(p.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
return {"error": f"vrsetting exited {p.returncode}"}
return out.get("result", {}) if out.get("ok") else {"error": out.get("error", "failed")}
def crash_cleanup():
guard = CORE.read_json(guard_path(), {}) or {}
try:
if guard.get("pgid"):
try:
os.killpg(int(guard["pgid"]), signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
subprocess.run([os.path.join(CORE.GEF, "files/bin/wineserver"), "-k"], env=CORE.wine_env(),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
finally:
vrsetting_subprocess("power", "pauseCompositorOnStandby", "b", True)
if guard.get("screen") is not None:
vrsetting_subprocess("power", "turnOffScreensTimeout", "f", float(guard["screen"]))
def bench_guarded(args, launcher):
read_fd, write_fd = os.pipe()
pid = os.fork()
if pid == 0: # child: measure, report through the pipe
os.close(read_fd)
code = 0
try:
vr = VR()
try:
out = {"ok": True, "result": bench_run(args, launcher, vr)}
finally:
vr.close()
except Exception as e: # noqa: BLE001 - reported to the parent as the command's error
out, code = {"ok": False, "error": f"{type(e).__name__}: {e}"}, 1
with os.fdopen(write_fd, "w") as w:
w.write(json.dumps(out))
os._exit(code)
os.close(write_fd)
try:
with os.fdopen(read_fd) as r:
raw = r.read()
_, status = os.waitpid(pid, 0)
out = json.loads(raw) if raw.strip() else None
if out is None: # crashed or killed: bench_run's own cleanup didn't run
crash_cleanup()
raise ValueError(f"benchmark process died ({'signal ' + str(-os.waitstatus_to_exitcode(status)) if os.WIFSIGNALED(status) else 'no result'}); display settings restored, game stopped")
if not out["ok"]:
raise ValueError(out["error"])
return out["result"]
finally:
try:
os.remove(guard_path())
except FileNotFoundError:
pass
def register(core):
global CORE
CORE = core
core.COMMANDS.update(settings_get=settings_get, settings_set=settings_set, perf_prepare=perf_prepare, bench=bench)
core.LAUNCHER_ENV_HOOKS.append(launcher_env)
# Use the existing setup step so --steps revive prepares the variants too, without another download.
def revive():
result = core.step_revive()
prepare_scales()
return result
core.STEPS = [(name, revive if name == "revive" else fn) for name, fn in core.STEPS]
+424 -29
View File
@@ -44,7 +44,7 @@ try:
except ImportError: # Windows: pc_revive loads this file for its VDF code only (GitHub #131)
fcntl = None
AGENT_VERSION = 89
AGENT_VERSION = 94
HOME = os.path.expanduser("~")
STEAM = os.path.join(HOME, ".local/share/Steam")
ANCHORS = os.path.join(HOME, "Applications/quest-frame")
@@ -957,7 +957,10 @@ def vdf_decode(data):
else:
raise AgentError(f"unsupported VDF value type {kind}; not modifying shortcuts.vdf")
if key in out:
raise AgentError("duplicate VDF key; not modifying shortcuts.vdf")
old_key = out._key(key)
# Older agents wrote lowercase twins of Steam's capitalized keys. Keep their position.
if key[:1].isupper() and not old_key[:1].isupper():
out = VdfMap((key if k == old_key else k, v) for k, v in out.items())
out[key] = value
root = node()
@@ -1139,7 +1142,7 @@ def shortcut_args(pkg):
icon = app_icon_for(dep, anchor, steam=True)[0] # a Linux app's own icon unless the user chose one
flat = dep.get("vr") is False
kind = dep.get("kind")
tag = ("Windows game on Frame" if flat else "PC VR on Frame") if kind == "pcvr" else \
tag = ("Windows game on Frame" if flat else "PC VR on Frame") if kind in ("pcvr", "frame_fex") else \
"Linux app on Frame" if kind == "linux" else "Quest on Frame"
return f'"{anchor}/launch.sh"', dep["title"], anchor, icon, tag, dep.get("tags") or [], not flat
@@ -1888,7 +1891,7 @@ def app_media_dirs(ext):
def lepton_external(pkg):
dep = deployment(pkg)
if not dep or dep.get("kind") == "pcvr":
if not dep or dep.get("kind") in ("pcvr", "frame_fex"):
raise AgentError(f"{pkg} is not an installed Quest (Lepton) game")
return os.path.join(dep["base"], "lepton-data", "external")
@@ -3043,7 +3046,7 @@ setsid {lepton_q} start >"$app_dir/launch.log" 2>&1 &
child=$!
{dashboard}
{logcat}
wait "$child"
{restart}
""")
@@ -3070,10 +3073,11 @@ SINGLE_LINE = ('exec 9>"$app_dir/.launch.lock"; flock -n 9 || '
'exit 0; }')
# Lepton mirrors the game's logcat into launch.log, and that reader sometimes dies right after the game starts
# ("logcat: Unexpected EOF!", seen with Vader Immortal on Lepton 3.0.5 and Under Cover on 2.8.14). The game runs on,
# but launch.log stays empty: no dashboard auto-hide, no launch-test result. _logcat_keeper then reads the
# container's logcat itself and appends it to launch.log.
# Lepton mirrors the game's logcat into launch.log, and that reader sometimes fails: it dies right after the game
# starts ("logcat: Unexpected EOF!", Vader Immortal on Lepton 3.0.5, Under Cover on 2.8.14), can't read ("Logcat read
# failure"), or runs and writes nothing (Lepton 3.0.5, 2026-10-14). The game runs on, but launch.log stays empty: no
# dashboard auto-hide, no launch-test result, no session triage. _logcat_keeper then reads the container's logcat
# itself and appends it to launch.log.
LOGCAT_LINE = ('python3 {agent_q} _logcat_keeper "$app_dir/launch.log" "$SteamAppId" $$ '
'>"$app_dir/logcat-keeper.log" 2>&1 9>&- &')
@@ -3088,6 +3092,71 @@ def dashboard_line():
return DASHBOARD_LINE.format(agent_q=shlex.quote(os.path.abspath(__file__)))
# Unreal (4.21+, r.ProgramBinaryCache.RestartAndroidAfterPrecompile) restarts the app once after its first-run shader
# precompile (the "optimizing" screen): it starts its own launcher activity and exits. Lepton ends the container when
# the first process exits, the restarted game with it (Sports Scramble stopped after its first start; skipping the
# restart left it on that screen). The launcher then starts Lepton once more, in the same Steam launch
# (_restart_requested reads the two logs). FRAMEPORT_NO_RESTART=1 turns it off.
RESTART_BLOCK = """rc=0; wait "$child" || rc=$?
if [[ -z "${{FRAMEPORT_NO_RESTART:-}}" ]] && python3 {agent_q} _restart_requested "$app_dir/launch.log" "$SteamAppId" \\
{pkg_q} 9>&-; then
mv -f "$app_dir/launch.log" "$app_dir/launch-before-restart.log" 2>/dev/null || true
setsid {lepton_q} start >"$app_dir/launch.log" 2>&1 &
child=$!
{dashboard}
rc=0; wait "$child" || rc=$?
fi
exit $rc"""
def restart_block(pkg, lepton):
return RESTART_BLOCK.format(agent_q=shlex.quote(os.path.abspath(__file__)), pkg_q=shlex.quote(pkg),
lepton_q=shlex.quote(lepton), dashboard=dashboard_line())
LOGCAT_TIME = re.compile(r"^(?:\x1b\[[0-9;]*m)?(\d\d-\d\d \d\d:\d\d:\d\d\.\d{3})")
def restart_requested(log, appid, pkg, max_gap=5.0):
"""Whether the game that just ended asked to be started again (RESTART_BLOCK): in Lepton's system log (dumped to
lepton-logcats/steamlaunch-<appid>/ when the container ends) the app itself (uid >= 10000; Lepton's own start is
uid 0) started its LAUNCHER activity by package, and at most max_gap s later the game's process called
System.exit(0) (launch.log; Android's WebView helper does too at every boot)."""
def when(line):
m = LOGCAT_TIME.match(line)
if not m:
return None
try:
t = time.strptime("2000-" + m.group(1)[:14], "%Y-%m-%d %H:%M:%S")
except ValueError:
return None
return time.mktime(t) + float(m.group(1)[14:])
try:
with open(log, errors="replace") as f:
exits = [when(ln) for ln in f if "System.exit called, status: 0" in ln and "WebViewLoader" not in ln]
syslog = os.path.join(STEAM, "logs", "lepton-logcats", f"steamlaunch-{appid}", "logcat-system.log")
with open(syslog, errors="replace") as f:
starts = []
for ln in f:
m = re.search(r"ActivityTaskManager: START u0 \{act=android\.intent\.action\.MAIN "
r"cat=\[android\.intent\.category\.LAUNCHER\][^}]* pkg=" + re.escape(pkg)
+ r"[ }][^\n]* from uid (\d+)", ln)
if m and int(m.group(1)) >= 10000:
starts.append(when(ln))
except OSError:
return False
for e in exits:
if e is not None and any(s is not None and 0 <= e - s <= max_gap for s in starts):
try:
with open(log, "a") as f:
f.write("FramePort: the game restarted itself (e.g. Unreal after its first-run shader "
"precompile): starting it again\n")
except OSError:
pass
return True
return False
def logcat_line():
return LOGCAT_LINE.format(agent_q=shlex.quote(os.path.abspath(__file__)))
@@ -3139,6 +3208,15 @@ def upgrade_launchers():
# the lock belongs to Lepton only: helpers that outlive the game must not keep it
new = new.replace("; fi; done ) & permfix=$!", "; fi; done ) 9>&- & permfix=$!", 1)
new = new.replace('>"$app_dir/dashboard.log" 2>&1 &', '>"$app_dir/dashboard.log" 2>&1 9>&- &', 1)
if "_restart_requested" not in new and new.endswith('\nwait "$child"\n') and "_dashboard_worker" in new:
m = re.search(r'\nsetsid (\S+) start >', new)
pkg = os.path.basename(os.path.dirname(path))
try:
lepton = shlex.split(m.group(1))[0] if m else None
except ValueError:
lepton = None
if lepton:
new = new[:-len('wait "$child"\n')] + restart_block(pkg, lepton) + "\n"
if PLAYS_LOG not in new:
start, end = plays_lines(os.path.dirname(path))
if "\nsetsid " in new and "\n trap - EXIT INT TERM\n" in new: # Lepton launcher
@@ -3531,7 +3609,7 @@ def write_launcher(anchor, base, pkg, title, appid, lepton, env, hw_video=False,
cloud_dirs=cloud_dirs_line(pkg),
video_codec=wrapper_lines(hw_video, gamepad),
plays_start=plays_lines(anchor)[0],
plays_end=plays_lines(anchor)[1])
plays_end=plays_lines(anchor)[1], restart=restart_block(pkg, lepton))
text = set_config_sync_line(text, pkg, config_sync)
path = os.path.join(anchor, "launch.sh")
with open(path + ".tmp", "w") as f:
@@ -5382,8 +5460,11 @@ def cmd_uninstall(args):
base = dep["base"]
pcvr = dep.get("kind") == "pcvr"
linux = dep.get("kind") == "linux"
if (pcvr_pids(base) if pcvr or linux else container_running(dep["appid"])):
fex = dep.get("kind") == "frame_fex"
if (pcvr_pids(base) if pcvr or linux or fex else container_running(dep["appid"])):
raise AgentError("the game is running")
if fex: # the game lives in the shared Meta runtime prefix (with the user's login): only the launcher goes
return fex_uninstall(pkg, dep, args)
if is_overlay(dep) or os.path.exists(os.path.join(ANCHORS, pkg, OVERLAY_MANIFEST)):
unregister_overlay(pkg) # SteamVR forgets the overlay app (before its manifest's folder goes)
keep_data = args.get("keep_data", True)
@@ -5734,6 +5815,8 @@ def cmd_stop(args):
run(["systemctl", "--user", "stop", f"frameport-test-{dep['appid']}"])
if dep.get("kind") == "pcvr":
stop_pcvr(dep)
elif dep.get("kind") == "frame_fex": # the launcher's EXIT trap stops Wine (wineserver -k)
run(["pkill", "-TERM", "-f", re.escape(os.path.join(ANCHORS, dep["package"], "launch.sh"))])
elif dep.get("kind") == "linux":
for pid in pcvr_pids(dep["base"]):
run(["kill", "-TERM", pid])
@@ -5846,6 +5929,8 @@ def cmd_launch_test(args):
if is_overlay(dep): # nothing to see without a game; register_vr_overlay's SteamVR check is the test
return {"state": "SKIPPED", "skipped": "overlay app", "elapsed": 0, "log": None, "log_size": 0,
"crash_log": None, "kind": dep.get("kind")}
if dep.get("kind") == "frame_fex":
raise AgentError("launch tests aren't available for Rift games with Meta's runtime (experimental) yet")
if dep.get("kind") == "pcvr":
return launch_test_pcvr(dep, anchor, log, seconds)
if dep.get("kind") == "linux":
@@ -6778,15 +6863,42 @@ def user_opened_dashboard(log, pos):
LOGCAT_EOF = "logcat: Unexpected EOF"
# Lepton's mirror fails in more ways than one: it ends ("Unexpected EOF"), can't read ("Logcat read failure"), or
# prints nothing at all after "Waiting for app" (seen on a first start after an APK change, 2026-10-14)
LOGCAT_FAILURES = (LOGCAT_EOF, "logcat: Logcat read failure")
LOGCAT_ROW = re.compile(r"\d\d-\d\d \d\d:\d\d:\d\d\.\d{3} +\d+ +\d+ [VDIWEF] ") # a logcat -v threadtime line
LEPTON_ROW = re.compile(r"\x1b\[[0-9;]*m\d\d-\d\d \d\d:\d\d:\d\d\.\d{3} ") # Lepton's mirror colours its lines
LOGCAT_SILENCE = 20.0 # seconds without a logcat line after "Waiting for app" = the mirror isn't working (a running
# game's container logs all the time: FrameBridge alone every 5 s)
LOGCAT_BUFFER = "16M" # the container's log buffer: a chatty game overwrote its own first minutes in the default one
def logcat_keeper(log, appid, parent, poll=2.0, restarts=5, popen=None):
"""Keep launch.log filling when Lepton's logcat mirror dies while the game runs (LOGCAT_LINE): once the log shows
LOGCAT_EOF after "Waiting for app", read the container's logcat ourselves (from its last 2000 lines, so the start
of the game isn't lost) and append it; restart it if it ends while the game still runs (at most `restarts` times).
Ends with the launcher."""
def logcat_keeper(log, appid, parent, poll=2.0, restarts=5, popen=None, run=None, clock=None,
silence=LOGCAT_SILENCE):
"""Keep launch.log filling when Lepton's logcat mirror doesn't (LOGCAT_LINE): after "Waiting for app", a failure
line (LOGCAT_FAILURES) or `silence` seconds without a logcat line start our own reader of the container's logcat
(`logcat -T <epoch>`: from the launcher's start when the mirror never wrote a line, else from just before its
last one; nothing is lost while the buffer holds it); restarted from where it stopped if it ends while the game
runs (at most `restarts` times), stopped again when Lepton's own (coloured) lines come back. Enlarges the
container's log buffer once it has booted. Every decision is printed (the launcher sends it to
logcat-keeper.log). Ends with the launcher."""
popen = popen or subprocess.Popen
run = run or subprocess.run
clock = clock or time.time
container = f"lepton-steamlaunch-{appid}"
start = clock() # the keeper starts with the launcher
# (Steam's LD_PRELOAD overlay libraries only add "ld.so: ... cannot be preloaded" lines to the log)
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
def say(text):
print(f"{time.strftime('%H:%M:%S')} {text}", flush=True)
def note(text): # also into launch.log, where triage and the dashboard worker read
try:
with open(log, "a") as f:
f.write(f"FramePort: {text}\n")
except OSError:
pass
def alive():
try:
@@ -6795,31 +6907,79 @@ def logcat_keeper(log, appid, parent, poll=2.0, restarts=5, popen=None):
except (OSError, ValueError):
return False
proc, started = None, 0
pos, booted, buffer_tries, waiting_since = 0, False, 0, None
lepton_rows, last_row, failure, proc, started = False, None, None, None, 0
while alive():
if proc is None or proc.poll() is not None:
try:
with open(log, "rb") as f:
f.seek(pos)
chunk = f.read().decode("utf-8", "replace")
pos = f.tell()
except OSError:
chunk = ""
if not booted and "Boot complete!" in chunk:
booted = True
if booted and buffer_tries < 5:
buffer_tries += 1
try:
with open(log, errors="replace") as f:
text = f.read()
except OSError:
text = ""
i = text.find("Waiting for app")
if i >= 0 and LOGCAT_EOF in text[i:] and started < restarts:
r = run(["podman", "exec", container, "logcat", "-G", LOGCAT_BUFFER], capture_output=True,
text=True, timeout=15, env=env)
ok = r.returncode == 0
say(f"log buffer {LOGCAT_BUFFER}: {'set' if ok else (r.stdout + r.stderr).strip()[:200]}")
except (OSError, subprocess.SubprocessError) as exc:
ok = False
say(f"log buffer {LOGCAT_BUFFER}: {exc}")
if ok:
buffer_tries = 5
if waiting_since is None:
i = chunk.find("Waiting for app")
if i >= 0:
waiting_since, chunk = clock(), chunk[i:]
say("Lepton is waiting for the app; watching its logcat mirror")
if waiting_since is not None and chunk:
ours = proc is not None and proc.poll() is None
if ours and LEPTON_ROW.search(chunk):
proc.terminate()
proc, failure, lepton_rows, last_row = None, None, True, clock()
say("Lepton's mirror is writing again: stopped our reader")
note("Lepton's logcat is back; stopped FramePort's reader")
elif not ours:
if any(m in chunk for m in LOGCAT_FAILURES):
failure = next(m for m in LOGCAT_FAILURES if m in chunk)
elif LOGCAT_ROW.search(chunk):
lepton_rows, last_row = True, clock()
if waiting_since is not None and (proc is None or proc.poll() is not None):
if proc is not None: # our reader ended while the game runs: go on from where it stopped
say(f"our reader ended ({proc.poll()})")
proc, lepton_rows, last_row = None, True, clock() # (go on from about now)
failure = failure or "FramePort's reader ended"
quiet = clock() - (last_row or waiting_since)
after = "" if lepton_rows else " after the app started"
reason = failure or (None if quiet < silence else f"no logcat line for {quiet:.0f} s{after}")
if reason and started < restarts:
started += 1
with open(log, "a") as f:
f.write(f"FramePort: Lepton's logcat ended; reading {container}'s logcat again ({started})\n")
# nothing came through yet: everything since the start; else from just before the last line seen
since = start if not lepton_rows else last_row - poll - 1
say(f"reading {container}'s logcat ourselves since {since:.3f} ({started}): {reason}")
note(f"Lepton's logcat isn't coming through ({reason}); reading {container}'s logcat ({started})")
out = open(log, "ab")
try:
proc = popen(["podman", "exec", container, "logcat", "-v", "threadtime", "-T", "2000"],
stdout=out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
proc = popen(["podman", "exec", container, "logcat", "-v", "threadtime", "-T", f"{since:.3f}"],
stdout=out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, env=env)
except OSError as exc:
print(f"logcat_keeper: {exc}", flush=True)
say(f"could not start logcat: {exc}")
proc = None
finally:
out.close()
# what our reader writes is ours: only Lepton's coloured lines count from here on
try:
pos = os.path.getsize(log)
except OSError:
pass
time.sleep(poll)
if proc is not None and proc.poll() is None:
proc.terminate()
say("launcher ended")
def dashboard_worker(log, parent, wait_start=240, window=120, poll=0.5, ui_log=None, max_hides=10):
@@ -7753,6 +7913,239 @@ def monitor_session(stdin, stdout, monitor=None, sleep=time.sleep, max_ticks=Non
return 0
# ------------------------------------------------------------------------------------------ Rift via FEX (experimental)
# Oculus Rift games that need Meta's PC runtime, on the Frame alone: x86_64 GE-Proton under FEX + Meta's runtime +
# Revive in one shared Wine prefix. The work is done by fexrift.py (uploaded with its binaries by the PC, see
# src/frameport/fexrift.py and native/fexwine/README.md); these commands only start it and track games (kind
# "frame_fex"; the game's files stay inside the prefix where Meta's app put them).
FEX_ROOT = os.path.join(HOME, ".local/share/frameport/fexrift")
FEX_ARTIFACTS = os.path.join(FEX_ROOT, "artifacts")
FEX_HELPER = os.path.join(FEX_ARTIFACTS, "fexrift.py")
def fex_helper(command, args=None, timeout=900):
if not os.path.isfile(FEX_HELPER):
raise AgentError("the files for Rift games on the Frame aren't here yet (run the setup first)")
# Game inventories can exceed Linux's per-argument limit; the helper already accepts JSON on stdin.
p = run([sys.executable, "-I", FEX_HELPER, command], input=json.dumps(args or {}), timeout=timeout)
try:
out = json.loads(p.stdout.strip().splitlines()[-1])
except (IndexError, ValueError):
raise AgentError(f"fexrift {command} failed: {(p.stderr or p.stdout)[-400:]}") from None
if not out.get("ok"):
raise AgentError(out.get("error") or f"fexrift {command} failed")
return out["result"]
def cmd_fex_prepare(args):
"""Where the PC uploads fexrift.py + its binaries (artifacts/) and the login archive (incoming/), and what's
already there (unchanged files aren't re-sent)."""
incoming = os.path.join(FEX_ROOT, "incoming")
for d in (FEX_ARTIFACTS, incoming):
os.makedirs(d, exist_ok=True)
os.chmod(incoming, 0o700)
st = os.statvfs(FEX_ROOT)
return {"root": FEX_ROOT, "artifacts": FEX_ARTIFACTS, "incoming": incoming,
"existing": tree_manifest(FEX_ARTIFACTS), "free_bytes": st.f_bavail * st.f_frsize,
"fex": os.path.isdir(os.path.join(STEAM, "steamapps/common/FEX-Emu"))}
def cmd_fex_status(args):
if not os.path.isfile(FEX_HELPER):
return {"helper": False}
res = fex_helper("status", timeout=60)
res["helper"] = True
return res
def cmd_fex_setup(args):
"""Start the setup (GE-Proton download, Meta's runtime from Meta's CDN, the prefix): ~10-20 min, detached;
progress via fex_status (setup.state / step / error)."""
if not os.path.isfile(FEX_HELPER):
raise AgentError("upload the files first (fex_prepare)")
steps = [s for s in args.get("steps") or [] if re.fullmatch(r"[a-z]+", str(s))]
unit = f"frameport-fexsetup-{int(time.time())}"
p = run(["systemd-run", "--user", "--collect", "--quiet", f"--unit={unit}", "--setenv=HOME=" + HOME,
sys.executable, "-I", FEX_HELPER, "setup", json.dumps({"steps": steps})])
if p.returncode != 0:
raise AgentError(f"couldn't start the setup: {p.stderr.strip()[-300:]}")
return {"started": True, "unit": unit}
def cmd_fex_import_login(args):
"""The login archive the PC uploaded to incoming/login.tar (fexrift.py deletes it afterwards)."""
return fex_helper("import_login", {"tar": os.path.join(FEX_ROOT, "incoming", "login.tar")})
# Local-copy extension commands: validate removable storage here (the helper has no drive discovery). Never let a
# missing mount silently turn an SD-card install into an upload to the root filesystem.
def fex_local_dest(dest):
if not dest or dest == "internal":
return None
for d in cmd_drives({})["drives"]:
if not d["internal"] and d["path"] == dest:
resolve_dest(dest) # existing filesystem / writable-mount checks
return dest
raise AgentError("--dest must name an available external drive's mount point (see frame drives)")
def cmd_fex_prepare_local(args):
pkg = check_pkg(args["package"])
dep = deployment(pkg)
if dep and (dep.get("kind") != "frame_fex" or dep.get("source") != "local_copy"
or dep.get("app") != args.get("app")):
raise AgentError(f"{pkg} is already installed in another way; uninstall it first")
return fex_helper("prepare_local", dict(args, package=pkg, dest=fex_local_dest(args.get("dest"))))
def cmd_fex_register_local(args):
info = fex_helper("local_info", {"app": args["app"]})
fex_local_dest(info.get("dest"))
return fex_helper("register_local", args, timeout=7200) # hashes large copies on the Frame, not on NTFS
def cmd_fex_runtime_state(args):
return fex_helper("runtime_state", {"app": args["app"]}, timeout=120)
# Browser sign-in: this block deliberately uses stdin, not fex_helper's JSON argv. A callback carries credentials.
FEX_LOGIN_PACKAGE = "linux.frameport_meta_signin"
def fex_login_call(command, args=None):
if not os.path.isfile(FEX_HELPER):
raise AgentError("run fex setup before signing in")
p = subprocess.run([sys.executable, "-I", FEX_HELPER, command], input=json.dumps(args or {}),
capture_output=True, text=True, timeout=120)
try:
out = json.loads(p.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
raise AgentError("Meta sign-in helper did not answer") from None
if not out.get("ok"):
# No raw subprocess output in errors for the commands handling URLs.
raise AgentError(out.get("error", "Meta sign-in failed") if command == "login_start" else
"Meta sign-in helper failed; retry fex login --stop")
return out["result"]
def cmd_fex_login(args):
result = fex_login_call("login_start", {"start_now": bool(args.get("start_now")),
"via_pc": bool(args.get("via_pc")),
"timeout": int(args.get("login_timeout") or 900)})
if not args.get("start_now"):
anchor = os.path.join(ANCHORS, FEX_LOGIN_PACKAGE)
os.makedirs(anchor, exist_ok=True)
launcher = os.path.join(anchor, "launch.sh")
if os.path.lexists(launcher):
os.remove(launcher)
os.symlink(result["launcher"], launcher)
with open(os.path.join(anchor, "deployment.json"), "w") as f:
json.dump({"package": FEX_LOGIN_PACKAGE, "kind": "linux", "title": "Meta sign-in (FramePort)",
"base": os.path.join(FEX_ROOT, "login"), "vr": False, "desktop_entry": False,
"appid": shortcut_appid(f'"{launcher}"', "Meta sign-in (FramePort)")}, f)
result["package"] = FEX_LOGIN_PACKAGE
return result
def cmd_fex_login_status(args):
return fex_login_call("login_status", {"take_url": bool(args.get("take_url"))})
def cmd_fex_login_callback(args):
return fex_login_call("login_callback", {"url": args.get("url")})
def cmd_fex_login_cancel(args):
result = fex_login_call("login_stop")
anchor = os.path.join(ANCHORS, FEX_LOGIN_PACKAGE)
if os.path.exists(os.path.join(anchor, "deployment.json")):
cmd_shortcuts({"remove": [{"exe": f'"{anchor}/launch.sh"'}], "restart": True})
devkit_unregister(FEX_LOGIN_PACKAGE, steam_running=run(["pgrep", "-x", "steam"]).returncode == 0)
remove_tree(anchor)
return result
def cmd_fex_install(args):
"""A game Meta's app downloaded (now in the prefix) as a Steam game: per-game fixes + launch.sh +
deployment.json (kind frame_fex). The Steam shortcut is added like for other games (shortcuts)."""
pkg = check_pkg(args["package"])
app = str(args.get("app") or "")
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]+", app):
raise AgentError(f"bad app name {app!r}")
anchor = os.path.join(ANCHORS, pkg)
dep = deployment(pkg)
if dep and dep.get("kind") != "frame_fex":
raise AgentError(f"{pkg} is already installed in another way")
local = None
if args.get("source") == "local_copy" or (dep or {}).get("source") == "local_copy":
local = fex_helper("local_info", {"app": app})
if local.get("package") != pkg or not local.get("registered"):
raise AgentError("local copy must be registered for this package first")
fex_local_dest(local.get("dest"))
msaa = args.get("msaa")
res = fex_helper("install", {"app": app, "anchor": anchor, "msaa": msaa if msaa in (1, 2, 4) else None,
"force_unverified": bool(args.get("force_unverified"))})
title = str(args.get("title") or res.get("title") or pkg).replace("\n", " ")
appid = dep["appid"] if dep else shortcut_appid(f'"{anchor}/launch.sh"', title)
dep = {"package": pkg, "kind": "frame_fex", "app": app, "appid": int(appid), "title": title,
"base": res["game_dir"], "exe": res["exe"], "tags": args.get("tags") or [], "vr": True,
"fixes": {k: res.get(k) for k in ("ime_patch", "msaa")}, "verified": bool(res.get("verified")),
"checks": res.get("checks") or {},
"agent_version": AGENT_VERSION, "installed": int(time.time())}
if local:
dep.update({k: local.get(k) for k in ("source", "app_id", "app_id_source", "store_app_id", "skipped", "dest")})
path = os.path.join(anchor, "deployment.json")
with open(path + ".tmp", "w") as f:
json.dump(dep, f, indent=1)
os.replace(path + ".tmp", path)
return {"package": pkg, "appid": dep["appid"], "title": title, "launcher": res["launcher"], "fixes": dep["fixes"],
"verified": dep["verified"], "checks": dep["checks"]}
# ---------------------------------------------------------------------- FEX launch-time settings / bounded bench
# Kept separate from install: settings are read at launch and never require changing the game's files.
def cmd_fex_settings(args):
values = args.get("values")
if values is not None and (not isinstance(values, dict) or "app" in values):
raise AgentError("values must be a settings object without app")
return fex_helper("settings_set" if values is not None else "settings_get",
dict(values or {}, app=args["app"]), timeout=60)
def cmd_fex_bench(args):
seconds = args.get("seconds", 120)
if type(seconds) is not int or not 1 <= seconds <= 120:
raise AgentError("seconds must be an integer in 1..120")
if game_running(): # includes Lepton containers even when their processes are in another PID namespace
raise AgentError("benchmark refused: a game or container is running")
app = args["app"]
for pkg in sorted(os.listdir(ANCHORS)) if os.path.isdir(ANCHORS) else []:
dep = deployment(pkg)
if dep and dep.get("kind") == "frame_fex" and dep.get("app") == app:
return fex_helper("bench", {"app": app, "seconds": seconds,
"launcher": os.path.join(ANCHORS, pkg, "launch.sh")},
timeout=seconds + 240) # + the wait for the game to start (START_WAIT)
raise AgentError("install this FEX game before benchmarking")
def fex_uninstall(pkg, dep, args):
"""Meta-owned games stay; FramePort local copies lose their game folder and manifests, preserving the prefix."""
anchor = os.path.join(ANCHORS, pkg)
if dep.get("source") == "local_copy":
fex_local_dest(dep.get("dest"))
fex_helper("unregister_local", {"app": dep["app"], "package": pkg}, timeout=180)
removed_sc = False
if args.get("remove_shortcut") and steam_users():
removed_sc = cmd_shortcuts({"remove": [{"exe": f'"{anchor}/launch.sh"', "appid": dep.get("appid")}]})["started"]
if args.get("remove_shortcut"):
try:
devkit_unregister(pkg, steam_running=run(["pgrep", "-x", "steam"]).returncode == 0)
except Exception: # noqa: BLE001 (the files go anyway at the next purge)
pass
remove_tree(anchor)
return {"removed": True, "kept_saves": True, "shortcut_removed": removed_sc}
COMMANDS = {n[4:]: f for n, f in globals().items() if n.startswith("cmd_")}
@@ -7785,6 +8178,8 @@ def main():
if len(sys.argv) >= 4 and sys.argv[1] == "_gamepad_links":
gamepad_links(sys.argv[2], sys.argv[3])
return 0
if len(sys.argv) >= 5 and sys.argv[1] == "_restart_requested":
return 0 if restart_requested(sys.argv[2], sys.argv[3], sys.argv[4]) else 1
if len(sys.argv) >= 4 and sys.argv[1] == "_dashboard_worker":
dashboard_worker(sys.argv[2], sys.argv[3])
return 0
+7 -4
View File
@@ -1,5 +1,8 @@
1a4dce5c4a6d0dfc5f20e55ac29e70c73cc2cc124c21ca6a7e1b316e6afb1c79 ./arm64-v8a/libVkLayer_fdm_darken.so
5becb96ee86fbda0ce98c0e0fd064f8ba092314aceaa400e3dcc785705dc3c23 ./arm64-v8a/libVkLayer_fp_shaderfix.so
fbc3b0238462d976d234fee6740db92b873c85d6bb22a6b01428e64e9058ed83 ./arm64-v8a/liba32bridge.so
c9c3da5cac224c38e2210b781bd12b7f97e02bd6b0ebb0ef85543e4ea4b76671 ./arm64-v8a/liba32rt.so
18d8d917e83a6d87008f41908eb478dff635e798844e125abd1e8a5cf31805e2 ./arm64-v8a/liba32stub.so
d6337034fb0bdcca7ef9b7063d85b7586b8508b63b435959e8fffaba0691091c ./arm64-v8a/libfp_langpack.so
69102b128e00fa1809489a7308e09c1505f563bf7091bbdd3fe5a58e4cc96c2c ./arm64-v8a/libfp_luajit.so
321da502e0f8f46f0880aad39fe6b84bdef88f925164568814cf704a1b31a577 ./arm64-v8a/libfp_ovrp.so
@@ -10,11 +13,11 @@ e8c0965c188665a4e565e4a3af983ef1866d1cf9225665cc90d8df286bc96ef3 ./arm64-v8a/li
5432674a59d02f411cd853a5dc57e3fa547d1ac518f25bf433fc54c43677177a ./arm64-v8a/libfpglmv.so
8a8f6b1da8952cb3933a5b53558424a5fc56043b2527a16bb6dd62a00d2de01a ./arm64-v8a/libframe_xrshim.so
19ba5ed3c4b780f5ae46251f6958f552acfc5f13c8bb39f995579593fa8990c6 ./arm64-v8a/libglshim.so
51f5e0c5b3d3556baab27ece2936257782d6b590183ae59601cc6d8158c96ee2 ./arm64-v8a/libopenxr_loader_generic.so
0f058921e9c1f5b9ef5847cc9e6b80a23e75028c76c1d3bb02d1610b535f81c9 ./arm64-v8a/libopenxr_loader_generic.so
1feaeafad467c4cafdf2b018a4d84b0bee200c3f711697b4ce97e66a3ba256ca ./arm64-v8a/libovrplatformcompat.so
7f30861c770361a4e311e3f486dcd2e48cd99a7f907961829ce68e24af17d775 ./arm64-v8a/libvrapi.so
7f30861c770361a4e311e3f486dcd2e48cd99a7f907961829ce68e24af17d775 ./arm64-v8a/libvrapi_foveation.so
6927f100536283a8c26b784af73ee400140dd910e9294e4a9d55f855547ffaf2 ./armeabi-v7a/libopenxr_loader_generic.so
a4ed80ae45ca90758239f152ea5a2e8c127d491e1e697ea5680db6fd7f72db07 ./arm64-v8a/libvrapi.so
a4ed80ae45ca90758239f152ea5a2e8c127d491e1e697ea5680db6fd7f72db07 ./arm64-v8a/libvrapi_foveation.so
9e8a7ce599b62a7c607b0d3637e4ec1b1ea1974c3373a7af3f5920ad2adc5e00 ./armeabi-v7a/libopenxr_loader_generic.so
1871eae093432d277da4bc751bf5f3269dfcf11f9168260b0c3caadb0dedb19d ./dex/oculusos-stubs.dex
b634ab5640e258563c536e658cad87080553df6f34f62269a21d554844e58bfe ./hevc/COPYING.FFmpeg
141de01f0d40b97d4f9a720db5ab8ea442f6aa35db5272048899292884994a1c ./hevc/libstagefrighthw.so
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Regular → Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
3e9099b5015e8f486c00bcea9d111ee721faba355a89bcf1df69561e3dc6325c ./digicert-assured-id-root-ca.der
e04db8044185c1c77941252e61794e84af7156c449fedcda4a826d7a9fc91989 ./dlls/crypt32.dll
ec1387fad1f9b65503077e5aa24e3a3b60b3b04b85fd9412e0f2c451772f9b25 ./dlls/dnsapi.dll
00ebfab0f3a066d9c85820332e0ec91cf4040797e580516dcafa048dfe758aa7 ./dlls/sechost.dll
41584c41db41991f20a0b55011efa94618e0817ab351579f793ca01dbb488a0e ./dlls/windows.devices.enumeration.dll
420b21045ddc4f166733bf6d2d7227f0131e20f161c4568accb2b9c15a6d8e86 ./fp_mem.so
f8d6aaaa123337c47837d0be5852f7f6687bb9c4bfaaa108aaab3f04af1ad5b9 ./fp_pipesend.exe
13d455b700b08f40eb3e3452ab264bf535cb3d176c92ec9a3324a635ce4f8588 ./windows.devices.wifi.dll
941a65274007db76b1c40880117fe7d881db32c5394ad09f80ccc44a08213a75 ./wineserver.arm64
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+14 -9
View File
@@ -4,14 +4,19 @@ tested_version: '1.0'
source_hint: Sports Scramble
engine: Unreal
xr: VrApi
status: unsupported
notes: 32-bit only; the Frame has no AArch32.
details: 32-bit (armeabi-v7a) only; the Frame has no AArch32.
alt_overport:
- patch_remove_unreal_force_quit
status: works
notes: 32-bit only (armeabi-v7a), runs through FramePort's 32-bit bridge (experimental). Both controllers work as
Touch controllers. The first start shows a one-time "optimizing" screen (a bit jittery) and then starts the game
again by itself.
details: 'Unreal Engine 4 NativeActivity with OVRPlugin + VrApi, GLES, OBB. The bridge needed AAsset_getBuffer
(copied into guest memory), AKeyEvent_getFlags and the remaining AConfiguration getters. A Santa Cruz (early
Quest) build: it requires 6DoF head tracking, so the bridge passes both Frame controllers through as Touch
controllers (assets/fp_a32_headset.txt) instead of the Gear VR remote. Unreal restarts the app after its
first-run shader precompile; the launcher starts Lepton again for it (agent 86). Plays in the headset (owner,
2026-10-13).'
frame:
- frame.a32_bridge
pcvr_alternative: Rift only; not on the Revive compatibility list.
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: e2e6788da99e2a38ea8f1e83e997ab44fed5492ce117d99ee3d376e6faeb0de4
date: '2026-10-13'
min_app: 0.12.1
@@ -0,0 +1,22 @@
package: com.FireproofStudios.GhostTown
title: Ghost Town
status: works
tested_version: '1.01'
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
- frame.hw_video_decode
device:
- device.text_input_window
adapter:
haptic_fix: 1
verified:
date: '2026-10-14'
known_good_sha256: 248b59ade696bdd4808fc05c2117aa9e8debe133d3d0874a276cc8cb67439f58
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 299
source_hint: Ghost Town
+24
View File
@@ -0,0 +1,24 @@
package: com.MeatSpace.Nakatomi
title: Vendetta Forever
status: works
tested_version: 1.0.4.0
engine: Unity
xr: OpenXR
frame:
- frame.bhaptics_permission
- frame.unity_text_input
- frame.unity_runtime_msaa_off
- frame.unity_gl_shim
device:
- device.text_input_window
adapter:
haptic_fix: 1
verified:
date: '2026-10-15'
known_good_sha256: 72885ad42f1b730a1bd7fad271b87665914e3cf14fde60409395868458ac7b06
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 321
source_hint: com.MeatSpace.Nakatomi
@@ -0,0 +1,23 @@
package: com.PotamWorks.SmashDrums
title: Smash Drums
status: works
tested_version: 5.2.1.4
engine: Unity
xr: OpenXR
frame:
- frame.bhaptics_permission
- frame.unity_text_input
device:
- device.text_input_window
adapter:
haptic_fix: 1
scene_emul: 1
verified:
date: '2026-10-15'
known_good_sha256: 67d36cdcadaf14c2f744849ae25af4f92bf8ea14ff935318562f40d7f2ddc88f
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 320
source_hint: com.PotamWorks.SmashDrums
@@ -0,0 +1,24 @@
package: com.RuneSkovboJohansen.EyeOfTheTemple
title: Eye of the Temple
status: works
tested_version: '1.528'
engine: Unity
xr: VrApi
frame:
- frame.unity_no_msaa
- frame.unity_oculus_check
- frame.unity_text_input
- frame.unity_runtime_msaa_off
- frame.hw_video_decode
- frame.unity_gl_shim
device:
- device.text_input_window
adapter:
haptic_fix: 1
verified:
date: '2026-10-15'
known_good_sha256: 78ad96eaf4383b02666e0a1af99c5985f718f97982466e5dca9ebb636974af00
app: 1.1.1
overport_cli: 1.2.5
issue: 302
source_hint: Eye of the Temple
@@ -0,0 +1,25 @@
package: com.TacticalNounours.QuantumVoid
title: Quantum Void
status: issues
notes: no hands
tested_version: '1.11'
engine: Unity
xr: OpenXR
frame:
- frame.bhaptics_permission
- frame.unity_text_input
device:
- device.text_input_window
adapter:
haptic_fix: 1
pose_time_fix: 1
foveation: tracked
verified:
date: '2026-10-14'
known_good_sha256: 1c7afccbd627b9bd2342884679aeca0efc2429df700f3c73ec162498db320098
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 307
source_hint: Quantum Void
+2 -2
View File
@@ -5,7 +5,7 @@ source_hint: Assassins Creed Nexus VR
engine: Unity
xr: OpenXR
status: works
notes: FrameBridge turns its upside-down UI panels upright (flip emulation, in place since FramePort 1.1.2). Ubisoft
notes: FrameBridge turns its upside-down UI panels upright (flip emulation, in place since FramePort 1.2.0). Ubisoft
login may not work.
details: Ubisoft online login may not work. Data folder holds raw assets (start0..2, .climb, bundles), not .obb
files; install to obb as-is.
@@ -19,4 +19,4 @@ verified:
no_appsw_90: '2026-10-02, OVRPort 1.2.5 (owner: 90 Hz felt better than 72 Hz; same known issues)'
flip_in_place: '2026-10-14, owner in the headset: launch warnings and tutorial pop-ups upright (GitHub #138)'
updated: '2026-10-14'
min_app: 1.1.2
min_app: 1.2.0
@@ -0,0 +1,22 @@
package: com.Virtuallyz.OperationWolf
title: 'Operation Wolf Returns: First Mission VR'
status: works
tested_version: '0.28'
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
- frame.hw_video_decode
device:
- device.text_input_window
adapter:
haptic_fix: 1
verified:
date: '2026-10-15'
known_good_sha256: aff311f10d3e938e1eeef22263da7fe84ca38f25786ca4483543596de335c702
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 318
source_hint: com.Virtuallyz.OperationWolf
+19
View File
@@ -0,0 +1,19 @@
package: com.Virtuos.R6DLM
title: 'Medal of Honor: Above and Beyond'
status: unknown
notes: 'Not yet tested on the Frame (the game is ~41 GB, too large to install on the dev unit). Its first-run
Downloader screen is invisible in Lepton, so it stayed stuck there; frame.unreal_skip_obb_delivery skips the check.
The OBB files still have to be present. Please report back whether it reaches the game (GitHub 159).'
details: 'Medal of Honor packs its data in OBBs behind Epic''s DownloaderActivity, whose name/size check is
obfuscated (its methods are renamed), so FramePort didn''t recognise it and the "skip the OBB delivery check"
option never appeared. Detection now recognises the obfuscated predicate and frame.unreal_skip_obb_delivery
rewrites it to pass. frame.hw_video_decode gives the game''s videos the Frame''s hardware decoder.'
tested_version: '0.518'
engine: Unreal
xr: VrApi
frame:
- frame.hw_video_decode
- frame.unreal_skip_obb_delivery
updated: '2026-10-15'
min_app: 1.2.0
source_hint: Medal of Honor
+20
View File
@@ -0,0 +1,20 @@
package: com.ccpgames.gunjack
title: Gunjack
status: works
notes: 'Gear VR game (32-bit only), runs through FramePort''s 32-bit bridge (experimental). Controls (right
controller): trigger = fire (hold the touchpad), A = tap, stick down = reload (swipe back), stick up = special
weapon (swipe forward), B = back.'
details: 'Unreal Engine 4.10 NativeActivity, VrApi, GLES, OBB inside the APK (assets/main.obb.png). The bridge answers
the game''s APK signature check with the original APK''s certificate and keeps the GLES session when Unreal leaves
and re-enters VR after loading. Controller input goes into the game''s AInputQueue as Gear VR touchpad events.
Runs in the headset (owner, 2026-10-12).'
tested_version: 1.4.1
engine: Unreal
xr: VrApi
headset: gearvr
frame:
- frame.a32_bridge
verified:
date: '2026-10-12'
min_app: 0.12.1
source_hint: Gunjack (Gear VR)
@@ -0,0 +1,23 @@
package: com.coatsink.augmentedempireremastered
title: AugmentedEmpire
status: works
tested_version: '1.1'
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
- frame.hw_video_decode
device:
- device.text_input_window
adapter:
haptic_fix: 1
scene_emul: 1
verified:
date: '2026-10-15'
known_good_sha256: e07afd561c305493cf09efe9c869be892e475a48538dfdf617e33a0be2e6c678
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 311
source_hint: com.coatsink.augmentedempireremastered
+11 -8
View File
@@ -4,13 +4,16 @@ tested_version: '1.4'
source_hint: Shadow Point
engine: Unity
xr: VrApi
status: unsupported
notes: 32-bit only; the Frame has no AArch32.
details: 32-bit (armeabi-v7a) only; the Frame has no AArch32. 64-bit conversion was researched and dropped (IL2CPP
+ FMOD + custom rasterizer).
status: works
notes: 32-bit only (armeabi-v7a), runs through FramePort's 32-bit bridge (experimental). Plays in the headset.
details: 'Unity with OVRPlugin + VrApi, GLES. Needed the bridge''s vrapi_GetTrackingTransform/SetTrackingTransform
(the game sets its floor level through them; without them the player stood below the floor). Plays in the headset
(owner, 2026-10-14).'
frame:
- frame.a32_bridge
device:
- device.text_input_window
pcvr_alternative: Rift version via Revive + SteamVR.
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: ea0c0d09d2c3d8da04d165732ead64875fef7573a5739608de0de9c93654007e
date: '2026-10-14'
min_app: 1.2.0
+20
View File
@@ -0,0 +1,20 @@
package: com.edde746.plezy
title: Plezy
status: issues
notes: Some videos play with strong artifacts and wrong colours; the cause is unknown, possibly hardware video decoding.
Otherwise works.
tested_version: 2.22.0
engine: Other
xr: '?'
frame:
- frame.hw_video_decode
as_is: true
verified:
date: '2026-10-13'
known_good_sha256: 893ae7c01d3d7688b27cbf4e7fc1260fb617614baeaf378fe5ca0af41febc92f
app: 1.1.0
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 85
issue: 270
source_hint: plezy
+21
View File
@@ -0,0 +1,21 @@
package: com.fallen.affected
title: 'AFFECTED: The Manor'
status: issues
notes: 'Gear VR game (32-bit only), runs through FramePort''s 32-bit bridge (experimental). Controls:
left stick = walk and strafe (the touchpad), right stick sideways = turn, stick press or A = touchpad click, right
trigger = trigger, B = back.'
details: 'Unity 5.6 + Mono, VrApi 1.0.4, GLES. The bridge translates its 32-bit libraries and VrApi to the 64-bit VrApi
bridge on OpenXR. Picture and sound confirmed in the headset by the owner (2026-10-10); the controller mapping was
reworked afterwards and is not yet confirmed.'
tested_version: '1.52'
engine: Unity
xr: VrApi
headset: gearvr
frame:
- frame.a32_bridge
device:
- device.text_input_window
verified:
date: '2026-10-10'
min_app: 0.12.1
source_hint: AFFECTED The Manor (Gear VR)
@@ -0,0 +1,22 @@
package: com.farbridge.vastreaches
title: 'Homeworld: Vast Reaches'
status: issues
notes: The game starts but after selecting to start a new game it seems to crash.
tested_version: 1.2.0-25215
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
device:
- device.text_input_window
adapter:
haptic_fix: 1
verified:
date: '2026-10-15'
known_good_sha256: 6c5cb4b56fd01d20cb854e834b1611c2b2e8f10d889585606e631104d2a9323e
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 314
source_hint: com.farbridge.vastreaches
@@ -0,0 +1,26 @@
package: com.nextgenreality.mmrx
title: Mini Motor Racing X
status: works
tested_version: 1.3.6
engine: Unity
xr: VrApi
frame:
- frame.unity_no_msaa
- frame.unity_oculus_check
- frame.unity_text_input
- frame.unity_runtime_msaa_off
- frame.unity_gl_shim
device:
- device.text_input_window
adapter:
haptic_fix: 1
pose_time_fix: 1
verified:
date: '2026-10-15'
known_good_sha256: f1df011117c918794b9d9da0c5a170fc7ac7cb7ec10eddc2dd4db649d855a531
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 317
source_hint: com.nextgenreality.mmrx
@@ -0,0 +1,27 @@
package: com.picselica.OceanRiftFullQuest
title: Ocean Rift
status: works
notes: eye tracked foveated rendering works great!
tested_version: '2.09'
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
- frame.unity_runtime_msaa_off
- frame.unity_gl_shim
device:
- device.text_input_window
adapter:
controller_models: 1
haptic_fix: 1
scene_emul: 1
foveation: tracked
verified:
date: '2026-10-14'
known_good_sha256: 63020505f27af3d463798679999000e2d9bc671e72913138a16171461e3c95d2
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 304
source_hint: Ocean Rift
+22
View File
@@ -0,0 +1,22 @@
package: com.polyarc.MossGame
title: Moss
status: works
notes: The initial loading image looks glitchy, but otherwise it works well.
tested_version: 1.0.3.151047
engine: Unreal
xr: VrApi
alt_overport:
- patch_remove_unreal_force_quit
frame:
- frame.hw_video_decode
adapter:
haptic_fix: 1
verified:
date: '2026-10-15'
known_good_sha256: 4aaae261dcc67de1d04309e31c0ea17dbc980b431adc8ce1917ae72ac4f9d417
app: 1.2.0
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 91
issue: 315
source_hint: com.polyarc.MossGame
@@ -0,0 +1,22 @@
package: com.resolutiongames.demeo
title: Demeo
status: works
tested_version: 1.42.40696-release
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
device:
- device.text_input_window
adapter:
haptic_fix: 1
scene_emul: 1
verified:
date: '2026-10-15'
known_good_sha256: adae217584c956e5574c5248868afdbb50a1f3ffd0609783215412d39b54e9ee
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 313
source_hint: com.resolutiongames.demeo
@@ -0,0 +1,24 @@
package: com.resolutiongames.jade
title: Battlemarked
status: works
tested_version: 7.2.39817-release
engine: Unity
xr: OpenXR
frame:
- frame.unity_text_input
- frame.hw_video_decode
device:
- device.text_input_window
adapter:
haptic_fix: 1
pose_time_fix: 1
scene_emul: 1
verified:
date: '2026-10-15'
known_good_sha256: 670c7c16ec8d85b3865b120d143143dc73387ec325feaa028320608b1f377e7d
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 312
source_hint: com.resolutiongames.jade
@@ -0,0 +1,21 @@
package: com.voidroom.TeaForGodEmperor
title: Tea For God
status: works
tested_version: 1.1.1
engine: Other
xr: OpenXR+VrApi
frame:
- frame.bhaptics_permission
- frame.hw_video_decode
adapter:
equirect_emul: 1
foveation: tracked
verified:
date: '2026-10-14'
known_good_sha256: 89b0b20d5a5b414604163def76b50aaed26961ac283dab08ff7eb469f5bacde6
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 295
source_hint: Tea For God
@@ -0,0 +1,23 @@
package: com.wanadev.ragnarockquest
title: Ragnarock
status: issues
tested_version: 2.8.0
engine: Unreal
xr: VrApi
alt_overport:
- patch_remove_unreal_force_quit
frame:
- frame.unreal_skip_obb_check
- frame.bhaptics_permission
- frame.hw_video_decode
adapter:
haptic_fix: 1
verified:
date: '2026-10-15'
known_good_sha256: 365f26d9a4991e2340311dfb40d14f097a066653f97fff55c632aa1876519d70
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 319
source_hint: com.wanadev.ragnarockquest
+10 -7
View File
@@ -4,14 +4,17 @@ tested_version: 1.0.479431
source_hint: Journey of the Gods
engine: Unreal
xr: VrApi
status: unsupported
notes: 32-bit only; the Frame has no AArch32.
details: 32-bit (armeabi-v7a) only; the Frame has no AArch32. UE4 cannot be rebuilt for arm64.
status: works
notes: 32-bit only (armeabi-v7a), runs through FramePort's 32-bit bridge (experimental). Plays in the headset.
details: 'Unreal Engine 4 NativeActivity with OVRPlugin + VrApi, GLES. Needed DT_ANDROID_RELR relocations in the 32-bit
loader (it crashed at start) and the VrApi bridge''s frame pacing: the Frame''s runtime can return from
xrWaitFrame early, and this light game then ran at ~120 fps on a 90 Hz display, so the scene slid and snapped
back. Plays in the headset (owner, 2026-10-14).'
alt_overport:
- patch_remove_unreal_force_quit
frame:
- frame.a32_bridge
pcvr_alternative: Rift (Meta PC) version via Revive + SteamVR.
verified:
date: '2026-09-28'
overport_cli: 1.2.3
overport_runtime: 3.4.3-23204ea
known_good_sha256: e85141e3e9a8a3226f653d8ffbd21b44268101f3a207f56e657454a3639b3201
date: '2026-10-14'
min_app: 1.2.0
+22
View File
@@ -0,0 +1,22 @@
package: io.doublejack.maestro
title: Maestro
status: works
tested_version: 0.0.397
engine: Unreal
xr: OpenXR
alt_overport:
- patch_remove_unreal_force_quit
frame:
- frame.unreal_skip_obb_check
- frame.hw_video_decode
adapter:
haptic_fix: 1
verified:
date: '2026-10-15'
known_good_sha256: 4ca71bf4464691ab2c675fbeca1ecc5f4d34599c0a810fd3a67374c91d47f6ee
app: 1.1.1
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 88
issue: 316
source_hint: io.doublejack.maestro
@@ -0,0 +1,21 @@
package: net.mobilemischief.spunkydungeon
title: Spunky Dungeon
status: issues
notes: 'Gear VR / Oculus Go game (32-bit only), runs through FramePort''s 32-bit bridge (experimental).
Controls: left stick = walk and strafe (the touchpad), right stick sideways = turn, stick press or A = touchpad
click, right trigger = trigger, B = back.'
details: 'Unity 2019.2 + Mono, OVRPlugin 1.46 on VrApi 1.31, GLES, Meta Platform SDK (OVRPort''s 32-bit dispatcher).
Played in the headset by the owner (2026-10-10): picture at 72 fps, floor-level tracking and walking work; turning
without a stick press was added afterwards and is not yet confirmed.'
tested_version: '1.4'
engine: Unity
xr: VrApi
headset: gearvr
frame:
- frame.a32_bridge
device:
- device.text_input_window
verified:
date: '2026-10-10'
min_app: 0.12.1
source_hint: Spunky Dungeon
+57 -7
View File
@@ -6,6 +6,50 @@
# with diagnostics. Launch tests and real play sessions (agent session_log, `frameport session`) are both matched.
# Sources: every failure we hit porting 34 games to the Steam Frame (see docs/PLAYBOOK.md).
signatures:
# FEX Rift compatibility (stream C): PC runtime/renderer failures; never suggest entitlement workarounds.
- id: fex-missing-entitlement
kind: pcvr
pattern: '(?i:Missing entitlement)'
severity: info
diagnosis: Meta reports that the signed-in account does not own this game. This is not a FramePort bug. Use an account that owns it; entitlement and Platform SDK checks remain intact.
suggest: []
- id: fex-registration-missing
kind: pcvr
pattern: '(?i:OVRServer[^\r\n]*install_available|install_available[^\r\n]*OVRServer)'
severity: error
diagnosis: Meta's runtime sees the app as available to install rather than registered as installed. Reinstall or register the game through the FEX install flow with its matching Meta manifest, then retry.
suggest: []
- id: fex-imu-fallback
kind: pcvr
pattern: 'Rejecting new committed universe since IMU fallback is active'
severity: warning
diagnosis: SteamVR has not acquired headset tracking since boot. Put the headset on once, wait for tracking, then retry the FEX game. A headless launch before that can wait forever.
suggest: []
- id: fex-librarian-stuck
kind: pcvr
pattern: '(?s)\A(?=.*(?i:Service invocation completed))(?=.*OVRLibrarian[^\r\n]*(?i:still running|did not exit))'
severity: warning
diagnosis: OVRLibrarian completed its work but remains alive under FEX and blocks later client registration. End only OVRLibrarian.exe after completion, then retry; the FEX launcher normally performs this cleanup.
suggest: []
- id: fex-vkd3d-init
kind: pcvr
pattern: '(?i:vkd3d[^\r\n]*(?:failed to (?:create|initialize)|could not (?:create|initialize)|no (?:suitable|compatible).*(?:device|adapter)))'
severity: error
diagnosis: The D3D12 route could not initialize vkd3d-proton or a Vulkan device. Check GE's shipped vkd3d-proton DLLs, clear PROTON_NO_D3D12 and PROTON_USE_WINED3D, and verify the FEX Vulkan thunk reaches Turnip. This route still needs a device test.
suggest: []
- id: fex-wined3d-init
kind: pcvr
pattern: '(?i:wined3d[^\r\n]*(?:failed to (?:create|initialize|find)|could not (?:create|initialize)|OpenGL support is disabled))'
severity: error
diagnosis: Wine's OpenGL renderer could not initialize. The FEX route has no configured GL thunk; verify the guest rootfs GL driver and display access. A Vulkan thunk alone does not provide host OpenGL. Prefer the game's D3D9 or D3D11 route when available.
suggest: []
- id: fex-revive-injector
kind: pcvr
pattern: '(?i:ReviveInjector[^\r\n]*(?:failed|unable|error (?:code|inject)))'
severity: error
diagnosis: ReviveInjector could not start or inject the game. Check the game executable and x86_64 Revive files in the shared GE-Proton prefix, and use OpenVR mode (without /openxr). An OpenVR-only game can launch directly. Do not change entitlement or Platform SDK checks.
suggest: []
# End FEX Rift compatibility (stream C).
- id: meta-asset-status-error
pattern: 'Asset status error\s+\(code 100\)'
severity: error
@@ -49,8 +93,8 @@ signatures:
- id: no-arm64
pattern: 'INSTALL_FAILED_NO_MATCHING_ABIS'
severity: fatal
diagnosis: This game is 32-bit only and can't run on the Frame (no AArch32). Use the PC (Rift) version through Revive.
suggest: []
diagnosis: 32-bit-only APK (e.g. a Gear VR or Oculus Go game). The Steam Frame has no 32-bit ARM support; FramePort's 32-bit bridge translates the game (experimental).
suggest: [frame.a32_bridge]
- id: android-too-new
pattern: '(NoClassDefFoundError|ClassNotFoundException|NoSuchMethodError)\b.*(Landroid/window/|android\.window\.|(storeStoreFence|loadLoadFence)\(\)V in class Ljava/lang/invoke/VarHandle)'
severity: fatal
@@ -91,7 +135,7 @@ signatures:
pattern: 'xrCreateSwapchain \d+x\d+ .*faces=6 .*result=-\d+'
unless: 'cube_standin: runtime refused'
severity: fatal
diagnosis: The game asked for a cube-map swapchain (for example an OVROverlay skybox or loading cube), which the Frame's runtime doesn't have. OVRPlugin goes on without images and crashes in ovrp_EndFrame4 (Unity's render thread SIGSEGV in memset, for example Budget Cuts Ultimate). FrameBridge from FramePort 0.12 serves such swapchains itself and drops their cube layers (cube_standin, GLES games) - rebuild and reinstall the game.
diagnosis: The game asked for a cube-map swapchain (for example an OVROverlay skybox or loading cube), which the Frame's runtime doesn't have. OVRPlugin goes on without images and crashes in ovrp_EndFrame4 (Unity's render thread SIGSEGV in memset, for example Budget Cuts Ultimate). FrameBridge from FramePort 0.12 serves such swapchains itself and drops their cube layers (cube_standin, GLES games); rebuild and reinstall a GLES game to try this workaround. For a Vulkan game, the current build cannot stand in for the cube swapchain yet.
suggest: [frame.adapter]
supersedes: [unity-render-crash, native-crash]
- id: swapchain-rect-invalid
@@ -99,6 +143,11 @@ signatures:
severity: fatal
diagnosis: The runtime rejects the game's frames, so it stops drawing (for example stuck at a "Waiting" box). An image rect reaches a few pixels past its swapchain on some Frames; FrameBridge from FramePort 0.11.0 clamps the rects, so rebuild and reinstall the game.
suggest: [frame.adapter]
- id: cylinder-menu-layers-rejected
pattern: 'xrEndFrame failed -16\b'
severity: error
diagnosis: The game draws a curved (cylinder) screen to each eye separately (for example the Doom3Quest / PreyVR menu). The Frame's runtime has no cylinder layers, so FrameBridge shows each as flat quad strips; a per-eye pair makes too many quad layers for one frame and the runtime rejects the whole frame (XR_ERROR_LAYER_INVALID), leaving the menu black while the game runs. FrameBridge from this build shows the left eye's strips to both eyes to halve the count; rebuild and reinstall the game to try it.
suggest: [frame.adapter]
- id: missing-ovr-symbol
pattern: '(UnsatisfiedLinkError|cannot locate symbol) .*"?(ovr_[A-Za-z0-9_]+|ovr[A-Z][A-Za-z0-9]*_ToString)'
severity: fatal
@@ -268,6 +317,7 @@ signatures:
supersedes: [direct-vrapi, native-crash]
- id: direct-vrapi
pattern: '(?<!called before )vrapi_Initialize|VrApi.*not supported|libvrapi\.so.*(not found|failed)'
unless: 'a32bridge: ' # a 32-bit game on the a32 bridge: it translates VrApi itself
severity: warning
diagnosis: The game uses Meta's VrApi directly and needs the VrApi bridge.
suggest: [frame.vrapi_bridge]
@@ -380,12 +430,12 @@ signatures:
The game stays on Unreal's OBB check screen (DownloaderActivity), which the Frame doesn't show, and never
starts VR (for example Contractors, GitHub #159). Unreal checks that the data file (.obb) has the name and size
this APK expects, and with bVerifyOBBOnStartUp it also reads the whole file to check it; a failed check waits
on an error screen. "Unreal - start without the OBB check" skips the content check. Copy the APK and OBB
on an error screen. "Unreal: start without the OBB check" (frame.unreal_skip_obb_check) skips only the CRC content check and applies only when the APK enables bVerifyOBBOnStartUp. Copy the APK and OBB
from the same install, add the game again and reinstall.
If the downloader still appears with bVerifyOBBOnStartUp=false (the skip patch already applied), try
"Unreal: skip the OBB delivery check", an experimental bypass of the separate Java name and size gate
If the downloader still appears with bVerifyOBBOnStartUp=false (already disabled in the APK or by the skip patch), try
"Unreal: skip the OBB delivery check" (frame.unreal_skip_obb_delivery), an experimental bypass of the separate Java name and size gate
(e.g. Into The Radius, GitHub #283). An external-storage path or visibility failure can reject an uploaded
OBB; the native engine still needs complete, matching, readable data.
OBB; neither option is a guaranteed fix, and the native engine still needs complete, matching, readable data.
suggest: [frame.unreal_skip_obb_check, frame.unreal_skip_obb_delivery]
- id: tbxr-fdm-shutdown-crash
pattern: '(?s)\A(?=.*Fatal signal 11)(?=.*fdm_injection_xrDestroySwapchain)(?=.*TBXR_LeaveVR)'
+2 -1
View File
@@ -11,10 +11,11 @@ Got a game working? [Share its recipe](INSTALL.md#share-a-recipe-or-report-a-pro
| Kind of game | On the Steam Frame |
|---|---|
| Quest games | Converted to OpenXR (the VR standard the Frame uses) by OVRPort and patched; they run in Lepton, Valve's Android runtime |
| 32-bit Gear VR, Oculus Go and early Quest games | Run through FramePort's 32-bit bridge (experimental): it translates the game's 32-bit code inside the app; the Frame's right controller acts as the Gear VR / Go controller |
| Other Android VR apps using OpenXR (for example Pico builds) | Converted the same way; the other headset's own features and store services aren't available |
| Android apps without VR | Installed unchanged and shown as a window in the headset |
| PC VR games | On the Frame through Proton (experimental), or on your PC and streamed to the Frame: see [PC VR games](INSTALL.md#pc-vr-games) |
| Can't run | 32-bit-only or x86-only Android apps, apps for Pico's or HTC's own VR system, Android XR apps, and games that check their license through the Oculus app |
| Can't run | x86-only Android apps, apps for Pico's or HTC's own VR system, Android XR apps, and games that check their license through the Oculus app |
Automatic launch tests show that a game starts; only the headset shows whether it looks right.
+1 -1
View File
@@ -28,7 +28,7 @@
200 keys, so ~200 launches after boot every container fails ("create keyring … Disk quota exceeded"). FramePort sets
`keyring = false` in `~/.config/containers/containers.conf`; a reboot clears already-leaked keys.
- Picks the activity with category LAUNCHER (`APP_ACTIVITY`). Game data is visible at `/sdcard/Android/{obb,data}/<pkg>`.
- 64-bit only (no AArch32).
- 64-bit only (no AArch32): 32-bit-only APKs run through FramePort's a32 bridge (`frame.a32_bridge`).
- `<install>/lepton-shaders/` holds Mesa's shader cache (Lepton sets `mesa.shader.cache.dir=/data/shaders`):
`foz_cache.foz` + `foz_cache_idx.foz` per graphics driver (Turnip Vulkan, zink GL), typically 4–6 files and 7–19 MB
per game, 2D apps included. It speeds up later starts; deleting it only costs one slower start.
+5 -1
View File
@@ -53,6 +53,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Ghostbusters: Rise of the Ghost Lord | Quest | ✅ Works | |
| GORN2 | Quest | ✅ Works | |
| Gravity Lab | Quest | ✅ Works | |
| Gunjack | Quest | ✅ Works | |
| H.U.N.T | Quest | ✅ Works | |
| I Am Cat | Quest | ✅ Works | |
| I Am Monkey | Quest | ✅ Works | |
@@ -102,6 +103,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Sniper Elite VR | Quest | ✅ Works | |
| Sniper Elite VR: Winter Warrior | Quest | ✅ Works | |
| Space Pirate Trainer Quest | Quest | ✅ Works | |
| Sports Scramble (Santa Cruz) | Quest | ✅ Works | |
| Star Wars Pinball VR | Quest | ✅ Works | |
| Star Wars: Tales from the Galaxy's Edge | Quest | ✅ Works | |
| Stremio | Quest | ✅ Works | |
@@ -133,6 +135,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Waltz of the Wizard: Extended Edition | Quest | ✅ Works | |
| Wander | Quest | ✅ Works | |
| ZombielandVR | Quest | ✅ Works | |
| AFFECTED: The Manor | Quest | ⚠️ Works with issues | Gear VR game (32-bit only), runs through FramePort's 32-bit bridge (experimental). |
| Ancient_Dungeon | Quest | ⚠️ Works with issues | Multiplayer isn't available (offline). |
| Arcsmith | Quest | ⚠️ Works with issues | Right eye distorts during movement (unresolved; swap, tracking, Valve layers, depth and pacing ruled out). |
| Does it Stack? | Quest | ⚠️ Works with issues | Mixed reality mode does not work (works on Demeo), everything else seems to be OK |
@@ -146,7 +149,9 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Myst | Quest | ⚠️ Works with issues | Minor graphical glitches on some objects. |
| Phantom: Covert Ops | Quest | ⚠️ Works with issues | DLC/store button crashes (no Meta store). |
| Pinball FX VR | Quest | ⚠️ Works with issues | Plays; mixed reality mode not working yet. |
| Plezy | Quest | ⚠️ Works with issues | Some videos play with strong artifacts and wrong colours; the cause is unknown, possibly hardware video decoding. |
| Silhouette | Quest | ⚠️ Works with issues | Hand-tracking game; the Frame synthesizes hands from controllers, so it is janky. |
| Spunky Dungeon | Quest | ⚠️ Works with issues | Gear VR / Oculus Go game (32-bit only), runs through FramePort's 32-bit bridge (experimental). |
| Swarm 2 | Quest | ⚠️ Works with issues | MSAA creates visible seams around edge geometry and also the skybox edge |
| The Light Brigade | Quest | ⚠️ Works with issues | Judder in weapons |
| The Thrill Of The Fight | Quest | ⚠️ Works with issues | Right eye doesn't draw the opponent or the referee. |
@@ -159,4 +164,3 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Journey of the Gods | Quest | ❌ Doesn't run | 32-bit only; the Frame has no AArch32. |
| Roblox | Quest | ❌ Doesn't run | Crashes on its first VR frame on the Frame. |
| Shadow Point | Quest | ❌ Doesn't run | 32-bit only; the Frame has no AArch32. |
| Sports Scramble (Santa Cruz) | Quest | ❌ Doesn't run | 32-bit only; the Frame has no AArch32. |
+53 -34
View File
@@ -2,7 +2,7 @@
# Patches
Every patch and game setting FramePort knows: 168 entries in 5 groups. A game's recipe is its chosen patches and settings; tested games get theirs from the catalog ([GAMES.md](GAMES.md)), and other games get the patches FramePort suggests from its analysis. You change them on the game page under Customize.
Every patch and game setting FramePort knows: 169 entries in 5 groups. A game's recipe is its chosen patches and settings; tested games get theirs from the catalog ([GAMES.md](GAMES.md)), and other games get the patches FramePort suggests from its analysis. You change them on the game page under Customize.
Each entry says what the patch does, whether it changes the APK or only the install, when FramePort suggests it, its options, the catalog games whose recipe names it and the launch-test signatures that suggest it. Patches that are on by default are on for every game, so the catalog rarely names them.
@@ -11,7 +11,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
## Groups
- [Patches from OVRPort](#group-overport) (25)
- [Steam Frame patches](#group-frame) (54)
- [Steam Frame patches](#group-frame) (55)
- [Game settings](#group-adapter) (68)
- [Files and settings on the Frame](#group-device) (8)
- [PC VR (Proton and Revive)](#group-pcvr) (13)
@@ -39,23 +39,24 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Patch Oculus detection for Unity](#patch_oculus_unity) | `patch_oculus_unity` | Patches from OVRPort | default |
| [Patch Oculus detection for Unreal](#patch_oculus_unreal) | `patch_oculus_unreal` | Patches from OVRPort | default |
| [Remove localized app names](#patch_remove_localized_names) | `patch_remove_localized_names` | Patches from OVRPort | default |
| [Remove Unreal's ForceQuit](#patch_remove_unreal_force_quit) | `patch_remove_unreal_force_quit` | Patches from OVRPort | 36 |
| [Remove Unreal's ForceQuit](#patch_remove_unreal_force_quit) | `patch_remove_unreal_force_quit` | Patches from OVRPort | 38 |
| [Remove uses-library](#patch_remove_uses_library) | `patch_remove_uses_library` | Patches from OVRPort | default |
| [Remove VrApi library](#patch_remove_vrapi) | `patch_remove_vrapi` | Patches from OVRPort | |
| [Replace application label and icon](#patch_replace_icon_label) | `patch_replace_icon_label` | Patches from OVRPort | default |
| [Pico/YVR/Quest metadata](#patch_vr_metadata) | `patch_vr_metadata` | Patches from OVRPort | default |
| [VrApi → OpenXR adapter (OVRPort)](#patch_vrapi_openxr) | `patch_vrapi_openxr` | Patches from OVRPort | |
| [32-bit ARM bridge (Gear VR / Go games)](#frame-a32_bridge) | `frame.a32_bridge` | Steam Frame patches | 6 |
| [FrameBridge OpenXR adapter](#frame-adapter) | `frame.adapter` | Steam Frame patches | default |
| [Content files from the game's data](#frame-asset_files) | `frame.asset_files` | Steam Frame patches | 1 |
| [Asset-file service bypass](#frame-asset_files_stub) | `frame.asset_files_stub` | Steam Frame patches | |
| [Skip Meta avatars](#frame-avatar_stub) | `frame.avatar_stub` | Steam Frame patches | 1 |
| [bHaptics: skip the Bluetooth permission request](#frame-bhaptics_permission) | `frame.bhaptics_permission` | Steam Frame patches | |
| [bHaptics: skip the Bluetooth permission request](#frame-bhaptics_permission) | `frame.bhaptics_permission` | Steam Frame patches | 5 |
| [BlazeRush: controllers without Meta avatars, own shader cache](#frame-blazerush) | `frame.blazerush` | Steam Frame patches | 1 |
| [Epic Online Services: stop the keychain retry loop](#frame-eos_keychain_loop) | `frame.eos_keychain_loop` | Steam Frame patches | |
| [OpenGL ES: multiview shaders on flat panels (HUD, menus)](#frame-gl_multiview_fbo) | `frame.gl_multiview_fbo` | Steam Frame patches | 1 |
| [GL shim (Mesa GLSL compatibility)](#frame-gl_shim) | `frame.gl_shim` | Steam Frame patches | 2 |
| [Godot apps: start without a clipboard service](#frame-godot_clipboard) | `frame.godot_clipboard` | Steam Frame patches | |
| [Hardware video decoding (H.264, HEVC, VP9)](#frame-hw_video_decode) | `frame.hw_video_decode` | Steam Frame patches | 8 |
| [Hardware video decoding (H.264, HEVC, VP9)](#frame-hw_video_decode) | `frame.hw_video_decode` | Steam Frame patches | 19 |
| [Language packs from the game's files](#frame-langpacks) | `frame.langpacks` | Steam Frame patches | |
| [Launcher category (INFO → LAUNCHER)](#frame-launcher) | `frame.launcher` | Steam Frame patches | default |
| [GL wrapper: OpenGL ES depth formats (Minecraft)](#frame-ltw_depth) | `frame.ltw_depth` | Steam Frame patches | default |
@@ -75,13 +76,13 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Start straight in VR (skip the 2D launcher)](#frame-start_activity) | `frame.start_activity` | Steam Frame patches | |
| [Allow swapchains larger than 4096 px](#frame-swapchain_limit) | `frame.swapchain_limit` | Steam Frame patches | default |
| [Team Beef ports: treat the Frame as a Meta headset](#frame-tbxr_vendor) | `frame.tbxr_vendor` | Steam Frame patches | 1 |
| [GL shim for Unity (no multisampled render-to-texture)](#frame-unity_gl_shim) | `frame.unity_gl_shim` | Steam Frame patches | 19 |
| [GL shim for Unity (no multisampled render-to-texture)](#frame-unity_gl_shim) | `frame.unity_gl_shim` | Steam Frame patches | 23 |
| [Unity: render each eye separately (no multiview)](#frame-unity_multipass) | `frame.unity_multipass` | Steam Frame patches | 1 |
| [Unity: disable MSAA](#frame-unity_no_msaa) | `frame.unity_no_msaa` | Steam Frame patches | 7 |
| [Unity: disable MSAA](#frame-unity_no_msaa) | `frame.unity_no_msaa` | Steam Frame patches | 9 |
| [Unity: skip OVROverlay layers (fades, splash screens)](#frame-unity_no_overlay_copy) | `frame.unity_no_overlay_copy` | Steam Frame patches | 2 |
| [Unity: start VR without Meta's system apps](#frame-unity_oculus_check) | `frame.unity_oculus_check` | Steam Frame patches | 10 |
| [Unity: keep MSAA off at runtime (OVRManager)](#frame-unity_runtime_msaa_off) | `frame.unity_runtime_msaa_off` | Steam Frame patches | 24 |
| [Make Unity text fields work](#frame-unity_text_input) | `frame.unity_text_input` | Steam Frame patches | 73 |
| [Unity: start VR without Meta's system apps](#frame-unity_oculus_check) | `frame.unity_oculus_check` | Steam Frame patches | 12 |
| [Unity: keep MSAA off at runtime (OVRManager)](#frame-unity_runtime_msaa_off) | `frame.unity_runtime_msaa_off` | Steam Frame patches | 28 |
| [Make Unity text fields work](#frame-unity_text_input) | `frame.unity_text_input` | Steam Frame patches | 85 |
| [Unity: share thread keys (games that run out of them)](#frame-unity_tls_key_pool) | `frame.unity_tls_key_pool` | Steam Frame patches | 1 |
| [Unity: headset always counts as worn](#frame-unity_user_presence) | `frame.unity_user_presence` | Steam Frame patches | 1 |
| [GL shim for Unreal (no multisampled render-to-texture)](#frame-unreal_gl_shim) | `frame.unreal_gl_shim` | Steam Frame patches | 1 |
@@ -89,8 +90,8 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Unreal: stand-ins for OVRPlugin functions OVRPort lacks](#frame-unreal_ovrp_entrypoints) | `frame.unreal_ovrp_entrypoints` | Steam Frame patches | 2 |
| [Unreal: Quest controller bindings (RPOC key map)](#frame-unreal_quest_keymap) | `frame.unreal_quest_keymap` | Steam Frame patches | 3 |
| [Unreal: don't wait for the Quest shader precompile](#frame-unreal_quest_precompile) | `frame.unreal_quest_precompile` | Steam Frame patches | 3 |
| [Unreal: start without the OBB check](#frame-unreal_skip_obb_check) | `frame.unreal_skip_obb_check` | Steam Frame patches | 3 |
| [Unreal: skip the OBB delivery check](#frame-unreal_skip_obb_delivery) | `frame.unreal_skip_obb_delivery` | Steam Frame patches | |
| [Unreal: start without the OBB check](#frame-unreal_skip_obb_check) | `frame.unreal_skip_obb_check` | Steam Frame patches | 5 |
| [Unreal: skip the OBB delivery check](#frame-unreal_skip_obb_delivery) | `frame.unreal_skip_obb_delivery` | Steam Frame patches | 1 |
| [Unreal: bypass the stalled loading splash](#frame-unreal_splash_bypass) | `frame.unreal_splash_bypass` | Steam Frame patches | 1 |
| [Unreal: thumb follows the capacitive touches](#frame-unreal_thumb_touch) | `frame.unreal_thumb_touch` | Steam Frame patches | 7 |
| [Vermillion: paint canvases in the scene](#frame-vermillion_scene_canvas) | `frame.vermillion_scene_canvas` | Steam Frame patches | 1 |
@@ -103,10 +104,10 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Pointer angle](#adapter-aim_pitch) | `adapter.aim_pitch` | Game settings | |
| [Pointer turn](#adapter-aim_yaw) | `adapter.aim_yaw` | Game settings | |
| [Use controllers](#adapter-controller_fix) | `adapter.controller_fix` | Game settings | 1 |
| [Show Steam Frame controllers](#adapter-controller_models) | `adapter.controller_models` | Game settings | 3 |
| [Show Steam Frame controllers](#adapter-controller_models) | `adapter.controller_models` | Game settings | 4 |
| [Stand in for cube layers](#adapter-cube_standin) | `adapter.cube_standin` | Game settings | |
| [Show curved menus and screens](#adapter-cylinder_strips) | `adapter.cylinder_strips` | Game settings | |
| [Show 360° backgrounds and videos](#adapter-equirect_emul) | `adapter.equirect_emul` | Game settings | 4 |
| [Show 360° backgrounds and videos](#adapter-equirect_emul) | `adapter.equirect_emul` | Game settings | 5 |
| [360° detail](#adapter-equirect_face) | `adapter.equirect_face` | Game settings | |
| [360° picture orientation](#adapter-equirect_flip) | `adapter.equirect_flip` | Game settings | |
| [360° video frame rate limit](#adapter-equirect_fps) | `adapter.equirect_fps` | Game settings | |
@@ -126,7 +127,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [GL shim: high-precision vertex shaders](#adapter-gl_highp_markers) | `adapter.gl_highp_markers` | Game settings | 1 |
| [GL shim: integer vertex inputs](#adapter-gl_int_attribs) | `adapter.gl_int_attribs` | Game settings | 1 |
| [Flat panel diagnostics (log)](#adapter-gl_mv_debug) | `adapter.gl_mv_debug` | Game settings | |
| [Fix freezes when controllers vibrate](#adapter-haptic_fix) | `adapter.haptic_fix` | Game settings | 66 |
| [Fix freezes when controllers vibrate](#adapter-haptic_fix) | `adapter.haptic_fix` | Game settings | 81 |
| [Vibration strength](#adapter-haptic_scale) | `adapter.haptic_scale` | Game settings | |
| [Turn off space warp](#adapter-hide_space_warp) | `adapter.hide_space_warp` | Game settings | 4 |
| [Controller input diagnostics (log)](#adapter-input_diag) | `adapter.input_diag` | Game settings | |
@@ -138,7 +139,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [See your room](#adapter-passthrough_emul) | `adapter.passthrough_emul` | Game settings | |
| [Steadier head tracking](#adapter-pose_consistency) | `adapter.pose_consistency` | Game settings | 1 |
| [Pose timing diagnostics (log)](#adapter-pose_debug) | `adapter.pose_debug` | Game settings | |
| [Fix hands lagging behind controllers](#adapter-pose_time_fix) | `adapter.pose_time_fix` | Game settings | 11 |
| [Fix hands lagging behind controllers](#adapter-pose_time_fix) | `adapter.pose_time_fix` | Game settings | 14 |
| [Treat newer Quest controllers as Touch](#adapter-profile_remap) | `adapter.profile_remap` | Game settings | |
| [Animate fingers from touch](#adapter-proximity_emul) | `adapter.proximity_emul` | Game settings | |
| [Keep pictures in bounds](#adapter-rect_clamp) | `adapter.rect_clamp` | Game settings | |
@@ -147,7 +148,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Re-create play space](#adapter-respace_kick) | `adapter.respace_kick` | Game settings | |
| [Sharpness](#adapter-scale) | `adapter.scale` | Game settings | 4 |
| [Room depth](#adapter-scene_depth) | `adapter.scene_depth` | Game settings | |
| [Pretend room layout](#adapter-scene_emul) | `adapter.scene_emul` | Game settings | 4 |
| [Pretend room layout](#adapter-scene_emul) | `adapter.scene_emul` | Game settings | 9 |
| [Room height](#adapter-scene_height) | `adapter.scene_height` | Game settings | |
| [Room width](#adapter-scene_width) | `adapter.scene_width` | Game settings | |
| [Eye-image snapshots (diagnostics)](#adapter-snapshot) | `adapter.snapshot` | Game settings | |
@@ -170,11 +171,11 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Keep the game's saved resolution in step](#device-config_sync) | `device.config_sync` | Files and settings on the Frame | 1 |
| [Show as VR or as a flat window](#device-display_mode) | `device.display_mode` | Files and settings on the Frame | |
| [Settings files for the game](#device-files) | `device.files` | Files and settings on the Frame | 2 |
| [Foveated rendering (Valve)](#device-foveation) | `device.foveation` | Files and settings on the Frame | |
| [Foveated rendering (Valve)](#device-foveation) | `device.foveation` | Files and settings on the Frame | 3 |
| [Hide Android's navigation bar](#device-hide_navbar) | `device.hide_navbar` | Files and settings on the Frame | |
| [Extra Lepton settings](#device-lepton_env) | `device.lepton_env` | Files and settings on the Frame | 3 |
| [Controllers as a gamepad (Steam Input)](#device-steam_gamepad) | `device.steam_gamepad` | Files and settings on the Frame | |
| [Show the app's Android window (for typing)](#device-text_input_window) | `device.text_input_window` | Files and settings on the Frame | 73 |
| [Show the app's Android window (for typing)](#device-text_input_window) | `device.text_input_window` | Files and settings on the Frame | 88 |
| [Launch options (SteamVR or OpenXR)](#pcvr-launch_args) | `pcvr.launch_args` | PC VR (Proton and Revive) | 2 |
| [Provide the Oculus runtime from Revive (Frame)](#pcvr-libovr_redirect) | `pcvr.libovr_redirect` | PC VR (Proton and Revive) | |
| [No Unreal crash reporter](#pcvr-no_crash_reporter) | `pcvr.no_crash_reporter` | PC VR (Proton and Revive) | |
@@ -419,7 +420,7 @@ Stops some Unreal games from closing themselves right after starting.
- `patch_remove_unreal_force_quit`
- **Changes:** Changes the APK (during the OVRPort conversion).
- **Offered (off):** Built as the alternate APK for Unreal games (use it if the game quits itself).
- **Catalog games (36):** Asgard's Wrath 2, BARTENDER VR SIMULATOR, Carve Snowboarding, Creed, Dance Central, Espire 1: VR Operative (Quest Edition), Espire 2, ExploreVR and 28 more.
- **Catalog games (38):** Asgard's Wrath 2, BARTENDER VR SIMULATOR, Carve Snowboarding, Creed, Dance Central, Espire 1: VR Operative (Quest Edition), Espire 2, ExploreVR and 30 more.
- **Suggested by launch-test signatures:**
- `force-quit` (error): The game quit itself right after starting.
- **Source:** [patches/overport.py](../src/frameport/patches/overport.py)
@@ -487,6 +488,20 @@ OVRPort's own converter for games that use Meta's oldest VR interface (experimen
FramePort's own changes to a converted Quest game, for what the Steam Frame lacks or does differently.
### <a id="frame-a32_bridge"></a>32-bit ARM bridge (Gear VR / Go games)
Runs a 32-bit game (Gear VR, Oculus Go, early Quest) on the Frame, which only runs 64-bit code. Experimental.
- `frame.a32_bridge` · experimental · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** 32-bit-only game: the Frame can't run 32-bit ARM code, the bridge translates it.
- **Catalog games (6):** AFFECTED: The Manor, Gunjack, Journey of the Gods, Shadow Point, Sports Scramble (Santa Cruz), Spunky Dungeon.
- **Suggested by launch-test signatures:**
- `no-arm64` (fatal): 32-bit-only APK (e.g. a Gear VR or Oculus Go game).
- **Source:** [patches/frame/a32_bridge.py](../src/frameport/patches/frame/a32_bridge.py)
> Runs a 32-bit-only game (armeabi-v7a: Gear VR, Oculus Go and early Quest games) on the Frame, which has no 32-bit ARM support: an AArch32 → AArch64 translator inside the app runs the game's own libraries, with GLES/EGL, OpenSL ES and VrApi translated to the Frame's 64-bit ones (VrApi through the VrApi → OpenXR bridge). The Gear VR / Go controller: left stick = touchpad (walk, strafe), right stick sideways = turn (a click at the touchpad's edge), stick press or A = click, right trigger, B = back. Experimental: games run slower than native ones.
### <a id="frame-adapter"></a>FrameBridge OpenXR adapter
FramePort's layer between the game and the Steam Frame: fills in what the Frame lacks (controllers, room, passthrough). Needed for every converted game.
@@ -496,6 +511,7 @@ FramePort's layer between the game and the Steam Frame: fills in what the Frame
- **Suggested (on):** Required for every OpenXR/overport build on the Frame.
- **Suggested by launch-test signatures:**
- `cube-swapchain-refused` (fatal): The game asked for a cube-map swapchain (for example an OVROverlay skybox or loading cube), which the Frame's runtime doesn't have.
- `cylinder-menu-layers-rejected` (error): The game draws a curved (cylinder) screen to each eye separately (for example the Doom3Quest / PreyVR menu).
- `graphics-requirements-missing` (fatal): The game can't start VR on the Frame; rebuild it with the current FramePort.
- `swapchain-rect-invalid` (fatal): The runtime rejects the game's frames, so it stops drawing (for example stuck at a "Waiting" box).
- `time-conversion` (warning): The Frame's runtime lacks timespec time conversion; the current adapter build emulates it.
@@ -549,6 +565,7 @@ Stops bHaptics from asking for a Bluetooth permission the Frame doesn't have (th
- `frame.bhaptics_permission` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** bHaptics asks for an Android 12 Bluetooth permission at start; the permission screen interrupts the game on the Frame.
- **Catalog games (5):** Quantum Void, Ragnarock, Smash Drums, Tea For God, Vendetta Forever.
- **Suggested by launch-test signatures:**
- `bhaptics-permission-prompt` (error): The game asked for Android 12's Bluetooth permission (bHaptics' vest SDK, for example Yupitergrad).
- **Source:** [patches/frame/bhaptics_permission.py](../src/frameport/patches/frame/bhaptics_permission.py)
@@ -628,7 +645,7 @@ Plays the game's videos on the Frame's video hardware, so 4K and 8K video runs s
- `frame.hw_video_decode` · also for 2D apps
- **Changes:** Install only: written on the Frame when the game is installed; the APK isn't changed.
- **Suggested (on):** The game plays video through Android's decoders (MediaCodec, ExoPlayer or VLC): decode it on the Frame's hardware.
- **Catalog games (8):** 4XVR Video Player, Batman: Arkham Shadow, Dance Central, Fruit Ninja, Ghostbusters: Rise of the Ghost Lord, Kill It With Fire VR, MacacoVR, Moss: Book II.
- **Catalog games (19):** 4XVR Video Player, AugmentedEmpire, Batman: Arkham Shadow, Battlemarked, Dance Central, Eye of the Temple, Fruit Ninja, Ghost Town and 11 more.
- **Source:** [patches/frame/hw_video_decode.py](../src/frameport/patches/frame/hw_video_decode.py)
> Decodes the game's videos on the Frame's hardware video decoder instead of Android's software decoders, which stutter or fall behind with 4K/8K video (for example video players, Batman: Arkham Shadow's cutscenes). Adds FramePort's codec plugin (OMX.frameport.avc/hevc/vp9.decoder) to this game's container only; the APK isn't changed. When the hardware is busy (for example Steam's own hardware video decoding is on) the video is decoded in software as before.
@@ -887,7 +904,7 @@ Stops a gray or frozen screen in Unity games that turn on anti-aliasing while ru
- `frame.unity_gl_shim`
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unity GLES game that may switch to MSAA at runtime: hide multisampled render-to-texture, which crashes the Frame's GL driver (for example The Room VR).
- **Catalog games (19):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 11 more.
- **Catalog games (23):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 15 more.
- **Suggested by launch-test signatures:**
- `unreal-msrtt-crash` (fatal): The game's graphics crashed a few seconds after start.
- **Source:** [patches/frame/vrapi_bridge.py](../src/frameport/patches/frame/vrapi_bridge.py)
@@ -914,7 +931,7 @@ Turns off a smoothing setting that crashes some older Unity games on the Frame.
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Legacy VrApi Unity game on GLES with MSAA (… quality levels): multisampled render-to-texture hangs the Frame's GL driver (for example Sniper Elite VR).
- **Offered (off):** GLES Unity game with MSAA on (… quality levels); enable if it hangs the GPU ('zink: DEVICE LOST').
- **Catalog games (7):** Audica, BattleSisters, IEYTD3, Jurassic World Aftermath Collection, Sniper Elite VR, SUPERHOT VR, The Room VR.
- **Catalog games (9):** Audica, BattleSisters, Eye of the Temple, IEYTD3, Jurassic World Aftermath Collection, Mini Motor Racing X, Sniper Elite VR, SUPERHOT VR and 1 more.
- **Suggested by launch-test signatures:**
- `zink-device-lost` (fatal): The GPU hung, so the game froze or closed.
- **Source:** [patches/frame/unity_no_msaa.py](../src/frameport/patches/frame/unity_no_msaa.py)
@@ -942,7 +959,7 @@ Lets older Unity games start VR without Meta's system apps (they'd stay on a 2D
- `frame.unity_oculus_check` · revision 5
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unity with built-in Oculus support: it checks for Meta's system apps before starting VR, else it runs as a 2D app (for example Accounting+, BattleSisters).
- **Catalog games (10):** Accounting+, Audica, BattleSisters, Cosmodread, End Space, Jurassic World Aftermath Collection, Shoot The Zombirds VR, Sniper Elite VR and 2 more.
- **Catalog games (12):** Accounting+, Audica, BattleSisters, Cosmodread, End Space, Eye of the Temple, Jurassic World Aftermath Collection, Mini Motor Racing X and 4 more.
- **Suggested by launch-test signatures:**
- `unity-vr-device-none` (fatal): Unity didn't start VR, so the game runs as a hidden 2D app.
- **Source:** [patches/frame/unity_oculus_check.py](../src/frameport/patches/frame/unity_oculus_check.py)
@@ -956,7 +973,7 @@ Keeps a smoothing setting off that the game turns on itself and that can freeze
- `frame.unity_runtime_msaa_off` · revision 2
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** GLES Unity game whose OVRManager turns 4x MSAA on at runtime: multisampled render-to-texture can hang the Frame's GPU.
- **Catalog games (24):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 16 more.
- **Catalog games (28):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 20 more.
- **Suggested by launch-test signatures:**
- `unity-render-crash` (fatal): The game's graphics crashed, so the picture freezes or stays gray.
- `unity-runtime-msaa` (info): The game turns MSAA on at runtime, which can hang the Frame's GPU.
@@ -972,7 +989,7 @@ Lets you type into this app's text fields on the Frame (they'd close at once).
- `frame.unity_text_input` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unity app with text fields (…): they close at once on the Frame because it has no system keyboard.
- **Catalog games (73):** AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arkio, Audica, BattleSisters, Beat Saber, Beat Saber (co-existence build) and 65 more.
- **Catalog games (85):** AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arkio, Audica, AugmentedEmpire, Battlemarked, BattleSisters and 77 more.
- **Source:** [patches/frame/unity_text_input.py](../src/frameport/patches/frame/unity_text_input.py)
> Unity's TMP_InputField / InputField wait for Android's on-screen keyboard and close themselves a frame later when there is none (Lepton has no on-screen keyboard; Meta's system keyboard does this on a Quest), so a selected text field only flashes a caret. Rewrites TouchScreenKeyboardShouldBeUsed -&gt; false and isKeyboardUsingEvents (TMP) / InPlaceEditing (uGUI) -&gt; true in libil2cpp.so, found per game with Cpp2IL (downloaded on first use), so fields stay selected and take key presses: Steam's keyboard (with "Show the app window") or Type on Frame from the PC.
@@ -1074,7 +1091,7 @@ Starts Unreal games without re-checking their data file (they'd seem to hang on
- `frame.unreal_skip_obb_check` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unreal checks the OBB's contents before starting (bVerifyOBBOnStartUp); on the Frame a failed or slow check can't be seen and the game seems to hang.
- **Catalog games (3):** Dance Central, Kill It With Fire VR, MacacoVR.
- **Catalog games (5):** Dance Central, Kill It With Fire VR, MacacoVR, Maestro, Ragnarock.
- **Suggested by launch-test signatures:**
- `unreal-obb-check-stuck` (fatal): The game stays on Unreal's OBB check screen (DownloaderActivity), which the Frame doesn't show, and never starts VR (for example Contractors, GitHub #159).
- **Source:** [patches/frame/unreal_obb_check.py](../src/frameport/patches/frame/unreal_obb_check.py)
@@ -1088,11 +1105,12 @@ Skips a separate data-file check when an Unreal game still hangs at startup with
- `frame.unreal_skip_obb_delivery` · experimental · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested:** not automatically; set on the game page (Customize), by a recipe or after a launch test.
- **Catalog games (1):** Medal of Honor: Above and Beyond.
- **Suggested by launch-test signatures:**
- `unreal-obb-check-stuck` (fatal): The game stays on Unreal's OBB check screen (DownloaderActivity), which the Frame doesn't show, and never starts VR (for example Contractors, GitHub #159).
- **Source:** [patches/frame/unreal_obb_check.py](../src/frameport/patches/frame/unreal_obb_check.py)
> Unreal's Java OBB delivery check can leave a game on an invisible DownloaderActivity screen even with the manifest CRC check off (e.g. Into The Radius). Makes known Unreal expansionFilesDelivered methods return true, bypassing the Java name and size gate. Experimental: the native engine still needs complete, matching, readable OBB data.
> Unreal's Java OBB delivery check can leave a game on an invisible DownloaderActivity screen even with the manifest CRC check off (e.g. Into The Radius). Makes known Unreal delivery predicates return true, including recognized obfuscated versions, bypassing the Java name and size gate. Experimental: the native engine still needs complete, matching, readable OBB data.
### <a id="frame-unreal_splash_bypass"></a>Unreal: bypass the stalled loading splash
@@ -1276,7 +1294,7 @@ For games that show the headset's own controllers. Takes effect after a reinstal
- **Options:**
- Value: int, default `0`.
- Game settings → Controllers → "Show Steam Frame controllers".
- **Catalog games (3):** SynthRiders, VR HOT Quest, Walkabout Mini Golf.
- **Catalog games (4):** Ocean Rift, SynthRiders, VR HOT Quest, Walkabout Mini Golf.
- **Suggested by launch-test signatures:**
- `render-model-requested` (info): The game shows Quest controllers (or none) because the Frame doesn't provide controller models.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
@@ -1321,7 +1339,7 @@ Video players' virtual theaters and 360° videos would otherwise stay black.
- **Options:**
- Value: int, default `0`.
- Game settings → 360° pictures and video → "Show 360° backgrounds and videos".
- **Catalog games (4):** 4XVR Video Player, Into The Radius 2, Pinball FX VR, Riven.
- **Catalog games (5):** 4XVR Video Player, Into The Radius 2, Pinball FX VR, Riven, Tea For God.
- **Suggested by launch-test signatures:**
- `equirect-layers-dropped` (warning): The game's 360° pictures (for example a video player's theater or 360° videos) are missing because the Frame's runtime can't show equirect layers.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
@@ -1614,7 +1632,7 @@ For games that freeze the Frame when a controller vibrates (for example Lucky's
- **Options:**
- Value: int, default `0`.
- Game settings → Controllers → "Fix freezes when controllers vibrate" (advanced).
- **Catalog games (66):** AgeOfJoy, Ancient_Dungeon, Audica, BattleSisters, Beat Saber, Caves, Clockwork, COMPOUND and 58 more.
- **Catalog games (81):** AgeOfJoy, Ancient_Dungeon, Audica, AugmentedEmpire, Battlemarked, BattleSisters, Beat Saber, Caves and 73 more.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
> Routes OVRPlugin through FramePort's extension shim, which turns Meta's amplitude-envelope vibrations into plain ones: OVRPort's loader reads their nanosecond duration as seconds and allocates gigabytes, freezing the Frame when the game vibrates a controller (for example Lucky's Tale's save slots, GitHub #9). Needs a rebuild.
@@ -1792,7 +1810,7 @@ For games whose hands trail the controllers when you move them (for example Batt
- **Options:**
- Value: int, default `0`.
- Game settings → Controllers → "Fix hands lagging behind controllers" (advanced).
- **Catalog games (11):** BattleSisters, Beat Saber, Dance Central, Dungeons of Eternity, Phantom: Covert Ops, Robo Recall, Star Wars: Tales from the Galaxy's Edge, Time Stall and 3 more.
- **Catalog games (14):** Battlemarked, BattleSisters, Beat Saber, Dance Central, Dungeons of Eternity, Mini Motor Racing X, Phantom: Covert Ops, Quantum Void and 6 more.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
> Poses a game asks for at a CLOCK_MONOTONIC time, or more than 0.5 s before the frame's display time, are located at the same moment in the runtime's time (or now). Meta's OVRPlugin passes the monotonic clock on as the OpenXR time, which on the Frame runs seconds behind the runtime's clock, so its "now" poses (Unity's physics step, controller poses) came from the past: hands trailing the controllers (for example BattleSisters, Sniper Elite VR).
@@ -1922,7 +1940,7 @@ Mixed-reality games that build their level from your room get a simple room with
- **Options:**
- Value: int, default `0`.
- Game settings → Mixed reality → "Pretend room layout".
- **Catalog games (4):** Arkio, Demeter, Ghostbusters: Rise of the Ghost Lord, Vermillion.
- **Catalog games (9):** Arkio, AugmentedEmpire, Battlemarked, Demeo, Demeter, Ghostbusters: Rise of the Ghost Lord, Ocean Rift, Smash Drums and 1 more.
- **Suggested by launch-test signatures:**
- `scene-missing` (warning): The game wants Meta's room data (scene API), which the Frame lacks.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
@@ -2269,6 +2287,7 @@ Render less detail outside your gaze; adjust the full-resolution area or darken
- `mode`: str, default empty — tracked, fixed or off (empty = Valve's default)
- `radius`: float, default `0.0`, 0–0.45 — Full-resolution radius; 0 keeps the current runtime default
- `test`: bool, default `False` — Darken lower-resolution regions (diagnostic)
- **Catalog games (3):** Ocean Rift, Quantum Void, Tea For God.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
> Reduces shading away from the full-resolution area, following each eye's gaze. Default area size keeps the runtime's current profile unchanged. Custom radius is a fraction of the shorter eye-image dimension; the transition ends at twice that radius. Larger areas retain more detail but save less GPU work. Fixed stops the area following your eyes. The optional test darkens actual coarse-shaded fragments; rebuild/reinstall to toggle it. Tested on RE4, Deadpool and Asgard's Wrath 2. The Climb 2 gets a version-guarded private bridge at 1.0 scale; Batman gets its hash-verified allocation fix (unsupported OVRPlugin versions are refused). Other games may need additional fixes; turn this off if artifacts appear.
@@ -2315,7 +2334,7 @@ Lets typing reach this app from Steam's on-screen keyboard or your PC's keyboard
- `device.text_input_window`
- **Changes:** Install only: written on the Frame when the game is installed; the APK isn't changed.
- **Suggested (on):** App with text fields: key presses only reach a shown Android window.
- **Catalog games (73):** AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arkio, Audica, Beat Saber, Beat Saber (co-existence build), Blade & Sorcery: Nomad and 65 more.
- **Catalog games (88):** AFFECTED: The Manor, AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arkio, Audica, AugmentedEmpire, Battlemarked and 80 more.
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
> Lepton runs VR apps headless: their Android window is never shown, so it never gets keyboard focus and no key press (Steam's on-screen keyboard, a USB/Bluetooth keyboard, Type on Frame) reaches the app's text fields. With Lepton's lepton-show-flatscreen marker the window is shown (behind the VR view, which keeps working) and Steam's keyboard opens for a selected text field. Steam lists the shown window as "Gamescope" (the Frame's compositor). Pairs with "Make Unity text fields work without a system keyboard".
+29 -4
View File
@@ -5,7 +5,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
## Fast path for a new game
1. `frameport scan <folder>` → check the suggested recipe (`frameport show <pkg>`). Direct-VrApi engines get the bridge.
2. `frameport build <pkg>` → all static checks must pass (32-bit-only → stop, it can't run).
2. `frameport build <pkg>` → all static checks must pass (32-bit-only → `frame.a32_bridge`, experimental).
3. `frameport install <pkg>` → `frameport test <pkg>`: want **RUNNING** + "Submitting frames" at ~72 fps.
4. Put the headset on and look. Headless tests can't judge visuals (no FOCUSED state without the headset worn).
5. Fix by symptom below, rebuild, repeat. When it's good: **Save as known-good** (GUI) or add a catalog YAML.
@@ -73,8 +73,15 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| The Climb 666.0: audio with no headset picture, `OVRPortVrApi: Unsupported frame flags or swap interval`; then SIGSEGV in `vulkan.freedreno.so` during `vkCmdEndRenderPass` once frames are accepted (GitHub #238) | The game submits the obsolete Quest texture-density debug flag (`0x100`), which the bridge rejected. It also binds the bridge's full-rate texture as a fragment-density attachment even though foveation support is reported off; Turnip reads density maps on the CPU, but an ordinary sampled image has no mapped backing memory | Updated `frame.vrapi_bridge` accepts the compositor debug/volume flags and creates the compatibility texture with `VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT`. Do not gate that usage on the advertised format features (the Frame reports R8G8_UNORM without the density bit). `device.files` selects `r_vr_foveated = 0` when the engine contains that cvar; The Climb 2 keeps `r_variable_rate_shading = 0`. Triage `vrapi-frame-rejected` marks rejected frames as fatal despite pacing logs. Picture confirmed on the headset. With the corrected config, an uncapped launch stayed running for over four minutes at a median 72 fps with no native crash or GPU fault. The user confirmed working menus and gameplay on 2026-10-12 |
| Unreal game: `JNI_OnLoad` (OVRPlugin), then silence: no OpenXR instance, no crash, no frames (GitHub #85 TRIANGLE STRATEGY; launch-test finding `missing-obb`) | Installed without its OBB: the manifest says `com.epicgames.ue4.GameActivity.bHasOBBFiles` = true (UE5: `com.epicgames.unreal.…`) but the library has no data folder (`data_dir` null, `data_bytes` 0) | Put the .obb files in a `<package>` (or `obb/`) folder next to the APK, add the folder again, reinstall. Analysis `extra.expects_obb`; the game page, the install question and `frameport scan`/`install` warn; launch tests that sent no frames get the `missing-obb` finding from the library (the game logs nothing). Unity split-binary builds count too (`extra.unity_split`, `analysis/unity_split.py`): an XR-plugin build (Oculus XR Plugin / Unity OpenXR library) without `assets/bin/Data/UnitySubsystems/` in the APK, or BuildSettings listing more scenes than the APK has `levelN` files (globalgamemanagers loose or read from the head of data.unity3d); exact on the 48 Unity APKs of the dumps (13 split, 17 full games; OBBs of full builds are asset bundles or sound banks) |
| Unreal game: launch.log ends with `ActivityTaskManager: START u0 {… cmp=<pkg>/.DownloaderActivity}` and `Displayed <pkg>/.DownloaderActivity`, then nothing: no OpenXR instance, no crash (GitHub #159 Contractors; triage `unreal-obb-check-stuck`, also when the OBB is on the Frame) | Epic's DownloaderActivity (started by GameActivity.onResume before the engine's main init) checks every OBB's name + size compiled into the APK (OBBData); with manifest meta-data `com.epicgames.ue4.GameActivity.bVerifyOBBOnStartUp=true` it then reads the whole OBB and compares each entry's CRC32 (cached in `files/cacheFile.txt` by the OBB's mtime). Its progress and error screens are invisible in Lepton (headless VR); a CRC mismatch waits for a button forever. A missing / wrong-size OBB starts Google Play's downloader (or a "No Google Play Store Key" dialog) and also waits | `frame.unreal_skip_obb_check` (suggested by analysis `unreal_verify_obb`): sets that meta-data to false (one boolean in the manifest, `axml.set_meta_data_bool`), which skips only the CRC pass. Still stuck: the OBB doesn't match the APK version (name `main.<versionCode>.<pkg>.obb` and its size) - copy APK + OBB from the same install |
| Unreal game has CRC verification off but the delivery bypass is unavailable (GitHub #159, Medal of Honor: Above and Beyond) | Obfuscation renamed `expansionFilesDelivered`: MoH calls boolean predicates `a()` and `d()` from its package DownloaderActivity.onCreate, both logging `Checking for file : ` and calling Google expansion filename/delivery helpers. The second gate can show “Select OBB to use” | Analysis recognizes these predicates by activity, caller, log and helper return types; stuck-downloader triage offers `frame.unreal_skip_obb_delivery` as an experimental opt-in. CRC stays off. The inspected build checks three Java OBB entries and has native indexed-patch filename support; its backup has 22 OBBs and 34 MP4s, all selected from the package folder. Bypassing Java delivery does not establish native data completeness or headset success |
| Unreal game still stays on `DownloaderActivity` with CRC checking off (`bVerifyOBBOnStartUp=false`) and a fully uploaded matching OBB (GitHub #283, Into The Radius) | The separate Java `expansionFilesDelivered()` name and size gate can reject an OBB through Android external storage in Lepton; disabling CRC does not bypass it | Try `frame.unreal_skip_obb_delivery` (opt-in, experimental, triage-only). It returns true from known Unreal/package delivery predicates in every dex, preserving normal downloader success and main init. Analysis `unreal_obb_delivery` (version 16) controls applicability. The native engine still needs complete, matching, readable OBB data; unverified on a device |
| `INSTALL_FAILED_NO_MATCHING_ABIS` | 32-bit-only APK; Frame has no AArch32 | None. PC/Rift version via Revive |
| `INSTALL_FAILED_NO_MATCHING_ABIS` | 32-bit-only APK (Gear VR / Go / early Quest); Frame has no AArch32 | `frame.a32_bridge` (suggested for every 32-bit-only APK, experimental): the a32 translator runs the game's 32-bit libraries inside the 64-bit app (native/a32translator/bridge) |
| a32 bridge faults at a low Thumb PC while loading a library, with the same unrelocated pointer in `.init_array` (e.g. Journey of the Gods: `0x1259e9` in OVRPlugin) | The guest loader ignored the older `DT_ANDROID_RELR` / `DT_ANDROID_RELRSZ` tags, leaving relative pointers at their link addresses | Fixed in the guest loader: both Android and standard RELR tags use the existing RELR decoder. Rebuild the a32 runtime and APK; host regression tests cover both tag families, but game startup still needs a Frame run |
| 32-bit game on the bridge: framerate falls over minutes, purple/garbled geometry, then `Could not allocate memory: System out of memory!` (Spunky Dungeon) | The bridge's guest copies of mapped GL buffers were tracked per buffer target: a second buffer mapped on the same target lost the first one's copy (never written back: garbage vertices; never freed: ~10 MB/s until the guest's 4 GiB were full) | Fixed in the bridge (gl.c: mappings per buffer object). Check: the guest's `[anon:scudo:*]` maps below 4 GiB in /proc/<pid>/maps must stay flat |
| 32-bit game on the bridge loads, leaves VR and its engine threads end, no crash, no finish() (Gunjack) | The game checks its own APK signature (UE4 `AndroidThunkJava_GetSignature` = Base64 of the signing certificate's SHA-1, compared in AndroidMain): every FramePort build is re-signed | `frame.a32_bridge` stores the original APK's value in `assets/fp_a32_signature.txt` (Unreal games) and the bridge answers the guest's call with it (log `AndroidThunkJava_GetSignature: original signature returned`). Find other such checks with `A32_BREAK` on the game's exit path (vrapi_LeaveVrMode logs its caller) |
| 32-bit NativeActivity game on the bridge ignores every controller (Gunjack, UE 4.10 Gear VR: no vrapi input functions, it reads the Gear VR touchpad/back button as Android input events from its AInputQueue) | The bridge sent its controller events through `Activity.dispatchKeyEvent`, which a NativeActivity never passes to native code | input.c puts synthetic touchpad (motion, touchscreen source) and back-key events in front of the game's AInputQueue: `ALooper_pollAll/pollOnce` return the queue's ident while one waits, `AInputQueue_getEvent` hands it out, the AInputEvent/AKeyEvent/AMotionEvent imports answer for it. Right trigger = hold the touchpad, A = tap, right stick = swipe (up/down = swipe forward/back along the touchpad's X axis: Gunjack's `OnFlick` takes flick angles <45°/>315° as reload, 135-225° as special weapon), B/left menu = back (log `controllers: the game reads its AInputQueue`) |
| GLES VrApi game aborts in `vrclient.so` (`CSharedSemaphoreLinux::WaitFromGPU` ← `CSxrGraphicsBindingGLOpenVR::PreBeginFrame`) right after it left VR mode and entered it again (Gunjack after loading) | The Frame's runtime fails the first frame of a second OpenXR session on the same GL context | VrApi bridge: `vrapi_LeaveVrMode` keeps a running GLES session, `vrapi_EnterVrMode` with the same context reuses it (log `Entered VR mode again (kept GLES session)`) |
| 32-bit Unity game on the bridge: player stands in the floor (Spunky Dungeon) | Unity's floor-level tracking origin: `vrapi_SetTrackingSpace(1)` (LOCAL_FLOOR) was ignored | The VrApi bridge puts the origin on the STAGE floor for LOCAL_FLOOR/STAGE |
| Crash at start: `NoClassDefFoundError: … Landroid/window/OnBackInvokedCallback;` or `NoSuchMethodError: No static method storeStoreFence()V in class Ljava/lang/invoke/VarHandle;` (GitHub #71/#72, triage `android-too-new`) | The APK needs Android 13+ (minSdk 33 or more; those were 34) and calls its classes at start; Lepton's Android is 11 (API 30). OVRPort lowers minSdk to 29, so it installs anyway. minSdk ≤ 32 (Quest's Android 12L) is fine: 16 working catalog games declare 32 | None (analysis `extra.min_sdk` > 32 → a warning on the game page/CLI and in the recipe notes; never unsupported from the manifest alone, the launch test's triage decides). Waits for Valve to update Lepton's Android |
| Nothing opens; `TWALauncherActivity: Using URL from Manifest (https://…)`, `Creating TwaLauncher for com.oculus.browser`, `NameNotFoundException: com.oculus.browser` (GitHub #86 Mahjong Table VR, triage `web-wrapper`) | The APK is a Trusted Web Activity (Bubblewrap / Meta's PWA packaging): a website that opens in Meta's browser, which Lepton doesn't have | None: open the URL in a browser. Analysis `extra.web_wrapper` (manifest meta-data `android.support.customtabs.trusted.DEFAULT_URL`, resolved through resources.arsc, or androidbrowserhelper's LauncherActivity) → a warning with the URL (not unsupported: the manifest alone never decides) |
| `UnsatisfiedLinkError` / `cannot locate symbol "ovr_…"` | overport's platform loader lacks Meta platform functions | `frame.ovrstubs` (automatic, generated stubs) |
@@ -82,6 +89,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| The game stays in its built-in language or waits at start although its OBB / files hold language packs (`<tag>.lang`, for example `de.lang`) | overport's platform loader answers `ovr_LanguagePack_GetCurrent/SetCurrent` with request id 0, so the game never gets the pack's path | `frame.langpacks` (opt-in, experimental, shown for games whose data has `*.lang`; `native/langpack`, build it with `python native/build.py --only langpack`). Default pack: the one the game applies, else env `FRAMEPORT_LANGPACK=<tag>`, else the only pack; search path override `FRAMEPORT_LANGPACK_DIRS`. Unreal games (Deadpool VR) gray out a pack whose asset `Metadata` differs from the game's version string: the patch writes the APK's versionName as Metadata (env `FRAMEPORT_LANGPACK_META` overrides) and reports the pack under the `/storage/emulated/0/Android/obb/<pkg>/` spelling of its path; with `/sdcard/…` the text switched but the dialogue stayed silent (verified in the headset with Deadpool VR) |
| `ClassNotFoundException com.oculus.os.AnalyticsEvent` → abort | Quest telemetry lookup in Meta XR Audio (Unreal build) or native code | `frame.metaxr_telemetry` + `frame.oculusos` (automatic) |
| `JNI DETECTED ERROR`, `GetStringUTFChars … NULL` | CheckJNI is on because overport marks the app debuggable | `frame.nodebug` |
| Unreal game shows a one-time "optimizing" screen on its very first start, then closes (`System.exit` status 0 right after the system log's `ActivityTaskManager: START … LAUNCHER … pkg=<own package> … from uid 10xxx`, Lepton "Exited!"); the next start works | UE 4.21+ restarts the app after its first-run shader precompile (`r.ProgramBinaryCache.RestartAndroidAfterPrecompile`, `AndroidThunkJava_RestartApplication`); Lepton ends the container with the first process, the restarted one with it (Sports Scramble). Skipping the restart or setting the cvar to 0 (`-ini:Engine:[ConsoleVariables]:…` in UE4CommandLine.txt: read, no restart requested) left Sports Scramble on the "optimizing" level for good: the game relies on the restart | launch.sh starts Lepton once more (agent v86 `_restart_requested` matches both log lines within 5 s; `launch-before-restart.log` keeps the first run; `FRAMEPORT_NO_RESTART=1` turns it off). Works for 32- and 64-bit games |
| Unreal game quits a few seconds after start (`System.exit`) | ForceQuit after a failed Quest platform check | alternate build with `patch_remove_unreal_force_quit` (`use_alt`) |
| Unreal game crashes a few seconds after the logo with no backtrace (Unreal's own signal handler hides it: logcat-crash.log empty, Zygote `exited due to signal 11`); the crashing thread is `GameThread`, pc in `libaaudio.so`, lr `libovrplatformloader.so (ovr_Microphone_GetOutputBufferMaxSize+0x10)`; the last platform call is `ovr_Microphone_Create` (for example The Walking Dead: Saints & Sinners Ch. 2) | OVRPort's platform loader opens the microphone's AAudio stream only in `ovr_Microphone_Start`, but `GetOutputBufferMaxSize` reads that stream unchecked; Unreal's Oculus voice asks for the size right after `Create` | `frame.ovr_microphone` (NULL check rewritten in place; size 0 until the microphone starts). OVRPort runtime 3.4.3-aa54c3f has the check itself: builds made with it leave the patch out (log "not needed: frame.ovr_microphone", `patches/upstream.py`) |
| `xrCreateSwapchain` -26 / format unsupported (GLES) | Frame takes only sRGB formats, no MSAA | adapter `swapchain_fix` (default on) |
@@ -96,6 +104,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| Unity game hangs right after its first frames, no `pacing:` lines; SIGQUIT dump shows UnityMain in a game library's `JNI_OnLoad` → `usleep` (for example SKYBOX: `libskybox.so`, `SignatureChecker`) | the game checks its APK signing certificate; every port is re-signed | can't be fixed without defeating anti-tamper (FramePort doesn't): mark "Can't run". Diagnose hangs: `podman exec <container> kill -3 <pid>` writes all thread stacks to launch.log |
| Video player doesn't list sent videos (for example 4XVR "Internal Storage" only shows some) | the player lists its own /sdcard folder (4XVR: /sdcard/4XPlayer), not /sdcard/Movies; Android's media index doesn't work in Lepton | game page "Add videos" / game menu "Add videos and files" (Videos + the app's own folder, hard links) or `frameport frame send <files> --app <pkg>` |
| One eye gray in a stereo video, log `xrCreateSwapchain … result=-10` | the runtime refused a swapchain (XR_ERROR_LIMIT_REACHED) | fewer/smaller swapchains: lower `equirect_res`; unresolved |
| VrApi game (32-bit bridge or `frame.vrapi_bridge`): holding the menu button to recenter turns the view ~90-120 degrees to the side | the bridge's app space is LOCAL + the head's yaw at the start; the Frame's recenter moves LOCAL to the head, so the old yaw was added again | fixed in the VrApi bridge (2026-10-13): on XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING (LOCAL) and on `vrapi_RecenterPose` it takes the origin from the head again (log `recentered: head yaw …`); rebuild the game |
| Menu/screen jumps to where you look (for example 4XVR) | the app re-creates LOCAL spaces (4XVR: every 2–4 s) and the Frame places them at the current head yaw, or the app recenters after the Frame's brief focus dips | turn on `adapter.layer_debug`, check `that LOCAL space sits at … deg` vs `focus_hold: hid a … ms focus dip`; patches: `adapter.stable_local` (new LOCAL spaces line up with the first) / `adapter.focus_hold` (on by default: hides dips up to `focus_hold_ms` once the game has been focused for a second; never at start-up: a global debounce broke AC Nexus) |
| Pointer misses menu items | the Frame's aim pose differs from Touch's | `adapter.layer_debug` logs `aim in grip … pitch/yaw`; correct with `aim_pitch`/`aim_yaw`/`aim_forward` (`frameport settings`, no rebuild) |
| Video stutters although fps is steady | video frame rate doesn't divide the refresh rate (30 fps at 72 Hz) | `adapter.refresh_rate` (for example 90 for 30 fps, 72 for 24 fps); `layer_debug` logs the offered rates and the app's own requests |
@@ -104,11 +113,11 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| Video player / app finds no local videos; MediaProvider "Requested path /home/steamos/... doesn't appear under ..." | Lepton's /sdcard is a symlink to a host path, so Android's media index rejects every file | upload in the Files tab (Videos = /sdcard/Movies) and browse folders in the app |
| Batman: Arkham Shadow closes during smoke-bomb effects; later input-tree corruption | Meta XR Audio Wwise deletes queued metadata still referenced by the current audio frame, then writes through the stale pointer | FrameBridge automatically retires metadata after current-frame references disappear, for the verified AArch64 SDK build only; see [AUDIO_METADATA.md](AUDIO_METADATA.md) |
| Game stays on a loading or "Waiting" box although it reached FOCUSED; log `FrameBridge: xrEndFrame failed -25` then no more `pacing:` lines (for example PowerWash Simulator on some Frames, GitHub #39) | The eye image rect ends a few pixels past its swapchain (Unity rounds the swapchain width, the runtime's recommended size differs per Frame); SteamVR rejects every frame with XR_ERROR_SWAPCHAIN_RECT_INVALID | FrameBridge clamps every projection/quad image rect to its swapchain (`rect_clamp`, default on since 0.11.0; log `rect_clamp: view N image rect clamped`): rebuild + reinstall the game |
| Unity game (OVRPlugin, GLES) crashes ~10 s in: `FrameBridge: xrCreateSwapchain … faces=6 … result=-2`, OVRPlugin `CreateSwapchain for eye 0: 0x0, 0 stages`, then render-thread SIGSEGV in memset ← libOVRPlugin ← `ovrp_EndFrame4` (libgallium/ANR follow; for example Budget Cuts Ultimate, GitHub #107); triage `cube-swapchain-refused` | The game shows a cube-map layer (OVROverlay cubemap); the Frame's runtime has no cube layers and refuses cube swapchains (XR_ERROR_RUNTIME_FAILURE); OVRPlugin doesn't check and writes into the image list it never got | FrameBridge `cube_standin` (default on): a refused cube swapchain is served as a GL cube map in the game's context and its layers are dropped (log `cube_standin: runtime refused …`): rebuild + reinstall. GLES only; a Vulkan game keeps the error |
| Unity game (OVRPlugin, GLES or Vulkan) crashes ~10 s in: `FrameBridge: xrCreateSwapchain … faces=6 … result=-2`, OVRPlugin `CreateSwapchain for eye 0: 0x0, 0 stages`, then render-thread SIGSEGV in memset ← libOVRPlugin ← `ovrp_EndFrame4` (libgallium/ANR follow; for example Budget Cuts Ultimate, GitHub #107); triage `cube-swapchain-refused` | The game shows a cube-map layer (OVROverlay cubemap); the Frame's runtime has no cube layers and refuses cube swapchains (XR_ERROR_RUNTIME_FAILURE); OVRPlugin doesn't check and writes into the image list it never got | FrameBridge `cube_standin` (default on): a refused cube swapchain is served as a GL cube map in the game's context or a device-local Vulkan cube image transitioned to COLOR_ATTACHMENT_OPTIMAL, and its layers are dropped (log `cube_standin: runtime refused …`): rebuild + reinstall. Vulkan path covers UNDERDOGS (GitHub #296); host-tested, headset verification pending |
| Game (Unity, GLES) freezes, `zink: DEVICE LOST` | multisampled render-to-texture hangs the GPU | `frame.unity_no_msaa`; if it persists: unfixable → PC version |
| Unreal GLES game crashes ~3 s after start: `Fatal signal 11 … fault addr 0x10000 in tid … (RHIThread)`, `#01 … libgallium_dri.so` (GitHub #83 Star Wars Pinball VR, triage `unreal-msrtt-crash`) | Unreal's mobile MSAA renders through multisampled render-to-texture; Zink's `find_rp_state` then indexes `rendering_state_cache[6]` one past its end (sample count ≥ 32) and calls a junk hash function (0x10000). Mesa bug (no bounds check) | `frame.unreal_gl_shim` (GL shim with `gl_hide_msrtt`, multiview kept for Unreal: Unreal 4.25 only enables multiview with GL_OVR_multiview, GL_OVR_multiview2 **and** GL_OVR_multiview_multisampled_render_to_texture, so the shim keeps the last one visible for Unreal and maps glFramebufferTextureMultisampleMultiviewOVR to the single-sampled glFramebufferTextureMultiviewOVR; log `multiview multisampled render-to-texture (N samples) drawn single-sampled`) |
| Crash with `SIGILL (ILL_ILLOPN)` and `*pc=0xd50323bf` (autiasp), for example on Unreal's HttpManager thread (GitHub #83 Star Wars Pinball VR, triage `pac-unpaired`) | The engine's OpenSSL ARMv8 assembly has autiasp without a matching paciasp (libUE4.so: 38 paciasp, 40 autiasp; Poly1305 NEON). Quest CPUs treat PAC hints as NOPs, the Frame's CPU checks them | `frame.pac_hints`: in a library with unpaired counts every paciasp/autiasp becomes a NOP (in place) |
| launch.log ends with `logcat: Unexpected EOF!` right after `Waiting for app …`; the game runs, but Steam's "Resume game" menu isn't closed and the launch test shows nothing (Vader Immortal on Lepton 3.0.5, Under Cover on 2.8.14; about 1 launch in 50) | Lepton's logcat mirror died | Agent v67 `_logcat_keeper` (started by launch.sh, added to older launchers by `upgrade_launchers`) reads the container's logcat itself (`podman exec lepton-steamlaunch-<appid> logcat -v threadtime -T 2000`) and appends it to launch.log; log `<base>/logcat-keeper.log` |
| launch.log stops at `Waiting for app …` (nothing after it, `logcat: Unexpected EOF!` or `Logcat read failure`); the game runs, but Steam's "Resume game" menu isn't closed, the launch test shows nothing and session triage has no log (Vader Immortal on Lepton 3.0.5, Under Cover on 2.8.14; a silent mirror twice on 3.0.5 on 2026-10-14) | Lepton's logcat mirror died or never wrote | `_logcat_keeper` (started by launch.sh, added to older launchers by `upgrade_launchers`; agent v91) reads the container's logcat itself after a failure line or 20 s without a logcat line (`podman exec lepton-steamlaunch-<appid> logcat -v threadtime -T <epoch>`: from the launcher's start, or from just before the mirror's last line), sets a 16 MiB log buffer and appends to launch.log; log `<base>/logcat-keeper.log` |
| A game no longer starts after a reinstall that was launch-tested right away: logcat `Zip: EOCD not found, …/base.apk is not zip` / `Failed to parse …base.apk`, no `Start proc` for the game (VR HOT, 2026-10-09) | The launch test's 45 s ran from the launcher, but the first start after an APK change spends ~1–2 min booting Lepton and installing the app: stopping the container mid-install left a broken installed copy | Agent v68: the test window counts from Lepton's `Waiting for app` (at most 240 s extra for boot + install). Repair a broken one: `touch <base>/lepton-app/game.apk` (Lepton re-installs it on the next start) |
| Unreal game (OVRPlugin) never starts VR: launch.log has `OVRPlugin: JNI_OnLoad` but never `CompositorOpenXR::PreInitialize`, no OpenXR session, then a crash a few seconds in (for example Star Wars Pinball VR, UE 4.25: null pointer in `FSceneRenderer::GetMultiViewSceneColor`, GitHub #83) | Unreal's Oculus module looks up every `ovrp_*` function of the OVRPlugin it was built against (`InitializeOculusPluginWrapper`, all ANDed); OVRPort's OpenXR OVRPlugin lacks a few old ones (UE 4.25 / OVRPlugin 1.44: `ovrp_GetPTWNear`), so the wrapper fails and OculusHMD is never pre-initialized | `frame.unreal_ovrp_entrypoints` (suggested when analysis `unreal_ovrp_lookups` name functions the shipped OVRPlugin lacks): generated `libfp_ovrpstubs.so` (DT_NEEDED of libOVRPlugin.so; dlsym on the plugin's handle searches its dependencies) with a stand-in per missing name returning ovrpFailure (-1000); build note lists the names |
| Only the Android home screen shows; the log has Unity's VR device as `None` (for example Accounting+, Unity 2017) | Unity 2017–2018 built-in Oculus support starts VR only when `com.oculus.systemactivities` is installed; Lepton has no Meta system apps, so Unity falls back to non-VR | `frame.unity_oculus_check`: that package name in libunity.so → `android`, plus `native/ovrpshim` (libfp_ovrp.so): Unity 2017's legacy frame loop (`ovrp_Update2`/`ovrp_BeginFrame`) never calls `ovrp_WaitToBeginFrame`, so without the shim no `xrWaitFrame` happens, `CompositorOpenXR::Update … outside of frame bounds` floods the log and the dashboard freezes. With it: log `ovrp frame loop shim: waited for frame N`, ~71 fps. Accounting+ then stops at "press any button" although its OVRInput gets clean input (`INPUT_PROBE` in the patch logs connected controllers/buttons/input focus per call) — unresolved |
@@ -258,3 +267,19 @@ Scan a folder with Rift game dumps (Windows game folders) like Quest dumps; they
| Proton game hangs at start in a headless/SSH launch; log `no driver could be loaded` / `explorer process failed to start` | no display session (DISPLAY/GAMESCOPE_WAYLAND_DISPLAY) | the Proton launch.sh takes them from the running Steam (built in) |
| Unreal game starts (window created) then `CrashReportClient` runs | the game crashed under Proton; often no VR runtime reached it (Revive off) | keep `pcvr.revive` on (repacks' bundled LibRevive64.dll isn't loaded by itself); read the game log + crash summary in the launch log |
| `VK_ERROR_DEVICE_LOST` under DXVK | freedreno GPU hang | `pcvr.proton_log` to capture; PC mode |
## Experimental Rift through FEX
These signatures apply to PC VR logs (`kind: pcvr`). Compatibility profiles describe static evidence until a
headset test verifies them. Meta's entitlement and runtime signature checks remain intact.
| Symptom | Cause | Fix |
|---|---|---|
| Meta runtime says `Missing entitlement` | The signed-in Meta account does not own the game | Informational, not a FramePort bug; use an account that owns it. No bypass or patch is offered (`fex-missing-entitlement`) |
| `OVRServer` reports `install_available` | The matching app is not registered as installed | Reinstall/register through the FEX install flow with the matching Meta manifest (`fex-registration-missing`) |
| `Rejecting new committed universe since IMU fallback is active` | SteamVR has not acquired headset tracking since boot | Wear the headset once and wait for tracking before retrying (`fex-imu-fallback`) |
| `Service invocation completed`, followed by confirmation `OVRLibrarian still running` | Wine Mono's OVRLibrarian never exits under FEX and blocks later clients | End only OVRLibrarian.exe after completion; check that the FEX launcher's cleanup runs. Completion alone is healthy (`fex-librarian-stuck`) |
| `vkd3d` fails to create/initialize a device | D3D12 renderer initialization failed | Check GE's bundled vkd3d-proton, clear inherited wined3d/no-D3D12 flags, verify FEX Vulkan thunk to Turnip (`fex-vkd3d-init`) |
| `wined3d` fails to initialize OpenGL | No working guest GL/display route; the Vulkan thunk does not provide a GL thunk | Inspect guest Mesa renderer and display access; prefer the game's D3D9/11 route if available (`fex-wined3d-init`) |
| `ReviveInjector` reports failure to start/inject | Wrong exe, missing x64 Revive files or injection failure | Check executable and shared GE prefix; use OpenVR mode, without `/openxr`. OpenVR-only games can run directly (`fex-revive-injector`) |
| Robo Recall has no IME CVar in ApplicationCore or Slate | Older modular Unreal keeps FWindowsApplication in Core | Search `*-Core-Win64-Shipping.dll` with the same anchored CVar finder; this surveyed build has the constructor default at RVA `0x15ffe5`. Never patch an unanchored boolean based on an assumed member offset |
+276
View File
@@ -0,0 +1,276 @@
# Rift through FEX: compatibility stream C
Compatibility is static evidence until a headset test verifies a build. First Contact remains the only verified
profile. No game entitlement, Platform SDK or Oculus signature checks are changed. A Meta account without ownership
must receive **Missing entitlement**; this is an informational result, not a bug to work around.
## Implementation and profile schema
`agent/fexrift_compat.py` registers a `GAME_INFO_HOOKS` handler, launcher environment handler and install-check
handler. `game_info()` obtains the exe and launch arguments from Meta's manifest, then applies a matching profile.
The helper reports `verified: false` for likely/untested builds. Likely profiles install with a warning (also in
`checks.profile_warnings`, which the parent agent forwards); untested builds need `force_unverified`; blocked
profiles are refused even with force. `checks` records the selected profile, status, route, cache eligibility and
32-bit warning. No agent version bump is included.
`agent/fexrift_games.json` is data, not executable configuration. Its `_comment` describes these fields:
| Field | Meaning |
|---|---|
| `match.canonical_names` | List of exact Meta canonical app names; no fuzzy title matching |
| `match.sha256` | List of exact executable SHA-256 strings |
| `match.executables` | List of `{name, size}` objects: case-insensitive basename **and** exact byte size must match |
| `status` | `verified`, `likely`, `untested`, `blocked` |
| `graphics` | `d3d11` (default), `d3d9`, `d3d12`, `opengl`, `vulkan` |
| `env` | String environment values |
| `ime_patch` | Optional fallback `{rva, old, new}`, with integer/hex RVA; null means no fallback |
| `fp_mem` | `off`, `candidate` (informational, no preload), `enabled` (verified per-game opt-in) |
| `bigcache_mb` | Cache size when enabled, default 256 |
| `dxvk` | List of dxvk.conf lines; launcher writes `$A/dxvk.conf` and exports `DXVK_CONFIG_FILE` |
| `args` | Optional argument list override; omit to preserve manifest arguments |
| `notes` | Evidence and first-launch cautions |
| `revive` | Optional, defaults true; false launches an OpenVR-only game directly |
Match alternatives are OR, while basename and size within an executable match are AND. Multiple matching profiles
are refused. With no `match`, the profile key is the exact canonical name (legacy First Contact compatibility).
The surveyed profiles use basename+size because the owner's folders do not establish authoritative Meta canonical
names; their keys identify profiles, **not** presumed Meta app IDs. They preserve the manifest's exe and arguments.
A different store build/size needs a new survey or an explicit untested install; do not guess its identity.
A SHA-only identity should be rechecked against the original executable after any game-byte patch: patching changes
its hash. Prefer canonical names or basename+size for profiles that need the IME fix. Size matches choose launch
settings only; the anchored finder independently verifies the bytes before patching.
`fp_mem: candidate` is set only when the surveyed lower bound of the UE version is >=4.18 (Binned2 big-block path).
It never enables the unzeroed cache. Every other game needs evidence that it fully overwrites reused memory before
an opt-in. First Contact's existing explicit environment/cache settings remain enabled.
## Older Unreal: Robo Recall
The premise that Robo Recall lacks `Slate.DeferWindowsMessageProcessing` was a search-location error. Its modular
`RoboRecall-Core-Win64-Shipping.dll` contains the UTF-16 CVar at file offset `0x1e1bb0`; the existing anchored finder
returns RVA `0x15ffe5`, old `c7860002000001000000`, new `c7860002000000000000`. This changes the constructor's
`mov dword ptr [rsi+0x200],1` immediate to zero, with the existing expected-byte guard and `.orig` backup.
Older Unreal placed `FWindowsApplication` in Runtime/Core; newer trees split it into Runtime/ApplicationCore.
`bAllowedToDeferMessageProcessing` and `GetDeferMessages` control the same Windows message deferral path, so an old
engine is not exempt from the IME deadlock merely because ApplicationCore/Slate lack the marker. The extension
extends `find_ime_target()` to search `*-Core-Win64-Shipping.dll` (and Win32/Core.dll forms), using the unchanged
CVar/xref/storage finder. It never patches a guessed member offset. Synthetic tests cover successful Core discovery,
repeat installs, and a CVar name without an anchored reference. No Unreal source checkout was available offline;
the observed binary is the evidence for this build, rather than an inferred engine-version exemption.
## Graphics and remaining device questions
DXVK handles D3D9/11; D3D12 uses GE's own vkd3d-proton selection. The launcher clears inherited
`PROTON_USE_WINED3D`, `PROTON_NO_D3D12` and `PROTON_NO_D3D11`, keeps `FP_VKTHUNK=1`, and lets Proton select/copy its
shipped DLLs. It makes no renderer DLL edits in a game. `checks.vkd3d_dlls` reports installed d3d12 DLLs under
`files/{lib,lib64}/wine/vkd3d-proton/{,x86_64-windows/,i386-windows/}`. These are discovery candidates, not a hardcoded
installation prerequisite. GE-Proton's script/archive was not available locally, and network/device access was
prohibited: verify the exact 11-7 layout and its script logic on the device before claiming D3D12 support.
The `opengl` profile exports `PROTON_USE_WINED3D=1`. A native OpenGL game still calls OpenGL directly; this flag
selects Wine's GL renderer for any D3D calls. There is **no configured FEX GL thunk**. Host acceleration would need
FEX's matching guest libGL/libEGL thunk libraries, host counterparts and enabled GL thunk configuration, with a
working display/GLX/EGL bridge. Guest rootfs Mesa might instead use software rendering or Zink through Vulkan;
inspect the actual renderer before attributing a game failure to Wine or promising hardware acceleration.
The Climb prefers its imported D3D9 route; imports alone do not prove which renderer its config selects.
A 32-bit exe is flagged in the survey and install checks. GE WoW64 under FEX still needs working 32-bit graphics
and SteamVR's 32-bit vrclient bridge; it is not promoted to likely based on engine alone. XAudio2 and Bink are facts
to watch; Media Foundation is flagged for a real movie-playback check. Anti-cheat detected by filenames/imports
makes a generated profile blocked. Absence of a static marker is not proof that runtime-loaded middleware is absent.
## Reproduce the offline survey
Use an isolated `FRAMEPORT_HOME`; never set `FRAMEPORT_WINDOWS_DATA`. No program in a dump is executed, no archive
is extracted, and no file in a game folder is written. The report contains local paths and must stay uncommitted.
```bash
export FRAMEPORT_HOME="$PWD/.home"
uv run python - <<'PY'
import subprocess, sys
from pathlib import Path
root = Path('/mnt/d/Backup Data/Misc/emus/VR_META_QUEST/ARMGDDN_PCVR_OCULUS')
cmd = [sys.executable, 'scripts/rift_fex_survey.py', '--out', '.home/survey']
for folder in sorted(root.iterdir()):
if folder.is_dir():
cmd += ['--folder', str(folder)]
subprocess.run(cmd, check=True)
PY
```
Outputs: `.home/survey/survey.json`, `survey.md`, and `profiles.json` (ready to paste, but review argument overrides
and direct OpenVR routing). The Unreal pak/ini reader is deliberately left in place for stream B's extraction.
## Owner's library: static results
All 19 selected game exes are x86_64; no selected 32-bit client was found. Eighteen use the Platform SDK; Rick and
Morty is the exception. The table contains **10** likely titles (including Robo Recall and all three Vader episodes),
plus nine untested titles. Profile IDs below are data keys matched by exe basename+size, not canonical app names.
`candidate` means cache eligibility only; it is off at launch. No surveyed game is promoted to verified.
| Game / profile ID | Route | Status | Platform SDK | fp_mem | Watch at first launch |
|---|---|---|---|---|---|
| Arktika 1 / `arktika-1` | d3d11 trial; API undetected | untested | yes | off | Establish actual renderer and custom-engine startup; do not infer D3D11 from this default |
| Asgard's Wrath / `asgards-wrath` | d3d11 | likely | yes | candidate | Large-block stalls/memory, Media Foundation movies, entitlement |
| Brass Tactics / `brass-tactics` | d3d11 | likely | yes | off | Media Foundation movies, tracking and IME startup |
| Chronos / `chronos` | d3d11 | likely | yes | off | Older UE D3D11 path, movies and controller input |
| Defector / `defector` | d3d11 | untested | yes | off | Custom-engine startup and Bink cutscenes |
| Hubris / `hubris` | d3d11 | likely | yes | candidate | XAudio2 sound, Media Foundation movies, shader/GPU cost |
| Lies Beneath / `lies-beneath` | d3d11 | likely | yes | candidate | Platform SDK delay load/entitlement; IME fix and movies |
| Lone Echo / `lone-echo` | d3d11 (also imports d3d9) | untested | yes | off | Runtime tracks client, entitlement; custom-engine startup and allocator stalls |
| Lone Echo II / `lone-echo-2` | d3d12 | untested | yes | off | vkd3d-proton DLL layout and Vulkan device creation on Turnip |
| Rick and Morty / `rick-and-morty-virtual-rick-ality` | opengl; direct OpenVR | untested | **no** | off | Actual GL renderer/acceleration; SteamVR bridge; speech WinRT; never inject Revive |
| Robo Recall / `robo-recall` | d3d11 | likely | yes | off | Core DLL IME fix at `0x15ffe5`; Meta entitlement and tracking |
| Skydance's Behemoth / `skydances-behemoth` | d3d11 | likely | yes | candidate | XAudio2 sound, Media Foundation movies and heavy GPU/memory use |
| Stormland / `stormland` | d3d11 | untested | yes | off | Custom engine, Media Foundation and Bink cutscenes |
| The Climb / `the-climb` | d3d9 preferred; also imports GL | untested | yes | off | Confirm CryEngine selects D3D9 and DXVK; GL import alone is not a selected renderer |
| The Unspoken / `the-unspoken` | d3d11 | untested | yes | off | Custom engine, Media Foundation and Bink cutscenes |
| Vader Immortal I / `vader-immortal-episode-i` | d3d11 | likely | yes | off (UE range starts at 4.16) | Movies, controller input, startup IME; leave MSAA at its game default |
| Vader Immortal II / `vader-immortal-episode-ii` | d3d11 | likely | yes | off (UE range starts at 4.16) | Movies, controller input, startup IME; leave MSAA at its game default |
| Vader Immortal III / `vader-immortal-episode-iii` | d3d11 | likely | yes | off (UE range starts at 4.16) | Movies, controller input, startup IME; leave MSAA at its game default |
| Wilson's Heart / `wilsons-heart` | d3d11 | untested | yes | off | Custom-engine startup and Bink cutscenes |
## Exact maintainer device checks (not executed here)
Only run one FEX game at a time: they share the Wine prefix and wineserver. The following uses the existing CLI;
stream A/B may add a direct login/install path at integration. Set `FRAMEPORT_HOME` to the development data folder
with the paired Frame configuration, then keep using that folder. The example `.home` is isolated from normal app
data and needs a paired Frame first. Never set `FRAMEPORT_WINDOWS_DATA`.
1. On the development PC, upload the integrated helper/extensions/profiles and verify setup:
```bash
export FRAMEPORT_HOME="$PWD/.home"
export FRAMEPORT_EXPERIMENTAL_FEX=1
uv run frameport fex setup
uv run frameport fex status
```
Wait for setup to finish. Expect `proton`, `prefix` and `fex` true; `apps` lists Meta canonical names. No token or
sign-in URL is needed in the output. If importing from an already signed-in PC Wine prefix, use the exact app
name from its Meta manifest filename (replace both example values):
```bash
app='actual-meta-canonical-name'
prefix='/path/to/signed-in/wine-prefix'
uv run frameport fex import-login "$prefix" --app "$app"
uv run frameport fex install "$app"
```
For a matching likely profile, expect `verified: false`, `checks.profile_status: likely`, a profile ID and
`checks.profile_warnings`; no `--force-unverified` should be needed. If the downloaded build differs from the
surveyed basename+size, expect refusal and review its own survey before forcing. An explicitly blocked profile
must still refuse with `--force-unverified`. An untested game needs that switch. The PC reporter also warns
that the game has not been verified on the Frame.
2. On the Frame, wear the headset once after boot and wait for tracking. Launch from the Steam shortcut. For these
checks in a Frame terminal, replace `app` with the same canonical name:
```bash
app='actual-meta-canonical-name'
pkg="rift.${app//-/_}"
anchor="$HOME/Applications/quest-frame/$pkg"
python3 - "$anchor/deployment.json" <<'PY'
import json, sys
d = json.load(open(sys.argv[1]))
for key in ('profile', 'profile_status', 'profile_warnings', 'graphics', 'fp_mem', 'exe_32bit', 'wow64', 'vkd3d_dlls'):
if key in d.get('checks', {}):
print(key, d['checks'][key])
PY
rg 'FramePort FEX: graphics=' "$anchor/launch.log"
rg 'PROTON_USE_WINED3D|PROTON_NO_D3D12|DXVK_CONFIG_FILE|export FP_MEM' "$anchor/launch.sh"
```
Expect the profile route. Candidate caches must have no `export FP_MEM=1`. For Rick and Morty also run
`rg 'taskset.*proton' "$anchor/launch.sh"`: the command must invoke the game directly with no ReviveInjector.
A graphics route marker proves selection of launcher settings, not successful rendering. Check both eyes,
tracking/controllers, sound and a movie in the headset before changing a profile to verified.
3. For Robo Recall, `checks.ime.file` should name `RoboRecall-Core-Win64-Shipping.dll` and `fixes.ime_patch` should be
`patched` on first install and `already` on repeat. On the Frame, verify the original backup exists and the
constructor immediate is zero (only the installed copy is read):
```bash
python3 - "$anchor/deployment.json" <<'PY'
import importlib.util, json, os, sys
d = json.load(open(sys.argv[1]))
path = os.path.join(os.path.dirname(d['exe']), d['checks']['ime']['file'])
helper = os.path.expanduser('~/.local/share/frameport/fexrift/artifacts/fexrift.py')
spec = importlib.util.spec_from_file_location('fx', helper)
fx = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fx)
b = open(path, 'rb').read()
p, reason = fx.find_ime_patch(b)
assert p and b[fx.pe_offset(b, p['rva']):fx.pe_offset(b, p['rva']) + len(bytes.fromhex(p['new']))] == bytes.fromhex(p['new']), reason
assert os.path.isfile(path + '.orig')
print('Core IME default zero; original backup present')
PY
```
4. For Lone Echo II (untested), install with `--force-unverified`. In a Frame terminal inspect only GE's files and
script; no network fetch is needed:
```bash
r="$HOME/.local/share/frameport/fexrift"
rg --files "$r/ge/files" | rg '/vkd3d-proton/.*/?d3d12(core)?\.dll$|/vkd3d-proton/d3d12(core)?\.dll$'
rg -n 'PROTON_USE_WINED3D|PROTON_NO_D3D12|vkd3d-proton|dxvk' "$r/ge/proton"
```
Expect bundled vkd3d-proton and script selection when wined3d/no-D3D12 are unset. `checks.vkd3d_dlls` should name
the installed layout. A vkd3d initialization failure is triaged `fex-vkd3d-init`; a successful Vulkan device plus
frames in both eyes is the first actual evidence of this route. If the file layout differs, update discovery
candidates without copying DLLs into the game. For GL, inspect the active **guest** renderer; an installed host
Mesa library or the Vulkan thunk does not establish guest GL acceleration.
5. Exercise each triage signature offline on the PC with
`uv run pytest -q tests/test_fexrift_compat.py -k triage`. On-device expected strings are `Missing entitlement`,
`OVRServer ... install_available`, SteamVR's IMU-fallback message, vkd3d/wined3d initialization failure, or a
ReviveInjector failure. Do not dump entire Meta log files: they may carry sign-in data. A Librarian completion
line alone must not diagnose a hang. After completion, confirm persistence using `pgrep -f '[O]VRLibrarian.exe'`;
only if it remains alive, record the safe diagnostic `OVRLibrarian still running` alongside the completion
marker. The launcher now emits the fixed combined marker itself if Librarian persists after cleanup and
completion is present; it never mirrors the log. The combined trace matches `fex-librarian-stuck`. Stop only that process after completion with
`pkill -9 -f '[O]VRLibrarian.exe'`; the normal launcher already does this. For an unowned title, accept Meta's
Missing entitlement result and stop that game test.
Undo: exit the game in Steam before touching files. Remove the selected profile from the device copy of
`artifacts/fexrift_games.json` and rerun install with `--force-unverified` to regenerate the default D3D11/Revive
launcher. For an OpenVR-only game, retain `revive: false` in an untested profile when comparing graphics routes.
Remove the anchor's `dxvk.conf` when no longer used. To undo the IME fix, restore **only the installed binary**
from its `.orig` copy after stopping the game; for example, on the Frame:
```bash
python3 - "$anchor/deployment.json" <<'PY'
import json, os, shutil, sys
record = json.load(open(sys.argv[1]))
path = os.path.join(os.path.dirname(record['exe']), record['checks']['ime']['file'])
shutil.copy2(path + '.orig', path)
print('Installed IME binary restored')
PY
```
Do not delete the shared prefix to undo a profile: it holds Meta's runtime and the owner's login/saves. Game dumps
are never modified. Re-running install reapplies the anchored IME fix; to compare launches, restore after install
and before Play.
## Validation in this worktree
- Offline survey completed for all 19 folders with no per-game errors. Every surveyed executable matched exactly
its intended committed profile through the compatibility hook. Ten profiles are likely, nine untested; the
separate First Contact profile stays verified. No selected or alternate candidate exe was 32-bit. No static
anti-cheat marker was found; this does not rule out runtime-loaded middleware.
- Focused FEX/survey/triage tests: **96 passed, 1 skipped**. Ruff passed for the new extension, survey and their tests.
- `uv run python scripts/patch_docs.py` was run; `--check` passes and generated patch docs needed no committed change.
- Final whole-suite run: **1,646 passed, 43 skipped, 11 failed, 16 setup errors**. All 27 unsuccessful cases failed
at local `socket()` creation with `PermissionError: [Errno 1] Operation not permitted`. They are existing local
HTTP/pairing/stream tests in `test_deeplink`, `test_devkit`, `test_install_links_extra`, `test_livestream`,
`test_setup_url`, and `test_ui_state`. They need a runner allowing loopback sockets; no application or test code
was changed to hide this restriction. Re-run the full suite there before integration.
- The prebuilt virtual environment was used with `UV_CACHE_DIR=/tmp/frameport-rift-uv UV_NO_SYNC=1` because the default
uv cache is read-only and offline metadata resolution cannot install hatchling. For example:
`UV_CACHE_DIR=/tmp/frameport-rift-uv UV_NO_SYNC=1 uv run pytest -q`.
- No device or external network access was attempted. D3D12, guest OpenGL acceleration, WoW64 and gameplay remain
device questions; the steps above specify the evidence needed. The GE script and Unreal source-history checkout
were unavailable locally; Robo Recall's actual Core DLL supplies direct evidence for the IME fix instead.
+228
View File
@@ -0,0 +1,228 @@
# Stream B: unchanged local Rift copies and Meta library registration
Implemented on `rift/install`. Device validation is pending: this workspace cannot reach the Frame or create local
network sockets. No entitlement, Platform SDK, runtime signature check, sign-in data or repack crack is changed by
this work. A Meta **Missing entitlement** response remains a failure to report to the owner.
## Implementation
`frameport fex install --from-library rift.<slug>` takes the Rift entry's `game_dir`, selected `exe`, title and
`launch_args` (also supported in `analysis.extra`). `--folder DIR [--title T]` uses the existing Rift analyzer to pick
the exe; ambiguous choices must first be resolved in the library. Optional positional `APP` overrides the generated
canonical name. Otherwise use the analysis's `canonical_name`, then a lowercase title slug. Local unverified games
require `--force-unverified` **before** any upload. Existing prefix-game installs still work without either option.
`src/frameport/fexinstall.py` stats the folder and reuses `installer.transfer_link()` and `upload_files()` unchanged:
fast link, SFTP `.part` append, tar batches, progress and Reporter cancellation all follow the existing install path.
Finished files are skipped by source size/mtime plus remote size; changed sources discard old completed/partial
bytes before retry. The source is statted again after transfer. This avoids hashing all source files over NTFS;
it cannot detect an edit that deliberately preserves both size and mtime. Do not edit the source during an install.
The free-space check reserves 1 GiB in addition to all pending bytes (conservative when `.part` files already exist).
Skipped, logged and recorded: case-insensitive `*.7z`, `*.7z.0*` split volumes (including backup suffixes), `Data.bin`,
`AGRepackInstaller.exe`, `VD.bat`, and `*.AG`. Nothing is extracted or executed on the PC. Every included file's bytes
are uploaded as supplied. Existing install-time generic fixes, including the Unreal IME fix, still run on the Frame
after registration; they may change the **Frame** executable. The source folder stays unchanged. Symlinks, path
escapes, duplicate Windows filenames and collisions with Meta-managed copies are refused.
App ID precedence:
1. `[OnlineSubsystemOculus]` in unencrypted pak `Config/DefaultEngine.ini`, then loose `DefaultEngine.ini`,
`Oculus.ini` or `OculusConfig.ini`; keys `RiftAppId`, `OculusAppId`, `AppId` in that order. Also checks only the
known JSON names `OculusConfig.json` / `oculus-platform-config.json` for `RiftAppId`, `OculusAppId`, `AppId`,
`app_id`. IDs must be positive numbers. No binary-string guessing or archive decryption.
2. Already cached OculusDB data: `details.store_url` (`fetch_details()` retains the ID in this URL, not an explicit
Rift-ID field). No lookup/network request is introduced. A Quest-linked details record can name its Quest store
product: check this fallback manually before testing a game with no config ID.
3. `--app-id ID`, used only if no earlier source supplies one.
`app_id_source` records the selected origin. `store_app_id` independently retains the cached store ID when present,
so a game ID such as First Contact's `1184903171584429` is not lost to store product `1217155751659625`. Manifest
`appId` uses the selected ID; device tests must establish whether Meta instead requires the store product ID for
particular builds. The version comes from a version-like folder name, then the exe's PE `.rsrc` FileVersion, else
`0.0.0`; versionCode is 1. The shared reader moved to `analysis/unreal_pak.py`; the survey re-exports it via imports
so its existing callers and tests keep working. Stream C should keep these imports when merging its survey edits.
`agent/fexrift_install.py` registers `prepare_local`, `register_local`, `local_info`, `unregister_local` and
`runtime_state`. Reservations/metadata live in `fexrift/local-games/<app>.json`, with no login information. They also
allow interrupted pre-registration uploads to resume. Registration hashes each file **on the Frame**, writes
`<library>/Manifests/<app>.json` and `.json.mini`, and imports the library registry entry through Wine. The extension
supplies the library manifest to `manifest_launch` / `game_info`; the existing static checks, IME patch and launcher
then run normally. The install check hook marks `local_copy: true`.
Manifest JSON matches the supplied real First Contact app fixtures: property order (derived properties first),
types, CRLF, two-space indentation, backslash `files` keys, forward-slash `launchFile`, and mini containing exe
records only. App packageType `APP`, isCore false, launchFile2D null, launchParameters2D empty string,
redistributables empty; other defaults come from `MANIFEST_DEFAULTS`. Launch parameters use Windows argv quoting;
the launcher preserves the original argv list (a small shared launcher hook avoids splitting local-copy arguments
while retaining the existing profiles' shell-fragment parsing).
Each file has its actual size and whole-file SHA-256, `segmentSize: 10000000`, and one segment per **decimal 10 MB**
chunk. Each triple is `[0, chunk_sha256, len(zlib.compress(chunk))]`. The fixture's third number is compressed length,
not uncompressed size. We do not know Meta's opaque first value and use 0 as an explicit placeholder; no fabricated
CDN identifiers or download URLs are written. Empty files have zero segments. **These manifests describe local
bytes, not a working Meta CDN repair recipe. Whether Meta accepts the placeholder without scheduling repair is an
open device question.** Do not initiate an update/repair from Meta's app to validate this.
Internal games: `<PFX>/drive_c/Program Files/Meta Horizon/Software/Software/<app>`, using Meta's existing default
library registration. `--dest <mount>` must exactly match an available external mount returned by the existing
`drives` command; existing `resolve_dest()` rejects unusable filesystems. No fallback on a missing card.
External games: `<mount>/FramePort/fexrift-games/<app>`. Their Meta library root is the sibling
`<mount>/FramePort/fexrift-library`, containing `Manifests/` and a `Software` symlink to `fexrift-games/`. A stable
UUID5 from the mount path identifies the registry library. A prefix `dosdevices/volume{GUID}` links to the mount,
and the first unused D:–Y: letter links there too (an existing letter for the same mount is reused). Registry
`Path` uses `\\?\Volume{GUID}\FramePort\fexrift-library`, `OriginalPath` uses the letter. The default library stays
default. Mount-path changes require uninstall/reinstall; moving these games through the general Move action has
not been implemented by this stream. Wine volume discovery and external-library scans need device validation.
Deployment kind stays `frame_fex`, with `source: local_copy`, `app_id`, `app_id_source`, `store_app_id`, `skipped`,
`dest`, and the existing launcher/check fields. Local-copy uninstall removes its files and both manifests. The last
game on an external library also removes that library's registry key; the shared default key, shared prefix, saves,
login and reusable drive/volume links remain. Imported Meta-managed games still keep their files on uninstall.
There is no agent-version bump; integration must bump it so updated agent commands reach existing devices.
The only other shared-agent helper change sends helper JSON on stdin, avoiding Linux's single-argument size limit
for large inventories. The extension files are already included by `artifact_files()` and need no packaging change.
## Runtime probe
`--runtime-check` calls the separate bounded `fex_runtime_state` command after install (helper `runtime_state`). It
reuses an existing OVRServer or starts it with the shared prefix's Wine environment. It examines only newly appended
Service/OVRServer log text, returning `runtime_state: ready`, `install_available` or `timeout` plus `reused_server`.
It never returns raw runtime log lines. If it started the server, it kills OVRLibrarian after a fresh invocation
completion and stops its Wine server at exit; a reused runtime is left running. The polling budget is 95 seconds,
with bounded process start/probe/cleanup, and the agent imposes a 120-second limit. A reused idle runtime may emit no
new state line and return `timeout`; that result is inconclusive. The probe does not start the game or prove account
ownership. The actual log naming/state-line format remains a device question.
## Offline validation
Use a writable UV cache in this sandbox (the default cache is read-only):
```sh
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline --no-sync pytest -q
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline --no-sync pytest -q \
tests/test_fex_install.py tests/test_fexrift.py tests/test_fexrift_ext.py tests/test_rift_fex_survey.py
```
The full run reached 1,654 passed, 43 skipped; 11 failures + 16 setup errors all tried to create network sockets
for existing localhost HTTP/streaming/pairing tests, which this sandbox forbids (`PermissionError: Operation not
permitted`). Rerun the whole suite without that sandbox restriction at integration. No socket tests were changed
to conceal this limitation. Triage/patch catalog files were not touched, so `patch_docs.py --check` is not required.
Final follow-up: 1,658 passed, 43 skipped, 27 deselected when excluding precisely those socket-dependent tests.
The final install/FEX/survey run (including an additional split-volume suffix case) passed 68 tests, 1 skipped.
Ruff passed for the new modules/tests and the survey; `git diff --check` passed.
## Exact maintainer device test
Run these only on the maintainer's connected PC. Keep `FRAMEPORT_HOME` pointing to this worktree's `.home`, with
its paired Frame target and Rift library entries. Do not point at the Windows FramePort data directory. Ensure the
maintainer's integration agent version includes this branch. Wear the headset once after boot; stop any running
FEX game before the runtime probe (all use one prefix).
```sh
export FRAMEPORT_HOME="$PWD/.home"
export FRAMEPORT_EXPERIMENTAL_FEX=1
uv run frameport fex setup
uv run frameport fex status
uv run frameport list
```
Setup uploads this extension and binaries; it may fetch the signed Meta runtime on the device. Use the login stream
to sign in with the owner's account first. `status` should show prefix/meta installed and `login: true` without
printing any session content. Do not copy session files, CoreData or sign-in URL queries into a report.
Pick a library ID the account owns; example (substitute the exact ID from `frameport list`):
```sh
uv run frameport fex install --from-library rift.robo_recall --force-unverified --runtime-check
```
Expect `Skipped repack leftover: ...` entries, `Meta app ID ... (config:...)` or the cached/CLI fallback, upload
progress, `Hash and register the game on the Frame`, then generic checks/Steam registration. Final JSON should
have `checks.local_copy: true`, with `checks.runtime_state: ready` if Meta emitted the state line. Check
`app_id_source` and both IDs in deployment with the filtered command below. `install_available` means registration
did not take; stop and report the IDs, canonical name and manifest shape. `timeout` requires inspecting the log
format **locally on the device**, keeping any account data private.
A folder install uses the same flow:
```sh
uv run frameport fex install --folder '/path/to/a/game copy' --title 'My Rift Game' \
--app-id 1234567890123456 --force-unverified --runtime-check
```
Replace the example ID with the game's actual ID; the option is a fallback and does not override a config ID.
Do not try registering over First Contact already imported by the login tar: the collision refusal is deliberate.
Inspect deployment fields and launch using the paired connection (edit the package below once):
```sh
uv run python - <<'PY'
import json
from frameport.cli import _fex_target
frame = _fex_target(None).frame
pkg = 'rift.robo_recall'
try:
games = frame.agent('list_installed', package=pkg, details=True)['games']
for game in games:
print(json.dumps({k: game.get(k) for k in
('package', 'kind', 'source', 'app_id', 'app_id_source', 'store_app_id', 'skipped', 'dest')}, indent=1))
print(frame.agent('launch', package=pkg))
finally:
frame.close()
PY
```
Expect `kind: frame_fex`, `source: local_copy`, IDs/provenance, and a Steam launch. In the headset check both eyes,
controllers, audio and reaching a scene. Look locally for runtime `state: ready`, launcher `FramePort: starting
Meta's runtime` / `FramePort: starting <title>`, and the game log. **Missing entitlement** is a valid ownership
failure to report, never a reason to modify the copy or checks. Robo Recall may lack the generic IME patch site;
report a hang without assuming the registration failed.
Resume: interrupt the upload with Ctrl-C, then repeat the identical install command. Expect completed files to be
skipped and big `.part` files to continue. Compare a few **non-patched** files' SHA-256 locally on source/Frame;
manifests should list actual sizes/hashes. No archive, installer, `.AG` file or `VD.bat` should have been uploaded.
External drive: first uninstall the test copy using the rollback below, then:
```sh
uv run frameport frame drives
uv run frameport fex install --from-library rift.robo_recall --force-unverified \
--dest /run/media/steamos/REPLACE_WITH_MOUNT --runtime-check
```
Use an actual `usable: true` mount. Expect physical files in `FramePort/fexrift-games/<canonical>`, sibling
`fexrift-library/Manifests`, a `Software` symlink, a separate registry library, and `runtime_state: ready`. With the
card removed, reinstall/uninstall must fail explicitly rather than writing/deleting internal storage. Reinsert at
the same mount path before rollback. Repeat with two games to confirm uninstalling one leaves the second library
registered; removing the last should remove its registry key.
## Undo
For an installed local copy, end the game in Steam first, then run (substitute its package):
```sh
uv run python - <<'PY'
from frameport.cli import _fex_target
frame = _fex_target(None).frame
try:
print(frame.agent('uninstall', package='rift.robo_recall', remove_shortcut=True, keep_data=True))
finally:
frame.close()
PY
```
Expect `removed: true`; game folder, both manifests, deployment and shortcut disappear. Shared prefix, login, saves
and unrelated games remain. For a cancelled upload that never produced a deployment, remove only its reservation
and uploaded copy through the helper on the Frame (replace canonical/package; stop shared-prefix games first):
```sh
python3 -I ~/.local/share/frameport/fexrift/artifacts/fexrift.py unregister_local \
'{"app":"robo-recall","package":"rift.robo_recall"}'
```
Reusable drive links and the empty external library scaffolding can remain for later installs; they contain no
game/login data. Do not delete the shared prefix to undo one local installation.
+178
View File
@@ -0,0 +1,178 @@
# Stream A: Meta sign-in on the Frame
Implemented on `rift/login`. No Frame or network access was used. The PE helper has **not** been compiled here
(llvm-mingw is unavailable); the browser portal and pipe framing remain device acceptance checks.
## What was built
`frameport fex login [--start-now] [--timeout 900] [--via-pc]` signs in through Meta's own Client.exe, running in the
existing shared FEX prefix. The default creates a temporary, flat Steam entry named **Meta sign-in (FramePort)**
using the existing shortcut installer. `--start-now` instead starts a detached user unit without restarting Steam.
`fex login --stop` repairs interrupted cleanup. All commands require `FRAMEPORT_EXPERIMENTAL_FEX=1`.
`agent/fexrift_login.py` registers `login_start`, `login_status`, `login_stop` and private broker/callback commands.
`agent/frameport_agent.py` has one separate `fex_login*` block; it passes login messages to the extension over stdin,
never JSON argv. No agent version bump or changes to other streams' hook points were needed.
The launch script imports Steam's display variables, disables gamescope WSI and preloads, starts the existing Meta
runtime, waits for OVRLibrarian's completion and kills its stuck process, then starts Client.exe with Proton. Its
stdout/stderr and Proton logging are disabled because Electron can print authentication URLs. A lock prevents a
second Client.exe launcher. A private broker must be alive before the launcher can run. Cancellation signals the
launcher (PID plus kernel start tick, to reject a reused PID), stops Wine, then restores the handler settings. This
also prevents an interrupted runtime warm-up from starting Client.exe after cleanup.
The prefix's WineBrowser `Browsers` setting temporarily points to `login/fp-open-url`. That helper sends the URL to
an owner-only Unix socket broker. The broker records only `page_opened_at`, `callback_received_at` and the fixed
query-free page URL in `login/state.json`. It opens the real URL with host xdg-open, with output discarded. The
temporary host `frameport-oculus.desktop` invokes `fp-oculus-callback`, which sends the callback to the same broker.
The broker passes it to `proton run fp_pipesend.exe` **through stdin**. Neither agent forwarding nor Wine invocation
puts the callback into argv. The desktop protocol invocation itself necessarily supplies `%u` to its short-lived
handler; do not collect process-command-line diagnostics during sign-in.
`native/fexwine/pipesend.c` sends a NUL-terminated UTF-8 callback to `\\.\pipe\oculus`. It retries a missing or busy pipe
for about 20 seconds and prints nothing. Exit codes: 0 written, 2 invalid input, 3 pipe unavailable, 4 write failed.
Only Meta's running client receives the link; a second Client.exe is never started to deliver it.
The extension snapshots the previous WineBrowser value/type, previous host scheme owner, desktop file and mimeapps
files before registration. `login/restore.json` contains **registration settings only**. A failed restoration leaves
this record for `--stop` to retry. Normal success, timeout, errors and Ctrl-C all clean up; a broker deadline also
restores the Frame settings if the PC disconnects (requested timeout plus 180 seconds for Steam shortcut setup).
An OS kill/reboot can interrupt this cleanup; rerun `--stop` after reconnecting. The temporary shortcut is removed
by the PC's cancel request, asynchronously through the existing shortcut worker. A disconnected PC cannot remove
that shortcut until it reconnects, but the launcher refuses to run without its broker.
## PC browser fallback
`--via-pc` keeps the full auth URL **only in broker memory**, draining it once through the agent's SSH status reply
when the PC explicitly requests `take_url`. Ordinary `fex_login_status` replies never contain the URL. The PC opens
the page in its default browser and temporarily borrows the `oculus` scheme. The handler POSTs directly to a loopback
server with a random endpoint; it never uses the normal install-link `links/*.link` inbox. HTTP logging is disabled.
WSL registers a Windows handler which invokes the WSL Python callback, and opens the sign-in page in Windows.
Windows/WSL restoration exports and restores the **entire** HKCU `Software\Classes\oculus` tree, including arbitrary
subkeys and value types, or removes it if absent before login. The non-secret export is deleted after restoration;
if importing it fails, a recovery copy is retained as `<FRAMEPORT_HOME>/oculus-handler-restore.reg` and the error
names it. Linux restores the exact previous desktop/mimeapps bytes, including an absent default. macOS fallback
is explicitly unsupported. These temporary registrations are separate from the permanent FramePort install-link
settings. The PC context restores registration even when sign-in, SSH forwarding or Frame cleanup raises.
Saved login state in `sessions/` and CoreData stays in the prefix. Status only checks whether a non-empty session
file exists; it does not read its contents, prove the session is unexpired, or imply entitlement to any game. This
change does not replace Platform SDK DLLs, alter entitlement checks, or access repack archives. A game reporting
**Missing entitlement** must remain an entitlement failure.
## Offline verification
Run from this worktree, keeping app data isolated in its existing `FRAMEPORT_HOME`:
```sh
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline pytest -q tests/test_fex_login.py tests/test_fexrift.py tests/test_fexrift_ext.py
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline ruff check agent/fexrift_login.py src/frameport/fexlogin.py src/frameport/urlhandler.py src/frameport/cli.py tests/test_fex_login.py
UV_CACHE_DIR=/tmp/frameport-uv-cache uv run --offline pytest -q
```
The focused suite passed (56 passed, 1 skipped); lint passed. The full suite rerun completed: **1,651 passed, 43 skipped,
11 failed, 16 errors**. Every failure/error was `PermissionError: [Errno 1] Operation not permitted` from existing
local HTTP/pairing/live-stream socket tests: this sandbox prohibits socket creation/binding. No other stream's files
or tests were changed to hide those failures. Run the whole suite on a host permitting loopback sockets before
integration. No triage/patch definitions were changed, so patch-doc regeneration is not required.
## Exact maintainer device acceptance steps
Use the maintainer's paired Frame configuration; do not copy credentials or configuration into this branch.
Close any Rift game first: sign-in uses the same Wine prefix and stopping it ends that prefix's processes.
1. Build the PE with llvm-mingw on an x86_64 host (or run the existing full `build_pe_dlls.sh` build):
```sh
x86_64-w64-mingw32-clang -O2 -s -Wl,--no-insert-timestamp -o artifacts/fexrift/fp_pipesend.exe native/fexwine/pipesend.c
uv run python - <<'PY'
import hashlib
from pathlib import Path
root = Path("artifacts/fexrift")
sums = root / "SHA256SUMS"
lines = [s for s in sums.read_text().splitlines() if s.strip() and s.split()[-1].lstrip("*") != "fp_pipesend.exe"]
lines.append(hashlib.sha256((root / "fp_pipesend.exe").read_bytes()).hexdigest() + " fp_pipesend.exe")
sums.write_text("\n".join(lines) + "\n")
PY
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex setup
```
Setup uploads the extension automatically alongside the existing FEX artifacts. Without the exe, login must fail
with `fp_pipesend.exe missing: build native/fexwine/pipesend.c and upload it with fex setup`.
2. Record the Frame's current scheme owner (substitute its paired SSH destination for `FRAME`):
```sh
ssh steamos@FRAME 'xdg-mime query default x-scheme-handler/oculus'
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --timeout 900
```
Expect `Put on the headset: open 'Meta sign-in (FramePort)' in your Steam library.` Open that entry. Allow about
two minutes for the runtime warm-up. Confirm Meta's app is a flat window, not another VR game.
3. Choose Meta's sign-in action. Confirm Chromium opens **on the Frame**. The PC should print `Sign-in page opened
on the Frame.` Complete the real Meta sign-in. When Chromium asks to open an external app, accept it. This is the
unproven Flatpak boundary: OpenURI through xdg-desktop-portal must resolve the host's temporary `oculus` handler.
Expect `Sign-in response reached Meta's app on the Frame.` followed by `Signed in.` The CLI closes the app/runtime,
restores handlers and requests removal of the Steam entry. Check the Steam entry disappears after the shortcut
worker finishes; Steam may restart. The saved login must remain visible as `"login": true` in:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex status
ssh steamos@FRAME 'xdg-mime query default x-scheme-handler/oculus'
```
The second command must return the original owner (including no owner, if originally unset). Do not dump Meta
logs, sessions, CoreData, process argv or the full browser URL for debugging.
4. On an unsigned-in test prefix, or before completing the first sign-in, test the alternate launch route:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --start-now --timeout 900
```
Expect `Meta's app is starting on the Frame.` There should be no Steam restart and no new shortcut. After a
successful login already exists, this command can immediately report `Signed in.` and clean up; that does not
exercise a fresh browser exchange. Do not delete the owner's session files just to force this test.
5. If the portal never delivers the callback, cancel with Ctrl-C and use:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --start-now --via-pc --timeout 900
```
Click sign-in in the Frame's Meta window; the page must open in the PC browser. Expect `Sign-in page opened in
the PC browser.`, then the response/success messages above. On Windows/WSL, verify Meta's previous
`HKCU\Software\Classes\oculus` registration is restored; on Linux verify the original xdg default. This also
needs a real Windows default-protocol check: OS UserChoice policy can override a Classes registration.
6. To inspect progress without exposing URLs, use the ordinary agent status command from a second terminal:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run python - <<'PY'
import json
from frameport.cli import _fex_target
frame = _fex_target(None).frame
print(json.dumps(frame.agent("fex_login_status"), indent=2))
PY
```
Expected keys: `runtime_running`, `client_running`, `page_opened_at`, `callback_received_at`, `signed_in`. Runtime
should become true before client; timestamps should appear in that order; signed_in should become true only
after a non-empty session file exists. If callback_received_at appears but signed_in never becomes true on a
fresh sign-in, the **pipe framing remains unverified**: this implementation uses UTF-8 plus a terminating NUL.
Compare against the maintainer's successful spike sender's bytes without printing the URL. Do not retry by
starting a second Client.exe, altering entitlement checks, or exposing tokens in diagnostics.
7. Test cancellation during runtime warm-up, timeout with `--timeout 10`, and repeatable repair/undo:
```sh
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --stop
FRAMEPORT_EXPERIMENTAL_FEX=1 uv run frameport fex login --stop
```
Expect `Meta sign-in stopped. Your saved login stays on the Frame.` both times. No delayed Client.exe should
appear after waiting two minutes. Status should show client/runtime false, the previous protocol owner should
be restored, and the session files should remain. If SSH was lost, the broker cleans up the Frame by its deadline;
reconnect and run `--stop` to remove a leftover shortcut or retry an interrupted restoration.
+276
View File
@@ -0,0 +1,276 @@
# Rift on Frame: performance stream
Implemented offline on `rift/perf`, from `98786ab`. No Frame measurements were made. Existing research measurements
are in `native/fexwine/README.md`; the commands below are for the maintainer to run on the paired Frame.
## What changed
`agent/fexrift_perf.py` registers `settings_get`, `settings_set`, `perf_prepare` and `bench`. Setup's existing `revive`
step also builds three Revive folders. The PC's existing artifact discovery uploads the extension automatically.
The only launcher template changes select the core list, Revive folder and motion-smoothing JSON from variables.
The agent and CLI have separate settings/bench blocks; the agent version is unchanged.
Settings live in `<ROOT>/settings/<Meta-app>.json`, separately from the game catalog. Defaults come from the game's
`perf` object, with the existing `env.FP_MEM` / `env.FP_BIGCACHE_MB` as backward-compatible defaults. Overrides take
precedence. `null` removes an override. Preparation runs on every launch, writes `<app>.dxvk.conf`, and exports
validated values before Wine starts. Updating a setting requires no reinstall after the new launcher is installed.
| Setting | Default | Accepted values / effect |
| --- | --- | --- |
| `dxvk_disable_msaa` | `false` | Boolean; `d3d11.disableMsaa` |
| `dxgi_sync_interval` | `-1` | Integer -1..4; `dxgi.syncInterval` |
| `dxgi_max_frame_latency` | `0` | Integer 0..16; `dxgi.maxFrameLatency` |
| `eye_scale` | `1.5` | Divisor 1.0 / 1.25 / 1.5 (100 / 80 / 67 percent nominal eye size) |
| `motion_smoothing` | `2` | 0 = default, 1 = force on, 2 = force off; SteamVR `motionSmoothingOverride` |
| `cores` | `4-7` | taskset CPU list within 0..7; e.g. `4-7` or `0-3,7` |
| `ntsync` | `true` | Off sets `PROTON_NO_NTSYNC=1`; on unsets it |
| `fp_mem` | per-game opt-in | Boolean; guest preload enabled only when true |
| `bigcache_mb` | `256` | Cache minimum block size, 1..6144 MiB (not the total cache budget) |
| `fp_mem_zero` | `false` | Boolean; `FP_MEM_ZERO=1` opts into lazy zero pages |
| `wine_large_address_aware` | `true` | Boolean; `WINE_LARGE_ADDRESS_AWARE=1/0` |
| `fex` | `{}` | JSON map of whitelisted keys with 0/1 values |
FEX keys: `FEX_TSOENABLED`, `FEX_VECTORTSOENABLED`, `FEX_MEMCPYSETTSOENABLED`, `FEX_MULTIBLOCK`,
`FEX_X87REDUCEDPRECISION`. The first three retain the launcher's default 0, MULTIBLOCK defaults to 1, X87 to 0.
Unknown keys, arbitrary environment variables, shell fragments and invalid paths are refused. The commands do not
inspect login files, print process command lines, or change Platform SDK/entitlement checks.
### Revive variants
The checked-in PC `REVIVE_PATCHES` contains the six visibility patches but **does not contain the research eye-size
redirect described in the brief**. Verified locally against the installed DLL's pinned upstream hash:
- Stock `LibRevive64.dll`: SHA-256 `ef9ffd5342bb4afad9b1c0f4fee1ca3bf32f9d3159d49dd841cc9e22f02663e4`.
- After the six PC patches: `eda2a449d230832c95734a03e8c83eeb531668ce676693f636e19c315765af4e`.
- RVA `0x12eab` (file `0x122ab`) is `movss xmm4,[rip+0x4bb15]`, loading a shared 1.0 constant.
- The research redirect loads the existing 1.5 at **RVA** `0x4eaa4` (file `0x4d4a4`). It is not file offset `0x4eaa4`.
The extension accepts the pinned six-patch upload, optionally with exactly that research redirect. It redirects
this one load into verified alignment padding at RVA `0x12e9c`, after the preceding function's `ret`. Each copy
gets its own divisor there. It leaves shared constants untouched. `revive-scales/{1,1.25,1.5}/` hard-links all other
files to `revive/`; the DLL is unlinked before writing, so variants and the base never modify one another. The
injector is launched from the selected folder, which is where it finds `LibRevive64.dll`.
Unexpected hashes, instructions or occupied padding fail explicitly. No Oculus binaries are patched here.
### fp_mem v3
`FP_MEM_ZERO=1` calls `madvise(MADV_DONTNEED)` on exactly the reused part before returning it: the requested prefix
for short/equal reuse, the cached prefix for a longer allocation. The fresh tail needs no advice. Failed advice
evicts the cache entry and falls through to real mmap, rather than returning stale contents. Without ZERO, v2's
unzeroed behavior remains. Debug output counts advice calls, discarded bytes and failures.
The fake-syscall host harness in `tests/test_fex_perf.py` checks equal, short and long reuse, advice failure,
unzeroed compatibility, and `FP_MEM_ZERO=0`. It skips only the C test when no host C compiler is installed.
The guest artifact has **not** been rebuilt in this stream. On an x86_64 glibc 2.34-compatible build host, from the
repository root, the maintainer must run:
```sh
gcc -O2 -shared -fPIC -o artifacts/fexrift/fp_mem.so native/fexwine/fp_mem.c -ldl -lpthread
python3 - <<'PY'
import hashlib
from pathlib import Path
root = Path('artifacts/fexrift')
manifest = root / 'SHA256SUMS'
lines = manifest.read_text().splitlines()
hash_ = hashlib.sha256((root / 'fp_mem.so').read_bytes()).hexdigest()
lines = [f'{hash_} ./fp_mem.so' if line.endswith(' ./fp_mem.so') else line for line in lines]
manifest.write_text('\n'.join(lines) + '\n')
PY
```
This is an **x86_64 guest** shared library, even though wineserver is native aarch64. Commit the rebuilt artifact
and checksum at integration. ZERO experiments with the old artifact would silently measure v2 instead.
## Benchmark behavior and limits
`frameport fex bench APP --seconds N` and `scripts/rift_fex_bench.py` each request exactly one run. N is an integer
1..120; it includes launcher/runtime startup, not just game sampling. The Frame enforces the deadline independently
of the PC connection. A bench lock excludes another bench. The agent first rejects active Lepton/FramePort games;
the helper rejects Wine/Proton/FEX processes, other Steam reapers, and Lepton container supervisors. It excludes
SteamVR's own AppId 250820 reaper. An open Meta login session also blocks the benchmark.
The helper requires `IVRSystem_022::GetTrackedDeviceActivityLevel(HMD)` to report **Standby (3)**. All other values,
including unknown, idle, recently interacting and interacting, are refused. A write to Steam's `logs/controller.txt`
within the last 60 seconds also blocks it (conservative: reconnection is enough). The same owner-activity checks run
while sampling; interaction stops the run. This does not claim to detect every desktop keyboard event; do not use
this headless tool while someone is using the Frame. A native non-Steam app outside Steam's reaper may also evade
the process guard. Do not run simultaneous Play/login/install operations against the shared prefix.
Before launch, read a positive finite `power/turnOffScreensTimeout`, set `power/pauseCompositorOnStandby=false`
through the existing `vrsetting` helper, and temporarily set the screen timeout to N+10. Start `launch.sh` in its
own process group. Finally, stop the shared-prefix wineserver (5-second limit), terminate/kill the launcher group,
set `pauseCompositorOnStandby=true`, and restore the original screen timeout. Each restoration is attempted even
when a preceding cleanup fails. SIGTERM and ordinary errors run this cleanup; SIGKILL, power loss or a dead SteamVR
service cannot execute Python's finally. The temporary screen timeout is finite even in those cases.
Every 0.5 seconds, read up to 128 compositor records via pinned `IVRCompositor_022::GetFrameTimings`. Deduplicate by
frame index, retain updated present counts, exclude the initial ring, and count only while scene focus belongs to
the game's PID. A hitch is one unique frame presented at least three times. GPU activity uses the actual game
process's DRM fdinfo engine-nanosecond deltas, deduplicating shared DRM client IDs; no debugfs permissions needed.
Thread wait states are histogrammed from the game's `/proc/<pid>/task/*/wchan` files. No shell commands or logs
containing account data enter the summary.
Successful stdout is one JSON line: effective settings, elapsed time, unique frames, `valid`, frame span, fps,
hitches (also per 20 seconds), average render GPU time and client frame interval, game GPU busy percent, and sampled
thread wait states. GPU busy is the sum of available engines and may exceed 100 percent on devices with independent
engines. `null` means unavailable, not zero. Client frame interval is **not CPU ApplicationTime**. `valid=false`,
zero frames or a short sample span means the launch produced insufficient data; do not treat it as a fast run.
Use equivalent spans and a stable scene when comparing results. A launcher exiting early is an error.
## Exact device checks
The maintainer runs these commands; this stream did not access the network or the Frame. Use the account owner's
normal sign-in workflow from the login stream. A missing entitlement is a failed run to report, never bypass.
1. Build/checksum the guest artifact above. From this worktree on the PC:
```sh
export FRAMEPORT_HOME="$PWD/.home"
export FRAMEPORT_EXPERIMENTAL_FEX=1
uv run frameport fex setup
uv run frameport fex install oculus-first-contact
uv run frameport fex settings oculus-first-contact
```
Setup should complete the `revive` step and create all three scale folders. Install once to get the new launcher.
Settings should show fp_mem on, threshold 256, eye divisor 1.5, motion smoothing 2, cores 4-7 and ntsync on.
Run the Frame helper with `python3 -I` as usual; no additional pip packages are needed there.
2. Wear the headset once after boot, then remove it and let it reach standby. End every game and the Meta client;
wait at least 60 seconds after controller input. A worn headset or a running game must make bench refuse **before
changing display settings**. Do not work around a refusal by disabling the checks.
3. Establish a baseline, then run exactly one bounded experiment per command pair below. Each line is independent;
restore the previous changed key with `null` before moving to the next experiment.
```sh
uv run frameport fex settings oculus-first-contact dxvk_disable_msaa=false dxgi_sync_interval=-1 dxgi_max_frame_latency=0 eye_scale=1.5 motion_smoothing=2 cores=4-7 ntsync=true fp_mem=true bigcache_mb=256 fp_mem_zero=false 'fex={}' wine_large_address_aware=true
uv run frameport fex bench oculus-first-contact --seconds 120
```
Expected: one summary JSON, `valid=true`, nonzero frames, finite fps/GPU timings; DRM busy may be null if fdinfo
is unavailable. After it returns, the game/runtime should be gone and the headset should sleep normally.
`launch.log` in the game's anchor should contain `FramePort: starting Meta's runtime` and
`FramePort: starting Oculus First Contact`. No rendering with `r.MobileMSAA=2` was proven; do not use that knob.
4. Run these candidate experiments separately, returning to the baseline between them:
```sh
uv run frameport fex settings oculus-first-contact dxvk_disable_msaa=true
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact dxvk_disable_msaa=null
uv run frameport fex settings oculus-first-contact dxgi_max_frame_latency=1
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact dxgi_max_frame_latency=null
uv run frameport fex settings oculus-first-contact eye_scale=1.25
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact eye_scale=null
uv run frameport fex settings oculus-first-contact 'fex={"FEX_X87REDUCEDPRECISION":1}'
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact fex=null
uv run frameport fex settings oculus-first-contact wine_large_address_aware=false
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact wine_large_address_aware=null
uv run frameport fex settings oculus-first-contact ntsync=false
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact ntsync=null
uv run frameport fex settings oculus-first-contact fp_mem_zero=true
uv run frameport fex bench oculus-first-contact --seconds 120
uv run frameport fex settings oculus-first-contact fp_mem_zero=null
```
The baseline covers eye divisor 1.5, ntsync on, and ZERO off. MSAA off previously improved GPU load but reduced
edge quality. Compare hitches, frame span, GPU time and thread wait distributions; this stream makes no claim
that X87 or large-address-awareness helps. GE may ignore the latter for a 64-bit game. Test image quality later
in an ordinary worn-headset Play session; the headless bench intentionally refuses that session.
Script alternative for a single run (do not run this in addition unless another run is intended):
```sh
uv run python scripts/rift_fex_bench.py oculus-first-contact --seconds 120
```
5. Interrupt a run by sending SIGTERM to the `python3 -I .../fexrift.py bench` helper **on the Frame**, after checking
its PID with `pgrep -af '[f]exrift.py bench'`. Use `kill -TERM <that-pid>` (never a broad pkill). Expected: interrupted
result, game stopped, compositor standby enabled and original screen timeout restored. Also check refusal while
the headset is worn and a deliberately invalid setting, e.g. `eye_scale=1.4`, without launching anything.
On the Frame, this reads the two settings without printing any account data:
```sh
python3 -I - <<'PY'
import ctypes as C, importlib.util, os
path = os.path.expanduser('~/.local/share/frameport/fexrift/artifacts/fexrift.py')
spec = importlib.util.spec_from_file_location('fx', path)
fx = importlib.util.module_from_spec(spec); spec.loader.exec_module(fx)
core, method, settings = fx.vr_settings()
try:
for key, idx, typ in [('pauseCompositorOnStandby', 5, C.c_bool), ('turnOffScreensTimeout', 7, C.c_float)]:
err = C.c_int()
value = method(settings, idx, typ, C.c_char_p, C.c_char_p, C.POINTER(C.c_int))(
b'power', key.encode(), C.byref(err))
print(key, value, 'error', err.value)
finally:
method(core, 1, None)()
PY
```
Record these values before the test. Afterwards expect `pauseCompositorOnStandby True error 0` and the original
positive timeout with error 0. Confirm the physical display sleeps. With guest `FP_MEM_DEBUG=1`, ZERO reuse logs
should show `fp_mem: zero calls ..., bytes ..., failures 0`. This debug variable can be set manually in a test
launcher for one run; remove that line afterwards (it is deliberately outside the user environment whitelist).
## Undo and remaining device questions
Reset every override (no login or game files removed):
```sh
uv run frameport fex settings oculus-first-contact dxvk_disable_msaa=null dxgi_sync_interval=null dxgi_max_frame_latency=null eye_scale=null motion_smoothing=null cores=null ntsync=null fp_mem=null bigcache_mb=null fp_mem_zero=null fex=null wine_large_address_aware=null
```
To remove this experiment entirely, restore the integration's previous launcher/module and guest artifact, then
remove only `settings/<app>.json`, `settings/<app>.dxvk.conf` and `revive-scales/` after stopping all FEX games.
Do not remove `compat/pfx`; it holds the owner's login and installed games. For emergency display restoration on the
Frame (replace 300 with the previously recorded timeout):
```sh
R="$HOME/.local/share/frameport/fexrift"
python3 -I "$R/artifacts/fexrift.py" vrsetting '{"section":"power","key":"pauseCompositorOnStandby","kind":"b","value":true}'
python3 -I "$R/artifacts/fexrift.py" vrsetting '{"section":"power","key":"turnOffScreensTimeout","kind":"f","value":300}'
```
Unverified: SteamVR's availability of the pinned historical compositor/system interfaces; whether scene focus PID
matches the FEX game's host PID; whether the HMD reports Standby while compositor rendering is forced; how many
usable game frames remain after runtime startup within 120 seconds; fdinfo visibility on this OS; the cost of ZERO
on the device; all visual/entitlement behavior for other games. Failures must stay visible, not be replaced by fake
performance numbers. If startup consumes the window, report `valid=false` and adjust startup in the owning stream
before drawing conclusions; do not silently extend the bounded run.
## Offline validation and integration
Run `uv run pytest -q` in a normal environment and `uv run python scripts/patch_docs.py --check`. In this sandbox,
use a writable UV cache and the already installed environment:
```sh
UV_CACHE_DIR=/tmp/frameport-perf-uv uv run --offline --no-sync pytest -q
UV_CACHE_DIR=/tmp/frameport-perf-uv uv run --offline --no-sync pytest -q tests/test_fex_perf.py tests/test_fexrift.py tests/test_fexrift_ext.py
```
The original worktree's Git common directory is mounted read-only. Commits are therefore in the local, writable
repository `/tmp/frameport-rift-perf.git` (same base and `rift/perf` ref) and exported as
`/tmp/frameport-rift-perf.bundle`. The worktree contains the complete edits. A maintainer with writable original
Git metadata can fetch that bundle and fast-forward/cherry-pick the commits; do not discard the worktree edits
until integration is confirmed. Local-only instruction files and `.home` are excluded from every commit.
Validation result in this environment: 80 focused tests passed, 1 skipped; Ruff passed for the three new Python
files; `scripts/patch_docs.py --check` passed; `git diff --check` passed. The full suite ran: **1676 passed,
43 skipped, 11 failed, 16 errors**. Every remaining failure/error raised `PermissionError: [Errno 1] Operation not
permitted` when existing pairing/download/live-stream tests attempted to create sockets. This sandbox forbids
sockets, including loopback; these tests were not disabled or modified. A clean full-suite pass remains an
integration check in a normal environment. The complete short traceback log is
`/tmp/frameport-rift-perf-pytest.log`.
+6
View File
@@ -0,0 +1,6 @@
out/
out-dev/
*.core
# generated by bridge/gen_stubs.py at every build
bridge/guest/gen/
bridge/host/gen/
+220
View File
@@ -0,0 +1,220 @@
# a32translator: AArch32 → AArch64 dynamic binary translator
`a32run` runs 32-bit ARM Linux programs (ARM, Thumb-2, VFPv4, NEON, plus the ARMv8 AArch32 additions) on an
AArch64 host without AArch32 support, such as the Steam Frame's SteamOS. It is a user-mode translator (like
`qemu-arm`). It decodes guest instructions, runs them through a JIT that emits native A64 code, and translates
system calls to the host kernel.
Status: proof of concept. It runs static bionic (Android NDK) programs, including C++ with exceptions, pthreads,
signals, fork, self-modifying code and NEON. The Android bridge (below) runs 32-bit JNI and NativeActivity
libraries inside a 64-bit app, verified in a Lepton container on the Frame; games additionally need GLES/EGL,
OpenSL/AAudio, libandroid and VrApi thunks (see "Next steps").
```
python native/a32translator/build.py # -> native/a32translator/out/a32run (static AArch64, NDK clang)
a32run [--interp] [--strace] [--trace] [--sysroot DIR] [-v] program [args...]
```
Environment: `A32_STATS=1` (block/chain statistics at exit), `A32_DUMP=file` (translated code, see
`tools/jitdump.py`), `A32_EXACT_ADDR=1` (guest address arithmetic modulo 2^32, see below), `A32_CACHE_KB=n`
(small code cache, exercises flushes), `A32_INTERP=1`, `A32_STRACE=1`, `A32_PERFMAP=<file>|1` (a perf map of the
translated code: `a32:<pc>` block bodies, `a32:exits` exit stubs, `a32:fpcr` FPCR writes; `1` writes
`/tmp/perf-<pid>.map`, which `perf report` reads).
32-bit bionic refuses pids above 65535, which hosts with a large `pid_max` (SteamOS: 4194304) exceed. Start such
programs in a fresh pid namespace: `unshare -Urpf --kill-child a32run prog`.
## How it works
```
guest bytes ─┬─ a32_decode.c (A32) ───┐
└─ t32_decode.c (T32) ───┼─► insn_t ─┬─► interp*.c (reference semantics, fallback)
vfp_neon_decode.c (VFP/NEON) ◄──────┘ └─► jit.c / jit_vfp.c (A64 code) ─► code cache
```
- **One instruction form, two backends.** Both decoders produce `insn_t` (`insn.h`). T32 VFP/NEON encodings are
rewritten to their A32 form first, so one decoder serves both instruction sets. The interpreter (`interp.c`,
`interp_vfp.c`, `interp_neon.c`) defines the semantics of everything. The JIT translates the common
instructions natively and calls the interpreter for the rest (`jx_call_helper`), so every instruction the
interpreter knows also works in JIT mode.
- **Register mapping.** Guest r0-r14 are pinned in x0-x14 (upper halves always zero), q0-q15 in v16-v31, and the
guest NZCV lives in the host NZCV. x19 points to the `a32_cpu` state. The guest PC is a translation-time
constant. Scratch registers: x15-x17, x20-x23, v0-v7. Within a block, scalar VFP values are cached in v8-v15:
writing a lane of a pinned Q register would chain loop iterations through the merge. The cache is flushed at
exits, helper calls and branches.
- **Flags.** A64 ADDS/SUBS/ADCS/SBCS set NZCV exactly like AArch32. Logical flag-setting instructions get N/Z
from the result, C from the shifter and V unchanged (`set_nzc`). Conditional instructions branch over their
code (the condition encodings match).
- **Floating point.** Guest FP operations run as the identical A64 instructions with the guest's FPSCR control
bits in FPCR (FPCR/FPSR share FPSCR's bit layout), so rounding, flush-to-zero, default NaN and exception flags
match by construction. Advanced SIMD floating point runs with the "standard FPSCR value" (DN, FZ, round to
nearest). Blocks switch FPCR only around such operations. VMLA/VMLS stay unfused (multiply, then add) and
VRECPS/VRSQRTS go to the interpreter (non-fused in AArch32, fused in A64). The interpreter uses inline A64
instructions as well.
- **Blocks.** A block (a superblock) ends at the first unconditional branch or other PC write, an SVC/UDF, or
after 96 instructions. Conditional branches and CBZ/CBNZ are side exits: translation continues on the
fall-through path, so a loop with an early exit is still one block. Blocks are keyed by (pc, Thumb, ITSTATE), so
IT blocks may span block boundaries. Direct exits are patchable `b` instructions that get chained to their
target. Indirect branches (BX LR, POP {pc}, LDR pc, TBB) look the target up inline in a direct-mapped table. A
branch back to the block's own start is a plain `b`/`b.cond`. Every block starts with a check of
`cpu->interrupt`, which signals and code flushes set, so chained loops still stop.
- **Code quality.** Conditional data-processing instructions that don't set flags become compute + `csel`
(branchless). VCMP followed by VMRS APSR_nzcv leaves the compare's flags in NZCV directly. LDREX/STREX (all
sizes) are an inline compare-and-swap loop (`ldxr`/`stxr`). Thumb's flag-setting register shifts
(LSLS/LSRS/ASRS/RORS Rdn, Rm) compute the AArch32 carry for 0-255 bit amounts inline. In the benchmark below,
no instruction goes to the interpreter (`A32_STATS=1` lists the ones that do).
- **Memory.** Guest addresses are host addresses: the low 4 GiB are reserved at start-up (`mem.c`) and the
guest's mappings live there, so loads and stores need no translation and most syscalls pass pointers through.
Translated code uses A64 addressing modes (`[xn, #imm]`). They differ from AArch32 only when guest address
arithmetic wraps past 4 GiB: such an access then faults above 4 GiB, and the fault is still delivered to the
guest. `A32_EXACT_ADDR=1` computes every address modulo 2^32 instead. Unaligned LDRD/LDM/VLDn are allowed
(newer arm64 kernels fix them up for AArch32 too); qemu raises SIGBUS. The host page size must be 4 KiB.
- **Self-modifying code.** `cacheflush` (what `__builtin___clear_cache` calls on ARM), `mprotect`, `munmap` and
`mremap` invalidate the translated blocks of the affected pages and unlink chains into them. Each guest page keeps
a list of its blocks, so an invalidation only visits those (Unity's Mono JIT flushes new code next to translated
code all the time; scanning every block made that 72 % of Spunky Dungeon's main thread). A full cache
(128 MiB) is flushed once every thread has left translated code.
- **Faults.** A guest memory fault in translated code is mapped back to the guest instruction (per-instruction
host offsets, plus the VFP cache state). The guest registers are rebuilt from the signal context, and the
guest's handler gets a proper ARM `rt_sigframe` (VFP state included). Returning from it restarts the
instruction.
- **Syscalls** (`syscall.c`): ARM EABI numbers (generated from the NDK headers, `tools/gen_syscalls.py`) map to
AArch64 ones. Structures whose 32-bit layout differs are converted: stat64, statfs64, timespec/timeval, iovec,
rusage, sysinfo, rlimit, flock, msghdr with control messages, getdents. The guest persona (`PER_LINUX32`) is
emulated, because hosts without AArch32 refuse it. ARM private calls (set_tls, cacheflush) and kuser helpers
(0xffff0fxx) are implemented. `execve` of a 32-bit ARM ELF re-executes `a32run`.
- **Signals** (`signals.c`): host handlers queue signals; delivery happens at block boundaries with the ARM
kernel's frame layouts (`sigframe`/`rt_sigframe`, `sigaltstack`, SA_RESTORER, SA_NODEFER, SA_RESETHAND).
Guest SIG_DFL/SIG_IGN dispositions stay on the host, so the kernel applies default actions itself.
- **Threads** (`threads.c`): `clone` with CLONE_VM|CLONE_THREAD starts a host pthread running its own `a32_cpu`.
Other clones become `fork`. The code cache is shared: a mutex guards translation and chaining only. The run loop
finds blocks without it (the inline lookup table first, then the hash chains) and puts each block it dispatched
back into the inline table, so a block translated later into the same slot can't shut a hot return target out.
Each thread flags itself while it is in the run loop or translated code; a cache flush waits for the flags (a
shared counter cost every dispatch a contended atomic).
LDREX/STREX are emulated as compare-and-swap on the exclusive value; ABA changes are not detected.
Not supported: big-endian data (SETEND BE), ARMv8.1+ AArch32 extensions (FP16 arithmetic, RDM, JSCVT, dot
product), VFP short vectors (Len/Stride, absent on ARMv8 anyway), robust futex lists, and the iWMMXt/ThumbEE
relics. FPSCR exception *traps* are not emulated (flags are).
## Android bridge
A converted APK runs its 32-bit libraries in its own 64-bit process, without Android's native-bridge mechanism
(Lepton would need `ro.dalvik.vm.native.bridge` and 32-bit ABI lists for that). Every 32-bit library `libX.so`
moves to `lib/arm64-v8a/libX.a32.so`; `libX.so` becomes a copy of the stub, next to the bridge and the guest
runtime:
```
python native/a32translator/bridge/build.py [--test]
out/bridge/liba32stub.so arm64 stub (copied as libX.so): JNI_OnLoad, ANativeActivity_onCreate -> bridge
out/bridge/liba32bridge.so arm64: the translator + bridge/host (exports a32b_*, bridge/host/a32bridge.h)
out/bridge/liba32rt.so 32-bit ARM static PIE: the guest runtime and the guest's "system libraries"
```
- **Guest runtime** (`bridge/guest`): bionic's static libc/libm/libz/libstdc++/libunwind, linked whole and
exported through a table (`gen/exports.S`), plus a loader for the game's libraries (bionic's lookup order, packed
relocations, RELR, `dlopen`/`dlsym`/`dladdr`/`dl_iterate_phdr`, ARM EHABI unwinding through
`dl_unwind_find_exidx`). Symbols nothing defines become stubs that log their name and return 0. Libraries the
guest knows as system libraries (`libGLESv2.so`, ...) resolve against the export table.
- **Hypercalls** (`bridge/abi.h`): guest code calls the host with `SVC 0` and `r7 = 0x0a32xxxx`; host-to-guest
calls return through a trampoline in the kuser page. The thread that starts the bridge becomes the guest's main
thread; any other host thread gets its own guest thread on its first call (the runtime's service thread creates
it, and the clone is handed to the waiting host thread). Calls nest: Java -> guest -> JNI -> Java -> guest.
- **JNI** (`bridge/host`): the guest gets 32-bit `JNIEnv`/`JavaVM` tables whose entries are hypercalls.
`gen_stubs.py` generates the simple functions from `jni.h`; `jni.c` has the rest (variadic/`va_list`/`jvalue[]`
calls read with the method's shorty, strings and arrays: shared when the data lies below 4 GiB, as ART's heap
does, else copied and written back). Objects, method and field IDs are 32-bit handles (`handles.c`). Native
methods (RegisterNatives, and exported `Java_*` functions, matched to their Java declarations by reflection) get a
trampoline slot (`tramp.S`, `natives.c`) that converts AAPCS64 arguments to AAPCS32.
- **NativeActivity** (`native_activity.c`): a 32-bit `ANativeActivity` mirrors the host's; the host callbacks
forward to the guest's. Windows, input queues and asset managers are handles. libandroid functions are listed in
`bridge/imports.txt` (generated host side).
- The bridge shares the low 4 GiB with the host process: `mem.c` reads `/proc/self/maps` and never hands out host
mappings; host faults go to the host's own handlers (ART's); translator reports on stderr go to logcat (tag
`a32`).
- **GLES/EGL** (`gen_gl.py`, `host/gl.c`): every function of the NDK's GLES 3.2 + extension and EGL headers is a
hypercall stub (Unity fetches most through `dlsym`/`eglGetProcAddress`); EGL objects and GLsyncs are handles,
driver strings are copied, buffer mappings outside the guest's reach get a guest copy written back at flush/unmap.
- **VrApi 1.x** (`host/vrapi.c`): Gear VR-era games call the old API (`vrapi_SubmitFrame` with `ovrFrameParms`,
`vrapi_GetPredictedTracking`). The runtime exports it itself (`libvrapi.so` is a system library; the game's copy is
Oculus' loader and is dropped) and translates it to FramePort's 64-bit VrApi -> OpenXR bridge (shipped as
`libfp_vrapi64.so`, with OVRPort's OpenXR dispatcher and the FrameBridge adapter). Layouts are VrApi 1.5's.
- **OpenSL ES** (`guest/opensles.c`): engine, output mix and PCM players with an Android buffer queue, implemented in
the guest (OpenSL objects are function tables); a guest thread per player writes to AAudio on the host.
- **Signals**: host handlers never use SA_RESTART; a blocking system call interrupted by a guest signal is
restarted after the guest's handler (as the kernel's -ERESTARTSYS), and a thread running host code (Java, a JNI or
GL call) runs the guest handler at once. Boehm GC (Unity's Mono) stops the world with signals and hung without it.
- `bridge/convert.py IN.apk OUT.apk` (prototype of the FramePort patch): moves the 32-bit libraries, adds the stubs,
bridge, runtime and VR libraries, sets LAUNCHER and targetSdkVersion >= 23 (an older one gets Android's "built for
an older version" dialog, which takes the focus: Unity never starts), and points libunity's Oculus check at
"android" (like `frame.unity_oculus_check`). Unity games also need the flat window (`device.text_input_window`):
Unity only renders with window focus.
- Debugging: `A32_WATCH=<s>` logs every guest thread's pc and the return addresses on its stack as `lib+offset`;
`A32B_TRACE=1` logs native registrations and calls; `A32_STRACE`, `A32_INTERP` as for a32run. Set them through the
recipe's `device.lepton_env` (`LEPTON_ENV_<NAME>`).
Learned on the way: `-static-pie` links `crtbegin_dynamic.o`, which leaves `.init_array` to a dynamic linker (so
none of libc's own constructors ran: bionic's systrace property crashed in an Android process); bionic's arm32
static start-up code also reads `PT_TLS`/`PT_GNU_RELRO` as if the program sat at its link address, so the loader
moves both by the load bias.
Tests:
- `python bridge/test/run.py [--interp]` (after `build.py --test`): the harness (`bridge/test/harness.c`) plays ART
with a fake JVM (`fakejni.c`) for three guest libraries: RegisterNatives and `Java_*` exports, 12-argument
natives (stack arguments on both sides), floats/doubles/bytes, strings, arrays below and above 4 GiB, every
Call*Method style, NewObject, nested calls, guest threads that attach, several host threads, exceptions, a
NativeActivity with a DT_NEEDED library, and C++ exceptions in guest libraries using ordinary REL,
standard RELR and Android's older RELR tags (with APS2). Runs under qemu-aarch64 or
natively (passes on the Frame with JIT and interpreter).
- `uv run python bridge/test/make_apk.py`: `org.frameport.a32test`, a NativeActivity APK without Java code whose
library is 32-bit (`bridge/test/libapktest.c`). Installed with FramePort (`frameport scan`, then `frameport
install org.frameport.a32test --apk ...`, `frameport test`), it logs `A32TEST ok|FAIL` lines (tag `a32test`):
real ART calls (`Build.MODEL`, `String.format`, `Math.hypot`, arrays, exceptions), a guest thread, a dlopen'd C++
library, and the activity's callbacks with the real window. All pass in Lepton (2026-10-10).
## Testing
All of these run on an x86-64 PC through `qemu-aarch64`, with `qemu-arm` as the reference, or natively on an
AArch64 machine with `--runner ""`.
- `tests/test_a64.py`: every A64 encoder in `src/a64.h` against `llvm-mc` (400 encodings).
- `tests/fuzz.py`: differential instruction fuzzer. Random encodings per class (`arm-dp`, `arm-ldst`,
`arm-media`, `arm-ldm`, `arm-vfp`, `arm-neon`, `arm-neon-ldst`, `arm-v8`, `t16`, `t32`, `t32-neon`,
`t32-vfp`) are filtered with `arm-none-eabi-objdump` and with the translator's own UNPREDICTABLE flag
(`tools/a32dis.c`). Each runs once in a harness that loads random registers, flags, FPSCR and NEON state, and
dumps them afterwards together with a hash of the touched memory. The harness's own signal handler records
UNDEF and memory faults per test, so UNDEF decoding is compared too. Runs `qemu-arm -cpu max`, then `a32run
--interp`, then `a32run`. Known, deliberate differences are filtered: qemu's alignment faults, ARMv8.1+
features, and encodings in ARMv7's unallocated space that qemu executes.
- `tests/run_programs.py`: C/C++ programs built with the NDK for ARM and Thumb (static bionic), compared with
`qemu-arm` in both modes: libc/libm/printf, memory and string routines, NEON intrinsics, pthreads and atomics,
signals (handlers, SIGSEGV recovery, itimers, fork), file system calls, C++ exceptions/RTTI/STL/std::thread,
run-time generated code (`jitguest`) and a benchmark. `A32_CACHE_KB=300` exercises cache flushes.
Benchmark (`tests/programs/bench.c 10`) on the Steam Frame, medians of three runs (the headset's clocks vary by
up to ±30 % between runs), against the same source built natively for AArch64:
| | native AArch64 | a32run, ARM build | a32run, Thumb build |
|---|---|---|---|
| sieve | 0.11 s | 0.12 s | 0.10 s |
| crc32 + sha256 | 0.39 s | 0.42 s | 0.57 s |
| qsort | 0.15 s | 0.21 s | 0.25 s |
| float matmul | 0.017 s (auto-vectorized) | 0.27 s (scalar VFP: ARMv7 compilers don't vectorize float) | 0.27 s |
| double mandelbrot | 0.21 s | 0.44 s | 0.41 s |
| libm | 0.06 s | 0.25 s | 0.27 s |
## Next steps
1. First game: AFFECTED The Manor (Gear VR, Unity 5.6.0f3 + Mono, OVRPlugin 1.12, 2017). Headless on the Frame
(2026-10-10): Unity and its C# scripts run, audio plays, the OpenXR session starts and submits frames at 72 fps.
Not yet seen in a headset. Open: Gear VR input (touchpad/back, controller API reports no devices), the rest of
libandroid (ALooper callbacks, AInputQueue, AAsset*), host-to-guest callbacks (GL debug output, sensor queues).
2. A FramePort patch that converts an APK (libraries moved, stubs, bridge, runtime, `extractNativeLibs=true`) +
triage signature + PLAYBOOK row.
3. Bridge gaps: guest threads of host threads that exit are never freed; `Java_*` functions of libraries the guest
dlopens itself aren't registered; `GetDirectBufferAddress` of buffers above 4 GiB returns 0; signals the guest
handles are only delivered to guest threads.
4. JIT: VLDn single-lane/all-lanes forms, flag liveness (skip unused C/V computations), keeping the VFP cache
across a loop's back edge, and VRECPS/VRSQRTS/VCVTR natively.
+41
View File
@@ -0,0 +1,41 @@
/* Interface between the guest runtime (liba32rt.so, 32-bit ARM) and the host bridge (arm64).
*
* The guest calls the host with a hypercall: SVC 0 with r7 = A32_HYPERCALL | n, arguments in r0-r3 and on the
* stack (AAPCS, softfp), result in r0 (r0:r1 for 64-bit values). The host calls guest functions on the calling
* thread's guest context; they return through A32_RETURN_TRAMPOLINE. Keep both sides in sync. */
#ifndef A32_BRIDGE_ABI_H
#define A32_BRIDGE_ABI_H
#define A32B_VERSION 1
/* hypercall numbers (low 16 bits of r7) */
#define HC_RETURN 1 /* end of a host-to-guest call; also parks a thread that has nothing to do */
#define HC_READY 2 /* r0 = struct grt_info *: the runtime is initialised (main thread parks here) */
#define HC_WAIT_WORK 3 /* service thread: blocks until the host has work; returns a WORK_* code */
#define HC_LOG 4 /* r0 = priority, r1 = tag, r2 = message */
#define HC_UNRESOLVED 5 /* r0 = symbol name: a guest library called a symbol nothing defines */
#define HC_ABORT 6 /* r0 = message: the guest runtime gave up */
#define HC_JNI 0x100 /* + JNINativeInterface index (0..232) */
#define HC_VM 0x200 /* + JNIInvokeInterface index (0..7) */
#define HC_IMPORT 0x300 /* + index into the host import table (bridge/imports.txt) */
#define HC_GL 0x1000 /* + index into the GLES/EGL table (gen_gl.py) */
/* service thread work */
#define WORK_NONE 0
#define WORK_ATTACH 1 /* pthread_create a thread that the waiting host thread adopts (threads.h) */
#define JNI_TABLE_SIZE 233
#define VM_TABLE_SIZE 8
/* Guest addresses the host needs, passed with HC_READY. All fields are 32-bit guest addresses. */
struct grt_info {
unsigned version;
unsigned jni_env; /* JNIEnv: one for every thread (the host finds the thread itself) */
unsigned java_vm; /* JavaVM */
unsigned fn_malloc, fn_free;
unsigned fn_dlopen, fn_dlsym, fn_dlerror; /* the runtime's loader (bionic semantics, LP32 RTLD_* values) */
unsigned fn_attached_entry;
unsigned fn_list_symbols; /* (handle, prefix) -> malloc'd (name, address) pairs, 0-terminated */
};
#endif
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Builds the Android bridge with the NDK (see ../README.md, "Android bridge"):
out/bridge/liba32rt.so guest runtime: static 32-bit ARM bionic program (static PIE), the "system libraries"
out/bridge/liba32bridge.so host bridge (arm64): the translator + JNI/NativeActivity/libandroid glue
out/bridge/liba32stub.so host stub (arm64), copied once per 32-bit library as libX.so
--test: out/bridge/test/harness (static arm64 program: fake JNI + the bridge) and libbtest.a32.so (armv7 guest
library); python bridge/test/run.py runs them
python bridge/build.py [--test] [--debug] [--ndk PATH]
"""
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
NDK_DEFAULT = ROOT.parent / ".cache" / "ndk-27.2.12479018"
OUT = ROOT / "out" / "bridge"
TRANSLATOR = ["dispatch.c", "mem.c", "loader.c", "syscall.c", "signals.c", "threads.c", "interp.c", "interp_vfp.c",
"interp_neon.c", "a32_decode.c", "t32_decode.c", "vfp_neon_decode.c", "jit.c", "jit_vfp.c",
"jit_glue.S"]
HOST = ["bridge.c", "handles.c", "jni.c", "natives.c", "native_activity.c", "android.c", "vrapi.c", "input.c", "tramp.S", "gen/jni_gen.c",
"gen/imports.c"]
HOST_GL = ["gl.c", "gen/gl.c"] # not in the PC harness (no GLES there)
GUEST = ["main.c", "loader.c", "compat.c", "log.c", "gl.c", "opensles.c", "hc.S", "gen/stubs.S", "gen/gl_stubs.S", "gen/exports.S"]
WARN = ["-Wall", "-Wextra", "-Wno-unused-parameter", "-Wno-missing-field-initializers"]
def run(cmd):
print(" ".join(str(c) for c in cmd[:1]) + " ... -o " + str(cmd[cmd.index("-o") + 1]))
r = subprocess.run([str(c) for c in cmd])
if r.returncode:
sys.exit(r.returncode)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ndk", default=str(NDK_DEFAULT))
ap.add_argument("--debug", action="store_true")
ap.add_argument("--test", action="store_true")
a = ap.parse_args()
bin_ = Path(a.ndk) / "toolchains/llvm/prebuilt/linux-x86_64/bin"
if not bin_.exists():
sys.exit(f"{bin_} not found (run python native/build.py once to fetch the NDK)")
cc64 = bin_ / "aarch64-linux-android30-clang"
cc32 = bin_ / "armv7a-linux-androideabi30-clang"
OUT.mkdir(parents=True, exist_ok=True)
subprocess.run([sys.executable, str(HERE / "gen_stubs.py"), "--ndk", a.ndk], check=True)
opt = ["-O0", "-g"] if a.debug else ["-O2", "-g"]
# The cache can be symlinked into a worktree. Clang records both the spelling
# used on the command line and the resolved NDK path, plus the compilation cwd.
prefix = [f"-ffile-prefix-map={ROOT.parent.parent}=frameport",
f"-ffile-prefix-map={ROOT}=a32translator",
f"-ffile-prefix-map={Path(a.ndk).absolute()}=ndk",
f"-ffile-prefix-map={Path(a.ndk).resolve()}=ndk"]
# guest runtime: everything a guest library may link against comes from the static archives (exports.S
# references each symbol, so the linker keeps them)
g = HERE / "guest"
# -static-pie links crtbegin_dynamic.o, which leaves .init_array to a dynamic linker that isn't there: use the
# static start files (libc's own constructors run from them)
crt = Path(a.ndk) / "toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/arm-linux-androideabi/30"
run([cc32, *opt, *prefix, *WARN, "-mthumb", "-mfpu=neon-vfpv4", "-std=gnu11", "-static-pie", "-nostartfiles",
crt / "crtbegin_static.o", *[g / s for s in GUEST], "-lz", "-lm", "-lstdc++", "-Wl,--no-gc-sections", "-Wl,--wrap=dl_unwind_find_exidx", crt / "crtend_android.o", "-o",
OUT / "liba32rt.so"])
h = HERE / "host"
src = ROOT / "src"
common = [*opt, *prefix, *WARN, "-march=armv8-a+crypto", "-std=gnu11", "-fno-strict-aliasing", "-fPIC"]
run([cc64, *common, "-shared", "-fvisibility=hidden", *[src / s for s in TRANSLATOR], *[h / s for s in HOST + HOST_GL],
"-llog", "-landroid", "-laaudio", "-lEGL", "-lGLESv3", "-ldl", "-lm", "-Wl,--no-undefined", "-Wl,-soname,liba32bridge.so", "-o", OUT / "liba32bridge.so"])
run([cc64, *common, "-shared", "-fvisibility=hidden", h / "stub.c", "-L", OUT, "-la32bridge",
"-Wl,--no-undefined", "-o", OUT / "liba32stub.so"])
if a.test:
t = HERE / "test"
to = OUT / "test"
to.mkdir(exist_ok=True)
# the harness is static (runs under qemu-aarch64 or on any arm64 Linux): high image base keeps the
# low 4 GiB free, like a32run's
run([cc64, *common, "-DA32B_STDERR_LOG", "-DA32B_TEST", "-static", "-Wl,--image-base=0x7000000000", "-I", h,
t / "harness.c", t / "fakejni.c", *[src / s for s in TRANSLATOR], *[h / s for s in HOST], "-lm", "-ldl",
"-o", to / "harness"])
run([cc32, *opt, *prefix, *WARN, "-mthumb", "-mfpu=neon-vfpv4", "-shared", "-fPIC", t / "libbtest.c",
"-Wl,-soname,libbtest.so", "-llog", "-o", to / "libbtest.a32.so"])
run([cc32, *opt, *prefix, *WARN, "-marm", "-mfpu=neon-vfpv4", "-shared", "-fPIC", t / "libbtest2.c",
to / "libbtest.a32.so", "-landroid", "-llog", "-o", to / "libbtest2.a32.so"])
run([bin_ / "armv7a-linux-androideabi30-clang++", *opt, *prefix, *WARN, "-mthumb", "-shared", "-fPIC",
"-static-libstdc++", t / "libbtest3.cpp", "-o", to / "libbtest3.a32.so"])
# Exercise both RELR tag families through the real guest loader. C++ constructors,
# pointer tables and exceptions need relative relocations; Android's older tags
# occur in Quest libraries (e.g. Journey of the Gods' OVRPlugin).
for tags in ("android", "standard"):
run([bin_ / "armv7a-linux-androideabi30-clang++", *opt, *prefix, *WARN, "-mthumb", "-shared", "-fPIC",
"-static-libstdc++", t / "libbtest3.cpp", "-Wl,--pack-dyn-relocs=android+relr",
"-Wl,--use-android-relr-tags" if tags == "android" else "-Wl,--no-use-android-relr-tags",
"-o", to / f"libbtest3_{tags}.a32.so"])
shutil.copy(OUT / "liba32rt.so", to / "liba32rt.so")
if __name__ == "__main__":
main()
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Converts a 32-bit-only APK to run on arm64 through the bridge, for bridge development (FramePort builds do the
same with the patch frame.a32_bridge, src/frameport/patches/frame/a32_bridge.py, which this script uses):
lib/armeabi-v7a/libX.so -> lib/arm64-v8a/libX.a32.so (the guest code) + lib/arm64-v8a/libX.so (the stub)
+ lib/arm64-v8a/liba32bridge.so, liba32rt.so; other ABIs dropped; extractNativeLibs forced on; signed with
FramePort's key for the package; INFO-only start activities get LAUNCHER (Lepton needs it); targetSdkVersion
raised to 23 (older ones get a dialog that takes the focus).
uv run python native/a32translator/bridge/convert.py IN.apk OUT.apk [--replace libvrapi.so=FILE ...]
Build the bridge first (python native/a32translator/bridge/build.py). --replace puts FILE (a 32-bit library) in
place of the APK's own copy.
"""
import argparse
import os
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
OUT = HERE.parent / "out" / "bridge"
REPO = HERE.parents[2]
# test builds instead of the artifacts: A32_VRAPI_BRIDGE (the 64-bit VrApi bridge), A32_FRAME_SETTINGS (FrameBridge
# settings, "key=value;..."); the bridge itself always comes from out/bridge (this script is for bridge development)
VRAPI_BRIDGE = Path(os.environ.get("A32_VRAPI_BRIDGE") or REPO / "artifacts/arm64-v8a/libvrapi.so")
FRAME_SETTINGS = (b"scale=1.0\nfoveation_fix=1\ncontroller_fix=1\n"
+ os.environ.get("A32_FRAME_SETTINGS", "").replace(";", "\n").encode())
def main():
ap = argparse.ArgumentParser()
ap.add_argument("apk")
ap.add_argument("out")
ap.add_argument("--replace", action="append", default=[], metavar="LIB=FILE")
a = ap.parse_args()
sys.path.insert(0, str(REPO / "src"))
from pyaxmlparser import APK
from frameport.apk import axml, sign
from frameport.apk.workspace import ApkWorkspace
from frameport.core.events import Reporter
from frameport.patches.frame import a32_bridge
from frameport.tools import overport
package = APK(a.apk).package
replace = {k: Path(v).read_bytes() for k, v in (r.split("=", 1) for r in a.replace)}
def prebuilt(name: str) -> bytes:
if name == "libvrapi.so":
return VRAPI_BRIDGE.read_bytes()
return (OUT / name if name.startswith("liba32") else REPO / "artifacts/arm64-v8a" / name).read_bytes()
def ovrport(name: str, abi: str) -> bytes:
return overport.ensure_runtime_lib(name, abi, Reporter()).read_bytes()
with ApkWorkspace(Path(a.apk)) as ws, tempfile.TemporaryDirectory() as td:
libs = a32_bridge.convert(ws, prebuilt, ovrport, replace)
if ws.has(a32_bridge.SIGNATURE_ASSET):
print("original APK signature for the UE4 check:", ws.read(a32_bridge.SIGNATURE_ASSET).decode().strip())
manifest = ws.read("AndroidManifest.xml")
ws.put("AndroidManifest.xml", axml.fix_launcher(manifest) or manifest) # Lepton starts the LAUNCHER activity
if ws.has(ws.lib("libopenxr_loader_generic.so")): # FrameBridge's settings (frame.adapter in a build)
ws.put(ws.lib("libframe_settings.so"), FRAME_SETTINGS)
unsigned = Path(td) / "unsigned.apk"
ws.write(unsigned)
sign.sign(unsigned, Path(a.out), package)
print(f"{a.out}: {package}, {len(libs)} libraries converted")
if __name__ == "__main__":
main()
+162
View File
@@ -0,0 +1,162 @@
"""GLES/EGL thunks, generated from the NDK's headers (called by gen_stubs.py):
guest/gen/gl_stubs.S one hypercall stub per function (HC_GL + index), exported by the runtime
host/gen/gl.c the host side: arguments read per type, the host function called through a pointer that
gl_resolve() looks up (libGLESv3/libEGL, else eglGetProcAddress)
Functions whose arguments can't be passed through as they are (pointer arrays, host pointers as results, callbacks)
are written by hand in host/gl.c (SPECIAL), or left out: their stub logs the name and returns 0.
"""
import re
from pathlib import Path
HEADERS = ["GLES3/gl32.h", "GLES2/gl2ext.h", "EGL/egl.h", "EGL/eglext.h"]
HC_GL = 0x1000
# host pointers the guest sees as handles (handles.c ptr2h)
HANDLES = {"EGLDisplay", "EGLSurface", "EGLContext", "EGLConfig", "EGLImageKHR", "EGLImage", "EGLSyncKHR", "EGLSync",
"EGLClientBuffer", "EGLNativeWindowType", "EGLNativePixmapType", "EGLNativeDisplayType", "EGLStreamKHR",
"GLeglImageOES", "EGLDeviceEXT", "EGLOutputLayerEXT", "EGLOutputPortEXT", "GLeglClientBufferEXT",
"EGLLabelKHR", "EGLObjectKHR", "EGLSyncNV"}
SYNC = {"GLsync"} # freed with glDeleteSync: their own table (gl.c)
FLOAT = {"GLfloat", "GLclampf"}
INT64 = {"GLint64", "GLuint64", "GLint64EXT", "GLuint64EXT", "EGLTimeKHR", "EGLTime", "EGLuint64KHR",
"EGLnsecsANDROID", "EGLuint64NV", "EGLTimeNV"}
INTPTR = {"GLintptr", "GLsizeiptr", "GLintptrARB", "EGLAttrib", "EGLAttribKHR", "EGLsizeiANDROID"}
CALLBACK = re.compile(r"PROC|Func")
# hand-written in host/gl.c as gl_<name>(a32_cpu *c, argreader *R, void *fn)
SPECIAL = {
"glShaderSource", "glGetString", "glGetStringi", "eglQueryString", "glMapBufferRange", "glMapBufferRangeEXT",
"glMapBufferOES", "glUnmapBuffer", "glUnmapBufferOES", "glFlushMappedBufferRange",
"glFlushMappedBufferRangeEXT", "eglChooseConfig", "eglGetConfigs", "glTransformFeedbackVaryings",
"glGetUniformIndices", "glDeleteSync", "glDebugMessageCallback", "glDebugMessageCallbackKHR",
}
GUEST_IMPL = {"eglGetProcAddress"} # implemented inside the runtime (guest/gl.c)
def parse(include: Path):
funcs = {}
for h in HEADERS:
text = (include / h).read_text()
text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
for m in re.finditer(r"(?:GL_APICALL|EGLAPI)\s+(.+?)\s*(?:GL_APIENTRY|EGLAPIENTRY)\s+(\w+)\s*\(([^;]*?)\)\s*;",
text, re.S):
ret, name, params = " ".join(m.group(1).split()), m.group(2), " ".join(m.group(3).split())
if name in funcs:
continue
ps = [] if params in ("", "void") else [p.strip() for p in params.split(",")]
types = []
for p in ps:
# drop the parameter name (the last identifier, unless the whole thing is a type)
t = re.sub(r"\b(\w+)\s*(\[\s*\w*\s*\])?$", "", p).strip() if not p.endswith("*") else p
if not t or t in ("const",):
t = p
if re.search(r"\[\s*\w*\s*\]$", p):
t += " *"
types.append(" ".join(t.split()))
funcs[name] = (ret, types)
return funcs
def kind(t: str) -> str:
t = t.replace("const", "").strip()
stars = t.count("*")
base = t.replace("*", "").strip()
if stars >= 2:
return "?"
if stars == 1:
if base in HANDLES or base in SYNC or base in INTPTR:
return "?" # arrays of host-sized values: by hand
return "P"
if CALLBACK.search(base):
return "?"
if base == "void":
return "v"
if base in HANDLES:
return "H"
if base in SYNC:
return "Y"
if base in FLOAT:
return "f"
if base in INT64:
return "J"
if base in INTPTR:
return "Z"
if base.startswith("__egl"): # eglGetProcAddress's result type
return "?"
return "I"
def generate(ndk: str, gdir: Path, hdir: Path) -> list[str]:
include = Path(ndk) / "toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include"
funcs = parse(include)
names = sorted(n for n in funcs if n not in GUEST_IMPL)
out = ["/* generated by bridge/gen_gl.py from the NDK's GLES/EGL headers: do not edit */", "",
"#define GL_GLEXT_PROTOTYPES 1", "#define EGL_EGLEXT_PROTOTYPES 1", "#include <EGL/egl.h>",
"#include <EGL/eglext.h>", "#include <GLES3/gl32.h>", "#include <GLES2/gl2ext.h>",
'#include "../gl_internal.h"', ""] + [f"void gl_{n}(a32_cpu *c, argreader *R, void *fn);" for n in sorted(SPECIAL)] + ["",
f"const int gl_count = {len(names)};", "const char *const gl_names[] = {"]
out += [f' "{n}",' for n in names] + ["};", "",
"int gl_dispatch_generated(a32_cpu *c, int index, argreader *R, void *fn)",
"{", " switch (index) {"]
skipped = []
for i, n in enumerate(names):
ret, types = funcs[n]
if n in SPECIAL:
out += [f" case {i}: gl_{n}(c, R, fn); return 1;"]
continue
ks = [kind(t) for t in types]
rk = kind(ret)
if "?" in ks or rk == "?" or "v" in ks or (rk == "P" and not re.search(r"char|GLubyte", ret)):
skipped.append(n)
continue
decl, args = [], []
for k, (kd, t) in enumerate(zip(ks, types)):
v = f"a{k}"
ct = t
if kd == "I":
decl.append(f"{ct} {v} = ({ct})rd32(R);")
elif kd == "f":
decl.append(f"{ct} {v} = rdf(R);")
elif kd == "J":
decl.append(f"{ct} {v} = ({ct})rd64(R);")
elif kd == "Z":
decl.append(f"{ct} {v} = ({ct})(int32_t)rd32(R);")
elif kd == "H":
decl.append(f"{ct} {v} = ({ct})h2ptr(rd32(R));")
elif kd == "Y":
decl.append(f"{ct} {v} = ({ct})h2sync(rd32(R));")
elif kd == "P":
decl.append(f"{ct} {v} = ({ct})g2p(rd32(R));")
args.append(v)
call = f"((__typeof__(&{n}))fn)({', '.join(args)})"
body = [" " + d for d in decl]
if rk == "v":
body.append(f" {call};")
elif rk == "I":
body.append(f" ret32(c, (uint32_t){call});")
elif rk == "f":
body.append(f" retf(c, {call});")
elif rk == "J":
body.append(f" ret64(c, (uint64_t){call});")
elif rk == "Z":
body.append(f" ret32(c, (uint32_t)(intptr_t){call});")
elif rk == "H":
body.append(f" ret32(c, ptr2h((void *){call}));")
elif rk == "Y":
body.append(f" ret32(c, sync2h((void *){call}));")
elif rk == "P":
body.append(f" ret32(c, gl_guest_string((const char *){call}));")
out += [f" case {i}: {{ /* {n} */"] + body + [" return 1;", " }"]
out += [" }", " return 0;", "}", ""]
(hdir / "gl.c").write_text("\n".join(out))
st = ["/* generated by bridge/gen_gl.py: do not edit */", " .syntax unified", " .arm", " .text",
" .p2align 2"]
for i, n in enumerate(names):
hc = 0x0A320000 | (HC_GL + i)
st += [f" .global {n}", f" .type {n}, %function", f"{n}:", " push {r7, lr}",
f" movw r7, #{hc & 0xffff:#x}", f" movt r7, #{hc >> 16:#x}", " svc 0", " pop {r7, pc}"]
st += [" .section .note.GNU-stack, \"\", %progbits", ""]
(gdir / "gl_stubs.S").write_text("\n".join(st))
(gdir / "gl_skipped.txt").write_text("\n".join(skipped) + "\n")
return names + sorted(GUEST_IMPL), len(skipped)
+342
View File
@@ -0,0 +1,342 @@
#!/usr/bin/env python3
"""Generates the bridge's tables from the NDK:
guest/gen/exports.S the runtime's "system library" exports: every libc/libm/libstdc++/libz symbol of the NDK's
arm API stubs that bionic's static archives define, plus the runtime's own dl*/liblog
implementations and the host import stubs; (name, address) pairs sorted by name
guest/gen/stubs.S JNIEnv / JavaVM function tables and host import stubs (each one a hypercall)
host/gen/jni_gen.c host side of every JNI function, marshalled from jni.h's signatures (special cases are
written by hand in host/jni.c)
host/gen/imports.c host side of the imports listed in imports.txt
python bridge/gen_stubs.py [--ndk PATH]
"""
import argparse
import re
import subprocess
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
NDK_DEFAULT = HERE.parents[1] / ".cache" / "ndk-27.2.12479018"
API = 30
HC_JNI, HC_VM, HC_IMPORT = 0x100, 0x200, 0x300
# exported names implemented by the runtime itself (name -> symbol)
OVERRIDES = {
"dlopen": "grt_dlopen", "dlsym": "grt_dlsym", "dlclose": "grt_dlclose", "dlerror": "grt_dlerror",
"dladdr": "grt_dladdr", "dl_iterate_phdr": "dl_iterate_phdr",
"dl_unwind_find_exidx": "__wrap_dl_unwind_find_exidx", "android_dlopen_ext": "grt_android_dlopen_ext",
"dlvsym": "grt_dlvsym", "eglGetProcAddress": "grt_eglGetProcAddress",
}
COMPAT = ["_tolower_tab_", "_toupper_tab_", "__isthreaded", "bsd_signal", "pthread_atfork", # pthread_atfork: crtbegin_static.o
"fdprintf", "vfdprintf",
"putw", "get_malloc_leak_info", "free_malloc_leak_info", "__page_size", "getdtablesize", "tkill",
"SHA1Init", "SHA1Update", "SHA1Final", "__google_potentially_blocking_region_begin",
"__google_potentially_blocking_region_end", # guest/compat.c
"slCreateEngine", "slQueryNumSupportedEngineInterfaces", "slQuerySupportedEngineInterfaces", "SL_IID_NULL",
"SL_IID_OBJECT", "SL_IID_ENGINE", "SL_IID_PLAY", "SL_IID_BUFFERQUEUE", "SL_IID_ANDROIDSIMPLEBUFFERQUEUE",
"SL_IID_VOLUME", "SL_IID_ANDROIDCONFIGURATION", "SL_IID_RECORD", "SL_IID_OUTPUTMIX"] # guest/opensles.c
LIBLOG = ["__android_log_write", "__android_log_print", "__android_log_vprint", "__android_log_buf_write",
"__android_log_buf_print", "__android_log_assert", "__android_log_is_loggable"]
# libc symbols that must not be exported (static-only internals)
SKIP = {"__libc_init", "__libc_preinit", "_start"}
OBJ = {"jobject", "jclass", "jstring", "jthrowable", "jarray", "jobjectArray", "jbooleanArray", "jbyteArray",
"jcharArray", "jshortArray", "jintArray", "jlongArray", "jfloatArray", "jdoubleArray", "jweak"}
INT = {"jint", "jsize", "jboolean", "jbyte", "jchar", "jshort", "jobjectRefType"}
# JNI functions written by hand in host/jni.c (pointer results, varargs, freeing handles, natives)
SPECIAL = re.compile(r"^(Call\w*Method[VA]?|NewObject[VA]?|Get\w*ArrayElements|Release\w*ArrayElements|"
r"GetStringUTFChars|ReleaseStringUTFChars|GetStringChars|ReleaseStringChars|"
r"GetStringCritical|ReleaseStringCritical|GetPrimitiveArrayCritical|"
r"ReleasePrimitiveArrayCritical|RegisterNatives|GetJavaVM|GetDirectBufferAddress|"
r"Delete\w*Ref|NewGlobalRef|NewWeakGlobalRef|PopLocalFrame|GetMethodID|GetStaticMethodID|"
r"FromReflectedMethod)$")
def tool(ndk, name):
return Path(ndk) / "toolchains/llvm/prebuilt/linux-x86_64/bin" / name
def defined(ndk, path, dynamic):
args = [str(tool(ndk, "llvm-nm")), "--defined-only", "-g", "-j"] + (["-D"] if dynamic else []) + [str(path)]
out = subprocess.run(args, capture_output=True, text=True).stdout
return {l.strip().split("@")[0] for l in out.splitlines() if l.strip() and not l.endswith(":")}
def code(t):
t = t.replace("const", "").strip()
if t.endswith("*") or "*" in t:
return "E" if t.replace(" ", "") in ("JNIEnv*", "JavaVM*") else "P"
if t in OBJ:
return "O"
if t == "jmethodID":
return "M"
if t == "jfieldID":
return "F"
if t in INT:
return "I"
if t == "jlong":
return "J"
if t == "jfloat":
return "f"
if t == "jdouble":
return "D"
if t == "va_list":
return "V"
if t == "...":
return "."
if t == "void":
return "v"
raise ValueError(t)
def parse_jni(ndk):
h = (Path(ndk) / "toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include/jni.h").read_text()
body = h[h.index("struct JNINativeInterface {"):]
body = body[:body.index("};")]
body = re.sub(r"/\*.*?\*/", "", body, flags=re.S)
funcs = []
for m in re.finditer(r"(void\*\s+reserved\d;)|([\w ]+?\**)\s*\(\*(\w+)\)\s*\(([^)]*)\);", body):
if m.group(1):
funcs.append(None)
continue
ret, name, params = m.group(2).strip(), m.group(3), m.group(4)
ptypes = []
for p in params.split(","):
p = p.strip()
if p == "...":
ptypes.append("...")
continue
p = re.sub(r"\b\w+$", "", p).strip() if not p.endswith("*") and len(p.split()) > 1 else p
ptypes.append(p)
funcs.append((name, ret, ptypes))
if len(funcs) != 233:
sys.exit(f"jni.h: {len(funcs)} JNINativeInterface entries, expected 233")
return funcs
CTYPE = {"O": "jobject", "M": "jmethodID", "F": "jfieldID", "I": "jint", "J": "jlong", "f": "jfloat",
"D": "jdouble", "P": "void *"}
def gen_jni_host(funcs, out):
lines = ["/* generated by bridge/gen_stubs.py from the NDK's jni.h: do not edit */", "",
'#include "../jni_internal.h"', "",
"int jni_dispatch_generated(a32_cpu *c, JNIEnv *env, int index, argreader *R)", "{",
" switch (index) {"]
names = []
for i, f in enumerate(funcs):
if f is None:
names.append("reserved")
continue
name, ret, ptypes = f
names.append(name)
if SPECIAL.match(name):
continue
codes = [code(p) for p in ptypes]
rc = code(ret)
assert codes[0] == "E", name
if any(c in ".V" for c in codes) or rc == "P":
sys.exit(f"{name}: needs a hand-written implementation (varargs or pointer result)")
decl, args = [], ["env"]
for k, (cd, t) in enumerate(zip(codes[1:], ptypes[1:]), 1):
v = f"a{k}"
if cd == "O":
decl.append(f"{t.replace('const', '').strip()} {v} = ({t.replace('const', '').strip()})h2o(rd32(R));")
elif cd == "M":
decl.append(f"jmethodID {v} = h2mid(rd32(R));")
elif cd == "F":
decl.append(f"jfieldID {v} = h2fid(rd32(R));")
elif cd == "I":
decl.append(f"{t} {v} = ({t})rd32(R);")
elif cd == "J":
decl.append(f"jlong {v} = (jlong)rd64(R);")
elif cd == "f":
decl.append(f"jfloat {v} = rdf(R);")
elif cd == "D":
decl.append(f"jdouble {v} = rdd(R);")
elif cd == "P":
decl.append(f"{t} {v} = ({t})g2p(rd32(R));")
args.append(v)
call = f"(*env)->{name}({', '.join(args)})"
lines.append(f" case {i}: {{ /* {name} */")
lines += [" " + d for d in decl]
if rc == "v":
lines.append(f" {call};")
elif rc == "O":
lines.append(f" ret32(c, o2h_local({call}));")
elif rc == "M":
lines.append(f" ret32(c, mid2h({call}));")
elif rc == "F":
lines.append(f" ret32(c, fid2h({call}));")
elif rc == "I":
lines.append(f" ret32(c, (uint32_t){call});")
elif rc == "J":
lines.append(f" ret64(c, (uint64_t){call});")
elif rc == "f":
lines.append(f" retf(c, {call});")
elif rc == "D":
lines.append(f" retd(c, {call});")
lines += [" return 1;", " }"]
lines += [" }", " return 0;", "}", "",
"const char *const jni_names[JNI_TABLE_SIZE] = {"]
lines += [f' "{n}",' for n in names]
lines += ["};", ""]
out.write_text("\n".join(lines))
def parse_imports():
out = []
for line in (HERE / "imports.txt").read_text().splitlines():
line = line.split("#")[0].strip()
if not line:
continue
m = re.match(r"(!\s*)?(\w)\s+(\w+)\s*\((\w*)\)$", line)
if not m:
sys.exit(f"imports.txt: bad line {line!r}")
out.append((m.group(3), m.group(2), m.group(4), bool(m.group(1))))
return out
def gen_imports_host(imports, out):
lines = ["/* generated by bridge/gen_stubs.py from imports.txt: do not edit */", "",
"#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"",
"#include <android/asset_manager_jni.h>", "#include <android/configuration.h>", "#include <android/input.h>", "#include <android/looper.h>",
"#include <android/native_window_jni.h>", "#include <android/sensor.h>",
'#include "../imports_internal.h"', ""]
for name, ret, args, manual in imports:
if manual:
lines.append(f"void imp_{name}(a32_cpu *c, argreader *R);")
else:
lines.append(f"extern __typeof__({name}) {name} __attribute__((weak));")
lines += ["", "int import_dispatch(a32_cpu *c, int index, argreader *R)", "{", " switch (index) {"]
for i, (name, ret, args, manual) in enumerate(imports):
if manual:
lines.append(f" case {i}: imp_{name}(c, R); return 1;")
continue
decl, vals = [], []
for k, a in enumerate(args):
v = f"a{k}"
if a == "I":
decl.append(f"int32_t {v} = (int32_t)rd32(R);")
elif a == "J":
decl.append(f"int64_t {v} = (int64_t)rd64(R);")
elif a == "f":
decl.append(f"float {v} = rdf(R);")
elif a == "P":
decl.append(f"void *{v} = g2p(rd32(R));")
elif a == "H":
decl.append(f"void *{v} = h2ptr(rd32(R));")
elif a == "A":
decl.append(f"ANativeActivity *{v} = guest_activity(rd32(R));")
elif a == "E":
decl.append(f"JNIEnv *{v} = (rd32(R), host_env());")
elif a == "O":
decl.append(f"jobject {v} = h2o(rd32(R));")
else:
sys.exit(f"imports.txt: {name}: unknown argument type {a}")
vals.append(v)
call = f"{name}({', '.join(vals)})"
lines.append(f" case {i}: {{ /* {name} */")
lines.append(f" if (!{name}) return 0;")
lines += [" " + d for d in decl]
if ret == "v":
lines.append(f" {call};")
elif ret == "I":
lines.append(f" ret32(c, (uint32_t){call});")
elif ret == "J":
lines.append(f" ret64(c, (uint64_t){call});")
elif ret == "f":
lines.append(f" retf(c, {call});")
elif ret == "H":
lines.append(f" ret32(c, ptr2h((void *){call}));")
elif ret == "S":
lines.append(f" ret32(c, guest_cstr({call}));")
else:
sys.exit(f"imports.txt: {name}: unknown result type {ret}")
lines += [" return 1;", " }"]
lines += [" }", " return 0;", "}", "", "const char *const import_names[] = {"]
lines += [f' "{n}",' for n, _, _, _ in imports]
lines += [" 0,", "};", ""]
out.write_text("\n".join(lines))
def stub(label, n):
hc = 0x0a320000 | n
return [f"{label}:", " push {r7, lr}",
f" movw r7, #{hc & 0xffff:#x}", f" movt r7, #{hc >> 16:#x}",
" svc 0", " pop {r7, pc}"]
def gen_guest(ndk, imports, gdir, extra):
sysroot = Path(ndk) / "toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/arm-linux-androideabi"
want = set()
for so in ("libc.so", "libm.so", "libstdc++.so", "libz.so"):
want |= defined(ndk, sysroot / str(API) / so, True)
have = set()
for a in ("libc.a", "libm.a", "libstdc++.a", "libz.a"):
have |= defined(ndk, sysroot / a, False)
have |= defined(ndk, Path(ndk) / "toolchains/llvm/prebuilt/linux-x86_64/lib/clang/18/lib/linux/arm/libunwind.a",
False)
names = {n: n for n in want & have if n not in SKIP}
for n in OVERRIDES:
names[n] = OVERRIDES[n]
for n in LIBLOG + COMPAT:
names[n] = n
for n, *_ in imports:
names[n] = n
for n in extra:
names.setdefault(n, OVERRIDES.get(n, n))
missing = sorted(want - have - set(OVERRIDES) - SKIP - set(COMPAT))
(gdir / "missing.txt").write_text("\n".join(missing) + "\n")
ex = ["/* generated by bridge/gen_stubs.py: do not edit */", " .section .rodata.grt_names, \"aMS\", %progbits, 1"]
order = sorted(names, key=lambda s: s.encode())
for k, n in enumerate(order):
ex.append(f".Ln{k}: .asciz \"{n}\"")
ex += [" .section .data.rel.ro.grt_exports, \"aw\"", " .p2align 2", " .global grt_export_table",
"grt_export_table:"]
for k, n in enumerate(order):
ex.append(f" .word .Ln{k}, {names[n]}")
ex += [" .global grt_export_count", "grt_export_count:", f" .word {len(order)}", ""]
(gdir / "exports.S").write_text("\n".join(ex))
st = ["/* generated by bridge/gen_stubs.py: do not edit */", " .syntax unified", " .arm", " .text",
" .p2align 2"]
for i in range(233):
st += stub(f"jni_{i}", HC_JNI + i)
for i in range(8):
st += stub(f"vm_{i}", HC_VM + i)
for i, (n, *_) in enumerate(imports):
st += [f" .global {n}", f" .type {n}, %function"] + stub(n, HC_IMPORT + i)
st += [" .section .data.rel.ro.grt_tables, \"aw\"", " .p2align 2", "grt_jni_table:"]
st += [f" .word jni_{i}" for i in range(233)]
st += ["grt_vm_table:"] + [f" .word vm_{i}" for i in range(8)]
st += [" .global grt_jni_env", "grt_jni_env:", " .word grt_jni_table",
" .global grt_java_vm", "grt_java_vm:", " .word grt_vm_table", ""]
(gdir / "stubs.S").write_text("\n".join(st))
return len(order), len(missing)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ndk", default=str(NDK_DEFAULT))
a = ap.parse_args()
imports = parse_imports()
gdir, hdir = HERE / "guest" / "gen", HERE / "host" / "gen"
gdir.mkdir(parents=True, exist_ok=True)
hdir.mkdir(parents=True, exist_ok=True)
import gen_gl
gl_names, gl_skipped = gen_gl.generate(a.ndk, gdir, hdir)
n, miss = gen_guest(a.ndk, imports, gdir, gl_names)
funcs = parse_jni(a.ndk)
gen_jni_host(funcs, hdir / "jni_gen.c")
gen_imports_host(imports, hdir / "imports.c")
print(f"{n} exports ({miss} stub symbols without a static definition, see guest/gen/missing.txt), "
f"{len(imports)} imports, {len(funcs)} JNI functions, {len(gl_names)} GLES/EGL functions ({gl_skipped} "
"not supported, see guest/gen/gl_skipped.txt)")
if __name__ == "__main__":
main()
+111
View File
@@ -0,0 +1,111 @@
/* LP32 bionic symbols that only libc.so has (old NDK binaries still link against them). */
#include <ctype.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
static short lower_tab[257], upper_tab[257];
const short *_tolower_tab_ = lower_tab;
const short *_toupper_tab_ = upper_tab;
int __isthreaded = 1;
__attribute__((constructor)) static void init_tabs(void)
{
lower_tab[0] = upper_tab[0] = -1; /* EOF */
for (int c = 0; c < 256; c++) {
lower_tab[c + 1] = (short)tolower(c);
upper_tab[c + 1] = (short)toupper(c);
}
}
sighandler_t bsd_signal(int sig, sighandler_t h) { return signal(sig, h); }
int vfdprintf(int fd, const char *fmt, va_list ap) { return vdprintf(fd, fmt, ap); }
int fdprintf(int fd, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
int r = vdprintf(fd, fmt, ap);
va_end(ap);
return r;
}
int putw(int w, FILE *f) { return fwrite(&w, sizeof w, 1, f) == 1 ? 0 : EOF; }
void get_malloc_leak_info(void **info, size_t *overall, size_t *isize, size_t *total, size_t *backtrace)
{
*info = 0;
*overall = *isize = *total = *backtrace = 0;
}
void free_malloc_leak_info(void *info) { (void)info; }
/* old LP32 libc.so also exported these (Unity 5 and Mono builds link against them) */
#include <stdint.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
unsigned int __page_size = 4096;
int getdtablesize(void) { return (int)sysconf(_SC_OPEN_MAX); }
int tkill(int tid, int sig) { return (int)syscall(__NR_tkill, tid, sig); }
typedef struct {
uint32_t state[5];
uint32_t count[2];
uint8_t buffer[64];
} SHA1_CTX;
#define ROL(v, b) (((v) << (b)) | ((v) >> (32 - (b))))
static void sha1_block(uint32_t st[5], const uint8_t b[64])
{
uint32_t w[80], a = st[0], bb = st[1], c = st[2], d = st[3], e = st[4];
for (int i = 0; i < 16; i++) w[i] = (uint32_t)b[4 * i] << 24 | (uint32_t)b[4 * i + 1] << 16 | (uint32_t)b[4 * i + 2] << 8 | b[4 * i + 3];
for (int i = 16; i < 80; i++) w[i] = ROL(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
for (int i = 0; i < 80; i++) {
uint32_t f, k;
if (i < 20) f = (bb & c) | (~bb & d), k = 0x5a827999;
else if (i < 40) f = bb ^ c ^ d, k = 0x6ed9eba1;
else if (i < 60) f = (bb & c) | (bb & d) | (c & d), k = 0x8f1bbcdc;
else f = bb ^ c ^ d, k = 0xca62c1d6;
uint32_t t = ROL(a, 5) + f + e + k + w[i];
e = d, d = c, c = ROL(bb, 30), bb = a, a = t;
}
st[0] += a, st[1] += bb, st[2] += c, st[3] += d, st[4] += e;
}
void SHA1Init(SHA1_CTX *ctx)
{
static const uint32_t init[5] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0};
memcpy(ctx->state, init, sizeof init);
ctx->count[0] = ctx->count[1] = 0;
}
void SHA1Update(SHA1_CTX *ctx, const uint8_t *data, uint32_t len)
{
uint32_t j = (ctx->count[0] >> 3) & 63;
if ((ctx->count[0] += len << 3) < (len << 3)) ctx->count[1]++;
ctx->count[1] += len >> 29;
uint32_t i = 0;
if (j + len > 63) {
memcpy(&ctx->buffer[j], data, (i = 64 - j));
sha1_block(ctx->state, ctx->buffer);
for (; i + 63 < len; i += 64) sha1_block(ctx->state, &data[i]);
j = 0;
}
memcpy(&ctx->buffer[j], &data[i], len - i);
}
void SHA1Final(uint8_t digest[20], SHA1_CTX *ctx)
{
uint8_t final[8];
for (int i = 0; i < 8; i++) final[i] = (uint8_t)(ctx->count[i >= 4 ? 0 : 1] >> ((3 - (i & 3)) * 8));
uint8_t c = 0x80;
SHA1Update(ctx, &c, 1);
c = 0;
while ((ctx->count[0] & 504) != 448) SHA1Update(ctx, &c, 1);
SHA1Update(ctx, final, 8);
for (int i = 0; i < 20; i++) digest[i] = (uint8_t)(ctx->state[i >> 2] >> ((3 - (i & 3)) * 8));
}
void __google_potentially_blocking_region_begin(void) {}
void __google_potentially_blocking_region_end(void) {}
+4
View File
@@ -0,0 +1,4 @@
/* eglGetProcAddress for guest code: the runtime's own GLES/EGL stubs (gen/gl_stubs.S), found by name. */
#include "grt.h"
void *grt_eglGetProcAddress(const char *name) { return name ? (void *)(uintptr_t)grt_export(name) : 0; }
+27
View File
@@ -0,0 +1,27 @@
/* Guest runtime (liba32rt.so): a static 32-bit bionic program that loads the game's libraries and connects them
* to the host bridge. */
#ifndef GRT_H
#define GRT_H
#include <stdint.h>
#include "../abi.h"
#define A32_HYPERCALL 0x0a320000u
uint32_t grt_hc_raw(uint32_t r7, uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3); /* hc.S */
static inline uint32_t grt_hc(uint32_t n, uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3)
{
return grt_hc_raw(A32_HYPERCALL | n, a0, a1, a2, a3);
}
void grt_log(int prio, const char *tag, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
uint32_t grt_export(const char *name); /* exports.S + main.c: address of a "system" symbol, 0 if none */
void loader_set_dir(const char *dir);
void *grt_dlopen(const char *name, int flags);
void *grt_dlsym(void *handle, const char *name);
char *grt_dlerror(void);
uint32_t *grt_list_symbols(void *handle, const char *prefix);
#endif
+19
View File
@@ -0,0 +1,19 @@
/* grt_hc_raw(r7 value, a0, a1, a2, a3): a hypercall (SVC 0 with r7 = A32_HYPERCALL | n), result in r0. Out of line
* because r7 is the Thumb frame pointer. */
.syntax unified
.arm
.text
.p2align 2
.global grt_hc_raw
.type grt_hc_raw, %function
grt_hc_raw:
push {r7, lr}
mov r7, r0
mov r0, r1
mov r1, r2
mov r2, r3
ldr r3, [sp, #8]
svc 0
pop {r7, pc}
.size grt_hc_raw, . - grt_hc_raw
.section .note.GNU-stack, "", %progbits
+731
View File
@@ -0,0 +1,731 @@
/* Guest dynamic loader: loads 32-bit ARM shared libraries (the game's) into the runtime, which is a static
* executable. Symbols resolve against the library itself, its DT_NEEDED libraries, every library loaded before,
* and the runtime's exports (libc, libm, liblog, ... = "system" libraries). Implements the bionic dl* API for
* guest code. */
#include <dlfcn.h>
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <link.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include "grt.h"
#ifndef PT_ARM_EXIDX
#define PT_ARM_EXIDX 0x70000001
#endif
#define DT_ANDROID_REL 0x6000000f
#define DT_ANDROID_RELSZ 0x60000010
/* Android used these OS-specific tags before RELR received standard ELF tags.
* The table encoding is identical (including ARM32's 31-bit bitmaps). */
#define DT_ANDROID_RELR 0x6fffe000
#define DT_ANDROID_RELRSZ 0x6fffe001
#define DT_RELR_ 36
#define DT_RELRSZ_ 35
#define R_ARM_NONE 0
#define R_ARM_ABS32 2
#define R_ARM_REL32 3
#define R_ARM_TLS_DTPMOD32 17
#define R_ARM_TLS_DTPOFF32 18
#define R_ARM_TLS_TPOFF32 19
#define R_ARM_GLOB_DAT 21
#define R_ARM_JUMP_SLOT 22
#define R_ARM_RELATIVE 23
#define R_ARM_IRELATIVE 160
typedef struct lib {
char name[128]; /* as requested (basename) */
char path[512];
uint32_t base; /* load bias */
uint32_t start, size; /* mapped range */
const Elf32_Phdr *phdr;
int phnum;
Elf32_Dyn *dyn;
const Elf32_Sym *symtab;
const char *strtab;
const uint32_t *hash; /* DT_HASH */
const uint32_t *gnu_hash; /* DT_GNU_HASH */
uint32_t nsyms;
uint32_t exidx, exidx_count;
struct lib **needed;
int nneeded;
int refs;
int initialised;
struct lib *next;
} lib;
/* "system" libraries: no file, symbols come from the runtime's export table */
static const char *const SYSTEM_LIBS[] = {
"libc.so", "libm.so", "libdl.so", "liblog.so", "libandroid.so", "libstdc++.so", "libz.so", "libEGL.so",
"libGLESv1_CM.so", "libGLESv2.so", "libGLESv3.so", "libOpenSLES.so", "libvulkan.so", "libjnigraphics.so",
"libaaudio.so", "libmediandk.so", "libnativewindow.so", "libsync.so", "libOpenMAXAL.so", "libcamera2ndk.so",
"libamidi.so", "libbinder_ndk.so", "libneuralnetworks.so",
"libvrapi.so", /* VrApi 1.x: translated by the host (host/vrapi.c); a game's own copy is the Oculus loader */
};
static lib system_lib = {.name = "libc.so", .refs = 1, .initialised = 1};
static lib *libs, *libs_tail;
static pthread_mutex_t lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
static __thread char err_buf[512];
static __thread int err_set;
static const char *lib_dir = ".";
void loader_set_dir(const char *dir) { lib_dir = dir; }
static void vset_error(int log, const char *fmt, va_list ap)
{
vsnprintf(err_buf, sizeof err_buf, fmt, ap);
err_set = 1;
if (log) grt_log(5, "a32rt", "%s", err_buf);
}
static void set_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vset_error(1, fmt, ap);
va_end(ap);
}
/* failures callers expect (dlsym probes, Mono looking for AOT images "X.dll.so"): not logged */
static void set_error_quiet(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vset_error(0, fmt, ap);
va_end(ap);
}
/* ------------------------------------------------------------------------------------------------ symbols */
static uint32_t elf_hash(const char *n)
{
uint32_t h = 0, g;
while (*n) {
h = (h << 4) + (uint8_t)*n++;
g = h & 0xf0000000u;
h ^= g >> 24;
h &= ~g;
}
return h;
}
static uint32_t gnu_hash(const char *n)
{
uint32_t h = 5381;
while (*n) h = h * 33 + (uint8_t)*n++;
return h;
}
static int sym_defined(const Elf32_Sym *s)
{
int bind = ELF32_ST_BIND(s->st_info);
return s->st_shndx != SHN_UNDEF && (bind == STB_GLOBAL || bind == STB_WEAK || bind == 10 /* GNU_UNIQUE */);
}
/* a defined, exported symbol of l, or NULL */
static const Elf32_Sym *lib_lookup(const lib *l, const char *name)
{
if (l == &system_lib) return NULL;
if (l->gnu_hash) {
const uint32_t *g = l->gnu_hash;
uint32_t nbuckets = g[0], symoffset = g[1], bloom_size = g[2], bloom_shift = g[3];
const uint32_t *bloom = g + 4, *buckets = bloom + bloom_size, *chain = buckets + nbuckets;
uint32_t h = gnu_hash(name);
uint32_t word = bloom[(h / 32) % bloom_size];
if (!((word >> (h % 32)) & (word >> ((h >> bloom_shift) % 32)) & 1)) return NULL;
uint32_t k = buckets[h % nbuckets];
if (k < symoffset) return NULL;
for (;; k++) {
uint32_t h2 = chain[k - symoffset];
if ((h | 1) == (h2 | 1)) {
const Elf32_Sym *s = &l->symtab[k];
if (sym_defined(s) && !strcmp(l->strtab + s->st_name, name)) return s;
}
if (h2 & 1) break;
}
return NULL;
}
if (l->hash) {
uint32_t nbucket = l->hash[0];
const uint32_t *bucket = l->hash + 2, *chain = bucket + nbucket;
for (uint32_t k = bucket[elf_hash(name) % nbucket]; k; k = chain[k]) {
const Elf32_Sym *s = &l->symtab[k];
if (sym_defined(s) && !strcmp(l->strtab + s->st_name, name)) return s;
}
}
return NULL;
}
/* address of name in l (or the runtime's exports for system libraries), 0 if absent */
static uint32_t lib_sym_addr(const lib *l, const char *name)
{
if (l == &system_lib) return grt_export(name);
const Elf32_Sym *s = lib_lookup(l, name);
return s ? l->base + s->st_value : 0;
}
/* bionic's order: the library itself, its DT_NEEDED (breadth first), then everything else that is loaded */
static uint32_t resolve(const lib *l, const char *name)
{
const lib *q[64];
int n = 0, h = 0;
q[n++] = l;
while (h < n) {
const lib *c = q[h++];
uint32_t a = lib_sym_addr(c, name);
if (a) return a;
for (int k = 0; k < c->nneeded && n < 64; k++) {
int seen = 0;
for (int j = 0; j < n; j++) seen |= q[j] == c->needed[k];
if (!seen) q[n++] = c->needed[k];
}
}
for (const lib *c = libs; c; c = c->next) {
uint32_t a = lib_sym_addr(c, name);
if (a) return a;
}
return grt_export(name);
}
/* code that reports the name of an unresolved symbol when called and returns 0: movw/movt r0, name; movw/movt r7;
* svc 0; bx lr */
static uint32_t unresolved_stub(const char *name)
{
static uint32_t *page, used;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&m);
if (!page || used + 6 > 1024) {
page = mmap(NULL, 4096, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
used = 0;
}
uint32_t *p = page + used, a = (uint32_t)(uintptr_t)strdup(name), hc = A32_HYPERCALL | HC_UNRESOLVED;
p[0] = 0xe3000000u | ((a & 0xf000) << 4) | (a & 0xfff); /* movw r0, #lo */
p[1] = 0xe3400000u | ((a >> 12) & 0xf0000) | ((a >> 16) & 0xfff); /* movt r0, #hi */
p[2] = 0xe3007000u | ((hc & 0xf000) << 4) | (hc & 0xfff); /* movw r7, #lo */
p[3] = 0xe3407000u | ((hc >> 12) & 0xf0000) | ((hc >> 16) & 0xfff); /* movt r7, #hi */
p[4] = 0xef000000u; /* svc 0 */
p[5] = 0xe12fff1eu; /* bx lr */
used += 6;
__builtin___clear_cache((char *)p, (char *)(p + 6));
pthread_mutex_unlock(&m);
return (uint32_t)(uintptr_t)p;
}
/* ------------------------------------------------------------------------------------------------ relocation */
static int reloc_one(lib *l, uint32_t offset, uint32_t info)
{
uint32_t type = ELF32_R_TYPE(info), symi = ELF32_R_SYM(info);
uint32_t *where = (uint32_t *)(uintptr_t)(l->base + offset);
uint32_t s = 0;
if (symi) {
const Elf32_Sym *sym = &l->symtab[symi];
const char *name = l->strtab + sym->st_name;
if (ELF32_ST_BIND(sym->st_info) == STB_LOCAL) {
s = l->base + sym->st_value;
} else {
s = resolve(l, name);
if (!s) {
if (ELF32_ST_BIND(sym->st_info) == STB_WEAK) {
s = 0;
} else if (type == R_ARM_JUMP_SLOT || (ELF32_ST_TYPE(sym->st_info) == STT_FUNC)) {
grt_log(5, "a32rt", "%s: unresolved function %s", l->name, name);
s = unresolved_stub(name);
} else if (type == R_ARM_GLOB_DAT || type == R_ARM_ABS32) {
/* untyped (functions referenced through the GOT): report when called */
grt_log(5, "a32rt", "%s: unresolved symbol %s", l->name, name);
s = unresolved_stub(name);
} else {
set_error("%s: cannot resolve %s", l->name, name);
return -1;
}
}
}
}
switch (type) {
case R_ARM_NONE: break;
case R_ARM_ABS32: *where += s; break;
case R_ARM_REL32: *where += s - (uint32_t)(uintptr_t)where; break;
case R_ARM_GLOB_DAT:
case R_ARM_JUMP_SLOT: *where = s; break;
case R_ARM_RELATIVE: *where += l->base; break;
case R_ARM_IRELATIVE: *where = ((uint32_t (*)(void))(uintptr_t)(l->base + *where))(); break;
case R_ARM_TLS_DTPMOD32:
case R_ARM_TLS_DTPOFF32:
case R_ARM_TLS_TPOFF32:
set_error("%s: ELF TLS relocations are not supported yet (type %u)", l->name, type);
return -1;
default:
set_error("%s: unsupported relocation type %u", l->name, type);
return -1;
}
return 0;
}
static int reloc_rel(lib *l, uint32_t addr, uint32_t size)
{
const Elf32_Rel *r = (const Elf32_Rel *)(uintptr_t)(l->base + addr);
for (uint32_t k = 0; k < size / sizeof *r; k++)
if (reloc_one(l, r[k].r_offset, r[k].r_info)) return -1;
return 0;
}
static int32_t sleb(const uint8_t **p)
{
int32_t v = 0;
int shift = 0;
uint8_t b;
do {
b = *(*p)++;
v |= (int32_t)(b & 0x7f) << shift;
shift += 7;
} while (b & 0x80);
if (shift < 32 && (b & 0x40)) v |= -(1 << shift);
return v;
}
/* Android's packed relocations ("APS2", bionic linker_reloc_iterators.h) */
static int reloc_android(lib *l, uint32_t addr, uint32_t size)
{
const uint8_t *p = (const uint8_t *)(uintptr_t)(l->base + addr);
if (size < 4 || memcmp(p, "APS2", 4)) {
set_error("%s: unknown packed relocation format", l->name);
return -1;
}
p += 4;
int32_t count = sleb(&p);
uint32_t offset = (uint32_t)sleb(&p), info = 0;
while (count > 0) {
int32_t gsize = sleb(&p), flags = sleb(&p), delta = 0;
if (flags & 2) delta = sleb(&p);
if (flags & 1) info = (uint32_t)sleb(&p);
if (flags & 8) {
set_error("%s: packed relocations with addends on a REL target", l->name);
return -1;
}
for (int32_t k = 0; k < gsize; k++) {
offset += (flags & 2) ? (uint32_t)delta : (uint32_t)sleb(&p);
if (!(flags & 1)) info = (uint32_t)sleb(&p);
if (reloc_one(l, offset, info)) return -1;
}
count -= gsize;
}
return 0;
}
static void reloc_relr(lib *l, uint32_t addr, uint32_t size)
{
const uint32_t *r = (const uint32_t *)(uintptr_t)(l->base + addr);
uint32_t *where = NULL;
for (uint32_t k = 0; k < size / 4; k++) {
uint32_t e = r[k];
if (!(e & 1)) {
where = (uint32_t *)(uintptr_t)(l->base + e);
*where++ += l->base;
} else {
for (uint32_t j = 0; (e >>= 1) != 0; j++)
if (e & 1) where[j] += l->base;
where += 31;
}
}
}
/* ------------------------------------------------------------------------------------------------ loading */
static lib *load_lib(const char *name);
static int is_system(const char *base)
{
for (size_t k = 0; k < sizeof SYSTEM_LIBS / sizeof *SYSTEM_LIBS; k++)
if (!strcmp(base, SYSTEM_LIBS[k])) return 1;
return 0;
}
static const char *basename_of(const char *p)
{
const char *s = strrchr(p, '/');
return s ? s + 1 : p;
}
/* The guest copy of libX.so is stored as libX.a32.so next to the host libraries (the package manager extracts
* lib*.so files only, and libX.so itself is the host stub). */
static int open_lib(const char *name, char *path, size_t n)
{
int fd;
size_t len = strlen(name);
if (strchr(name, '/')) {
/* a path into the app's library folder names the host stub: its guest code is next to it */
if (len > 3 && !strcmp(name + len - 3, ".so")) {
snprintf(path, n, "%.*s.a32.so", (int)(len - 3), name);
if ((fd = open(path, O_RDONLY | O_CLOEXEC)) >= 0) return fd;
}
snprintf(path, n, "%s", name);
if ((fd = open(path, O_RDONLY | O_CLOEXEC)) >= 0) return fd;
name = basename_of(name);
len = strlen(name);
}
if (len > 3 && !strcmp(name + len - 3, ".so")) {
snprintf(path, n, "%s/%.*s.a32.so", lib_dir, (int)(len - 3), name);
if ((fd = open(path, O_RDONLY | O_CLOEXEC)) >= 0) return fd;
}
snprintf(path, n, "%s/%s", lib_dir, name);
return open(path, O_RDONLY | O_CLOEXEC);
}
static int map_lib(lib *l, int fd)
{
Elf32_Ehdr eh;
if (pread(fd, &eh, sizeof eh, 0) != sizeof eh || memcmp(eh.e_ident, ELFMAG, SELFMAG) ||
eh.e_ident[EI_CLASS] != ELFCLASS32 || eh.e_machine != EM_ARM || eh.e_type != ET_DYN || eh.e_phnum > 64) {
set_error("%s: not a 32-bit ARM shared library", l->path);
return -1;
}
Elf32_Phdr ph[64];
if (pread(fd, ph, eh.e_phnum * sizeof *ph, eh.e_phoff) != (ssize_t)(eh.e_phnum * sizeof *ph)) return -1;
uint32_t lo = 0xffffffffu, hi = 0;
for (int k = 0; k < eh.e_phnum; k++)
if (ph[k].p_type == PT_LOAD) {
if (ph[k].p_vaddr < lo) lo = ph[k].p_vaddr;
if (ph[k].p_vaddr + ph[k].p_memsz > hi) hi = ph[k].p_vaddr + ph[k].p_memsz;
}
lo &= ~4095u;
hi = (hi + 4095) & ~4095u;
void *res = mmap(NULL, hi - lo, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (res == MAP_FAILED) {
set_error("%s: no room for %u bytes", l->path, hi - lo);
return -1;
}
l->start = (uint32_t)(uintptr_t)res;
l->base = l->start - lo;
l->size = hi - lo;
for (int k = 0; k < eh.e_phnum; k++) {
const Elf32_Phdr *p = &ph[k];
if (p->p_type == PT_DYNAMIC) l->dyn = (Elf32_Dyn *)(uintptr_t)(l->base + p->p_vaddr);
if (p->p_type == PT_ARM_EXIDX) {
l->exidx = l->base + p->p_vaddr;
l->exidx_count = p->p_memsz / 8;
}
if (p->p_type != PT_LOAD || !p->p_memsz) continue;
uint32_t va = l->base + p->p_vaddr, start = va & ~4095u;
uint32_t fend = va + p->p_filesz, mend = va + p->p_memsz, fpend = (fend + 4095) & ~4095u;
/* writable while relocating; final protections are applied afterwards */
if (p->p_filesz) {
void *m = mmap((void *)(uintptr_t)start, fpend - start, PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_FIXED, fd, p->p_offset - (va - start));
if (m == MAP_FAILED) {
set_error("%s: mapping a segment failed (%s)", l->path, strerror(errno));
return -1;
}
if (mend > fend && fpend > fend) memset((void *)(uintptr_t)fend, 0, fpend - fend);
} else {
fpend = start;
}
uint32_t mpend = (mend + 4095) & ~4095u;
if (mpend > fpend &&
mmap((void *)(uintptr_t)fpend, mpend - fpend, PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) == MAP_FAILED) {
set_error("%s: mapping .bss failed", l->path);
return -1;
}
if (!l->phdr && eh.e_phoff >= p->p_offset && eh.e_phoff < p->p_offset + p->p_filesz)
l->phdr = (const Elf32_Phdr *)(uintptr_t)(va + (eh.e_phoff - p->p_offset));
}
l->phnum = eh.e_phnum;
if (!l->dyn) {
set_error("%s: no dynamic section", l->path);
return -1;
}
return 0;
}
static void protect_lib(lib *l)
{
for (int k = 0; k < l->phnum; k++) {
const Elf32_Phdr *p = &l->phdr[k];
if (p->p_type != PT_LOAD || !p->p_memsz) continue;
int prot = (p->p_flags & PF_R ? PROT_READ : 0) | (p->p_flags & PF_W ? PROT_WRITE : 0) |
(p->p_flags & PF_X ? PROT_EXEC : 0);
uint32_t s = (l->base + p->p_vaddr) & ~4095u, e = (l->base + p->p_vaddr + p->p_memsz + 4095) & ~4095u;
mprotect((void *)(uintptr_t)s, e - s, prot);
}
for (int k = 0; k < l->phnum; k++) {
const Elf32_Phdr *p = &l->phdr[k];
if (p->p_type != PT_GNU_RELRO) continue;
uint32_t s = (l->base + p->p_vaddr) & ~4095u, e = (l->base + p->p_vaddr + p->p_memsz) & ~4095u;
if (e > s) mprotect((void *)(uintptr_t)s, e - s, PROT_READ);
}
}
static void init_lib(lib *l)
{
if (l->initialised) return;
l->initialised = 1;
for (int k = 0; k < l->nneeded; k++) init_lib(l->needed[k]);
uint32_t init = 0, arr = 0, arrsz = 0;
for (Elf32_Dyn *d = l->dyn; d->d_tag != DT_NULL; d++) {
if (d->d_tag == DT_INIT) init = l->base + d->d_un.d_ptr;
else if (d->d_tag == DT_INIT_ARRAY) arr = l->base + d->d_un.d_ptr;
else if (d->d_tag == DT_INIT_ARRAYSZ) arrsz = d->d_un.d_val;
}
extern char **environ;
if (init) ((void (*)(int, char **, char **))(uintptr_t)init)(0, NULL, environ);
for (uint32_t k = 0; k < arrsz / 4; k++) {
uint32_t f = ((uint32_t *)(uintptr_t)arr)[k];
if (f && f != 0xffffffffu) ((void (*)(int, char **, char **))(uintptr_t)f)(0, NULL, environ);
}
}
static lib *find_loaded(const char *base)
{
for (lib *l = libs; l; l = l->next)
if (!strcmp(l->name, base)) return l;
return NULL;
}
static lib *load_lib(const char *name)
{
const char *base = basename_of(name);
lib *l = find_loaded(base);
if (l) {
l->refs++;
return l;
}
/* VrApi is always the runtime's: lib/ may hold a host libvrapi.so of that name (the app's Java side loads one) */
if (!strcmp(base, "libvrapi.so")) return &system_lib;
char path[512];
int fd = open_lib(name, path, sizeof path);
if (fd < 0) {
if (is_system(base)) return &system_lib;
size_t nl = strlen(name);
if (nl > 7 && !strcmp(name + nl - 7, ".dll.so")) set_error_quiet("dlopen failed: library \"%s\" not found", name);
else set_error("dlopen failed: library \"%s\" not found", name);
return NULL;
}
l = calloc(1, sizeof *l);
snprintf(l->name, sizeof l->name, "%s", base);
snprintf(l->path, sizeof l->path, "%s", path);
l->refs = 1;
int r = map_lib(l, fd);
close(fd);
if (r) {
free(l);
return NULL;
}
uint32_t rel = 0, relsz = 0, jmprel = 0, jmprelsz = 0, arel = 0, arelsz = 0, relr = 0, relrsz = 0;
int nneeded = 0;
for (Elf32_Dyn *d = l->dyn; d->d_tag != DT_NULL; d++) {
uint32_t v = d->d_un.d_val;
switch (d->d_tag) {
case DT_SYMTAB: l->symtab = (const Elf32_Sym *)(uintptr_t)(l->base + v); break;
case DT_STRTAB: l->strtab = (const char *)(uintptr_t)(l->base + v); break;
case DT_HASH: l->hash = (const uint32_t *)(uintptr_t)(l->base + v); break;
case DT_GNU_HASH: l->gnu_hash = (const uint32_t *)(uintptr_t)(l->base + v); break;
case DT_REL: rel = v; break;
case DT_RELSZ: relsz = v; break;
case DT_JMPREL: jmprel = v; break;
case DT_PLTRELSZ: jmprelsz = v; break;
case DT_ANDROID_REL: arel = v; break;
case DT_ANDROID_RELSZ: arelsz = v; break;
case DT_ANDROID_RELR:
case DT_RELR_: relr = v; break;
case DT_ANDROID_RELRSZ:
case DT_RELRSZ_: relrsz = v; break;
case DT_NEEDED: nneeded++; break;
case DT_RELA: set_error("%s: RELA relocations on ARM32?", l->name); return NULL;
}
}
if (l->hash) l->nsyms = l->hash[1];
/* published before its dependencies load: a cycle finds it instead of loading it twice */
if (libs_tail) libs_tail->next = l;
else libs = l;
libs_tail = l;
l->needed = calloc(nneeded ? nneeded : 1, sizeof *l->needed);
for (Elf32_Dyn *d = l->dyn; d->d_tag != DT_NULL; d++) {
if (d->d_tag != DT_NEEDED) continue;
const char *dep = l->strtab + d->d_un.d_val;
lib *dl = load_lib(dep);
if (!dl) {
grt_log(5, "a32rt", "%s: needed library %s missing (%s)", l->name, dep, err_buf);
continue;
}
l->needed[l->nneeded++] = dl;
}
if ((relr && relrsz && (reloc_relr(l, relr, relrsz), 0)) || (arel && reloc_android(l, arel, arelsz)) ||
(rel && reloc_rel(l, rel, relsz)) || (jmprel && reloc_rel(l, jmprel, jmprelsz))) {
grt_log(6, "a32rt", "%s: relocation failed: %s", l->name, err_buf);
return NULL;
}
protect_lib(l);
grt_log(4, "a32rt", "loaded %s at 0x%08x (%u KiB)", l->path, l->start, l->size / 1024);
return l;
}
/* ------------------------------------------------------------------------------------------------ dl* API */
void *grt_dlopen(const char *name, int flags)
{
(void)flags;
if (!name) return &system_lib; /* the "main program": global lookup */
pthread_mutex_lock(&lock);
lib *l = load_lib(name);
if (l) init_lib(l);
pthread_mutex_unlock(&lock);
return l;
}
void *grt_dlsym(void *handle, const char *name)
{
uint32_t a = 0;
pthread_mutex_lock(&lock);
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || handle == &system_lib) {
for (lib *l = libs; l && !a; l = l->next) a = lib_sym_addr(l, name);
if (!a) a = grt_export(name);
} else {
a = resolve(handle, name);
}
pthread_mutex_unlock(&lock);
if (!a) set_error_quiet("undefined symbol: %s", name);
return (void *)(uintptr_t)a;
}
int grt_dlclose(void *handle)
{
(void)handle; /* libraries stay loaded (as bionic does for most of them) */
return 0;
}
char *grt_dlerror(void)
{
if (!err_set) return NULL;
err_set = 0;
return err_buf;
}
static lib *lib_at(uint32_t a)
{
for (lib *l = libs; l; l = l->next)
if (a >= l->start && a - l->start < l->size) return l;
return NULL;
}
/* number of entries in l's dynamic symbol table */
static uint32_t lib_nsyms(const lib *l)
{
uint32_t n = l->nsyms;
if (!n && l->gnu_hash) {
/* the highest symbol index in the GNU hash chains */
const uint32_t *g = l->gnu_hash;
uint32_t nb = g[0], so = g[1], bs = g[2];
const uint32_t *b = g + 4 + bs, *ch = b + nb;
for (uint32_t k = 0; k < nb; k++)
if (b[k] >= n) n = b[k];
if (n >= so)
while (!(ch[n - so] & 1)) n++;
n++;
}
return n;
}
/* The defined symbols of a library whose names start with prefix: a malloc'd array of (name, address) pairs,
* ended by a 0 name. For the host bridge (Java_* functions). */
uint32_t *grt_list_symbols(void *handle, const char *prefix)
{
lib *l = handle;
size_t plen = strlen(prefix), n = 0, cap = 16;
uint32_t *v = malloc(cap * 8);
pthread_mutex_lock(&lock);
if (l && l != &system_lib) {
uint32_t ns = lib_nsyms(l);
for (uint32_t k = 1; k < ns; k++) {
const Elf32_Sym *s = &l->symtab[k];
const char *nm = l->strtab + s->st_name;
if (!sym_defined(s) || strncmp(nm, prefix, plen)) continue;
if (n + 2 > cap) v = realloc(v, (cap *= 2) * 8);
v[2 * n] = (uint32_t)(uintptr_t)nm;
v[2 * n + 1] = l->base + s->st_value;
n++;
}
}
pthread_mutex_unlock(&lock);
v[2 * n] = v[2 * n + 1] = 0;
return v;
}
int grt_dladdr(const void *addr, Dl_info *info)
{
uint32_t a = (uint32_t)(uintptr_t)addr;
pthread_mutex_lock(&lock);
lib *l = lib_at(a);
if (!l) {
pthread_mutex_unlock(&lock);
return 0;
}
info->dli_fname = l->path;
info->dli_fbase = (void *)(uintptr_t)l->base;
info->dli_sname = NULL;
info->dli_saddr = NULL;
uint32_t best = 0;
uint32_t n = lib_nsyms(l);
for (uint32_t k = 1; k < n; k++) {
const Elf32_Sym *s = &l->symtab[k];
if (!sym_defined(s) || !s->st_value) continue;
uint32_t sa = l->base + s->st_value;
if (sa <= a && sa > best && (a - sa < s->st_size || !s->st_size)) {
best = sa;
info->dli_sname = l->strtab + s->st_name;
info->dli_saddr = (void *)(uintptr_t)sa;
}
}
pthread_mutex_unlock(&lock);
return 1;
}
int dl_iterate_phdr(int (*cb)(struct dl_phdr_info *, size_t, void *), void *data)
{
int r = 0;
for (lib *l = libs; l && !r; l = l->next) {
struct dl_phdr_info i;
memset(&i, 0, sizeof i);
i.dlpi_addr = l->base;
i.dlpi_name = l->path;
i.dlpi_phdr = l->phdr;
i.dlpi_phnum = (Elf32_Half)l->phnum;
r = cb(&i, sizeof i, data);
}
return r;
}
/* libc.a has its own dl_unwind_find_exidx, which only knows the runtime itself: the link wraps it (--wrap), so
* the runtime's unwinder sees guest libraries too */
uint32_t __real_dl_unwind_find_exidx(uint32_t pc, int *count);
uint32_t __wrap_dl_unwind_find_exidx(uint32_t pc, int *count)
{
lib *l = lib_at(pc);
if (!l) return __real_dl_unwind_find_exidx(pc, count);
if (!l->exidx) {
*count = 0;
return 0;
}
*count = (int)l->exidx_count;
return l->exidx;
}
/* the "(see bionic)" variants */
void *grt_android_dlopen_ext(const char *name, int flags, const void *extinfo)
{
(void)extinfo;
return grt_dlopen(name, flags);
}
void *grt_dlvsym(void *handle, const char *name, const char *version)
{
(void)version;
return grt_dlsym(handle, name);
}
+65
View File
@@ -0,0 +1,65 @@
/* liblog for guest libraries: formatted here, written by the host's liblog. */
#include <android/log.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "grt.h"
int __android_log_write(int prio, const char *tag, const char *msg)
{
grt_hc(HC_LOG, (uint32_t)prio, (uint32_t)(uintptr_t)(tag ? tag : ""), (uint32_t)(uintptr_t)(msg ? msg : ""), 0);
return 1;
}
int __android_log_vprint(int prio, const char *tag, const char *fmt, va_list ap)
{
char buf[1024];
vsnprintf(buf, sizeof buf, fmt, ap);
return __android_log_write(prio, tag, buf);
}
int __android_log_print(int prio, const char *tag, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
int r = __android_log_vprint(prio, tag, fmt, ap);
va_end(ap);
return r;
}
int __android_log_buf_write(int buf, int prio, const char *tag, const char *msg)
{
(void)buf;
return __android_log_write(prio, tag, msg);
}
int __android_log_buf_print(int buf, int prio, const char *tag, const char *fmt, ...)
{
(void)buf;
va_list ap;
va_start(ap, fmt);
int r = __android_log_vprint(prio, tag, fmt, ap);
va_end(ap);
return r;
}
void __android_log_assert(const char *cond, const char *tag, const char *fmt, ...)
{
char buf[1024];
if (fmt) {
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
} else {
snprintf(buf, sizeof buf, "assertion failed: %s", cond ? cond : "");
}
__android_log_write(ANDROID_LOG_FATAL, tag, buf);
abort();
}
int __android_log_is_loggable(int prio, const char *tag, int def)
{
(void)tag;
return prio >= def;
}
+83
View File
@@ -0,0 +1,83 @@
/* Runtime entry: started by the host bridge as `liba32rt.so <library dir>`. Starts the service thread, reports
* the addresses the host needs (HC_READY) and parks; from then on the host calls guest functions directly. */
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "grt.h"
extern const uint32_t grt_export_table[]; /* gen/exports.S: (name, address) pairs sorted by name */
extern const uint32_t grt_export_count;
extern const uint32_t grt_jni_env, grt_java_vm; /* gen/stubs.S */
uint32_t grt_export(const char *name)
{
uint32_t lo = 0, hi = grt_export_count;
while (lo < hi) {
uint32_t mid = (lo + hi) / 2;
int c = strcmp(name, (const char *)(uintptr_t)grt_export_table[2 * mid]);
if (!c) return grt_export_table[2 * mid + 1];
if (c < 0) hi = mid;
else lo = mid + 1;
}
return 0;
}
void grt_log(int prio, const char *tag, const char *fmt, ...)
{
char msg[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof msg, fmt, ap);
va_end(ap);
grt_hc(HC_LOG, (uint32_t)prio, (uint32_t)(uintptr_t)tag, (uint32_t)(uintptr_t)msg, 0);
}
/* a host thread adopted this guest thread (WORK_ATTACH): it only ever runs host-to-guest calls */
static void *attached_entry(void *arg)
{
(void)arg;
for (;;) grt_hc(HC_RETURN, 0, 0, 0, 0);
return NULL;
}
static void *service(void *arg)
{
(void)arg;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for (;;) {
uint32_t w = grt_hc(HC_WAIT_WORK, 0, 0, 0, 0);
if (w == WORK_ATTACH) {
pthread_t t;
int e = pthread_create(&t, &attr, attached_entry, NULL);
if (e) grt_log(6, "a32rt", "attach: pthread_create failed (%d)", e);
}
}
return NULL;
}
int main(int argc, char **argv)
{
if (argc > 1) loader_set_dir(argv[1]);
pthread_t svc;
if (pthread_create(&svc, NULL, service, NULL)) {
grt_hc(HC_ABORT, (uint32_t)(uintptr_t)"cannot start the service thread", 0, 0, 0);
return 1;
}
static struct grt_info info;
info.version = A32B_VERSION;
info.jni_env = (uint32_t)(uintptr_t)&grt_jni_env;
info.java_vm = (uint32_t)(uintptr_t)&grt_java_vm;
info.fn_malloc = (uint32_t)(uintptr_t)malloc;
info.fn_free = (uint32_t)(uintptr_t)free;
info.fn_dlopen = (uint32_t)(uintptr_t)grt_dlopen;
info.fn_dlsym = (uint32_t)(uintptr_t)grt_dlsym;
info.fn_dlerror = (uint32_t)(uintptr_t)grt_dlerror;
info.fn_attached_entry = (uint32_t)(uintptr_t)attached_entry;
info.fn_list_symbols = (uint32_t)(uintptr_t)grt_list_symbols;
grt_hc(HC_READY, (uint32_t)(uintptr_t)&info, 0, 0, 0);
for (;;) grt_hc(HC_RETURN, 0, 0, 0, 0);
}
@@ -0,0 +1,455 @@
/* OpenSL ES for guest code: the part audio engines use for output (an engine, an output mix and PCM audio players
* fed by an Android simple buffer queue), implemented here in the guest and played through the host's AAudio
* (a32_audio_*, host/android.c). OpenSL's objects are tables of function pointers, so keeping them on the guest side
* needs no thunks; each playing player has a guest thread that writes its queued buffers (blocking, which paces the
* queue like a real device) and calls the buffer-queue callback. Recording and everything else report "not
* supported". */
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <pthread.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "grt.h"
/* host/android.c (imports.txt) */
uint32_t a32_audio_open(int rate, int channels, int bits);
int a32_audio_write(uint32_t stream, const void *data, int frames);
void a32_audio_start(uint32_t stream);
void a32_audio_pause(uint32_t stream);
void a32_audio_close(uint32_t stream);
/* interface IDs: only their addresses matter (callers pass ours back) */
static const struct SLInterfaceID_ ids[] = {
{0xc7b1b6a0, 0, 0, 0, {0}}, {1, 0, 0, 0, {0}}, {2, 0, 0, 0, {0}}, {3, 0, 0, 0, {0}}, {4, 0, 0, 0, {0}},
{5, 0, 0, 0, {0}}, {6, 0, 0, 0, {0}}, {7, 0, 0, 0, {0}}, {8, 0, 0, 0, {0}}, {9, 0, 0, 0, {0}},
};
const SLInterfaceID SL_IID_NULL = &ids[0];
const SLInterfaceID SL_IID_OBJECT = &ids[1];
const SLInterfaceID SL_IID_ENGINE = &ids[2];
const SLInterfaceID SL_IID_PLAY = &ids[3];
const SLInterfaceID SL_IID_BUFFERQUEUE = &ids[4];
const SLInterfaceID SL_IID_ANDROIDSIMPLEBUFFERQUEUE = &ids[5];
const SLInterfaceID SL_IID_VOLUME = &ids[6];
const SLInterfaceID SL_IID_ANDROIDCONFIGURATION = &ids[7];
const SLInterfaceID SL_IID_RECORD = &ids[8];
const SLInterfaceID SL_IID_OUTPUTMIX = &ids[9];
enum { K_ENGINE, K_MIX, K_PLAYER };
#define QMAX 64
typedef struct obj {
const struct SLObjectItf_ *object;
const struct SLEngineItf_ *engine;
const struct SLPlayItf_ *play;
const struct SLAndroidSimpleBufferQueueItf_ *queue;
const struct SLVolumeItf_ *volume;
const struct SLAndroidConfigurationItf_ *config;
int kind;
SLuint32 state;
/* player */
int rate, channels, bits;
SLuint32 play_state;
slAndroidSimpleBufferQueueCallback qcb;
void *qctx;
slPlayCallback pcb;
void *pctx;
SLuint32 pmask;
struct { const void *data; SLuint32 size; } q[QMAX];
SLuint32 qhead, qcount, qindex;
SLmillibel level;
SLboolean mute;
uint32_t stream;
uint64_t frames_played;
pthread_t thread;
int quit, has_thread;
pthread_mutex_t lock;
pthread_cond_t cond;
} obj;
#define OBJ(self, field) ((obj *)((char *)(self) - offsetof(obj, field)))
/* ---------------------------------------------------------------- the player thread */
static void *player_thread(void *arg)
{
obj *o = arg;
pthread_mutex_lock(&o->lock);
for (;;) {
while (!o->quit && (o->play_state != SL_PLAYSTATE_PLAYING || !o->qcount)) pthread_cond_wait(&o->cond, &o->lock);
if (o->quit) break;
const void *data = o->q[o->qhead].data;
SLuint32 size = o->q[o->qhead].size;
pthread_mutex_unlock(&o->lock);
int frame = o->channels * o->bits / 8;
if (o->stream && frame) a32_audio_write(o->stream, data, (int)(size / (SLuint32)frame));
pthread_mutex_lock(&o->lock);
if (o->qcount && o->q[o->qhead].data == data) { /* not cleared meanwhile */
o->qhead = (o->qhead + 1) % QMAX;
o->qcount--;
o->qindex++;
o->frames_played += frame ? size / (SLuint32)frame : 0;
slAndroidSimpleBufferQueueCallback cb = o->qcb;
void *ctx = o->qctx;
pthread_mutex_unlock(&o->lock);
if (cb) cb((SLAndroidSimpleBufferQueueItf)&o->queue, ctx);
pthread_mutex_lock(&o->lock);
}
}
pthread_mutex_unlock(&o->lock);
return NULL;
}
/* ---------------------------------------------------------------- SLObjectItf */
static SLresult obj_realize(SLObjectItf self, SLboolean async)
{
obj *o = OBJ(self, object);
if (o->kind == K_PLAYER && !o->stream) {
o->stream = a32_audio_open(o->rate, o->channels, o->bits);
if (!o->stream) return SL_RESULT_RESOURCE_ERROR;
o->has_thread = !pthread_create(&o->thread, NULL, player_thread, o);
}
o->state = SL_OBJECT_STATE_REALIZED;
return SL_RESULT_SUCCESS;
}
static SLresult obj_resume(SLObjectItf self, SLboolean async) { return SL_RESULT_SUCCESS; }
static SLresult obj_get_state(SLObjectItf self, SLuint32 *state)
{
*state = OBJ(self, object)->state;
return SL_RESULT_SUCCESS;
}
static SLresult obj_get_interface(SLObjectItf self, const SLInterfaceID iid, void *out)
{
obj *o = OBJ(self, object);
void **p = out;
if (iid == SL_IID_OBJECT) *p = &o->object;
else if (iid == SL_IID_ENGINE && o->kind == K_ENGINE) *p = &o->engine;
else if (iid == SL_IID_PLAY && o->kind == K_PLAYER) *p = &o->play;
else if ((iid == SL_IID_ANDROIDSIMPLEBUFFERQUEUE || iid == SL_IID_BUFFERQUEUE) && o->kind == K_PLAYER) *p = &o->queue;
else if (iid == SL_IID_VOLUME && o->kind == K_PLAYER) *p = &o->volume;
else if (iid == SL_IID_ANDROIDCONFIGURATION && o->kind == K_PLAYER) *p = &o->config;
else return SL_RESULT_FEATURE_UNSUPPORTED;
return SL_RESULT_SUCCESS;
}
static SLresult obj_register_callback(SLObjectItf self, slObjectCallback cb, void *ctx) { return SL_RESULT_SUCCESS; }
static void obj_abort(SLObjectItf self) {}
static void obj_destroy(SLObjectItf self)
{
obj *o = OBJ(self, object);
if (o->kind == K_PLAYER) {
pthread_mutex_lock(&o->lock);
o->quit = 1;
pthread_cond_broadcast(&o->cond);
pthread_mutex_unlock(&o->lock);
if (o->has_thread) pthread_join(o->thread, NULL);
if (o->stream) a32_audio_close(o->stream);
}
pthread_mutex_destroy(&o->lock);
pthread_cond_destroy(&o->cond);
free(o);
}
static SLresult obj_set_priority(SLObjectItf self, SLint32 p, SLboolean pre) { return SL_RESULT_SUCCESS; }
static SLresult obj_get_priority(SLObjectItf self, SLint32 *p, SLboolean *pre)
{
*p = 0, *pre = SL_BOOLEAN_FALSE;
return SL_RESULT_SUCCESS;
}
static SLresult obj_set_loss(SLObjectItf self, SLint16 n, SLInterfaceID *ids_, SLboolean enabled)
{
return SL_RESULT_SUCCESS;
}
static const struct SLObjectItf_ object_itf = {obj_realize, obj_resume, obj_get_state, obj_get_interface,
obj_register_callback, obj_abort, obj_destroy, obj_set_priority,
obj_get_priority, obj_set_loss};
/* ---------------------------------------------------------------- SLPlayItf */
static SLresult play_set_state(SLPlayItf self, SLuint32 state)
{
obj *o = OBJ(self, play);
pthread_mutex_lock(&o->lock);
SLuint32 old = o->play_state;
o->play_state = state;
if (state == SL_PLAYSTATE_STOPPED) { /* stopping drops the queue */
o->qcount = 0;
o->frames_played = 0;
}
pthread_cond_broadcast(&o->cond);
pthread_mutex_unlock(&o->lock);
if (o->stream && old != state) {
if (state == SL_PLAYSTATE_PLAYING) a32_audio_start(o->stream);
else a32_audio_pause(o->stream);
}
return SL_RESULT_SUCCESS;
}
static SLresult play_get_state(SLPlayItf self, SLuint32 *state)
{
*state = OBJ(self, play)->play_state;
return SL_RESULT_SUCCESS;
}
static SLresult play_get_duration(SLPlayItf self, SLmillisecond *ms)
{
*ms = SL_TIME_UNKNOWN;
return SL_RESULT_SUCCESS;
}
static SLresult play_get_position(SLPlayItf self, SLmillisecond *ms)
{
obj *o = OBJ(self, play);
*ms = o->rate ? (SLmillisecond)(o->frames_played * 1000 / (uint64_t)o->rate) : 0;
return SL_RESULT_SUCCESS;
}
static SLresult play_register_callback(SLPlayItf self, slPlayCallback cb, void *ctx)
{
obj *o = OBJ(self, play);
o->pcb = cb, o->pctx = ctx;
return SL_RESULT_SUCCESS;
}
static SLresult play_set_mask(SLPlayItf self, SLuint32 mask)
{
OBJ(self, play)->pmask = mask;
return SL_RESULT_SUCCESS;
}
static SLresult play_get_mask(SLPlayItf self, SLuint32 *mask)
{
*mask = OBJ(self, play)->pmask;
return SL_RESULT_SUCCESS;
}
static SLresult play_set_ms(SLPlayItf self, SLmillisecond ms) { return SL_RESULT_SUCCESS; }
static SLresult play_clear(SLPlayItf self) { return SL_RESULT_SUCCESS; }
static SLresult play_get_ms(SLPlayItf self, SLmillisecond *ms)
{
*ms = 0;
return SL_RESULT_SUCCESS;
}
static const struct SLPlayItf_ play_itf = {play_set_state, play_get_state, play_get_duration, play_get_position,
play_register_callback, play_set_mask, play_get_mask, play_set_ms,
play_clear, play_get_ms, play_set_ms, play_get_ms};
/* ---------------------------------------------------------------- SLAndroidSimpleBufferQueueItf */
static SLresult queue_enqueue(SLAndroidSimpleBufferQueueItf self, const void *buf, SLuint32 size)
{
obj *o = OBJ(self, queue);
pthread_mutex_lock(&o->lock);
if (o->qcount == QMAX) {
pthread_mutex_unlock(&o->lock);
return SL_RESULT_BUFFER_INSUFFICIENT;
}
static int logged;
if (logged < 8 || logged % 2000 == 0)
grt_log(4, "a32sles", "enqueue #%d: %u bytes (%u ms), %u queued", logged, size,
o->rate && o->channels ? size * 1000u / (SLuint32)(o->rate * o->channels * 2) : 0, o->qcount);
logged++;
SLuint32 at = (o->qhead + o->qcount) % QMAX;
o->q[at].data = buf, o->q[at].size = size;
o->qcount++;
pthread_cond_broadcast(&o->cond);
pthread_mutex_unlock(&o->lock);
return SL_RESULT_SUCCESS;
}
static SLresult queue_clear(SLAndroidSimpleBufferQueueItf self)
{
obj *o = OBJ(self, queue);
pthread_mutex_lock(&o->lock);
o->qcount = 0;
pthread_mutex_unlock(&o->lock);
return SL_RESULT_SUCCESS;
}
static SLresult queue_get_state(SLAndroidSimpleBufferQueueItf self, SLAndroidSimpleBufferQueueState *st)
{
obj *o = OBJ(self, queue);
pthread_mutex_lock(&o->lock);
st->count = o->qcount, st->index = o->qindex;
pthread_mutex_unlock(&o->lock);
return SL_RESULT_SUCCESS;
}
static SLresult queue_register_callback(SLAndroidSimpleBufferQueueItf self, slAndroidSimpleBufferQueueCallback cb,
void *ctx)
{
obj *o = OBJ(self, queue);
o->qcb = cb, o->qctx = ctx;
return SL_RESULT_SUCCESS;
}
static const struct SLAndroidSimpleBufferQueueItf_ queue_itf = {queue_enqueue, queue_clear, queue_get_state,
queue_register_callback};
/* ---------------------------------------------------------------- SLVolumeItf (kept, not applied) */
static SLresult vol_set_level(SLVolumeItf self, SLmillibel l)
{
OBJ(self, volume)->level = l;
return SL_RESULT_SUCCESS;
}
static SLresult vol_get_level(SLVolumeItf self, SLmillibel *l)
{
*l = OBJ(self, volume)->level;
return SL_RESULT_SUCCESS;
}
static SLresult vol_get_max(SLVolumeItf self, SLmillibel *l)
{
*l = 0;
return SL_RESULT_SUCCESS;
}
static SLresult vol_set_mute(SLVolumeItf self, SLboolean m)
{
OBJ(self, volume)->mute = m;
return SL_RESULT_SUCCESS;
}
static SLresult vol_get_mute(SLVolumeItf self, SLboolean *m)
{
*m = OBJ(self, volume)->mute;
return SL_RESULT_SUCCESS;
}
static SLresult vol_enable_pos(SLVolumeItf self, SLboolean e) { return SL_RESULT_SUCCESS; }
static SLresult vol_is_pos(SLVolumeItf self, SLboolean *e)
{
*e = SL_BOOLEAN_FALSE;
return SL_RESULT_SUCCESS;
}
static SLresult vol_set_pos(SLVolumeItf self, SLpermille p) { return SL_RESULT_SUCCESS; }
static SLresult vol_get_pos(SLVolumeItf self, SLpermille *p)
{
*p = 0;
return SL_RESULT_SUCCESS;
}
static const struct SLVolumeItf_ volume_itf = {vol_set_level, vol_get_level, vol_get_max, vol_set_mute, vol_get_mute,
vol_enable_pos, vol_is_pos, vol_set_pos, vol_get_pos};
/* ---------------------------------------------------------------- SLAndroidConfigurationItf */
static SLresult cfg_set(SLAndroidConfigurationItf self, const SLchar *key, const void *value, SLuint32 size)
{
return SL_RESULT_SUCCESS;
}
static SLresult cfg_get(SLAndroidConfigurationItf self, const SLchar *key, SLuint32 *size, void *value)
{
return SL_RESULT_PARAMETER_INVALID;
}
static const struct SLAndroidConfigurationItf_ config_itf = {cfg_set, cfg_get};
/* ---------------------------------------------------------------- SLEngineItf */
static obj *new_obj(int kind)
{
obj *o = calloc(1, sizeof *o);
o->object = &object_itf;
o->kind = kind;
o->state = SL_OBJECT_STATE_UNREALIZED;
pthread_mutex_init(&o->lock, NULL);
pthread_cond_init(&o->cond, NULL);
return o;
}
static SLresult unsupported(void) { return SL_RESULT_FEATURE_UNSUPPORTED; }
static SLresult engine_create_player(SLEngineItf self, SLObjectItf *player, SLDataSource *src, SLDataSink *sink,
SLuint32 n, const SLInterfaceID *iids, const SLboolean *required)
{
SLuint32 loc = src && src->pLocator ? *(SLuint32 *)src->pLocator : 0;
SLuint32 fmt = src && src->pFormat ? *(SLuint32 *)src->pFormat : 0;
if ((loc != SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE && loc != SL_DATALOCATOR_BUFFERQUEUE) ||
(fmt != SL_DATAFORMAT_PCM && fmt != SL_ANDROID_DATAFORMAT_PCM_EX)) {
grt_log(5, "a32sles", "audio player source (locator %u, format %u) isn't supported", loc, fmt);
return SL_RESULT_CONTENT_UNSUPPORTED;
}
const SLDataFormat_PCM *pcm = src->pFormat;
if (fmt == SL_ANDROID_DATAFORMAT_PCM_EX && ((const SLAndroidDataFormat_PCM_EX *)pcm)->representation ==
SL_ANDROID_PCM_REPRESENTATION_FLOAT) {
grt_log(5, "a32sles", "float PCM isn't supported");
return SL_RESULT_CONTENT_UNSUPPORTED;
}
obj *o = new_obj(K_PLAYER);
o->play = &play_itf;
o->queue = &queue_itf;
o->volume = &volume_itf;
o->config = &config_itf;
o->rate = (int)(pcm->samplesPerSec / 1000); /* milliHz */
o->channels = (int)pcm->numChannels;
o->bits = (int)pcm->bitsPerSample;
o->play_state = SL_PLAYSTATE_STOPPED;
grt_log(4, "a32sles", "audio player: %d Hz, %d channels, %d bits", o->rate, o->channels, o->bits);
*player = (SLObjectItf)&o->object;
return SL_RESULT_SUCCESS;
}
static SLresult engine_create_mix(SLEngineItf self, SLObjectItf *mix, SLuint32 n, const SLInterfaceID *iids,
const SLboolean *required)
{
obj *o = new_obj(K_MIX);
*mix = (SLObjectItf)&o->object;
return SL_RESULT_SUCCESS;
}
static SLresult engine_query_num_ext(SLEngineItf self, SLuint32 *n)
{
*n = 0;
return SL_RESULT_SUCCESS;
}
static SLresult engine_is_ext(SLEngineItf self, const SLchar *name, SLboolean *supported)
{
*supported = SL_BOOLEAN_FALSE;
return SL_RESULT_SUCCESS;
}
static const struct SLEngineItf_ engine_itf = {
.CreateLEDDevice = (void *)unsupported,
.CreateVibraDevice = (void *)unsupported,
.CreateAudioPlayer = engine_create_player,
.CreateAudioRecorder = (void *)unsupported,
.CreateMidiPlayer = (void *)unsupported,
.CreateListener = (void *)unsupported,
.Create3DGroup = (void *)unsupported,
.CreateOutputMix = engine_create_mix,
.CreateMetadataExtractor = (void *)unsupported,
.CreateExtensionObject = (void *)unsupported,
.QueryNumSupportedInterfaces = (void *)unsupported,
.QuerySupportedInterfaces = (void *)unsupported,
.QueryNumSupportedExtensions = engine_query_num_ext,
.QuerySupportedExtension = (void *)unsupported,
.IsExtensionSupported = engine_is_ext,
};
SLresult slCreateEngine(SLObjectItf *engine, SLuint32 n_opts, const SLEngineOption *opts, SLuint32 n,
const SLInterfaceID *iids, const SLboolean *required)
{
obj *o = new_obj(K_ENGINE);
o->engine = &engine_itf;
*engine = (SLObjectItf)&o->object;
return SL_RESULT_SUCCESS;
}
SLresult slQueryNumSupportedEngineInterfaces(SLuint32 *n)
{
*n = 1;
return SL_RESULT_SUCCESS;
}
SLresult slQuerySupportedEngineInterfaces(SLuint32 index, SLInterfaceID *id)
{
if (index) return SL_RESULT_PARAMETER_INVALID;
*id = SL_IID_ENGINE;
return SL_RESULT_SUCCESS;
}
@@ -0,0 +1,48 @@
/* Public API of the host bridge (liba32bridge.so), used by the per-library stubs (stub.c) and the PC harness.
*
* A converted APK keeps every 32-bit library libX.so as libX.a32.so next to the 64-bit ones. libX.so itself
* becomes a copy of the stub, which forwards JNI_OnLoad and ANativeActivity_onCreate to the bridge. The bridge
* runs the guest runtime (liba32rt.so, from the same folder) in this process and loads the guest libraries into
* it. */
#ifndef A32BRIDGE_H
#define A32BRIDGE_H
#include <jni.h>
#include <stddef.h>
#include <stdint.h>
#define A32B_API __attribute__((visibility("default")))
#ifdef __cplusplus
extern "C" {
#endif
struct ANativeActivity;
/* Starts the guest runtime once (later calls return at once). libdir holds liba32rt.so and the guest libraries.
* Returns 0 on success. */
A32B_API int a32b_init(JavaVM *vm, const char *libdir);
/* Loads the guest library for the stub at stub_path (".../libX.so" -> guest libX.so). Returns a guest handle, 0 on
* failure. */
A32B_API uint32_t a32b_load(const char *stub_path);
/* What a stub's JNI_OnLoad does: init, load, the guest JNI_OnLoad, then registers the library's exported Java_*
* functions with their classes. Returns the JNI version for ART (JNI_ERR on failure). */
A32B_API jint a32b_jni_onload(JavaVM *vm, const char *stub_path);
/* What a stub's ANativeActivity_onCreate does (the guest library's own ANativeActivity_onCreate). */
A32B_API void a32b_native_activity_oncreate(struct ANativeActivity *activity, void *saved, size_t saved_size,
const char *stub_path);
/* Address of a guest symbol (0 if none). */
A32B_API uint32_t a32b_sym(uint32_t handle, const char *name);
/* Calls a guest function (AAPCS words: 64-bit values as an even-aligned pair). Returns r0 | r1 << 32. */
A32B_API uint64_t a32b_call(uint32_t fn, const uint32_t *words, int n);
#ifdef __cplusplus
}
#endif
#endif
+332
View File
@@ -0,0 +1,332 @@
/* libandroid functions that gen_stubs.py can't generate (imports.txt "!" lines). */
#include <android/sensor.h>
#include <stdlib.h>
#include "imports_internal.h"
extern __typeof__(ASensorManager_getSensorList) ASensorManager_getSensorList __attribute__((weak));
extern __typeof__(ASensorManager_createEventQueue) ASensorManager_createEventQueue __attribute__((weak));
/* the list is an array of host pointers: the guest gets an array of handles (made once per call; tiny) */
void imp_ASensorManager_getSensorList(a32_cpu *c, argreader *R)
{
ASensorManager *m = h2ptr(rd32(R));
uint32_t out = rd32(R);
ASensorList list = NULL;
int n = ASensorManager_getSensorList ? ASensorManager_getSensorList(m, &list) : 0;
uint32_t g = guest_malloc(n > 0 ? 4u * (uint32_t)n : 4);
for (int k = 0; k < n && g; k++) st32(g + 4u * (uint32_t)k, ptr2h((void *)list[k]));
if (out) st32(out, g);
ret32(c, (uint32_t)n);
}
void imp_ASensorManager_createEventQueue(a32_cpu *c, argreader *R)
{
ASensorManager *m = h2ptr(rd32(R));
ALooper *looper = h2ptr(rd32(R));
int ident = (int)rd32(R);
uint32_t cb = rd32(R), data = rd32(R);
if (cb) bridge_log(ANDROID_LOG_WARN, "ASensorManager_createEventQueue: guest callbacks aren't supported yet");
ASensorEventQueue *q = ASensorManager_createEventQueue ? ASensorManager_createEventQueue(m, looper, ident, NULL, g2p(data)) : NULL;
ret32(c, ptr2h(q));
}
/* ---------------------------------------------------------------- audio output (guest/opensles.c) */
#include <aaudio/AAudio.h>
#define W(f) extern __typeof__(f) f __attribute__((weak))
W(AAudio_createStreamBuilder); W(AAudioStreamBuilder_setSampleRate); W(AAudioStreamBuilder_setChannelCount);
W(AAudioStreamBuilder_setFormat); W(AAudioStreamBuilder_setPerformanceMode); W(AAudioStreamBuilder_openStream);
W(AAudioStreamBuilder_delete); W(AAudioStream_requestStart); W(AAudioStream_requestPause);
W(AAudioStream_requestFlush); W(AAudioStream_write); W(AAudioStream_close); W(AAudio_convertResultToText);
W(AAudioStream_setBufferSizeInFrames); W(AAudioStream_getBufferCapacityInFrames); W(AAudioStream_getXRunCount);
#undef W
typedef struct {
AAudioStream *stream;
int frame_bytes;
} audio_out;
void imp_a32_audio_open(a32_cpu *c, argreader *R)
{
int rate = (int)rd32(R), channels = (int)rd32(R), bits = (int)rd32(R);
AAudioStreamBuilder *b = NULL;
if (!AAudio_createStreamBuilder || bits != 16 || AAudio_createStreamBuilder(&b) != AAUDIO_OK) {
bridge_log(ANDROID_LOG_ERROR, "audio: can't open a %d Hz, %d channel, %d bit stream", rate, channels, bits);
ret32(c, 0);
return;
}
AAudioStreamBuilder_setSampleRate(b, rate);
AAudioStreamBuilder_setChannelCount(b, channels);
AAudioStreamBuilder_setFormat(b, AAUDIO_FORMAT_PCM_I16);
/* a roomy buffer: the guest's mixer is fed back through the translator and would underrun a low-latency one */
AAudioStreamBuilder_setPerformanceMode(b, AAUDIO_PERFORMANCE_MODE_NONE);
AAudioStream *s = NULL;
aaudio_result_t r = AAudioStreamBuilder_openStream(b, &s);
AAudioStreamBuilder_delete(b);
if (r != AAUDIO_OK) {
bridge_log(ANDROID_LOG_ERROR, "audio: AAudio open failed: %s", AAudio_convertResultToText(r));
ret32(c, 0);
return;
}
/* ~40 ms: writes block at the device's pace. A larger buffer let the player thread drain the guest's queue
* faster than real time, and the guest's mixer (FMOD) fell behind: crackling */
if (AAudioStream_setBufferSizeInFrames) AAudioStream_setBufferSizeInFrames(s, rate / 25);
audio_out *o = calloc(1, sizeof *o);
o->stream = s;
o->frame_bytes = channels * 2;
bridge_log(ANDROID_LOG_INFO, "audio: %d Hz, %d channels through AAudio", rate, channels);
ret32(c, ptr2h(o));
}
/* blocking, like a full OpenSL buffer queue: this paces the guest's audio thread */
void imp_a32_audio_write(a32_cpu *c, argreader *R)
{
audio_out *o = h2ptr(rd32(R));
const void *data = g2p(rd32(R));
int frames = (int)rd32(R);
aaudio_result_t r = o ? AAudioStream_write(o->stream, data, frames, 1000000000LL) : 0;
static int xruns;
if (o && AAudioStream_getXRunCount) {
int x = AAudioStream_getXRunCount(o->stream);
if (x > xruns && (xruns < 20 || x % 100 == 0)) bridge_log(ANDROID_LOG_WARN, "audio: %d underruns", x);
xruns = x;
}
ret32(c, (uint32_t)r);
}
void imp_a32_audio_start(a32_cpu *c, argreader *R)
{
audio_out *o = h2ptr(rd32(R));
if (o) AAudioStream_requestStart(o->stream);
}
void imp_a32_audio_pause(a32_cpu *c, argreader *R)
{
audio_out *o = h2ptr(rd32(R));
if (o) AAudioStream_requestPause(o->stream);
}
void imp_a32_audio_close(a32_cpu *c, argreader *R)
{
audio_out *o = h2ptr(rd32(R));
if (!o) return;
AAudioStream_close(o->stream);
free(o);
}
/* ---------------------------------------------------------------- looper, input queue, assets (native_app_glue) */
#include <android/asset_manager.h>
#include <dlfcn.h>
#include <pthread.h>
#include <string.h>
#include <android/input.h>
#include <android/looper.h>
#define W(f) extern __typeof__(f) f __attribute__((weak))
W(ALooper_addFd); W(ALooper_pollOnce); W(AInputQueue_attachLooper); W(AInputQueue_getEvent); W(ALooper_forThread);
W(AAssetDir_getNextFileName); W(AAsset_openFileDescriptor); W(AAsset_openFileDescriptor64);
W(AAsset_getBuffer); W(AAsset_getLength64); W(AAsset_close);
#undef W
/* a guest ALooper callback int (*)(int fd, int events, void *data), called on the polling (guest) thread */
typedef struct {
uint32_t fn, data;
} looper_cb;
static int looper_call(int fd, int events, void *p)
{
looper_cb *cb = p;
uint32_t w[3] = {(uint32_t)fd, (uint32_t)events, cb->data};
return (int)guest_call(cb->fn, w, 3);
}
/* host data for a guest (callback, data) pair: the callback's own record (kept: the looper may call it until the
* fd is removed), or the guest's data pointer itself when there is no callback */
static void *looper_data(uint32_t fn, uint32_t data, ALooper_callbackFunc *host_fn)
{
*host_fn = NULL;
if (!fn) return g2p(data);
looper_cb *cb = malloc(sizeof *cb);
if (!cb) return NULL;
cb->fn = fn, cb->data = data;
*host_fn = looper_call;
return cb;
}
void imp_ALooper_addFd(a32_cpu *c, argreader *R)
{
ALooper *l = h2ptr(rd32(R));
int fd = (int)rd32(R), ident = (int)rd32(R), events = (int)rd32(R);
uint32_t fn = rd32(R), data = rd32(R);
ALooper_callbackFunc host_fn;
void *d = looper_data(fn, data, &host_fn);
ret32(c, ALooper_addFd ? (uint32_t)ALooper_addFd(l, fd, ident, events, host_fn, d) : (uint32_t)-1);
}
void imp_AInputQueue_attachLooper(a32_cpu *c, argreader *R)
{
AInputQueue *q = h2ptr(rd32(R));
ALooper *l = h2ptr(rd32(R));
int ident = (int)rd32(R);
uint32_t fn = rd32(R), data = rd32(R);
ALooper_callbackFunc host_fn;
void *d = looper_data(fn, data, &host_fn);
if (AInputQueue_attachLooper) AInputQueue_attachLooper(q, l, ident, host_fn, d);
input_queue_attached(q, l, ident, data, fn != 0); /* the controllers' synthetic events go here (input.c) */
}
/* outData is a void ** (4 bytes on the guest side); data without a callback is the guest's own pointer */
static void poll(a32_cpu *c, argreader *R, int all)
{
int timeout = (int)rd32(R);
uint32_t out_fd = rd32(R), out_events = rd32(R), out_data = rd32(R);
int fd = 0, events = 0;
void *data = NULL;
/* a synthetic input event waits (input.c): the input queue's ident, like a readable queue fd */
int ident;
uint32_t gdata;
if (input_queue_pending(ALooper_forThread(), &ident, &gdata)) {
if (out_fd) st32(out_fd, (uint32_t)-1);
if (out_events) st32(out_events, ALOOPER_EVENT_INPUT);
if (out_data) st32(out_data, gdata);
ret32(c, (uint32_t)ident);
return;
}
/* ALooper_pollAll: removed from the NDK headers (it may miss wakes), still in libandroid for old apps */
static int (*poll_all)(int, int *, int *, void **);
if (all && !poll_all) poll_all = (int (*)(int, int *, int *, void **))dlsym(RTLD_DEFAULT, "ALooper_pollAll");
int (*f)(int, int *, int *, void **) = all ? poll_all : ALooper_pollOnce;
int r = f ? f(timeout, &fd, &events, &data) : ALOOPER_POLL_ERROR;
if (out_fd) st32(out_fd, (uint32_t)fd);
if (out_events) st32(out_events, (uint32_t)events);
if (out_data) st32(out_data, (uint32_t)(uintptr_t)data);
ret32(c, (uint32_t)r);
}
void imp_ALooper_pollAll(a32_cpu *c, argreader *R) { poll(c, R, 1); }
void imp_ALooper_pollOnce(a32_cpu *c, argreader *R) { poll(c, R, 0); }
void imp_AInputQueue_getEvent(a32_cpu *c, argreader *R)
{
AInputQueue *q = h2ptr(rd32(R));
uint32_t out = rd32(R);
AInputEvent *e = input_queue_pop(q); /* synthetic controller events first */
int r = e ? 0 : AInputQueue_getEvent ? AInputQueue_getEvent(q, &e) : -1;
if (out) st32(out, r >= 0 ? ptr2h(e) : 0);
ret32(c, (uint32_t)r);
}
/* the name is valid until the next call: one guest buffer, refilled each time */
void imp_AAssetDir_getNextFileName(a32_cpu *c, argreader *R)
{
AAssetDir *d = h2ptr(rd32(R));
const char *name = AAssetDir_getNextFileName ? AAssetDir_getNextFileName(d) : NULL;
static uint32_t buf;
static size_t size;
size_t n = name ? strlen(name) + 1 : 0;
if (n > size) {
guest_free(buf);
size = n < 256 ? 256 : n;
buf = guest_malloc((uint32_t)size);
if (!buf) size = 0;
}
if (n && buf) memcpy(g2p(buf), name, n);
ret32(c, n && buf ? buf : 0);
}
/* off_t is 32-bit for the guest (AAsset_openFileDescriptor) and 64-bit in the 64 variant */
static void open_fd(a32_cpu *c, argreader *R, int wide)
{
AAsset *a = h2ptr(rd32(R));
uint32_t out_start = rd32(R), out_len = rd32(R);
off64_t start = 0, len = 0;
int fd = AAsset_openFileDescriptor64 ? AAsset_openFileDescriptor64(a, &start, &len) : -1;
if (wide) {
if (out_start) memcpy(g2p(out_start), &start, 8);
if (out_len) memcpy(g2p(out_len), &len, 8);
} else {
if (start > 0x7fffffff || len > 0x7fffffff)
bridge_log(ANDROID_LOG_WARN, "AAsset_openFileDescriptor: offset/length past 2 GiB for a 32-bit app");
if (out_start) st32(out_start, (uint32_t)start);
if (out_len) st32(out_len, (uint32_t)len);
}
ret32(c, (uint32_t)fd);
}
void imp_AAsset_openFileDescriptor(a32_cpu *c, argreader *R) { open_fd(c, R, 0); }
void imp_AAsset_openFileDescriptor64(a32_cpu *c, argreader *R) { open_fd(c, R, 1); }
/* AAsset_getBuffer's memory is the host's (above 4 GiB): the guest gets a copy in its own memory, kept until
* AAsset_close like the original (Unreal reads small config/text assets this way) */
typedef struct asset_buf {
struct asset_buf *next;
AAsset *asset;
uint32_t buf;
} asset_buf;
static pthread_mutex_t asset_lock = PTHREAD_MUTEX_INITIALIZER;
static asset_buf *asset_bufs;
void imp_AAsset_getBuffer(a32_cpu *c, argreader *R)
{
AAsset *a = h2ptr(rd32(R));
uint32_t g = 0;
pthread_mutex_lock(&asset_lock);
for (asset_buf *b = asset_bufs; b; b = b->next)
if (b->asset == a) g = b->buf;
pthread_mutex_unlock(&asset_lock);
if (g || !a || !AAsset_getBuffer) {
ret32(c, g);
return;
}
const void *p = AAsset_getBuffer(a);
off64_t len = p ? AAsset_getLength64(a) : 0;
if (!p || len < 0 || len > 0x40000000) {
if (p) bridge_log(ANDROID_LOG_WARN, "AAsset_getBuffer: %lld bytes is too big for a 32-bit app", (long long)len);
ret32(c, 0);
return;
}
asset_buf *b = malloc(sizeof *b);
g = b ? guest_malloc(len ? (uint32_t)len : 1) : 0;
if (!g) {
free(b);
bridge_log(ANDROID_LOG_WARN, "AAsset_getBuffer: no guest memory for %lld bytes", (long long)len);
ret32(c, 0);
return;
}
memcpy(g2p(g), p, (size_t)len);
b->asset = a, b->buf = g;
pthread_mutex_lock(&asset_lock);
b->next = asset_bufs, asset_bufs = b;
pthread_mutex_unlock(&asset_lock);
ret32(c, g);
}
void imp_AAsset_close(a32_cpu *c, argreader *R)
{
AAsset *a = h2ptr(rd32(R));
asset_buf *found = NULL;
pthread_mutex_lock(&asset_lock);
for (asset_buf **pp = &asset_bufs; *pp; pp = &(*pp)->next)
if ((*pp)->asset == a) {
found = *pp;
*pp = found->next;
break;
}
pthread_mutex_unlock(&asset_lock);
if (found) {
guest_free(found->buf);
free(found);
}
if (a && AAsset_close) AAsset_close(a);
}
/* logged: a game that quits by itself shows it here */
void imp_ANativeActivity_finish(a32_cpu *c, argreader *R)
{
ANativeActivity *a = guest_activity(rd32(R));
bridge_log(ANDROID_LOG_INFO, "guest called ANativeActivity_finish");
if (a) ANativeActivity_finish(a);
}
+553
View File
@@ -0,0 +1,553 @@
/* Host side of the bridge: runs the guest runtime (liba32rt.so) inside this process, dispatches its hypercalls
* and calls guest functions on behalf of host threads.
*
* Threads: the thread that calls a32b_init becomes the guest's main thread. Any other host thread that calls into
* the guest first gets a guest thread of its own: the runtime's service thread pthread_creates one (WORK_ATTACH)
* and the clone hands it to the waiting host thread (threads.c, thread_adopt), which then owns it for good. Guest
* threads (pthread_create in guest code) are host pthreads with their guest context from the start. A host-to-guest
* call saves the thread's guest state, runs the function until it returns to A32_RETURN_TRAMPOLINE (hypercall
* HC_RETURN), and restores the state: calls nest (Java -> guest -> JNI -> Java -> guest ...). */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <android/log.h>
#include "a32bridge.h"
#include "imports_internal.h"
#include "../../src/signals.h"
struct grt_info g_info;
JavaVM *g_vm;
static pthread_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER;
static volatile int ready;
/* ---------------------------------------------------------------- logging */
static void log_write(int prio, const char *tag, const char *msg)
{
#ifdef A32B_STDERR_LOG
fprintf(stderr, "%c/%s: %s\n", "??VDIWEF"[prio & 7], tag, msg);
#else
__android_log_write(prio, tag, msg);
#endif
}
void bridge_log(int prio, const char *fmt, ...)
{
char msg[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof msg, fmt, ap);
va_end(ap);
log_write(prio, "a32bridge", msg);
}
void a32_report(const char *fmt, ...)
{
char msg[512];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof msg, fmt, ap);
va_end(ap);
log_write(ANDROID_LOG_WARN, "a32", msg);
}
JNIEnv *host_env(void)
{
JNIEnv *env = NULL;
if (!g_vm || (*g_vm)->GetEnv(g_vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) return NULL;
return env;
}
#ifndef A32B_STDERR_LOG
/* The translator reports guest crashes and internal errors on stderr, which is /dev/null in an app: forward it to
* the system log. */
static void *stderr_pump(void *arg)
{
FILE *f = fdopen((int)(intptr_t)arg, "r");
char line[1024];
while (f && fgets(line, sizeof line, f)) {
line[strcspn(line, "\n")] = 0;
log_write(ANDROID_LOG_WARN, "a32", line);
}
return NULL;
}
static void forward_stderr(void)
{
int p[2];
if (pipe2(p, O_CLOEXEC)) return;
dup2(p[1], 2);
close(p[1]);
setvbuf(stderr, NULL, _IOLBF, 0);
pthread_t t;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&t, &attr, stderr_pump, (void *)(intptr_t)p[0]);
pthread_attr_destroy(&attr);
}
#endif
/* A32_WATCH=<seconds>: logs every guest thread's pc/lr periodically, plus the return-address candidates on its
* stack (words pointing into executable guest libraries, as lib+offset): where a game hangs or spins. Threads in
* translated code are asked to leave it first, so their registers are current. */
typedef struct {
uint32_t lo, hi, off;
char name[48];
} xmap;
static int exec_maps(xmap *m, int max)
{
FILE *f = fopen("/proc/self/maps", "re");
int n = 0;
char line[512];
while (f && n < max && fgets(line, sizeof line, f)) {
unsigned long long lo, hi, off;
char perms[8], path[400] = "";
if (sscanf(line, "%llx-%llx %7s %llx %*s %*s %399s", &lo, &hi, perms, &off, path) < 4) continue;
size_t pl = strlen(path);
if (hi > 0x100000000ull || pl < 3 || strcmp(path + pl - 3, ".so")) continue; /* guest code isn't host-executable */
const char *b = strrchr(path, '/');
m[n].lo = (uint32_t)lo, m[n].hi = (uint32_t)hi, m[n].off = (uint32_t)off;
snprintf(m[n].name, sizeof m[n].name, "%s", b ? b + 1 : path);
n++;
}
if (f) fclose(f);
return n;
}
static int describe(const xmap *m, int n, uint32_t a, char *out, size_t sz)
{
for (int k = 0; k < n; k++)
if (a >= m[k].lo && a < m[k].hi) {
snprintf(out, sz, "%s+%x", m[k].name, a - m[k].lo + m[k].off);
return 1;
}
return 0;
}
/* return addresses found on a guest stack (lib+offset), for logs */
static size_t stack_scan(const xmap *maps, int nm, uint32_t sp, char *bt, size_t sz)
{
size_t k = 0;
int found = 0;
for (uint32_t a = sp & ~3u, e = a + 4096; a < e && found < 10 && mem_readable(a, 4); a += 4) {
char d[64];
uint32_t w = ld32(a);
if ((w & 1) || ((w & 3) == 0)) /* Thumb return addresses are odd, ARM ones word-aligned */
if (describe(maps, nm, (w & ~1u) - 2, d, sizeof d) && k + 70 < sz) {
k += (size_t)snprintf(bt + k, sz - k, " %s", d);
found++;
}
}
return k;
}
/* logs where the current guest call came from: its return address and a scan of the stack */
void guest_backtrace(a32_cpu *c, const char *what)
{
static xmap maps[256];
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&m);
int nm = exec_maps(maps, 256);
char lr[64] = "?", bt[600] = "";
describe(maps, nm, c->r[14] & ~1u, lr, sizeof lr);
stack_scan(maps, nm, c->r[13], bt, sizeof bt);
pthread_mutex_unlock(&m);
bridge_log(ANDROID_LOG_INFO, "%s: called from %s |%s", what, lr, bt);
}
static void *watch(void *arg)
{
int secs = (int)(intptr_t)arg;
static xmap maps[256];
for (;;) {
sleep((unsigned)secs);
threads_interrupt_all();
usleep(2000);
int nm = exec_maps(maps, 256);
for (a32_thread *t = thread_main(); t; t = t->next) {
char pc[64] = "?", lr[64] = "?", bt[600] = "";
describe(maps, nm, t->cpu.r[15], pc, sizeof pc);
describe(maps, nm, t->cpu.r[14] & ~1u, lr, sizeof lr);
stack_scan(maps, nm, t->cpu.r[13], bt, sizeof bt);
char comm[32] = "", cp[64];
snprintf(cp, sizeof cp, "/proc/self/task/%d/comm", t->tid);
FILE *cf = fopen(cp, "re");
if (cf) {
if (fgets(comm, sizeof comm, cf)) comm[strcspn(comm, "\n")] = 0;
fclose(cf);
}
bridge_log(ANDROID_LOG_INFO, "watch: tid %d %s pc %s lr %s r0 %08x%s |%s", t->tid, comm, pc, lr, t->cpu.r[0],
t->in_guest ? " running" : "", bt);
}
}
return NULL;
}
/* ---------------------------------------------------------------- guest threads for host threads */
static pthread_mutex_t wq_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t wq_cond = PTHREAD_COND_INITIALIZER;
static a32_adopt *wq[64];
static int wq_n;
/* the calling host thread's guest thread (created on first use) */
static a32_thread *guest_thread(void)
{
if (g_self) return g_self;
a32_adopt ad;
memset(&ad, 0, sizeof ad);
pthread_mutex_lock(&wq_lock);
while (wq_n == (int)(sizeof wq / sizeof *wq)) pthread_cond_wait(&wq_cond, &wq_lock);
wq[wq_n++] = &ad;
pthread_cond_broadcast(&wq_cond);
pthread_mutex_unlock(&wq_lock);
thread_adopt(&ad);
a32_thread *t = g_self;
t->cpu.thread = t;
/* the new guest thread starts in bionic's thread entry and parks in attached_entry (HC_RETURN) */
run_guest(&t->cpu);
t->in_host = 1;
return t;
}
/* HC_WAIT_WORK, on the service thread */
static uint32_t wait_work(void)
{
pthread_mutex_lock(&wq_lock);
while (!wq_n) pthread_cond_wait(&wq_cond, &wq_lock);
a32_adopt *ad = wq[0];
memmove(wq, wq + 1, (size_t)--wq_n * sizeof *wq);
pthread_cond_broadcast(&wq_cond);
pthread_mutex_unlock(&wq_lock);
g_clone_adopt = ad; /* the service thread's next clone (its pthread_create) goes to ad */
return WORK_ATTACH;
}
/* ---------------------------------------------------------------- calls into the guest */
typedef struct {
uint32_t r[16], nzcv, q, ge, thumb, itstate, fpscr_nzcv, fpcr, fpsr, excl_valid;
uint64_t d[32];
} saved_regs;
static void save_regs(const a32_cpu *c, saved_regs *s)
{
memcpy(s->r, c->r, sizeof s->r);
s->nzcv = c->nzcv, s->q = c->q, s->ge = c->ge, s->thumb = c->thumb, s->itstate = c->itstate;
s->fpscr_nzcv = c->fpscr_nzcv, s->fpcr = c->fpcr, s->fpsr = c->fpsr, s->excl_valid = c->excl_valid;
memcpy(s->d, c->d, sizeof s->d);
}
static void restore_regs(a32_cpu *c, const saved_regs *s)
{
memcpy(c->r, s->r, sizeof s->r);
c->nzcv = s->nzcv, c->q = s->q, c->ge = s->ge, c->thumb = s->thumb, c->itstate = s->itstate;
c->fpscr_nzcv = s->fpscr_nzcv, c->fpcr = s->fpcr, c->fpsr = s->fpsr, c->excl_valid = s->excl_valid;
memcpy(c->d, s->d, sizeof s->d);
}
uint64_t guest_call(uint32_t fn, const uint32_t *words, int n)
{
a32_thread *t = guest_thread();
a32_cpu *c = &t->cpu;
saved_regs s;
save_regs(c, &s);
int nstack = n > 4 ? n - 4 : 0;
/* below the interrupted code's stack pointer: everything there is free */
uint32_t sp = (c->r[13] - 64 - 4u * (uint32_t)nstack) & ~7u;
for (int k = 0; k < nstack; k++) st32(sp + 4u * (uint32_t)k, words[4 + k]);
for (int k = 0; k < 4; k++) c->r[k] = k < n ? words[k] : 0;
c->r[13] = sp;
c->r[14] = A32_RETURN_TRAMPOLINE;
c->r[15] = fn & ~1u;
c->thumb = fn & 1;
c->itstate = 0;
c->last_exit = 0; /* never chain the interrupted code's last exit to the callee */
int in_host = t->in_host;
t->in_host = 0;
run_guest(c);
t->in_host = in_host;
uint64_t r = c->r[0] | (uint64_t)c->r[1] << 32;
restore_regs(c, &s);
c->last_exit = 0;
return r;
}
uint32_t guest_malloc(uint32_t size)
{
return (uint32_t)guest_call(g_info.fn_malloc, &size, 1);
}
void guest_free(uint32_t p)
{
if (p) guest_call(g_info.fn_free, &p, 1);
}
uint32_t guest_strdup(const char *s)
{
size_t n = strlen(s) + 1;
uint32_t p = guest_malloc((uint32_t)n);
if (p) memcpy(g2p(p), s, n);
return p;
}
uint32_t guest_cstr(const char *s)
{
static struct { const char *host; uint32_t guest; } cache[256];
static int n;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
if (!s) return 0;
if (in_guest_reach(s, strlen(s) + 1)) return p2g(s);
pthread_mutex_lock(&m);
for (int k = 0; k < n; k++)
if (cache[k].host == s) {
uint32_t g = cache[k].guest;
pthread_mutex_unlock(&m);
return g;
}
pthread_mutex_unlock(&m);
uint32_t g = guest_strdup(s);
pthread_mutex_lock(&m);
if (n < 256) cache[n].host = s, cache[n++].guest = g;
pthread_mutex_unlock(&m);
return g;
}
A32B_API uint64_t a32b_call(uint32_t fn, const uint32_t *words, int n) { return guest_call(fn, words, n); }
/* ---------------------------------------------------------------- hypercalls */
/* gl.c; the PC harness has no GLES */
__attribute__((weak)) int gl_dispatch(a32_cpu *c, int index, argreader *R)
{
(void)c, (void)index, (void)R;
return 0;
}
static void unresolved(const char *name)
{
/* once per name: games call missing optional functions in loops */
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static char *seen[256];
static int nseen;
pthread_mutex_lock(&m);
for (int k = 0; k < nseen; k++)
if (!strcmp(seen[k], name)) {
pthread_mutex_unlock(&m);
return;
}
if (nseen < 256) seen[nseen++] = strdup(name);
pthread_mutex_unlock(&m);
bridge_log(ANDROID_LOG_ERROR, "guest called %s, which no library defines (returned 0)", name);
}
static void hypercall(a32_cpu *c, uint32_t n);
/* while a hypercall runs host code, guest signals for this thread are delivered at once (signals.c) */
void a32_hypercall(a32_cpu *c, uint32_t n)
{
a32_thread *t = c->thread;
int in_host = t->in_host;
t->in_host = 1;
hypercall(c, n);
t->in_host = in_host;
}
static void hypercall(a32_cpu *c, uint32_t n)
{
a32_thread *t = c->thread;
switch (n) {
case HC_RETURN:
t->stop = 1;
return;
case HC_READY:
memcpy(&g_info, g2p(c->r[0]), sizeof g_info);
t->stop = 1;
return;
case HC_WAIT_WORK:
c->r[0] = wait_work();
return;
case HC_LOG:
log_write((int)c->r[0], c->r[1] ? (const char *)g2p(c->r[1]) : "", c->r[2] ? (const char *)g2p(c->r[2]) : "");
return;
case HC_UNRESOLVED:
unresolved((const char *)g2p(c->r[0]));
c->r[0] = c->r[1] = 0;
return;
case HC_ABORT:
bridge_log(ANDROID_LOG_FATAL, "guest runtime: %s", (const char *)g2p(c->r[0]));
abort();
}
if (n >= HC_JNI && n < HC_JNI + JNI_TABLE_SIZE && jni_dispatch(c, (int)(n - HC_JNI))) return;
if (n >= HC_VM && n < HC_VM + VM_TABLE_SIZE && vm_dispatch(c, (int)(n - HC_VM))) return;
if (n >= HC_GL && n < HC_GL + 0x1000) {
argreader R;
ar_init(&R, c, 0, c->r[13] + 8);
if (gl_dispatch(c, (int)(n - HC_GL), &R)) return;
}
if (n >= HC_IMPORT && n < HC_IMPORT + 0x100) {
argreader R;
ar_init(&R, c, 0, c->r[13] + 8); /* the stub pushed {r7, lr} */
if (import_dispatch(c, (int)(n - HC_IMPORT), &R)) return;
unresolved(import_names[n - HC_IMPORT]);
c->r[0] = c->r[1] = 0;
return;
}
bridge_log(ANDROID_LOG_ERROR, "unknown hypercall 0x%x", n);
c->r[0] = (uint32_t)-ENOSYS;
}
/* ---------------------------------------------------------------- start-up and libraries */
extern char **environ;
A32B_API int a32b_init(JavaVM *vm, const char *libdir)
{
if (ready) return 0;
pthread_mutex_lock(&init_lock);
if (ready) {
pthread_mutex_unlock(&init_lock);
return 0;
}
g_vm = vm;
opt_bridge = 1;
#ifndef A32B_STDERR_LOG
forward_stderr();
#endif
if (getenv("A32_INTERP")) opt_interp = 1;
if (getenv("A32_STRACE")) opt_strace = 1;
if (getenv("A32_BREAK")) {
char *p = getenv("A32_BREAK");
for (int b = 0; b < 4 && *p; b++) {
a32_break_pc[b] = (uint32_t)strtoul(p, &p, 0);
if (*p == ',') p++;
}
}
if (getenv("A32_VERBOSE")) opt_verbose = 1;
a32_thread *t = thread_main();
g_self = t;
t->tid = (int)syscall(__NR_gettid);
t->cpu.thread = t;
int r = -1;
if (mem_init()) {
bridge_log(ANDROID_LOG_FATAL, "cannot set up the guest address space");
goto out;
}
signals_init();
static char rt[PATH_MAX], dir[PATH_MAX];
snprintf(dir, sizeof dir, "%s", libdir);
snprintf(rt, sizeof rt, "%s/liba32rt.so", libdir);
char *argv[] = {rt, dir, NULL};
load_args la = {rt, NULL, 2, argv, environ};
if (load_program(&la, &t->cpu)) {
bridge_log(ANDROID_LOG_FATAL, "cannot load the guest runtime %s", rt);
goto out;
}
t->cpu.thread = t;
run_guest(&t->cpu); /* until HC_READY */
if (g_info.version != A32B_VERSION) {
bridge_log(ANDROID_LOG_FATAL, "guest runtime version %u, bridge %u", g_info.version, A32B_VERSION);
goto out;
}
t->in_host = 1;
bridge_log(ANDROID_LOG_INFO, "guest runtime ready (%s, %s)", rt, opt_interp ? "interpreter" : "JIT");
if (getenv("A32_WATCH")) {
pthread_t w;
pthread_create(&w, NULL, watch, (void *)(intptr_t)atoi(getenv("A32_WATCH")));
}
ready = 1;
r = 0;
out:
pthread_mutex_unlock(&init_lock);
return r;
}
static const char *base_name(const char *p)
{
const char *s = strrchr(p, '/');
return s ? s + 1 : p;
}
A32B_API uint32_t a32b_load(const char *stub_path)
{
if (!ready) return 0;
uint32_t name = guest_strdup(base_name(stub_path));
uint32_t w[2] = {name, 2 /* RTLD_NOW */};
uint32_t h = (uint32_t)guest_call(g_info.fn_dlopen, w, 2);
if (!h) {
uint32_t e = (uint32_t)guest_call(g_info.fn_dlerror, NULL, 0);
bridge_log(ANDROID_LOG_ERROR, "cannot load the guest library %s: %s", base_name(stub_path),
e ? (const char *)g2p(e) : "?");
}
guest_free(name);
return h;
}
A32B_API uint32_t a32b_sym(uint32_t handle, const char *name)
{
uint32_t gn = guest_strdup(name);
uint32_t w[2] = {handle, gn};
uint32_t a = (uint32_t)guest_call(g_info.fn_dlsym, w, 2);
guest_free(gn);
return a;
}
static int dir_of(const char *path, char *out, size_t n)
{
const char *s = strrchr(path, '/');
if (!s) return snprintf(out, n, "."), 0;
snprintf(out, n, "%.*s", (int)(s - path), path);
return 0;
}
A32B_API jint a32b_jni_onload(JavaVM *vm, const char *stub_path)
{
char dir[PATH_MAX];
dir_of(stub_path, dir, sizeof dir);
if (a32b_init(vm, dir)) return JNI_ERR;
uint32_t h = a32b_load(stub_path);
if (!h) return JNI_ERR;
jint ver = JNI_VERSION_1_6;
uint32_t fn = a32b_sym(h, "JNI_OnLoad");
if (fn) {
uint32_t w[2] = {g_info.java_vm, 0};
ver = (jint)guest_call(fn, w, 2);
bridge_log(ANDROID_LOG_INFO, "%s: JNI_OnLoad returned 0x%x", base_name(stub_path), ver);
}
JNIEnv *env = host_env();
if (env) natives_register_java(env, h, base_name(stub_path));
return ver;
}
A32B_API void a32b_native_activity_oncreate(struct ANativeActivity *activity, void *saved, size_t saved_size,
const char *stub_path)
{
char dir[PATH_MAX];
dir_of(stub_path, dir, sizeof dir);
if (a32b_init(activity->vm, dir)) abort();
uint32_t h = a32b_load(stub_path);
uint32_t fn = h ? a32b_sym(h, "ANativeActivity_onCreate") : 0;
if (!fn) {
bridge_log(ANDROID_LOG_FATAL, "%s has no ANativeActivity_onCreate", base_name(stub_path));
abort();
}
activity_create(activity, saved, saved_size, fn);
}
/* A32_BREAK: where the guest came from */
void a32_break_hit(a32_cpu *c)
{
char what[40];
snprintf(what, sizeof what, "A32_BREAK %08x", c->r[15]);
guest_backtrace(c, what);
}
+388
View File
@@ -0,0 +1,388 @@
/* GLES/EGL for guest code: function lookup, GLsync handles, driver strings, buffer mappings, and the functions
* gen_gl.py leaves to hand-written code (pointer arrays, host pointers as results, callbacks). Everything else is
* generated (gen/gl.c). */
#include <dlfcn.h>
#include <stdlib.h>
#define GL_GLEXT_PROTOTYPES 1
#define EGL_EGLEXT_PROTOTYPES 1
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl32.h>
#include <GLES2/gl2ext.h>
#include "gl_internal.h"
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
/* ---------------------------------------------------------------- function lookup */
#define MISSING ((void *)1)
static void **fns;
static void *lookup(const char *name)
{
static void *gles, *egl;
static void *(*get_proc)(const char *);
if (!egl) {
egl = dlopen("libEGL.so", RTLD_NOW);
gles = dlopen("libGLESv3.so", RTLD_NOW);
if (!gles) gles = dlopen("libGLESv2.so", RTLD_NOW);
get_proc = egl ? (void *(*)(const char *))dlsym(egl, "eglGetProcAddress") : NULL;
}
void *f = gles ? dlsym(gles, name) : NULL;
if (!f && egl) f = dlsym(egl, name);
if (!f && get_proc) f = get_proc(name);
return f;
}
static void *fn_at(int index)
{
void *f = __atomic_load_n(&fns[index], __ATOMIC_ACQUIRE);
if (!f) {
f = lookup(gl_names[index]);
if (!f) f = MISSING;
__atomic_store_n(&fns[index], f, __ATOMIC_RELEASE);
}
return f == MISSING ? NULL : f;
}
/* a host function by name, for the hand-written code */
static void *host_fn(const char *name)
{
for (int k = 0; k < gl_count; k++)
if (!strcmp(gl_names[k], name)) return fn_at(k);
return lookup(name);
}
static void once_per_name(const char *what, const char *name)
{
static const char *seen[512];
static int n;
pthread_mutex_lock(&lock);
for (int k = 0; k < n; k++)
if (seen[k] == name) {
pthread_mutex_unlock(&lock);
return;
}
if (n < 512) seen[n++] = name;
pthread_mutex_unlock(&lock);
bridge_log(ANDROID_LOG_WARN, "%s %s (returned 0)", what, name);
}
int gl_dispatch(a32_cpu *c, int index, argreader *R)
{
if (index < 0 || index >= gl_count) return 0;
if (!fns) {
pthread_mutex_lock(&lock);
if (!fns) fns = calloc((size_t)gl_count, sizeof *fns);
pthread_mutex_unlock(&lock);
}
void *f = fn_at(index);
if (f && gl_dispatch_generated(c, index, R, f)) return 1;
once_per_name(f ? "the bridge doesn't support" : "the system has no", gl_names[index]);
c->r[0] = c->r[1] = 0;
return 1;
}
/* ---------------------------------------------------------------- GLsync handles */
static void **syncs;
static uint32_t nsyncs, capsyncs, sync_free_list; /* index + 1 */
uint32_t sync2h(void *s)
{
if (!s) return 0;
pthread_mutex_lock(&lock);
uint32_t i;
if (sync_free_list) {
i = sync_free_list - 1;
sync_free_list = (uint32_t)(uintptr_t)syncs[i];
} else {
if (nsyncs == capsyncs) syncs = realloc(syncs, (capsyncs = capsyncs ? capsyncs * 2 : 64) * sizeof *syncs);
i = nsyncs++;
}
syncs[i] = s;
pthread_mutex_unlock(&lock);
return (i + 1) << 2 | 1; /* odd: never mistaken for another kind of handle in logs */
}
void *h2sync(uint32_t h)
{
if (!h) return NULL;
uint32_t i = (h >> 2) - 1;
pthread_mutex_lock(&lock);
void *s = i < nsyncs ? syncs[i] : NULL;
pthread_mutex_unlock(&lock);
return s;
}
static void sync_release(uint32_t h)
{
uint32_t i = (h >> 2) - 1;
pthread_mutex_lock(&lock);
if (h && i < nsyncs) {
syncs[i] = (void *)(uintptr_t)sync_free_list;
sync_free_list = i + 1;
}
pthread_mutex_unlock(&lock);
}
void gl_glDeleteSync(a32_cpu *c, argreader *R, void *fn)
{
uint32_t h = rd32(R);
((__typeof__(&glDeleteSync))fn)((GLsync)h2sync(h));
sync_release(h);
}
/* ---------------------------------------------------------------- strings */
uint32_t gl_guest_string(const char *s) { return guest_cstr(s); }
void gl_glGetString(a32_cpu *c, argreader *R, void *fn)
{
GLenum name = (GLenum)rd32(R);
ret32(c, gl_guest_string((const char *)((__typeof__(&glGetString))fn)(name)));
}
void gl_glGetStringi(a32_cpu *c, argreader *R, void *fn)
{
GLenum name = (GLenum)rd32(R);
GLuint index = (GLuint)rd32(R);
ret32(c, gl_guest_string((const char *)((__typeof__(&glGetStringi))fn)(name, index)));
}
void gl_eglQueryString(a32_cpu *c, argreader *R, void *fn)
{
EGLDisplay dpy = h2ptr(rd32(R));
EGLint name = (EGLint)rd32(R);
ret32(c, gl_guest_string(((__typeof__(&eglQueryString))fn)(dpy, name)));
}
/* ---------------------------------------------------------------- pointer arrays */
static const GLchar **string_array(uint32_t g, GLsizei n)
{
const GLchar **v = calloc(n > 0 ? (size_t)n : 1, sizeof *v);
for (GLsizei k = 0; k < n; k++) v[k] = g2p(ld32(g + 4u * (uint32_t)k));
return v;
}
void gl_glShaderSource(a32_cpu *c, argreader *R, void *fn)
{
GLuint shader = rd32(R);
GLsizei count = (GLsizei)rd32(R);
uint32_t strings = rd32(R);
const GLint *length = g2p(rd32(R));
const GLchar **v = string_array(strings, count);
((__typeof__(&glShaderSource))fn)(shader, count, v, length);
free(v);
}
void gl_glTransformFeedbackVaryings(a32_cpu *c, argreader *R, void *fn)
{
GLuint program = rd32(R);
GLsizei count = (GLsizei)rd32(R);
const GLchar **v = string_array(rd32(R), count);
GLenum mode = rd32(R);
((__typeof__(&glTransformFeedbackVaryings))fn)(program, count, v, mode);
free(v);
}
void gl_glGetUniformIndices(a32_cpu *c, argreader *R, void *fn)
{
GLuint program = rd32(R);
GLsizei count = (GLsizei)rd32(R);
const GLchar **v = string_array(rd32(R), count);
GLuint *indices = g2p(rd32(R));
((__typeof__(&glGetUniformIndices))fn)(program, count, v, indices);
free(v);
}
static void configs_out(uint32_t gconfigs, EGLConfig *cfg, EGLint n)
{
for (EGLint k = 0; k < n; k++) st32(gconfigs + 4u * (uint32_t)k, ptr2h(cfg[k]));
}
void gl_eglChooseConfig(a32_cpu *c, argreader *R, void *fn)
{
EGLDisplay dpy = h2ptr(rd32(R));
const EGLint *attrib = g2p(rd32(R));
uint32_t gconfigs = rd32(R);
EGLint size = (EGLint)rd32(R);
EGLint *num = g2p(rd32(R));
EGLConfig *cfg = gconfigs && size > 0 ? calloc((size_t)size, sizeof *cfg) : NULL;
EGLBoolean r = ((__typeof__(&eglChooseConfig))fn)(dpy, attrib, cfg, cfg ? size : 0, num);
if (r && cfg) configs_out(gconfigs, cfg, *num < size ? *num : size);
free(cfg);
ret32(c, r);
}
void gl_eglGetConfigs(a32_cpu *c, argreader *R, void *fn)
{
EGLDisplay dpy = h2ptr(rd32(R));
uint32_t gconfigs = rd32(R);
EGLint size = (EGLint)rd32(R);
EGLint *num = g2p(rd32(R));
EGLConfig *cfg = gconfigs && size > 0 ? calloc((size_t)size, sizeof *cfg) : NULL;
EGLBoolean r = ((__typeof__(&eglGetConfigs))fn)(dpy, cfg, cfg ? size : 0, num);
if (r && cfg) configs_out(gconfigs, cfg, *num < size ? *num : size);
free(cfg);
ret32(c, r);
}
/* ---------------------------------------------------------------- callbacks */
void gl_glDebugMessageCallback(a32_cpu *c, argreader *R, void *fn)
{
(void)c, (void)R, (void)fn;
once_per_name("ignored (guest callbacks aren't supported yet):", "glDebugMessageCallback");
}
void gl_glDebugMessageCallbackKHR(a32_cpu *c, argreader *R, void *fn) { gl_glDebugMessageCallback(c, R, fn); }
/* ---------------------------------------------------------------- buffer mappings */
/* A mapping the guest can't reach (driver memory above 4 GiB) gets a guest copy: filled when mapped for reading,
* written back at flush/unmap when mapped for writing. One per (context, buffer object): GL maps buffers, not
* targets, and an app may keep several buffers of one target mapped (Unity's dynamic vertex buffers); keyed by the
* target, a second map dropped the first one's copy (never freed, never written back: garbage vertices). */
typedef struct {
EGLContext ctx;
GLuint buffer;
uint8_t *host;
uint32_t guest;
uint32_t len;
GLbitfield access;
} mapping;
#define MAX_MAPS 256
static mapping maps[MAX_MAPS];
static mapping *find_map(EGLContext ctx, GLuint buffer)
{
for (int k = 0; k < MAX_MAPS; k++)
if (maps[k].host && maps[k].ctx == ctx && maps[k].buffer == buffer) return &maps[k];
return NULL;
}
static EGLContext current_context(void)
{
static __typeof__(&eglGetCurrentContext) f;
if (!f) f = (__typeof__(f))host_fn("eglGetCurrentContext");
return f ? f() : NULL;
}
/* the buffer object bound to a buffer target */
static GLuint bound_buffer(GLenum target)
{
GLenum binding;
switch (target) {
case 0x8892: binding = 0x8894; break; /* ARRAY_BUFFER */
case 0x8893: binding = 0x8895; break; /* ELEMENT_ARRAY_BUFFER */
case 0x8A11: binding = 0x8A28; break; /* UNIFORM_BUFFER */
case 0x88EB: binding = 0x88ED; break; /* PIXEL_PACK_BUFFER */
case 0x88EC: binding = 0x88EF; break; /* PIXEL_UNPACK_BUFFER */
case 0x8C8E: binding = 0x8C8F; break; /* TRANSFORM_FEEDBACK_BUFFER */
case 0x90D2: binding = 0x90D3; break; /* SHADER_STORAGE_BUFFER */
case 0x8F3F: binding = 0x8F43; break; /* DRAW_INDIRECT_BUFFER */
case 0x90EE: binding = 0x90EF; break; /* DISPATCH_INDIRECT_BUFFER */
case 0x92C0: binding = 0x92C1; break; /* ATOMIC_COUNTER_BUFFER */
case 0x8C2A: binding = 0x8C2C; break; /* TEXTURE_BUFFER */
default: binding = target; break; /* COPY_READ/WRITE_BUFFER: the binding has the target's value */
}
static __typeof__(&glGetIntegerv) gi;
if (!gi) gi = (__typeof__(gi))host_fn("glGetIntegerv");
GLint name = 0;
if (gi) gi(binding, &name);
return (GLuint)name;
}
static uint32_t map_result(GLenum target, void *p, uint32_t len, GLbitfield access)
{
if (!p) return 0;
if (in_guest_reach(p, len)) return p2g(p);
uint32_t g = guest_malloc(len ? len : 1);
if (!g) return 0;
if (access & GL_MAP_READ_BIT) memcpy(g2p(g), p, len);
GLuint buffer = bound_buffer(target);
uint32_t stale = 0;
pthread_mutex_lock(&lock);
EGLContext ctx = current_context();
mapping *m = find_map(ctx, buffer);
if (m) stale = m->guest; /* mapped again without an unmap (the GL error case): the old copy goes */
if (!m)
for (int k = 0; k < MAX_MAPS && !m; k++)
if (!maps[k].host) m = &maps[k];
if (m) *m = (mapping){ctx, buffer, p, g, len, access};
pthread_mutex_unlock(&lock);
if (stale) guest_free(stale);
if (!m) {
static int full;
if (!full++) bridge_log(ANDROID_LOG_ERROR, "glMapBuffer: more than %d buffers mapped at once", MAX_MAPS);
guest_free(g);
return 0;
}
return g;
}
void gl_glMapBufferRange(a32_cpu *c, argreader *R, void *fn)
{
GLenum target = rd32(R);
GLintptr offset = (int32_t)rd32(R);
GLsizeiptr length = (int32_t)rd32(R);
GLbitfield access = rd32(R);
void *p = ((__typeof__(&glMapBufferRange))fn)(target, offset, length, access);
ret32(c, map_result(target, p, (uint32_t)length, access));
}
void gl_glMapBufferRangeEXT(a32_cpu *c, argreader *R, void *fn) { gl_glMapBufferRange(c, R, fn); }
void gl_glMapBufferOES(a32_cpu *c, argreader *R, void *fn)
{
GLenum target = rd32(R);
GLenum access = rd32(R);
GLint size = 0;
__typeof__(&glGetBufferParameteriv) gp = (__typeof__(gp))host_fn("glGetBufferParameteriv");
if (gp) gp(target, GL_BUFFER_SIZE, &size);
void *p = ((__typeof__(&glMapBufferOES))fn)(target, access);
ret32(c, map_result(target, p, (uint32_t)size, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT));
}
/* copies a mapping's guest data back (whole range, or [off, off+len) for an explicit flush) */
static void write_back(GLenum target, uint32_t off, uint32_t len, int unmap)
{
GLuint buffer = bound_buffer(target);
pthread_mutex_lock(&lock);
mapping *m = find_map(current_context(), buffer);
mapping copy;
if (m) {
copy = *m;
if (unmap) m->host = NULL;
}
pthread_mutex_unlock(&lock);
if (!m) return;
if (copy.access & GL_MAP_WRITE_BIT) {
if (unmap) off = 0, len = copy.len;
if (off < copy.len) memcpy(copy.host + off, g2p(copy.guest + off), len > copy.len - off ? copy.len - off : len);
}
if (unmap) guest_free(copy.guest);
}
void gl_glFlushMappedBufferRange(a32_cpu *c, argreader *R, void *fn)
{
GLenum target = rd32(R);
GLintptr offset = (int32_t)rd32(R);
GLsizeiptr length = (int32_t)rd32(R);
write_back(target, (uint32_t)offset, (uint32_t)length, 0);
((__typeof__(&glFlushMappedBufferRange))fn)(target, offset, length);
}
void gl_glFlushMappedBufferRangeEXT(a32_cpu *c, argreader *R, void *fn) { gl_glFlushMappedBufferRange(c, R, fn); }
void gl_glUnmapBuffer(a32_cpu *c, argreader *R, void *fn)
{
GLenum target = rd32(R);
write_back(target, 0, 0, 1);
ret32(c, ((__typeof__(&glUnmapBuffer))fn)(target));
}
void gl_glUnmapBufferOES(a32_cpu *c, argreader *R, void *fn) { gl_glUnmapBuffer(c, R, fn); }
@@ -0,0 +1,17 @@
/* GLES/EGL for guest code (gl.c, gen/gl.c). */
#ifndef A32B_GL_INTERNAL_H
#define A32B_GL_INTERNAL_H
#include "imports_internal.h"
/* gen/gl.c */
extern const int gl_count;
extern const char *const gl_names[];
int gl_dispatch_generated(a32_cpu *c, int index, argreader *R, void *fn);
/* gl.c */
uint32_t sync2h(void *s); /* GLsync handles: freed by glDeleteSync */
void *h2sync(uint32_t h);
uint32_t gl_guest_string(const char *s); /* a guest copy of a driver string (kept for good) */
#endif
+191
View File
@@ -0,0 +1,191 @@
/* Handle tables: 32-bit guest values for 64-bit host references, method/field IDs and other pointers. */
#include <pthread.h>
#include <stdlib.h>
#include "jni_internal.h"
enum { K_FREE, K_LOCAL, K_GLOBAL, K_WEAK, K_KEEP };
typedef struct {
void *p;
uint32_t serial;
uint8_t kind;
} slot;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static slot *objs;
static uint32_t nobjs, capobjs, freelist = 0; /* freelist: index + 1 of a free slot (p holds the next) */
static uint32_t serial_ctr;
/* per thread: the local handles created on it (index, serial), popped with the native frame */
static __thread struct { uint32_t *v; uint32_t n, cap; } locals;
static uint32_t new_obj(void *p, uint8_t kind)
{
if (!p) return 0;
pthread_mutex_lock(&lock);
uint32_t i;
if (freelist) {
i = freelist - 1;
freelist = (uint32_t)(uintptr_t)objs[i].p;
} else {
if (nobjs == capobjs) {
capobjs = capobjs ? capobjs * 2 : 1024;
objs = realloc(objs, capobjs * sizeof *objs);
}
i = nobjs++;
}
objs[i].p = p;
objs[i].kind = kind;
objs[i].serial = ++serial_ctr;
uint32_t serial = objs[i].serial;
pthread_mutex_unlock(&lock);
if (kind == K_LOCAL) {
if (locals.n + 2 > locals.cap) {
locals.cap = locals.cap ? locals.cap * 2 : 256;
locals.v = realloc(locals.v, locals.cap * sizeof *locals.v);
}
locals.v[locals.n++] = i;
locals.v[locals.n++] = serial;
}
return (i + 1) << 2;
}
uint32_t o2h_local(jobject o) { return new_obj(o, K_LOCAL); }
uint32_t o2h_global(jobject o) { return new_obj(o, K_GLOBAL); }
uint32_t o2h_weak(jobject o) { return new_obj(o, K_WEAK); }
uint32_t o2h_keep(jobject o) { return new_obj(o, K_KEEP); }
jobject h2o(uint32_t h)
{
if (!h) return NULL;
uint32_t i = (h >> 2) - 1;
pthread_mutex_lock(&lock);
void *p = i < nobjs && objs[i].kind != K_FREE ? objs[i].p : NULL;
pthread_mutex_unlock(&lock);
if (!p) bridge_log(6, "invalid object handle 0x%x", h);
return p;
}
static void free_slot(uint32_t i)
{
objs[i].kind = K_FREE;
objs[i].p = (void *)(uintptr_t)freelist;
freelist = i + 1;
}
void h_free(uint32_t h)
{
if (!h) return;
uint32_t i = (h >> 2) - 1;
pthread_mutex_lock(&lock);
if (i < nobjs && objs[i].kind != K_FREE) free_slot(i);
pthread_mutex_unlock(&lock);
}
uint32_t frame_mark(void) { return locals.n; }
void frame_pop(uint32_t mark)
{
if (locals.n <= mark) return;
pthread_mutex_lock(&lock);
for (uint32_t k = mark; k + 1 < locals.n; k += 2) {
uint32_t i = locals.v[k], serial = locals.v[k + 1];
if (i < nobjs && objs[i].kind == K_LOCAL && objs[i].serial == serial) free_slot(i);
}
pthread_mutex_unlock(&lock);
locals.n = mark;
}
/* ---------------------------------------------------------------- IDs and pointers: stable, never freed */
typedef struct {
void *p;
char *shorty;
} idslot;
typedef struct {
idslot *v;
uint32_t n, cap;
uint32_t *hash; /* open addressing: index + 1 */
uint32_t hcap;
} idtab;
static idtab mids, fids, ptrs;
static uint32_t hashp(void *p) { return (uint32_t)(((uintptr_t)p * 0x9e3779b97f4a7c15ull) >> 32); }
static uint32_t id_get(idtab *t, void *p)
{
if (!p) return 0;
pthread_mutex_lock(&lock);
if (t->n * 2 >= t->hcap) {
uint32_t nc = t->hcap ? t->hcap * 2 : 1024;
uint32_t *nh = calloc(nc, 4);
for (uint32_t k = 0; k < t->n; k++) {
uint32_t j = hashp(t->v[k].p) & (nc - 1);
while (nh[j]) j = (j + 1) & (nc - 1);
nh[j] = k + 1;
}
free(t->hash);
t->hash = nh;
t->hcap = nc;
}
uint32_t j = hashp(p) & (t->hcap - 1);
while (t->hash[j]) {
if (t->v[t->hash[j] - 1].p == p) {
uint32_t h = t->hash[j] << 2;
pthread_mutex_unlock(&lock);
return h;
}
j = (j + 1) & (t->hcap - 1);
}
if (t->n == t->cap) {
t->cap = t->cap ? t->cap * 2 : 512;
t->v = realloc(t->v, t->cap * sizeof *t->v);
}
t->v[t->n].p = p;
t->v[t->n].shorty = NULL;
t->hash[j] = ++t->n;
uint32_t h = t->n << 2;
pthread_mutex_unlock(&lock);
return h;
}
static idslot *id_slot(idtab *t, uint32_t h)
{
uint32_t i = (h >> 2) - 1;
return h && i < t->n ? &t->v[i] : NULL;
}
static void *id_ptr(idtab *t, uint32_t h)
{
pthread_mutex_lock(&lock);
idslot *s = id_slot(t, h);
void *p = s ? s->p : NULL;
pthread_mutex_unlock(&lock);
return p;
}
uint32_t mid2h(jmethodID m) { return id_get(&mids, m); }
jmethodID h2mid(uint32_t h) { return id_ptr(&mids, h); }
uint32_t fid2h(jfieldID f) { return id_get(&fids, f); }
jfieldID h2fid(uint32_t h) { return id_ptr(&fids, h); }
uint32_t ptr2h(void *p) { return id_get(&ptrs, p); }
void *h2ptr(uint32_t h) { return id_ptr(&ptrs, h); }
void mid_set_shorty(uint32_t h, const char *shorty)
{
pthread_mutex_lock(&lock);
idslot *s = id_slot(&mids, h);
if (s && !s->shorty) s->shorty = strdup(shorty);
pthread_mutex_unlock(&lock);
}
const char *mid_shorty(uint32_t h)
{
pthread_mutex_lock(&lock);
idslot *s = id_slot(&mids, h);
const char *r = s ? s->shorty : NULL;
pthread_mutex_unlock(&lock);
return r;
}
@@ -0,0 +1,37 @@
/* Host side of the bridge: libandroid imports, NativeActivity glue and native method registration. */
#ifndef A32B_IMPORTS_INTERNAL_H
#define A32B_IMPORTS_INTERNAL_H
#include <android/native_activity.h>
#include <android/native_window.h>
#include "jni_internal.h"
/* bridge.c: logs the current guest call's caller (lib+offset) and the return addresses on its stack */
void guest_backtrace(a32_cpu *c, const char *what);
/* gen/imports.c (from imports.txt) */
int import_dispatch(a32_cpu *c, int index, argreader *R);
extern const char *const import_names[];
/* gl.c: GLES/EGL (HC_GL + index); 0 if the function is unknown */
int gl_dispatch(a32_cpu *c, int index, argreader *R);
/* native_activity.c */
ANativeActivity *guest_activity(uint32_t g); /* the host activity behind a guest ANativeActivity * */
void activity_create(ANativeActivity *a, void *saved, size_t saved_size, uint32_t oncreate);
extern volatile int g_window_w, g_window_h; /* the activity's window size (0 before it exists) */
/* input.c: synthetic input events for NativeActivity guests (Unreal: native_app_glue reads its AInputQueue) */
void input_queue_attached(void *queue, void *looper, int ident, uint32_t data, int has_callback);
void input_queue_detached(void *queue);
/* a synthetic event is waiting for the queue attached to this looper: its ident and guest poll data */
int input_queue_pending(void *looper, int *ident, uint32_t *data);
void *input_queue_pop(void *queue); /* the next synthetic AInputEvent of this queue, or NULL */
/* natives.c: registers the exported Java_* functions of a guest library with their classes */
void natives_register_java(JNIEnv *env, uint32_t handle, const char *libname);
/* a host function pointer that calls guest function fn with the JNI signature sig ("(IJ)V") */
void *natives_trampoline(uint32_t fn, const char *sig);
void *natives_trampoline_named(uint32_t fn, const char *sig, const char *name); /* name: for tracing */
#endif
+568
View File
@@ -0,0 +1,568 @@
/* Controller input for Gear VR-era games. They read the headset's touchpad and back button and Bluetooth gamepads
* as Android input events (Unity: mouse/touch, Escape, joystick buttons and axes). A thread polls the Frame's
* controllers through the 64-bit VrApi bridge and turns them into such events, handed to the game the way Android
* would: NativeActivity games (Unreal, native_app_glue) get them in their AInputQueue (synthetic AInputEvents the
* AInputQueue, AInputEvent, AKeyEvent and AMotionEvent imports know), Unity games through
* UnityPlayer.injectEvent, others through the activity's dispatchKeyEvent. Off with A32_NO_INPUT=1.
*
* Gear VR had a touchpad on the headset (tap, hold, swipe) and a back button; games that took a gamepad read it too:
* right trigger -> touchpad held (Gear VR games: walk), A -> a short tap
* right stick -> a swipe in that direction (flick it); NativeActivity games: up/down = swipe forward/back
* B, left menu -> back (Unity: Escape)
* X, Y, sticks -> gamepad X/Y, joystick axes X/Y (left) and Z/RZ (right), as a real gamepad if there is one */
#include <android/input.h>
#include <android/looper.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "imports_internal.h"
/* weak like the generated imports (the PC test harness has no libandroid) */
#define W(f) extern __typeof__(f) f __attribute__((weak))
W(ALooper_wake); W(AInputQueue_detachLooper); W(AInputQueue_hasEvents); W(AInputQueue_preDispatchEvent);
W(AInputQueue_finishEvent); W(AInputEvent_getType); W(AInputEvent_getDeviceId); W(AInputEvent_getSource);
W(AKeyEvent_getAction); W(AKeyEvent_getKeyCode); W(AKeyEvent_getMetaState); W(AKeyEvent_getRepeatCount); W(AKeyEvent_getFlags);
W(AMotionEvent_getAction); W(AMotionEvent_getPointerCount); W(AMotionEvent_getPointerId); W(AMotionEvent_getX);
W(AMotionEvent_getY); W(AMotionEvent_getRawX); W(AMotionEvent_getRawY); W(AMotionEvent_getAxisValue);
W(AMotionEvent_getButtonState);
#undef W
typedef struct { int32_t Type; uint32_t DeviceID; } caps_header;
typedef struct {
caps_header Header;
uint32_t ControllerCapabilities, ButtonCapabilities;
uint16_t TrackpadMaxX, TrackpadMaxY;
float TrackpadSizeX, TrackpadSizeY;
uint32_t HapticSamplesMax, HapticSampleDurationMS, TouchCapabilities, Reserved4, Reserved5;
} remote_caps;
typedef struct {
int32_t ControllerType;
double TimeInSeconds;
uint32_t Buttons, TrackpadStatus;
float TrackpadPosition[2];
uint8_t Battery, RecenterCount;
uint16_t Reserved;
float IndexTrigger, GripTrigger;
uint32_t Touches, Reserved5a;
float Joystick[2], JoystickNoDeadZone[2];
} remote_state;
_Static_assert(sizeof(remote_caps) == 48 && sizeof(remote_state) == 72, "VrApi input ABI");
#define TRACKED_REMOTE 4
#define LEFT_HAND 4u
#define B_A 0x1u
#define B_B 0x2u
#define B_RTHUMB 0x4u
#define B_X 0x100u
#define B_Y 0x200u
#define B_LTHUMB 0x400u
#define B_ENTER 0x100000u
/* android.view.KeyEvent / MotionEvent / InputDevice constants */
#define KEY_DOWN 0
#define KEY_UP 1
#define KEYCODE_BACK 4
#define KEYCODE_BUTTON_A 96
#define KEYCODE_BUTTON_B 97
#define KEYCODE_BUTTON_X 99
#define KEYCODE_BUTTON_Y 100
#define KEYCODE_BUTTON_THUMBL 106
#define KEYCODE_BUTTON_THUMBR 107
#define SOURCE_KEYBOARD 0x101
#define SOURCE_GAMEPAD 0x401
#define SOURCE_TOUCHSCREEN 0x1002
#define SOURCE_JOYSTICK 0x1000010
#define ACTION_DOWN 0
#define ACTION_UP 1
#define ACTION_MOVE 2
#define AXIS_X 0
#define AXIS_Y 1
#define AXIS_Z 11
#define AXIS_RZ 14
typedef struct {
int (*enumerate)(void *, uint32_t, caps_header *);
int (*caps)(void *, caps_header *);
int (*state)(void *, uint32_t, remote_state *);
} input_api;
extern int a32_remote_in_use; /* vrapi.c */
static struct {
void *mobile;
input_api api;
jobject activity, target; /* target: the UnityPlayer, else the activity */
jmethodID inject; /* UnityPlayer.injectEvent(InputEvent), else Activity.dispatchKeyEvent */
int unity, java; /* java: the Java delivery is set up */
jclass key_class, motion_class, coords_class, props_class, clock_class;
jmethodID key_init, motion_obtain, motion_obtain_full, motion_set_source, motion_recycle, coords_init,
coords_set_axis, props_init, uptime;
jfieldID props_id, props_tool;
volatile int running, gen; /* gen: a new input_start ends the previous thread */
int gamepad_id; /* an Android input device with gamepad buttons, or 0 */
} I;
/* ---------------------------------------------------------------- synthetic AInputEvents (NativeActivity) */
/* native_app_glue attaches the activity's AInputQueue to its looper without a callback and polls it; the bridge
* puts its own events in front of the queue's: pollAll/pollOnce return the queue's ident while one waits (an
* ALooper_wake ends a blocking poll), AInputQueue_getEvent hands it out, finishEvent frees it. */
#define NFAKE 256
#define TOUCH_DEVICE 1 /* the Gear VR touchpad's device ID, as the game sees it */
typedef struct {
int used, type, source, device, action, code;
float x, y;
} fake_event;
static fake_event pool[NFAKE];
static int fifo[NFAKE], fifo_head, fifo_count, pool_next;
static pthread_mutex_t nq_lock = PTHREAD_MUTEX_INITIALIZER;
static struct {
void *queue, *looper;
int ident;
uint32_t data;
} NQ;
static int is_fake(const void *p) { return (const char *)p >= (const char *)pool && (const char *)p < (const char *)(pool + NFAKE); }
static int native_active(void) { return NQ.queue != NULL; }
void input_queue_attached(void *queue, void *looper, int ident, uint32_t data, int has_callback)
{
if (has_callback) {
bridge_log(ANDROID_LOG_WARN, "controllers: input queue attached with a callback: synthetic events not supported");
return;
}
pthread_mutex_lock(&nq_lock);
NQ.queue = queue, NQ.looper = looper, NQ.ident = ident, NQ.data = data;
pthread_mutex_unlock(&nq_lock);
bridge_log(ANDROID_LOG_INFO, "controllers: the game reads its AInputQueue (ident %d): Gear VR touchpad events go there", ident);
}
void input_queue_detached(void *queue)
{
pthread_mutex_lock(&nq_lock);
if (NQ.queue == queue) {
memset(&NQ, 0, sizeof NQ);
for (int k = 0; k < NFAKE; k++) pool[k].used = 0;
fifo_count = 0;
}
pthread_mutex_unlock(&nq_lock);
}
static void native_push(int type, int source, int device, int action, int code, float x, float y)
{
pthread_mutex_lock(&nq_lock);
void *looper = NQ.looper;
fake_event *e = NULL;
for (int k = 0; k < NFAKE && NQ.queue && fifo_count < NFAKE; k++) {
int i = (pool_next + k) % NFAKE;
if (pool[i].used) continue;
e = &pool[i];
pool_next = (i + 1) % NFAKE;
fifo[(fifo_head + fifo_count++) % NFAKE] = i;
break;
}
if (e) *e = (fake_event){1, type, source, device, action, code, x, y};
pthread_mutex_unlock(&nq_lock);
if (e && looper && ALooper_wake) ALooper_wake(looper);
}
int input_queue_pending(void *looper, int *ident, uint32_t *data)
{
pthread_mutex_lock(&nq_lock);
int r = NQ.queue && looper && NQ.looper == looper && fifo_count > 0;
if (r) *ident = NQ.ident, *data = NQ.data;
pthread_mutex_unlock(&nq_lock);
return r;
}
void *input_queue_pop(void *queue)
{
void *e = NULL;
pthread_mutex_lock(&nq_lock);
if (queue && queue == NQ.queue && fifo_count > 0) {
e = &pool[fifo[fifo_head]];
fifo_head = (fifo_head + 1) % NFAKE;
fifo_count--;
}
pthread_mutex_unlock(&nq_lock);
return e;
}
static int queue_has_fake(void *queue)
{
pthread_mutex_lock(&nq_lock);
int r = queue && queue == NQ.queue && fifo_count > 0;
pthread_mutex_unlock(&nq_lock);
return r;
}
/* the guest's view of the queue and events (imports.txt "!" lines) */
void imp_AInputQueue_detachLooper(a32_cpu *c, argreader *R)
{
AInputQueue *q = h2ptr(rd32(R));
input_queue_detached(q);
if (q && AInputQueue_detachLooper) AInputQueue_detachLooper(q);
}
void imp_AInputQueue_hasEvents(a32_cpu *c, argreader *R)
{
AInputQueue *q = h2ptr(rd32(R));
ret32(c, queue_has_fake(q) ? 1u : q && AInputQueue_hasEvents ? (uint32_t)AInputQueue_hasEvents(q) : 0u);
}
void imp_AInputQueue_preDispatchEvent(a32_cpu *c, argreader *R)
{
AInputQueue *q = h2ptr(rd32(R));
AInputEvent *e = h2ptr(rd32(R));
ret32(c, is_fake(e) || !q || !e || !AInputQueue_preDispatchEvent ? 0u : (uint32_t)AInputQueue_preDispatchEvent(q, e));
}
void imp_AInputQueue_finishEvent(a32_cpu *c, argreader *R)
{
AInputQueue *q = h2ptr(rd32(R));
AInputEvent *e = h2ptr(rd32(R));
int handled = (int)rd32(R);
if (is_fake(e)) {
pthread_mutex_lock(&nq_lock);
((fake_event *)e)->used = 0;
pthread_mutex_unlock(&nq_lock);
} else if (q && e && AInputQueue_finishEvent) {
AInputQueue_finishEvent(q, e, handled);
}
}
#define EV(fn, member) \
void imp_##fn(a32_cpu *c, argreader *R) \
{ \
const AInputEvent *e = h2ptr(rd32(R)); \
ret32(c, is_fake(e) ? (uint32_t)((const fake_event *)e)->member \
: e && fn ? (uint32_t)fn(e) : 0u); \
}
EV(AInputEvent_getType, type)
EV(AInputEvent_getDeviceId, device)
EV(AInputEvent_getSource, source)
EV(AKeyEvent_getAction, action)
EV(AKeyEvent_getKeyCode, code)
EV(AMotionEvent_getAction, action)
#undef EV
void imp_AKeyEvent_getMetaState(a32_cpu *c, argreader *R)
{
const AInputEvent *e = h2ptr(rd32(R));
ret32(c, is_fake(e) || !e || !AKeyEvent_getMetaState ? 0u : (uint32_t)AKeyEvent_getMetaState(e));
}
void imp_AKeyEvent_getRepeatCount(a32_cpu *c, argreader *R)
{
const AInputEvent *e = h2ptr(rd32(R));
ret32(c, is_fake(e) || !e || !AKeyEvent_getRepeatCount ? 0u : (uint32_t)AKeyEvent_getRepeatCount(e));
}
void imp_AKeyEvent_getFlags(a32_cpu *c, argreader *R)
{
const AInputEvent *e = h2ptr(rd32(R));
ret32(c, is_fake(e) || !e || !AKeyEvent_getFlags ? 0u : (uint32_t)AKeyEvent_getFlags(e));
}
void imp_AMotionEvent_getPointerCount(a32_cpu *c, argreader *R)
{
const AInputEvent *e = h2ptr(rd32(R));
ret32(c, is_fake(e) ? 1u : e && AMotionEvent_getPointerCount ? (uint32_t)AMotionEvent_getPointerCount(e) : 0u);
}
void imp_AMotionEvent_getPointerId(a32_cpu *c, argreader *R)
{
const AInputEvent *e = h2ptr(rd32(R));
size_t i = rd32(R);
ret32(c, is_fake(e) || !e || !AMotionEvent_getPointerId ? 0u : (uint32_t)AMotionEvent_getPointerId(e, i));
}
static void motion_xy(a32_cpu *c, argreader *R, int y, float (*real)(const AInputEvent *, size_t))
{
const AInputEvent *e = h2ptr(rd32(R));
size_t i = rd32(R);
retf(c, is_fake(e) ? (y ? ((const fake_event *)e)->y : ((const fake_event *)e)->x) : e && real ? real(e, i) : 0.0f);
}
void imp_AMotionEvent_getX(a32_cpu *c, argreader *R) { motion_xy(c, R, 0, AMotionEvent_getX); }
void imp_AMotionEvent_getY(a32_cpu *c, argreader *R) { motion_xy(c, R, 1, AMotionEvent_getY); }
void imp_AMotionEvent_getRawX(a32_cpu *c, argreader *R) { motion_xy(c, R, 0, AMotionEvent_getRawX); }
void imp_AMotionEvent_getRawY(a32_cpu *c, argreader *R) { motion_xy(c, R, 1, AMotionEvent_getRawY); }
void imp_AMotionEvent_getAxisValue(a32_cpu *c, argreader *R)
{
const AInputEvent *e = h2ptr(rd32(R));
int32_t axis = (int32_t)rd32(R);
size_t i = rd32(R);
if (is_fake(e)) {
const fake_event *f = (const fake_event *)e;
retf(c, axis == AMOTION_EVENT_AXIS_X ? f->x : axis == AMOTION_EVENT_AXIS_Y ? f->y : 0.0f);
} else {
retf(c, e && AMotionEvent_getAxisValue ? AMotionEvent_getAxisValue(e, axis, i) : 0.0f);
}
}
void imp_AMotionEvent_getButtonState(a32_cpu *c, argreader *R)
{
const AInputEvent *e = h2ptr(rd32(R));
ret32(c, is_fake(e) || !e || !AMotionEvent_getButtonState ? 0u : (uint32_t)AMotionEvent_getButtonState(e));
}
/* ---------------------------------------------------------------- Java delivery */
static jlong now_ms(JNIEnv *env) { return (*env)->CallStaticLongMethod(env, I.clock_class, I.uptime); }
static void deliver(JNIEnv *env, jobject ev)
{
if (!ev || !I.java) return;
(*env)->CallBooleanMethod(env, I.target, I.inject, ev);
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
(*env)->DeleteLocalRef(env, ev);
}
static void key(JNIEnv *env, int action, int code, int source)
{
if (native_active()) {
/* no gamepad: Unreal assigns gamepads through Java's InputDevice list, which doesn't have ours */
if (source != SOURCE_GAMEPAD) native_push(AINPUT_EVENT_TYPE_KEY, source, 0, action, code, 0, 0);
return;
}
if (!I.java) return;
jlong t = now_ms(env);
int dev = source == SOURCE_GAMEPAD ? I.gamepad_id : 0;
jobject ev = (*env)->NewObject(env, I.key_class, I.key_init, t, t, action, code, 0, 0, dev, 0, 0, source);
deliver(env, ev);
}
#define CX 960.0f
#define CY 540.0f
/* the touchpad, as Unity saw it on a Gear VR: touch events (mouse button 0 and the mouse position); positions are
* given on a 1920x1080 screen and scaled to the activity's window for NativeActivity games (Unreal divides them by
* its window size) */
static void touch(JNIEnv *env, int action, float x, float y)
{
if (native_active()) {
float w = g_window_w > 0 ? (float)g_window_w : 2 * CX, h = g_window_h > 0 ? (float)g_window_h : 2 * CY;
native_push(AINPUT_EVENT_TYPE_MOTION, SOURCE_TOUCHSCREEN, TOUCH_DEVICE, action, 0, x / (2 * CX) * w,
y / (2 * CY) * h);
return;
}
if (!I.java || !I.unity) return; /* dispatchKeyEvent takes key events only */
static jlong down;
jlong t = now_ms(env);
if (action == ACTION_DOWN) down = t;
jobject ev = (*env)->CallStaticObjectMethod(env, I.motion_class, I.motion_obtain, down, t, action, x, y, 0);
if (!ev) return;
(*env)->CallVoidMethod(env, ev, I.motion_set_source, SOURCE_TOUCHSCREEN);
deliver(env, ev);
}
static void tap(JNIEnv *env, int action) { touch(env, action, CX, CY); }
static void sticks(JNIEnv *env, float x, float y, float z, float rz)
{
if (native_active() || !I.java || !I.unity) return;
jlong t = now_ms(env);
jobjectArray props = (*env)->NewObjectArray(env, 1, I.props_class, NULL);
jobjectArray coords = (*env)->NewObjectArray(env, 1, I.coords_class, NULL);
jobject p = (*env)->NewObject(env, I.props_class, I.props_init);
jobject c = (*env)->NewObject(env, I.coords_class, I.coords_init);
(*env)->SetIntField(env, p, I.props_id, 0);
(*env)->SetIntField(env, p, I.props_tool, 0);
(*env)->CallVoidMethod(env, c, I.coords_set_axis, AXIS_X, x);
(*env)->CallVoidMethod(env, c, I.coords_set_axis, AXIS_Y, -y); /* Android: down is positive */
(*env)->CallVoidMethod(env, c, I.coords_set_axis, AXIS_Z, z);
(*env)->CallVoidMethod(env, c, I.coords_set_axis, AXIS_RZ, -rz);
(*env)->SetObjectArrayElement(env, props, 0, p);
(*env)->SetObjectArrayElement(env, coords, 0, c);
jobject ev = (*env)->CallStaticObjectMethod(env, I.motion_class, I.motion_obtain_full, t, t, ACTION_MOVE, 1, props,
coords, 0, 0, 1.0f, 1.0f, I.gamepad_id, 0, SOURCE_JOYSTICK, 0);
deliver(env, ev);
(*env)->DeleteLocalRef(env, p);
(*env)->DeleteLocalRef(env, c);
(*env)->DeleteLocalRef(env, props);
(*env)->DeleteLocalRef(env, coords);
}
static int setup(JNIEnv *env)
{
#define CLS(v, n) if (!(I.v = (*env)->NewGlobalRef(env, (*env)->FindClass(env, n)))) return 0
CLS(key_class, "android/view/KeyEvent");
CLS(motion_class, "android/view/MotionEvent");
CLS(coords_class, "android/view/MotionEvent$PointerCoords");
CLS(props_class, "android/view/MotionEvent$PointerProperties");
CLS(clock_class, "android/os/SystemClock");
#undef CLS
I.key_init = (*env)->GetMethodID(env, I.key_class, "<init>", "(JJIIIIIIII)V");
I.motion_obtain = (*env)->GetStaticMethodID(env, I.motion_class, "obtain", "(JJIFFI)Landroid/view/MotionEvent;");
I.motion_obtain_full = (*env)->GetStaticMethodID(env, I.motion_class, "obtain",
"(JJII[Landroid/view/MotionEvent$PointerProperties;[Landroid/view/MotionEvent$PointerCoords;IIFFIIII)Landroid/view/MotionEvent;");
I.motion_set_source = (*env)->GetMethodID(env, I.motion_class, "setSource", "(I)V");
I.coords_init = (*env)->GetMethodID(env, I.coords_class, "<init>", "()V");
I.coords_set_axis = (*env)->GetMethodID(env, I.coords_class, "setAxisValue", "(IF)V");
I.props_init = (*env)->GetMethodID(env, I.props_class, "<init>", "()V");
I.props_id = (*env)->GetFieldID(env, I.props_class, "id", "I");
I.props_tool = (*env)->GetFieldID(env, I.props_class, "toolType", "I");
I.uptime = (*env)->GetStaticMethodID(env, I.clock_class, "uptimeMillis", "()J");
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
return 0;
}
/* a real gamepad (Unity only takes joystick input from devices Android knows) */
jclass dc = (*env)->FindClass(env, "android/view/InputDevice");
jmethodID ids = dc ? (*env)->GetStaticMethodID(env, dc, "getDeviceIds", "()[I") : NULL;
jmethodID get = dc ? (*env)->GetStaticMethodID(env, dc, "getDevice", "(I)Landroid/view/InputDevice;") : NULL;
jmethodID src = dc ? (*env)->GetMethodID(env, dc, "getSources", "()I") : NULL;
jmethodID name = dc ? (*env)->GetMethodID(env, dc, "getName", "()Ljava/lang/String;") : NULL;
jintArray all = ids ? (*env)->CallStaticObjectMethod(env, dc, ids) : NULL;
jint n = all ? (*env)->GetArrayLength(env, all) : 0;
for (jint k = 0; k < n && get && src && name; k++) {
jint id;
(*env)->GetIntArrayRegion(env, all, k, 1, &id);
jobject d = (*env)->CallStaticObjectMethod(env, dc, get, id);
if (!d) continue;
jint sources = (*env)->CallIntMethod(env, d, src);
jstring nm = (*env)->CallObjectMethod(env, d, name);
const char *u = nm ? (*env)->GetStringUTFChars(env, nm, NULL) : NULL;
bridge_log(ANDROID_LOG_INFO, "controllers: Android input device %d \"%s\" sources 0x%x", id, u ? u : "?", sources);
if ((sources & SOURCE_GAMEPAD) == SOURCE_GAMEPAD && !I.gamepad_id) I.gamepad_id = id;
if (u) (*env)->ReleaseStringUTFChars(env, nm, u);
(*env)->DeleteLocalRef(env, d);
}
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
/* Unity: UnityPlayerActivity.mUnityPlayer.injectEvent(InputEvent) */
jclass ac = (*env)->GetObjectClass(env, I.activity);
jfieldID f = (*env)->GetFieldID(env, ac, "mUnityPlayer", "Lcom/unity3d/player/UnityPlayer;");
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
jobject player = f ? (*env)->GetObjectField(env, I.activity, f) : NULL;
if (player) {
jclass pc = (*env)->GetObjectClass(env, player);
I.inject = (*env)->GetMethodID(env, pc, "injectEvent", "(Landroid/view/InputEvent;)Z");
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
if (I.inject) I.target = (*env)->NewGlobalRef(env, player), I.unity = 1;
}
if (!I.inject) {
I.inject = (*env)->GetMethodID(env, ac, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z");
I.target = I.activity;
}
return I.inject != NULL && I.key_init && I.motion_obtain && I.motion_obtain_full && I.uptime;
}
static void *poll_thread(void *arg)
{
int gen = (int)(intptr_t)arg;
JNIEnv *env = NULL;
JavaVMAttachArgs a = {JNI_VERSION_1_6, "a32 controllers", NULL};
if ((*g_vm)->AttachCurrentThread(g_vm, &env, &a) != JNI_OK) return NULL;
if (!I.java) I.java = setup(env);
if (!I.java && !native_active()) {
bridge_log(ANDROID_LOG_ERROR, "controllers: can't set up Android input events");
(*g_vm)->DetachCurrentThread(g_vm);
return NULL;
}
bridge_log(ANDROID_LOG_INFO, "controllers -> %s, gamepad device %d (trigger: hold touchpad, A: tap, right stick: "
"swipe, B/menu: back), window %dx%d", native_active() ? "AInputQueue" : I.unity ?
"UnityPlayer.injectEvent" : "Activity.dispatchKeyEvent", I.gamepad_id, g_window_w, g_window_h);
uint32_t prev_buttons = 0, prev_back = 0;
int prev_tap = 0, sticks_active = 0, logged = 0;
int swipe_step = 0, swipe_armed = 1, tap_frames = 0;
float swipe_dx = 0, swipe_dy = 0;
while (I.running && I.gen == gen) {
uint32_t buttons = 0;
float lx = 0, ly = 0, rx = 0, ry = 0, trigger = 0;
int devices = 0;
for (uint32_t i = 0; i < 4; i++) {
caps_header h = {0, 0};
if (I.api.enumerate(I.mobile, i, &h) < 0) break;
if (h.Type != TRACKED_REMOTE) continue;
remote_caps caps;
memset(&caps, 0, sizeof caps);
caps.Header = h;
if (I.api.caps(I.mobile, &caps.Header) < 0) continue;
remote_state st;
memset(&st, 0, sizeof st);
st.ControllerType = TRACKED_REMOTE;
if (I.api.state(I.mobile, h.DeviceID, &st) < 0) continue;
devices++;
int left = (caps.ControllerCapabilities & LEFT_HAND) != 0;
buttons |= st.Buttons;
if (left) lx = st.Joystick[0], ly = st.Joystick[1];
else rx = st.Joystick[0], ry = st.Joystick[1], trigger = st.IndexTrigger;
}
if (devices && !logged++) bridge_log(ANDROID_LOG_INFO, "controllers: %d found", devices);
static const struct { uint32_t bit; int code; } map[] = {
{B_X, KEYCODE_BUTTON_X}, {B_Y, KEYCODE_BUTTON_Y},
{B_LTHUMB, KEYCODE_BUTTON_THUMBL}, {B_RTHUMB, KEYCODE_BUTTON_THUMBR},
};
for (size_t k = 0; k < sizeof map / sizeof *map; k++) {
uint32_t now = buttons & map[k].bit, was = prev_buttons & map[k].bit;
if (now != was) key(env, now ? KEY_DOWN : KEY_UP, map[k].code, SOURCE_GAMEPAD);
}
if (a32_remote_in_use) {
/* the game reads the right controller as its Gear VR Controller: only the left menu button stays (back) */
buttons &= B_ENTER | B_X | B_Y | B_LTHUMB;
trigger = rx = ry = 0;
if (prev_tap && !swipe_step) tap(env, ACTION_UP), prev_tap = 0;
}
uint32_t back = buttons & (B_ENTER | B_B);
if (!!back != !!prev_back) key(env, back ? KEY_DOWN : KEY_UP, KEYCODE_BACK, SOURCE_KEYBOARD);
/* touchpad held: the trigger; A gives a short tap (~100 ms) */
if ((buttons & B_A) && !(prev_buttons & B_A)) tap_frames = 9;
int tapping = trigger > 0.6f || (prev_tap && trigger > 0.4f) || tap_frames > 0;
if (tap_frames > 0) tap_frames--;
if (tapping != prev_tap && !swipe_step) tap(env, tapping ? ACTION_DOWN : ACTION_UP);
else if (tapping != prev_tap) tapping = prev_tap;
/* a flick of the right stick: a swipe across the touchpad (down, 6 moves, up) */
float mag = rx * rx + ry * ry;
if (mag < 0.09f) swipe_armed = 1;
if (!swipe_step && swipe_armed && mag > 0.5f && !prev_tap) {
swipe_armed = 0;
if (rx * rx > ry * ry) swipe_dx = rx > 0 ? 1 : -1, swipe_dy = 0;
/* NativeActivity games get the touchpad's own axes: X runs front to back, so stick up = swipe forward,
* down = swipe back (Gunjack: back = reload, forward = special weapon) */
else if (native_active()) swipe_dx = ry > 0 ? -1 : 1, swipe_dy = 0;
else swipe_dx = 0, swipe_dy = ry > 0 ? -1 : 1; /* stick forward: swipe towards the front */
touch(env, ACTION_DOWN, CX, CY);
swipe_step = 1;
} else if (swipe_step) {
float d = 50.0f * (float)swipe_step;
if (swipe_step <= 6) touch(env, ACTION_MOVE, CX + swipe_dx * d, CY + swipe_dy * d);
else {
touch(env, ACTION_UP, CX + swipe_dx * 300, CY + swipe_dy * 300);
swipe_step = -1;
}
swipe_step++;
}
int moving = lx * lx + ly * ly > 0.0025f;
if (moving || sticks_active) sticks(env, lx, ly, 0, 0); /* one centred event after movement stops */
sticks_active = moving;
prev_buttons = buttons, prev_back = back, prev_tap = tapping;
usleep(11000);
}
(*g_vm)->DetachCurrentThread(g_vm);
return NULL;
}
void input_start(void *mobile, void *enumerate, void *caps, void *state, jobject activity)
{
if (getenv("A32_NO_INPUT") || I.running || !enumerate || !caps || !state || !activity) return;
I.mobile = mobile;
I.api.enumerate = enumerate, I.api.caps = caps, I.api.state = state;
I.activity = activity;
I.running = 1;
int gen = ++I.gen; /* a thread of an earlier VR mode that hasn't seen running == 0 yet ends */
pthread_t t;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (pthread_create(&t, &attr, poll_thread, (void *)(intptr_t)gen)) I.running = 0;
pthread_attr_destroy(&attr);
}
void input_stop(void) { I.running = 0; }
+653
View File
@@ -0,0 +1,653 @@
/* JNI for guest code, the parts gen_stubs.py can't generate: the Call*Method / NewObject families (variadic,
* va_list and jvalue[] arguments, read with the method's shorty), method IDs (which remember their shorty),
* references, strings and primitive arrays (shared when the host's data lies in the guest's 4 GiB, as ART's heap
* does, else copied), RegisterNatives (trampolines, natives.c) and the JavaVM functions. */
#include <stdlib.h>
#include "imports_internal.h"
/* ---------------------------------------------------------------- original APK signature */
/* UE4's GameActivity.AndroidThunkJava_GetSignature() hashes the APK's signing certificate, which AndroidMain compares
* with the original one (a tamper check): with the original value from the conversion (native_activity.c) the
* guest's call gets it instead of the re-signed APK's */
extern char *g_orig_signature;
static uint32_t signature_mid; /* method handle of AndroidThunkJava_GetSignature()Ljava/lang/String; */
/* ---------------------------------------------------------------- shorties */
/* "(I[Ljava/lang/String;J)V" -> "ILJ)V" */
void make_shorty(const char *sig, char *out, size_t n)
{
size_t k = 0;
const char *p = sig;
if (*p == '(') p++;
while (*p && *p != ')') {
char t = *p;
if (t == '[') {
while (*p == '[') p++;
if (*p == 'L') p = strchr(p, ';');
if (!p) break;
p++;
t = 'L';
} else if (t == 'L') {
p = strchr(p, ';');
if (!p) break;
p++;
} else {
p++;
}
if (k + 3 < n) out[k++] = t;
}
char r = 'V';
if (p && *p == ')') {
p++;
r = *p == '[' ? 'L' : *p ? *p : 'V';
}
out[k++] = ')';
out[k++] = r;
out[k] = 0;
}
/* JVM type letter of a class object: "int" -> 'I', anything not primitive -> 'L' */
static char class_letter(JNIEnv *env, jclass k)
{
static jmethodID get_name;
if (!get_name) get_name = (*env)->GetMethodID(env, (*env)->FindClass(env, "java/lang/Class"), "getName",
"()Ljava/lang/String;");
jstring s = (*env)->CallObjectMethod(env, k, get_name);
const char *n = s ? (*env)->GetStringUTFChars(env, s, NULL) : NULL;
char r = 'L';
if (n) {
static const char *const prim[] = {"boolean", "byte", "char", "short", "int", "long", "float", "double",
"void"};
static const char letters[] = "ZBCSIJFDV";
for (int i = 0; i < 9; i++)
if (!strcmp(n, prim[i])) r = letters[i];
(*env)->ReleaseStringUTFChars(env, s, n);
}
if (s) (*env)->DeleteLocalRef(env, s);
return r;
}
/* the shorty of a java.lang.reflect.Method / Constructor */
static int reflected_shorty(JNIEnv *env, jobject m, char *out, size_t n)
{
jclass mc = (*env)->GetObjectClass(env, m);
jmethodID params = (*env)->GetMethodID(env, mc, "getParameterTypes", "()[Ljava/lang/Class;");
jmethodID ret = (*env)->GetMethodID(env, mc, "getReturnType", "()Ljava/lang/Class;");
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); /* a Constructor has no getReturnType */
if (!params) return -1;
jobjectArray a = (*env)->CallObjectMethod(env, m, params);
jsize np = a ? (*env)->GetArrayLength(env, a) : 0;
size_t k = 0;
for (jsize i = 0; i < np && k + 3 < n; i++) {
jclass pk = (*env)->GetObjectArrayElement(env, a, i);
out[k++] = class_letter(env, pk);
(*env)->DeleteLocalRef(env, pk);
}
out[k++] = ')';
char r = 'V';
if (ret) {
jclass rk = (*env)->CallObjectMethod(env, m, ret);
r = class_letter(env, rk);
(*env)->DeleteLocalRef(env, rk);
}
out[k++] = r;
out[k] = 0;
return 0;
}
/* ---------------------------------------------------------------- function classes */
enum {
S_NONE, S_CALL, S_GET_ELEMS, S_REL_ELEMS, S_GET_METHOD, S_FROM_REFLECTED, S_NEW_GLOBAL, S_DELETE_GLOBAL,
S_DELETE_LOCAL, S_NEW_WEAK, S_DELETE_WEAK, S_POP_FRAME, S_GET_STRING_CHARS, S_REL_STRING_CHARS,
S_GET_STRING_UTF, S_REL_STRING_UTF, S_GET_CRITICAL, S_REL_CRITICAL, S_REGISTER, S_GET_VM, S_DIRECT_ADDR,
};
enum { K_VIRTUAL = 1, K_NONVIRTUAL, K_STATIC, K_NEW };
static struct {
uint8_t special, kind, var; /* var: 0 "...", 1 va_list, 2 jvalue[] */
char type; /* result (calls) or element type (arrays) */
} fn[JNI_TABLE_SIZE];
static pthread_once_t fn_once = PTHREAD_ONCE_INIT;
static char type_word(const char **p)
{
static const struct { const char *w; char t; } words[] = {
{"Object", 'L'}, {"Boolean", 'Z'}, {"Byte", 'B'}, {"Char", 'C'}, {"Short", 'S'},
{"Int", 'I'}, {"Long", 'J'}, {"Float", 'F'}, {"Double", 'D'}, {"Void", 'V'},
};
for (size_t k = 0; k < sizeof words / sizeof *words; k++) {
size_t n = strlen(words[k].w);
if (!strncmp(*p, words[k].w, n)) {
*p += n;
return words[k].t;
}
}
return 0;
}
static void classify(void)
{
static const struct { const char *name; uint8_t s; } named[] = {
{"GetMethodID", S_GET_METHOD}, {"GetStaticMethodID", S_GET_METHOD},
{"FromReflectedMethod", S_FROM_REFLECTED}, {"NewGlobalRef", S_NEW_GLOBAL},
{"DeleteGlobalRef", S_DELETE_GLOBAL}, {"DeleteLocalRef", S_DELETE_LOCAL},
{"NewWeakGlobalRef", S_NEW_WEAK}, {"DeleteWeakGlobalRef", S_DELETE_WEAK},
{"PopLocalFrame", S_POP_FRAME}, {"GetStringChars", S_GET_STRING_CHARS},
{"ReleaseStringChars", S_REL_STRING_CHARS}, {"GetStringCritical", S_GET_STRING_CHARS},
{"ReleaseStringCritical", S_REL_STRING_CHARS}, {"GetStringUTFChars", S_GET_STRING_UTF},
{"ReleaseStringUTFChars", S_REL_STRING_UTF}, {"GetPrimitiveArrayCritical", S_GET_CRITICAL},
{"ReleasePrimitiveArrayCritical", S_REL_CRITICAL}, {"RegisterNatives", S_REGISTER},
{"GetJavaVM", S_GET_VM}, {"GetDirectBufferAddress", S_DIRECT_ADDR},
};
for (int i = 0; i < JNI_TABLE_SIZE; i++) {
const char *n = jni_names[i];
for (size_t k = 0; k < sizeof named / sizeof *named; k++)
if (!strcmp(n, named[k].name)) fn[i].special = named[k].s;
if (fn[i].special) continue;
const char *p = n;
uint8_t kind = 0;
char t = 0;
if (!strncmp(p, "NewObject", 9) && (!p[9] || !strcmp(p + 9, "V") || !strcmp(p + 9, "A"))) {
kind = K_NEW, t = 'L', p += 9;
} else if (!strncmp(p, "CallNonvirtual", 14)) {
p += 14, kind = K_NONVIRTUAL, t = type_word(&p);
} else if (!strncmp(p, "CallStatic", 10)) {
p += 10, kind = K_STATIC, t = type_word(&p);
} else if (!strncmp(p, "Call", 4)) {
p += 4, kind = K_VIRTUAL, t = type_word(&p);
}
if (kind && t) {
if (kind != K_NEW) {
if (strncmp(p, "Method", 6)) continue;
p += 6;
}
fn[i].special = S_CALL;
fn[i].kind = kind;
fn[i].type = t;
fn[i].var = *p == 'V' ? 1 : *p == 'A' ? 2 : 0;
continue;
}
int get = !strncmp(n, "Get", 3), rel = !strncmp(n, "Release", 7);
if ((get || rel) && strstr(n, "ArrayElements")) {
p = n + (get ? 3 : 7);
t = type_word(&p);
if (t && t != 'L' && !strcmp(p, "ArrayElements")) {
fn[i].special = get ? S_GET_ELEMS : S_REL_ELEMS;
fn[i].type = t;
}
}
}
}
/* ---------------------------------------------------------------- method calls */
static jvalue arg_value(char t, argreader *A)
{
jvalue v;
v.j = 0;
switch (t) {
case 'Z': v.z = (jboolean)rd32(A); break;
case 'B': v.b = (jbyte)rd32(A); break;
case 'C': v.c = (jchar)rd32(A); break;
case 'S': v.s = (jshort)rd32(A); break;
case 'I': v.i = (jint)rd32(A); break;
case 'J': v.j = (jlong)rd64(A); break;
case 'F': v.f = (jfloat)rdd(A); break; /* promoted to double */
case 'D': v.d = rdd(A); break;
default: v.l = h2o(rd32(A)); break;
}
return v;
}
static jvalue array_value(char t, uint32_t a)
{
jvalue v;
v.j = 0;
switch (t) {
case 'Z': v.z = ld8(a); break;
case 'B': v.b = (jbyte)ld8(a); break;
case 'C': v.c = ld16(a); break;
case 'S': v.s = (jshort)ld16(a); break;
case 'I': v.i = (jint)ld32(a); break;
case 'J': v.j = (jlong)ld64(a); break;
case 'F': { uint32_t b = ld32(a); memcpy(&v.f, &b, 4); break; }
case 'D': { uint64_t b = ld64(a); memcpy(&v.d, &b, 8); break; }
default: v.l = h2o(ld32(a)); break;
}
return v;
}
#define CALL(T) \
(kind == K_VIRTUAL ? (*env)->Call##T##MethodA(env, obj, m, a) \
: kind == K_NONVIRTUAL ? (*env)->CallNonvirtual##T##MethodA(env, obj, cls, m, a) \
: (*env)->CallStatic##T##MethodA(env, cls, m, a))
static void call_method(a32_cpu *c, JNIEnv *env, int index, argreader *R)
{
int kind = fn[index].kind;
jobject obj = NULL;
jclass cls = NULL;
if (kind == K_VIRTUAL || kind == K_NONVIRTUAL) obj = h2o(rd32(R));
if (kind != K_VIRTUAL) cls = (jclass)h2o(rd32(R));
uint32_t mh = rd32(R);
jmethodID m = h2mid(mh);
const char *shorty = mid_shorty(mh);
if (!m || !shorty) {
bridge_log(ANDROID_LOG_ERROR, "%s: unknown method ID 0x%x", jni_names[index], mh);
c->r[0] = c->r[1] = 0;
return;
}
if (mh == signature_mid && g_orig_signature && fn[index].type == 'L' && kind != K_NEW) {
static int logged;
if (!logged++) bridge_log(ANDROID_LOG_INFO, "AndroidThunkJava_GetSignature: original signature returned");
ret32(c, o2h_local((*env)->NewStringUTF(env, g_orig_signature)));
return;
}
jvalue a[256];
int n = 0;
if (fn[index].var == 2) {
uint32_t arr = rd32(R);
for (const char *p = shorty; *p != ')' && n < 256; p++, n++) a[n] = array_value(*p, arr + 8u * (uint32_t)n);
} else {
argreader V, *A = R;
if (fn[index].var == 1) {
ar_init(&V, c, 4, rd32(R)); /* va_list: a pointer to the next argument in memory */
A = &V;
}
for (const char *p = shorty; *p != ')' && n < 256; p++, n++) a[n] = arg_value(*p, A);
}
switch (fn[index].type) {
case 'V': CALL(Void); break;
case 'Z': ret32(c, CALL(Boolean)); break;
case 'B': ret32(c, (uint32_t)(int32_t)CALL(Byte)); break;
case 'C': ret32(c, CALL(Char)); break;
case 'S': ret32(c, (uint32_t)(int32_t)CALL(Short)); break;
case 'I': ret32(c, (uint32_t)CALL(Int)); break;
case 'J': ret64(c, (uint64_t)CALL(Long)); break;
case 'F': retf(c, CALL(Float)); break;
case 'D': retd(c, CALL(Double)); break;
default:
if (kind == K_NEW) ret32(c, o2h_local((*env)->NewObjectA(env, cls, m, a)));
else ret32(c, o2h_local(CALL(Object)));
break;
}
}
/* ---------------------------------------------------------------- copies of host data in guest memory */
/* Guest buffers that stand for host data outside the guest's 4 GiB (guest address -> size in bytes). */
static pthread_mutex_t copies_lock = PTHREAD_MUTEX_INITIALIZER;
static struct { uint32_t g, size; } *copies;
static int ncopies, capcopies;
static void copy_add(uint32_t g, uint32_t size)
{
pthread_mutex_lock(&copies_lock);
if (ncopies == capcopies) copies = realloc(copies, (size_t)(capcopies = capcopies ? capcopies * 2 : 64) * sizeof *copies);
copies[ncopies].g = g;
copies[ncopies++].size = size;
pthread_mutex_unlock(&copies_lock);
}
/* -1 if g isn't a copy, else its size (forgotten unless keep) */
static int64_t copy_find(uint32_t g, int keep)
{
int64_t r = -1;
pthread_mutex_lock(&copies_lock);
for (int k = ncopies - 1; k >= 0; k--)
if (copies[k].g == g) {
r = copies[k].size;
if (!keep) copies[k] = copies[--ncopies];
break;
}
pthread_mutex_unlock(&copies_lock);
return r;
}
static int elem_size(char t)
{
switch (t) {
case 'Z': case 'B': return 1;
case 'C': case 'S': return 2;
case 'J': case 'D': return 8;
default: return 4;
}
}
/* element size of a primitive array from its class name ("[I") */
static int array_elem_size(JNIEnv *env, jarray a)
{
static jmethodID get_name;
jclass k = (*env)->GetObjectClass(env, a);
if (!get_name) get_name = (*env)->GetMethodID(env, (*env)->FindClass(env, "java/lang/Class"), "getName",
"()Ljava/lang/String;");
jstring s = (*env)->CallObjectMethod(env, k, get_name);
const char *n = (*env)->GetStringUTFChars(env, s, NULL);
int r = n && n[0] == '[' ? elem_size(n[1]) : 1;
(*env)->ReleaseStringUTFChars(env, s, n);
(*env)->DeleteLocalRef(env, s);
(*env)->DeleteLocalRef(env, k);
return r;
}
static void set_is_copy(uint32_t is_copy, int v)
{
if (is_copy) st8(is_copy, (uint8_t)v);
}
/* host data p (bytes) -> what the guest gets: p itself when the guest can reach it, else a copy */
static uint32_t share_or_copy(void *p, size_t bytes, int *copied)
{
if (in_guest_reach(p, bytes)) {
*copied = 0;
return p2g(p);
}
uint32_t g = guest_malloc(bytes ? (uint32_t)bytes : 1);
if (g) memcpy(g2p(g), p, bytes);
*copied = 1;
return g;
}
static uint32_t get_elems(JNIEnv *env, char t, jarray a, uint32_t is_copy)
{
void *p = NULL;
switch (t) {
case 'Z': p = (*env)->GetBooleanArrayElements(env, a, NULL); break;
case 'B': p = (*env)->GetByteArrayElements(env, a, NULL); break;
case 'C': p = (*env)->GetCharArrayElements(env, a, NULL); break;
case 'S': p = (*env)->GetShortArrayElements(env, a, NULL); break;
case 'I': p = (*env)->GetIntArrayElements(env, a, NULL); break;
case 'J': p = (*env)->GetLongArrayElements(env, a, NULL); break;
case 'F': p = (*env)->GetFloatArrayElements(env, a, NULL); break;
case 'D': p = (*env)->GetDoubleArrayElements(env, a, NULL); break;
}
if (!p) return 0;
size_t bytes = (size_t)(*env)->GetArrayLength(env, a) * (size_t)elem_size(t);
int copied;
uint32_t g = share_or_copy(p, bytes, &copied);
if (copied) {
switch (t) {
case 'Z': (*env)->ReleaseBooleanArrayElements(env, a, p, JNI_ABORT); break;
case 'B': (*env)->ReleaseByteArrayElements(env, a, p, JNI_ABORT); break;
case 'C': (*env)->ReleaseCharArrayElements(env, a, p, JNI_ABORT); break;
case 'S': (*env)->ReleaseShortArrayElements(env, a, p, JNI_ABORT); break;
case 'I': (*env)->ReleaseIntArrayElements(env, a, p, JNI_ABORT); break;
case 'J': (*env)->ReleaseLongArrayElements(env, a, p, JNI_ABORT); break;
case 'F': (*env)->ReleaseFloatArrayElements(env, a, p, JNI_ABORT); break;
case 'D': (*env)->ReleaseDoubleArrayElements(env, a, p, JNI_ABORT); break;
}
copy_add(g, (uint32_t)bytes);
}
set_is_copy(is_copy, copied);
return g;
}
/* a guest copy of array data goes back through the critical accessor (any element type) */
static void write_back(JNIEnv *env, jarray a, uint32_t g, uint32_t size)
{
void *p = (*env)->GetPrimitiveArrayCritical(env, a, NULL);
if (!p) return;
memcpy(p, g2p(g), size);
(*env)->ReleasePrimitiveArrayCritical(env, a, p, 0);
}
static void release_elems(JNIEnv *env, char t, jarray a, uint32_t g, jint mode)
{
int64_t size = copy_find(g, mode == JNI_COMMIT);
if (size >= 0) {
if (mode != JNI_ABORT) write_back(env, a, g, (uint32_t)size);
if (mode != JNI_COMMIT) guest_free(g);
return;
}
void *p = g2p(g);
switch (t) {
case 'Z': (*env)->ReleaseBooleanArrayElements(env, a, p, mode); break;
case 'B': (*env)->ReleaseByteArrayElements(env, a, p, mode); break;
case 'C': (*env)->ReleaseCharArrayElements(env, a, p, mode); break;
case 'S': (*env)->ReleaseShortArrayElements(env, a, p, mode); break;
case 'I': (*env)->ReleaseIntArrayElements(env, a, p, mode); break;
case 'J': (*env)->ReleaseLongArrayElements(env, a, p, mode); break;
case 'F': (*env)->ReleaseFloatArrayElements(env, a, p, mode); break;
case 'D': (*env)->ReleaseDoubleArrayElements(env, a, p, mode); break;
}
}
/* ---------------------------------------------------------------- dispatch */
static void register_natives(a32_cpu *c, JNIEnv *env, argreader *R)
{
jclass cls = (jclass)h2o(rd32(R));
uint32_t methods = rd32(R);
jint n = (jint)rd32(R);
JNINativeMethod *hm = calloc(n > 0 ? (size_t)n : 1, sizeof *hm);
for (jint k = 0; k < n; k++) {
uint32_t e = methods + 12u * (uint32_t)k;
hm[k].name = g2p(ld32(e));
hm[k].signature = g2p(ld32(e + 4));
hm[k].fnPtr = natives_trampoline_named(ld32(e + 8), hm[k].signature, hm[k].name);
if (!hm[k].fnPtr) {
free(hm);
ret32(c, (uint32_t)JNI_ERR);
return;
}
}
jint r = (*env)->RegisterNatives(env, cls, hm, n);
if (r) bridge_log(ANDROID_LOG_ERROR, "RegisterNatives of %d methods failed (%d)", n, r);
ret32(c, (uint32_t)r);
free(hm);
}
static pthread_once_t unattached_once = PTHREAD_ONCE_INIT;
static void unattached_warning(void) { bridge_log(ANDROID_LOG_ERROR, "JNI call on a thread not attached to the VM"); }
int jni_dispatch(a32_cpu *c, int index)
{
pthread_once(&fn_once, classify);
JNIEnv *env = host_env();
if (!env) {
pthread_once(&unattached_once, unattached_warning);
c->r[0] = c->r[1] = 0;
return 1;
}
argreader R;
ar_init(&R, c, 1, c->r[13] + 8); /* r0 = the guest's JNIEnv; the stub pushed {r7, lr} */
switch (fn[index].special) {
case S_NONE:
if (jni_dispatch_generated(c, env, index, &R)) return 1;
bridge_log(ANDROID_LOG_ERROR, "JNI function %d (%s) is not supported", index, jni_names[index]);
c->r[0] = c->r[1] = 0;
return 1;
case S_CALL:
call_method(c, env, index, &R);
return 1;
case S_GET_METHOD: {
jclass cls = (jclass)h2o(rd32(&R));
const char *name = g2p(rd32(&R)), *sig = g2p(rd32(&R));
jmethodID m = !strcmp(jni_names[index], "GetMethodID") ? (*env)->GetMethodID(env, cls, name, sig)
: (*env)->GetStaticMethodID(env, cls, name, sig);
uint32_t h = mid2h(m);
if (h) {
char shorty[260];
make_shorty(sig, shorty, sizeof shorty);
mid_set_shorty(h, shorty);
if (!strcmp(name, "AndroidThunkJava_GetSignature") && !strcmp(sig, "()Ljava/lang/String;"))
signature_mid = h;
}
ret32(c, h);
return 1;
}
case S_FROM_REFLECTED: {
jobject o = h2o(rd32(&R));
uint32_t h = mid2h((*env)->FromReflectedMethod(env, o));
char shorty[260];
if (h && !mid_shorty(h) && !reflected_shorty(env, o, shorty, sizeof shorty)) mid_set_shorty(h, shorty);
ret32(c, h);
return 1;
}
case S_NEW_GLOBAL:
ret32(c, o2h_global((*env)->NewGlobalRef(env, h2o(rd32(&R)))));
return 1;
case S_NEW_WEAK:
ret32(c, o2h_weak((*env)->NewWeakGlobalRef(env, h2o(rd32(&R)))));
return 1;
case S_DELETE_GLOBAL:
case S_DELETE_LOCAL:
case S_DELETE_WEAK: {
uint32_t h = rd32(&R);
jobject o = h2o(h);
if (o) {
if (fn[index].special == S_DELETE_GLOBAL) (*env)->DeleteGlobalRef(env, o);
else if (fn[index].special == S_DELETE_WEAK) (*env)->DeleteWeakGlobalRef(env, o);
else (*env)->DeleteLocalRef(env, o);
}
h_free(h);
return 1;
}
case S_POP_FRAME:
ret32(c, o2h_local((*env)->PopLocalFrame(env, h2o(rd32(&R)))));
return 1;
case S_GET_STRING_CHARS: {
jstring s = (jstring)h2o(rd32(&R));
uint32_t is_copy = rd32(&R);
jsize n = (*env)->GetStringLength(env, s);
uint32_t g = guest_malloc(2u * (uint32_t)n + 2);
if (g) {
(*env)->GetStringRegion(env, s, 0, n, g2p(g));
st16(g + 2u * (uint32_t)n, 0);
}
set_is_copy(is_copy, 1);
ret32(c, g);
return 1;
}
case S_GET_STRING_UTF: {
jstring s = (jstring)h2o(rd32(&R));
uint32_t is_copy = rd32(&R);
const char *p = (*env)->GetStringUTFChars(env, s, NULL);
uint32_t g = p ? guest_strdup(p) : 0;
if (p) (*env)->ReleaseStringUTFChars(env, s, p);
set_is_copy(is_copy, 1);
ret32(c, g);
return 1;
}
case S_REL_STRING_CHARS:
case S_REL_STRING_UTF:
rd32(&R);
guest_free(rd32(&R));
return 1;
case S_GET_ELEMS: {
jarray a = (jarray)h2o(rd32(&R));
uint32_t is_copy = rd32(&R);
ret32(c, a ? get_elems(env, fn[index].type, a, is_copy) : 0);
return 1;
}
case S_REL_ELEMS: {
jarray a = (jarray)h2o(rd32(&R));
uint32_t g = rd32(&R);
jint mode = (jint)rd32(&R);
release_elems(env, fn[index].type, a, g, mode);
return 1;
}
case S_GET_CRITICAL: {
jarray a = (jarray)h2o(rd32(&R));
uint32_t is_copy = rd32(&R);
void *p = a ? (*env)->GetPrimitiveArrayCritical(env, a, NULL) : NULL;
if (!p) {
ret32(c, 0);
return 1;
}
if (in_guest_reach(p, 1)) {
set_is_copy(is_copy, 0);
ret32(c, p2g(p));
return 1;
}
/* outside the guest's reach: copy (the size needs the class, which can't be asked for in a critical
* region) */
(*env)->ReleasePrimitiveArrayCritical(env, a, p, JNI_ABORT);
uint32_t size = (uint32_t)(*env)->GetArrayLength(env, a) * (uint32_t)array_elem_size(env, a);
uint32_t g = guest_malloc(size ? size : 1);
p = (*env)->GetPrimitiveArrayCritical(env, a, NULL);
if (g && p) memcpy(g2p(g), p, size);
if (p) (*env)->ReleasePrimitiveArrayCritical(env, a, p, JNI_ABORT);
copy_add(g, size);
set_is_copy(is_copy, 1);
ret32(c, g);
return 1;
}
case S_REL_CRITICAL: {
jarray a = (jarray)h2o(rd32(&R));
uint32_t g = rd32(&R);
jint mode = (jint)rd32(&R);
int64_t size = copy_find(g, mode == JNI_COMMIT);
if (size >= 0) {
if (mode != JNI_ABORT) write_back(env, a, g, (uint32_t)size);
if (mode != JNI_COMMIT) guest_free(g);
} else {
(*env)->ReleasePrimitiveArrayCritical(env, a, g2p(g), mode);
}
return 1;
}
case S_REGISTER:
register_natives(c, env, &R);
return 1;
case S_GET_VM:
st32(rd32(&R), g_info.java_vm);
ret32(c, 0);
return 1;
case S_DIRECT_ADDR: {
void *p = (*env)->GetDirectBufferAddress(env, h2o(rd32(&R)));
if (p && !in_guest_reach(p, 1)) {
bridge_log(ANDROID_LOG_ERROR, "GetDirectBufferAddress: buffer at %p is outside the guest's reach", p);
p = NULL;
}
ret32(c, p2g(p));
return 1;
}
}
return 0;
}
/* JNIInvokeInterface: reserved0-2, DestroyJavaVM, AttachCurrentThread, DetachCurrentThread, GetEnv,
* AttachCurrentThreadAsDaemon */
int vm_dispatch(a32_cpu *c, int index)
{
argreader R;
ar_init(&R, c, 1, c->r[13] + 8);
switch (index) {
case 4:
case 7: {
uint32_t penv = rd32(&R), args = rd32(&R);
JavaVMAttachArgs a = {JNI_VERSION_1_6, NULL, NULL}, *ap = NULL;
if (args) {
a.version = (jint)ld32(args);
a.name = ld32(args + 4) ? g2p(ld32(args + 4)) : NULL;
a.group = h2o(ld32(args + 8));
ap = &a;
}
JNIEnv *env = NULL;
jint r = index == 4 ? (*g_vm)->AttachCurrentThread(g_vm, &env, ap)
: (*g_vm)->AttachCurrentThreadAsDaemon(g_vm, &env, ap);
if (penv) st32(penv, r == JNI_OK ? g_info.jni_env : 0);
ret32(c, (uint32_t)r);
return 1;
}
case 5:
ret32(c, (uint32_t)(*g_vm)->DetachCurrentThread(g_vm));
return 1;
case 6: {
uint32_t penv = rd32(&R);
jint version = (jint)rd32(&R);
JNIEnv *env = NULL;
jint r = (*g_vm)->GetEnv(g_vm, (void **)&env, version);
if (penv) st32(penv, r == JNI_OK ? g_info.jni_env : 0);
ret32(c, (uint32_t)r);
return 1;
}
default:
ret32(c, (uint32_t)JNI_ERR);
return 1;
}
}
@@ -0,0 +1,156 @@
/* Host side of the bridge: shared declarations. */
#ifndef A32B_JNI_INTERNAL_H
#define A32B_JNI_INTERNAL_H
#include <android/log.h>
#include <jni.h>
#include <pthread.h>
#include <stdint.h>
#include <string.h>
#include "../../src/interp.h"
#include "../../src/runtime.h"
#include "../../src/threads.h"
#include "../abi.h"
/* ---------------------------------------------------------------- arguments (AAPCS32, softfp) */
/* Reads a guest call's arguments in order: core registers r[ncrn..3], then the stack. Doubleword values take an
* even register pair or an 8-byte aligned stack slot; once one spills, every later argument is on the stack.
* Also reads a va_list (ncrn = 4, nsaa = the va_list pointer). Variadic floats arrive promoted to double. */
typedef struct {
a32_cpu *c;
int ncrn;
uint32_t nsaa;
} argreader;
static inline void ar_init(argreader *R, a32_cpu *c, int first, uint32_t stack)
{
R->c = c;
R->ncrn = first;
R->nsaa = stack;
}
static inline uint32_t rd32(argreader *R)
{
if (R->ncrn < 4) return R->c->r[R->ncrn++];
uint32_t v = ld32(R->nsaa);
R->nsaa += 4;
return v;
}
static inline uint64_t rd64(argreader *R)
{
if (R->ncrn & 1) R->ncrn++;
if (R->ncrn <= 2) {
uint64_t v = R->c->r[R->ncrn] | (uint64_t)R->c->r[R->ncrn + 1] << 32;
R->ncrn += 2;
return v;
}
R->ncrn = 4;
R->nsaa = (R->nsaa + 7) & ~7u;
uint64_t v = ld64(R->nsaa);
R->nsaa += 8;
return v;
}
static inline float rdf(argreader *R)
{
uint32_t b = rd32(R);
float f;
memcpy(&f, &b, 4);
return f;
}
static inline double rdd(argreader *R)
{
uint64_t b = rd64(R);
double d;
memcpy(&d, &b, 8);
return d;
}
/* host data the guest can address directly (it lies in the low 4 GiB) */
static inline int in_guest_reach(const void *p, size_t n) { return (uintptr_t)p + n <= 0x100000000ull; }
static inline void *g2p(uint32_t a) { return (void *)(uintptr_t)a; }
static inline uint32_t p2g(const void *p) { return (uint32_t)(uintptr_t)p; }
static inline void ret32(a32_cpu *c, uint32_t v) { c->r[0] = v; }
static inline void ret64(a32_cpu *c, uint64_t v)
{
c->r[0] = (uint32_t)v;
c->r[1] = (uint32_t)(v >> 32);
}
static inline void retf(a32_cpu *c, float f)
{
uint32_t b;
memcpy(&b, &f, 4);
c->r[0] = b;
}
static inline void retd(a32_cpu *c, double d)
{
uint64_t b;
memcpy(&b, &d, 8);
ret64(c, b);
}
/* Builds a guest call's argument words (AAPCS32): doublewords at an even word index (registers r0-r3 are words
* 0-3, the stack follows 8-byte aligned). */
typedef struct {
uint32_t w[64];
int n;
} argbuilder;
static inline void ab_32(argbuilder *B, uint32_t v)
{
if (B->n < 64) B->w[B->n++] = v;
}
static inline void ab_64(argbuilder *B, uint64_t v)
{
if (B->n & 1) ab_32(B, 0);
ab_32(B, (uint32_t)v);
ab_32(B, (uint32_t)(v >> 32));
}
/* ---------------------------------------------------------------- handles (handles.c) */
/* Guest code holds 32-bit values; host references and IDs are 64-bit pointers. Each gets a handle. */
uint32_t o2h_local(jobject o); /* a local reference: freed with the current native frame */
uint32_t o2h_global(jobject o);
uint32_t o2h_weak(jobject o);
uint32_t o2h_keep(jobject o); /* a host reference the bridge owns (never freed by the guest) */
jobject h2o(uint32_t h);
void h_free(uint32_t h); /* forgets the handle (the host reference is the caller's business) */
uint32_t mid2h(jmethodID m);
jmethodID h2mid(uint32_t h);
uint32_t fid2h(jfieldID f);
jfieldID h2fid(uint32_t h);
uint32_t ptr2h(void *p); /* other host pointers (ANativeWindow *, AAssetManager *, ...) */
void *h2ptr(uint32_t h);
/* the method's argument types: 'Z','B','C','S','I','J','F','D','L' per parameter, then the result after ')' */
void mid_set_shorty(uint32_t h, const char *shorty);
const char *mid_shorty(uint32_t h);
/* native frames: local handles created after frame_mark() are forgotten by frame_pop() */
uint32_t frame_mark(void);
void frame_pop(uint32_t mark);
/* ---------------------------------------------------------------- bridge (bridge.c) */
extern struct grt_info g_info;
extern JavaVM *g_vm;
JNIEnv *host_env(void); /* NULL if this thread isn't attached to the VM */
void bridge_log(int prio, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
/* calls a guest function on this thread's guest context (attaching one first if needed) */
uint64_t guest_call(uint32_t fn, const uint32_t *words, int n);
uint32_t guest_malloc(uint32_t size);
void guest_free(uint32_t p);
uint32_t guest_strdup(const char *s);
uint32_t guest_cstr(const char *s); /* a host string the guest can read: itself, or a copy kept for good */
/* jni.c */
int jni_dispatch(a32_cpu *c, int index);
int vm_dispatch(a32_cpu *c, int index);
int jni_dispatch_generated(a32_cpu *c, JNIEnv *env, int index, argreader *R);
extern const char *const jni_names[JNI_TABLE_SIZE];
void make_shorty(const char *sig, char *out, size_t n);
#endif
@@ -0,0 +1,230 @@
/* NativeActivity for guest libraries. The guest gets its own 32-bit ANativeActivity (and callback table) that
* mirrors the host's; the host activity's callbacks forward to whatever the guest's ANativeActivity_onCreate put
* in its table. Windows, input queues and the asset manager are host pointers: the guest sees handles (ptr2h). */
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <stdlib.h>
#include "imports_internal.h"
/* struct ANativeActivity, 32-bit */
#define GA_CALLBACKS 0
#define GA_VM 4
#define GA_ENV 8
#define GA_CLAZZ 12
#define GA_INTERNAL_PATH 16
#define GA_EXTERNAL_PATH 20
#define GA_SDK 24
#define GA_INSTANCE 28
#define GA_ASSETS 32
#define GA_OBB_PATH 36
#define GA_SIZE 40
#define NCALLBACKS 16 /* ANativeActivityCallbacks: onStart ... onLowMemory */
enum {
CB_START, CB_RESUME, CB_SAVE_STATE, CB_PAUSE, CB_STOP, CB_DESTROY, CB_FOCUS, CB_WINDOW_CREATED,
CB_WINDOW_RESIZED, CB_WINDOW_REDRAW, CB_WINDOW_DESTROYED, CB_QUEUE_CREATED, CB_QUEUE_DESTROYED, CB_CONTENT_RECT,
CB_CONFIG, CB_LOW_MEMORY,
};
typedef struct {
ANativeActivity *host;
uint32_t guest;
} activity;
static activity acts[8];
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
/* What UE4's GameActivity.AndroidThunkJava_GetSignature() returned for the original APK (Base64 of the SHA-1 of its
* signing certificate, with Base64.DEFAULT's newline): the conversion stores it in assets/fp_a32_signature.txt (patch
* frame.a32_bridge), jni.c answers the guest's call with it, since the re-signed APK has another certificate. */
char *g_orig_signature;
/* weak: the PC test harness has no libandroid */
extern __typeof__(AAssetManager_open) AAssetManager_open __attribute__((weak));
extern __typeof__(AAsset_getLength) AAsset_getLength __attribute__((weak));
extern __typeof__(AAsset_read) AAsset_read __attribute__((weak));
extern __typeof__(AAsset_close) AAsset_close __attribute__((weak));
static void load_orig_signature(AAssetManager *mgr)
{
if (g_orig_signature || !mgr || !AAssetManager_open) return;
AAsset *asset = AAssetManager_open(mgr, "fp_a32_signature.txt", AASSET_MODE_BUFFER);
if (!asset) return;
off_t n = AAsset_getLength(asset);
char *s = n > 0 && n < 256 ? malloc((size_t)n + 1) : NULL;
if (s && AAsset_read(asset, s, (size_t)n) == n) {
s[n] = 0;
g_orig_signature = s;
bridge_log(ANDROID_LOG_INFO, "original APK signature loaded (%d bytes)", (int)n);
} else {
free(s);
}
AAsset_close(asset);
}
ANativeActivity *guest_activity(uint32_t g)
{
ANativeActivity *r = NULL;
pthread_mutex_lock(&lock);
for (int k = 0; k < 8; k++)
if (acts[k].guest == g && g) r = acts[k].host;
pthread_mutex_unlock(&lock);
return r;
}
static uint32_t guest_of(ANativeActivity *a)
{
uint32_t r = 0;
pthread_mutex_lock(&lock);
for (int k = 0; k < 8; k++)
if (acts[k].host == a) r = acts[k].guest;
pthread_mutex_unlock(&lock);
return r;
}
/* calls the guest's callback cb (if it set one) with the guest activity and up to two more words */
static const char *const CB_NAMES[NCALLBACKS] = {
"onStart", "onResume", "onSaveInstanceState", "onPause", "onStop", "onDestroy", "onWindowFocusChanged",
"onNativeWindowCreated", "onNativeWindowResized", "onNativeWindowRedrawNeeded", "onNativeWindowDestroyed",
"onInputQueueCreated", "onInputQueueDestroyed", "onContentRectChanged", "onConfigurationChanged", "onLowMemory",
};
static uint64_t forward(ANativeActivity *a, int cb, int n, uint32_t w1, uint32_t w2, int *called)
{
uint32_t g = guest_of(a);
uint32_t fn = g ? ld32(ld32(g + GA_CALLBACKS) + 4u * (uint32_t)cb) : 0;
if (cb != CB_WINDOW_REDRAW && cb != CB_CONTENT_RECT) /* the lifecycle, for logs (rare) */
bridge_log(ANDROID_LOG_INFO, "activity %s(0x%x)%s", CB_NAMES[cb], w1, fn ? "" : " (no guest callback)");
if (called) *called = fn != 0;
if (!fn) return 0;
uint32_t w[3] = {g, w1, w2};
return guest_call(fn, w, n + 1);
}
static void on_start(ANativeActivity *a) { forward(a, CB_START, 0, 0, 0, NULL); }
static void on_resume(ANativeActivity *a) { forward(a, CB_RESUME, 0, 0, 0, NULL); }
static void on_pause(ANativeActivity *a) { forward(a, CB_PAUSE, 0, 0, 0, NULL); }
static void on_stop(ANativeActivity *a) { forward(a, CB_STOP, 0, 0, 0, NULL); }
static void on_low_memory(ANativeActivity *a) { forward(a, CB_LOW_MEMORY, 0, 0, 0, NULL); }
static void on_config(ANativeActivity *a) { forward(a, CB_CONFIG, 0, 0, 0, NULL); }
static void on_focus(ANativeActivity *a, int focused) { forward(a, CB_FOCUS, 1, (uint32_t)focused, 0, NULL); }
volatile int g_window_w, g_window_h;
extern __typeof__(ANativeWindow_getWidth) ANativeWindow_getWidth __attribute__((weak));
extern __typeof__(ANativeWindow_getHeight) ANativeWindow_getHeight __attribute__((weak));
static void note_window(ANativeWindow *w)
{
if (!w || !ANativeWindow_getWidth || !ANativeWindow_getHeight) return;
int ww = ANativeWindow_getWidth(w), wh = ANativeWindow_getHeight(w);
if (ww > 0 && wh > 0) g_window_w = ww, g_window_h = wh;
}
static void on_window_created(ANativeActivity *a, ANativeWindow *w)
{
note_window(w);
forward(a, CB_WINDOW_CREATED, 1, ptr2h(w), 0, NULL);
}
static void on_window_resized(ANativeActivity *a, ANativeWindow *w)
{
note_window(w);
forward(a, CB_WINDOW_RESIZED, 1, ptr2h(w), 0, NULL);
}
static void on_window_redraw(ANativeActivity *a, ANativeWindow *w) { forward(a, CB_WINDOW_REDRAW, 1, ptr2h(w), 0, NULL); }
static void on_window_destroyed(ANativeActivity *a, ANativeWindow *w) { forward(a, CB_WINDOW_DESTROYED, 1, ptr2h(w), 0, NULL); }
static void on_queue_created(ANativeActivity *a, AInputQueue *q) { forward(a, CB_QUEUE_CREATED, 1, ptr2h(q), 0, NULL); }
static void on_queue_destroyed(ANativeActivity *a, AInputQueue *q)
{
forward(a, CB_QUEUE_DESTROYED, 1, ptr2h(q), 0, NULL);
input_queue_detached(q);
}
static void on_content_rect(ANativeActivity *a, const ARect *r)
{
uint32_t g = guest_malloc(sizeof *r);
if (!g) return;
memcpy(g2p(g), r, sizeof *r);
forward(a, CB_CONTENT_RECT, 1, g, 0, NULL);
guest_free(g);
}
static void *on_save_state(ANativeActivity *a, size_t *out_len)
{
*out_len = 0;
uint32_t len = guest_malloc(4);
if (!len) return NULL;
st32(len, 0);
int called;
uint32_t p = (uint32_t)forward(a, CB_SAVE_STATE, 1, len, 0, &called);
void *r = NULL;
uint32_t n = ld32(len);
if (p && n) {
/* the framework frees the result with free() */
r = malloc(n);
if (r) {
memcpy(r, g2p(p), n);
*out_len = n;
}
}
guest_free(p);
guest_free(len);
return r;
}
static void on_destroy(ANativeActivity *a)
{
forward(a, CB_DESTROY, 0, 0, 0, NULL);
pthread_mutex_lock(&lock);
for (int k = 0; k < 8; k++)
if (acts[k].host == a) acts[k].host = NULL, acts[k].guest = 0;
pthread_mutex_unlock(&lock);
/* the guest structures stay: the guest may still look at them while it shuts down */
}
void activity_create(ANativeActivity *a, void *saved, size_t saved_size, uint32_t oncreate)
{
load_orig_signature(a->assetManager);
uint32_t g = guest_malloc(GA_SIZE + 4 * NCALLBACKS);
memset(g2p(g), 0, GA_SIZE + 4 * NCALLBACKS);
st32(g + GA_CALLBACKS, g + GA_SIZE);
st32(g + GA_VM, g_info.java_vm);
st32(g + GA_ENV, g_info.jni_env);
st32(g + GA_CLAZZ, o2h_keep(a->clazz));
st32(g + GA_INTERNAL_PATH, a->internalDataPath ? guest_strdup(a->internalDataPath) : 0);
st32(g + GA_EXTERNAL_PATH, a->externalDataPath ? guest_strdup(a->externalDataPath) : 0);
st32(g + GA_SDK, (uint32_t)a->sdkVersion);
st32(g + GA_ASSETS, ptr2h(a->assetManager));
st32(g + GA_OBB_PATH, a->obbPath ? guest_strdup(a->obbPath) : 0);
pthread_mutex_lock(&lock);
int k = 0;
while (k < 7 && acts[k].host) k++;
acts[k].host = a;
acts[k].guest = g;
pthread_mutex_unlock(&lock);
ANativeActivityCallbacks *cb = a->callbacks;
cb->onStart = on_start;
cb->onResume = on_resume;
cb->onSaveInstanceState = on_save_state;
cb->onPause = on_pause;
cb->onStop = on_stop;
cb->onDestroy = on_destroy;
cb->onWindowFocusChanged = on_focus;
cb->onNativeWindowCreated = on_window_created;
cb->onNativeWindowResized = on_window_resized;
cb->onNativeWindowRedrawNeeded = on_window_redraw;
cb->onNativeWindowDestroyed = on_window_destroyed;
cb->onInputQueueCreated = on_queue_created;
cb->onInputQueueDestroyed = on_queue_destroyed;
cb->onContentRectChanged = on_content_rect;
cb->onConfigurationChanged = on_config;
cb->onLowMemory = on_low_memory;
uint32_t gs = 0;
if (saved && saved_size) {
gs = guest_malloc((uint32_t)saved_size);
if (gs) memcpy(g2p(gs), saved, saved_size);
}
uint32_t w[3] = {g, gs, (uint32_t)saved_size};
guest_call(oncreate, w, 3);
bridge_log(ANDROID_LOG_INFO, "guest ANativeActivity_onCreate done");
}
+272
View File
@@ -0,0 +1,272 @@
/* Java native methods implemented by guest code. RegisterNatives (jni.c) and the exported Java_* functions of a
* guest library both end up as a trampoline slot (tramp.S) that ART calls with the host ABI; a32b_native_call
* converts the arguments to AAPCS32 (objects become handles, valid until the native method returns) and calls the
* guest function. */
#include <stdlib.h>
#include "imports_internal.h"
#define NTRAMP 4096 /* tramp.S */
extern const char a32b_tramp_table[];
typedef struct {
uint32_t fn;
char *shorty;
char *name; /* for A32B_TRACE */
} native;
int a32b_trace = -1; /* A32B_TRACE=1: log native registrations and calls */
static int tracing(void)
{
if (a32b_trace < 0) a32b_trace = getenv("A32B_TRACE") != NULL;
return a32b_trace;
}
static native natives[NTRAMP];
static int nnatives;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *natives_trampoline_named(uint32_t fn, const char *sig, const char *name)
{
char shorty[260];
make_shorty(sig, shorty, sizeof shorty);
pthread_mutex_lock(&lock);
int k;
for (k = 0; k < nnatives; k++)
if (natives[k].fn == fn && !strcmp(natives[k].shorty, shorty)) break;
if (k == nnatives) {
if (nnatives == NTRAMP) {
pthread_mutex_unlock(&lock);
bridge_log(ANDROID_LOG_ERROR, "out of native method trampolines (%d)", NTRAMP);
return NULL;
}
natives[k].fn = fn;
natives[k].shorty = strdup(shorty);
natives[k].name = strdup(name ? name : "?");
__atomic_store_n(&nnatives, k + 1, __ATOMIC_RELEASE);
}
pthread_mutex_unlock(&lock);
if (tracing()) bridge_log(ANDROID_LOG_INFO, "native %s%s -> guest 0x%08x (slot %d)", name ? name : "?", sig, fn, k);
return (void *)(a32b_tramp_table + 8 * k);
}
void *natives_trampoline(uint32_t fn, const char *sig) { return natives_trampoline_named(fn, sig, NULL); }
__attribute__((visibility("hidden"))) uint64_t a32b_native_call(uint64_t index, const uint64_t *gpr,
const uint64_t *fpr, const uint64_t *stack)
{
const native *nt = &natives[index];
if (tracing()) bridge_log(ANDROID_LOG_INFO, "call %s", nt->name);
uint32_t mark = frame_mark();
argbuilder B;
B.n = 0;
ab_32(&B, g_info.jni_env);
ab_32(&B, o2h_local((jobject)gpr[1])); /* this or the class */
int ng = 2, nf = 0, ns = 0;
for (const char *p = nt->shorty; *p != ')'; p++) {
uint64_t v = (*p == 'F' || *p == 'D') ? (nf < 8 ? fpr[nf++] : stack[ns++]) : (ng < 8 ? gpr[ng++] : stack[ns++]);
switch (*p) {
case 'Z': ab_32(&B, (uint8_t)v); break;
case 'B': ab_32(&B, (uint32_t)(int32_t)(int8_t)v); break;
case 'C': ab_32(&B, (uint16_t)v); break;
case 'S': ab_32(&B, (uint32_t)(int32_t)(int16_t)v); break;
case 'I':
case 'F': ab_32(&B, (uint32_t)v); break; /* a float's bits are the low half of its register / slot */
case 'J':
case 'D': ab_64(&B, v); break;
default: ab_32(&B, o2h_local((jobject)v)); break;
}
}
uint64_t r = guest_call(nt->fn, B.w, B.n);
const char *rt = strchr(nt->shorty, ')') + 1;
switch (*rt) {
case 'V': r = 0; break;
case 'Z': r = (uint8_t)r; break;
case 'B': r = (uint64_t)(int64_t)(int8_t)r; break;
case 'C': r = (uint16_t)r; break;
case 'S': r = (uint64_t)(int64_t)(int16_t)r; break;
case 'I': r = (uint64_t)(int64_t)(int32_t)r; break;
case 'F': r = (uint32_t)r; break;
case 'J':
case 'D': break;
default: r = (uint64_t)(uintptr_t)h2o((uint32_t)r); break; /* still a valid reference: popped below is only the handle */
}
frame_pop(mark);
return r;
}
/* ---------------------------------------------------------------- Java_* exports */
/* JNI short/long names: Java_<class>_<method>[__<argument types>] with '/' as '_' and the escapes _0xxxx (UTF-16
* unit), _1 '_', _2 ';', _3 '['. Returns 0 and fills cls ("a/b/C"), method and args (the long name's argument
* types, "" for a short name; *has_args says which). */
static int demangle(const char *s, char *cls, char *method, char *args, size_t n, int *has_args)
{
char path[512];
size_t k = 0;
char *out = path;
size_t cap = sizeof path;
*has_args = 0;
args[0] = 0;
for (s += 5; *s; s++) {
char ch = *s;
if (ch == '_') {
char e = s[1];
if (e == '1') ch = '_', s++;
else if (e == '2') ch = ';', s++;
else if (e == '3') ch = '[', s++;
else if (e == '0') {
unsigned u = 0;
for (int j = 0; j < 4; j++) {
char h = s[2 + j];
if (!h) return -1;
u = u * 16 + (unsigned)(h <= '9' ? h - '0' : (h | 0x20) - 'a' + 10);
}
s += 5;
if (u >= 0x80) return -1; /* non-ASCII class names: not worth it */
ch = (char)u;
} else if (e == '_' && out == path) {
/* start of the long name's argument types */
out[k] = 0;
out = args;
cap = n;
k = 0;
*has_args = 1;
s++;
continue;
} else {
ch = '/';
}
}
if (k + 1 >= cap) return -1;
out[k++] = ch;
}
out[k] = 0;
char *slash = strrchr(path, '/');
if (!slash) return -1;
*slash = 0;
snprintf(cls, n, "%s", path);
snprintf(method, n, "%s", slash + 1);
return 0;
}
/* descriptor of a class object: "I", "Ljava/lang/String;", "[I" */
static void class_descriptor(JNIEnv *env, jclass k, jmethodID get_name, char *out, size_t n)
{
jstring s = (*env)->CallObjectMethod(env, k, get_name);
const char *nm = s ? (*env)->GetStringUTFChars(env, s, NULL) : NULL;
out[0] = 0;
if (nm) {
static const char *const prim[] = {"boolean", "byte", "char", "short", "int", "long", "float", "double",
"void"};
static const char letters[] = "ZBCSIJFDV";
int found = 0;
for (int i = 0; i < 9; i++)
if (!strcmp(nm, prim[i])) snprintf(out, n, "%c", letters[i]), found = 1;
if (!found) snprintf(out, n, nm[0] == '[' ? "%s" : "L%s;", nm);
for (char *p = out; *p; p++)
if (*p == '.') *p = '/';
(*env)->ReleaseStringUTFChars(env, s, nm);
}
if (s) (*env)->DeleteLocalRef(env, s);
}
/* The JNI signature of the native method `name` of cls (with argument types args when has_args). */
static int native_signature(JNIEnv *env, jclass cls, const char *name, const char *args, int has_args, char *sig,
size_t n)
{
jclass kc = (*env)->FindClass(env, "java/lang/Class");
jclass km = (*env)->FindClass(env, "java/lang/reflect/Method");
jmethodID get_methods = (*env)->GetMethodID(env, kc, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;");
jmethodID get_name = (*env)->GetMethodID(env, kc, "getName", "()Ljava/lang/String;");
jmethodID m_name = (*env)->GetMethodID(env, km, "getName", "()Ljava/lang/String;");
jmethodID m_mods = (*env)->GetMethodID(env, km, "getModifiers", "()I");
jmethodID m_params = (*env)->GetMethodID(env, km, "getParameterTypes", "()[Ljava/lang/Class;");
jmethodID m_ret = (*env)->GetMethodID(env, km, "getReturnType", "()Ljava/lang/Class;");
if (!get_methods || !get_name || !m_name || !m_mods || !m_params || !m_ret) return -1;
jobjectArray ms = (*env)->CallObjectMethod(env, cls, get_methods);
if (!ms || (*env)->ExceptionCheck(env)) return -1;
int found = -1;
jsize nm = (*env)->GetArrayLength(env, ms);
for (jsize i = 0; i < nm && found; i++) {
jobject m = (*env)->GetObjectArrayElement(env, ms, i);
jstring mn = (*env)->CallObjectMethod(env, m, m_name);
const char *mname = (*env)->GetStringUTFChars(env, mn, NULL);
int match = mname && !strcmp(mname, name) && ((*env)->CallIntMethod(env, m, m_mods) & 0x100 /* native */);
if (mname) (*env)->ReleaseStringUTFChars(env, mn, mname);
(*env)->DeleteLocalRef(env, mn);
if (match) {
char buf[1024], d[256];
size_t k = 0;
buf[k++] = '(';
jobjectArray ps = (*env)->CallObjectMethod(env, m, m_params);
jsize np = ps ? (*env)->GetArrayLength(env, ps) : 0;
for (jsize j = 0; j < np; j++) {
jclass pk = (*env)->GetObjectArrayElement(env, ps, j);
class_descriptor(env, pk, get_name, d, sizeof d);
(*env)->DeleteLocalRef(env, pk);
k += (size_t)snprintf(buf + k, sizeof buf - k, "%s", d);
if (k >= sizeof buf - 1) break;
}
if (ps) (*env)->DeleteLocalRef(env, ps);
buf[k] = 0;
if (!has_args || !strcmp(buf + 1, args)) {
jclass rk = (*env)->CallObjectMethod(env, m, m_ret);
class_descriptor(env, rk, get_name, d, sizeof d);
(*env)->DeleteLocalRef(env, rk);
snprintf(sig, n, "%s)%s", buf, d);
found = 0;
}
}
(*env)->DeleteLocalRef(env, m);
}
(*env)->DeleteLocalRef(env, ms);
return found;
}
void natives_register_java(JNIEnv *env, uint32_t handle, const char *libname)
{
uint32_t prefix = guest_strdup("Java_");
uint32_t w[2] = {handle, prefix};
uint32_t list = (uint32_t)guest_call(g_info.fn_list_symbols, w, 2);
guest_free(prefix);
if (!list) return;
int ok = 0, failed = 0;
for (uint32_t e = list; ld32(e); e += 8) {
const char *sym = g2p(ld32(e));
uint32_t addr = ld32(e + 4);
char cls[512], method[512], args[512], sig[1024];
int has_args;
if (demangle(sym, cls, method, args, sizeof cls, &has_args)) {
bridge_log(ANDROID_LOG_WARN, "%s: can't decode %s", libname, sym);
failed++;
continue;
}
jclass k = (*env)->FindClass(env, cls);
if (!k) {
(*env)->ExceptionClear(env);
bridge_log(ANDROID_LOG_WARN, "%s: %s: class %s not found", libname, sym, cls);
failed++;
continue;
}
if (native_signature(env, k, method, args, has_args, sig, sizeof sig)) {
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
bridge_log(ANDROID_LOG_WARN, "%s: %s: no native method %s in %s", libname, sym, method, cls);
(*env)->DeleteLocalRef(env, k);
failed++;
continue;
}
JNINativeMethod m = {method, sig, natives_trampoline_named(addr, sig, method)};
if (!m.fnPtr || (*env)->RegisterNatives(env, k, &m, 1)) {
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
bridge_log(ANDROID_LOG_WARN, "%s: registering %s.%s%s failed", libname, cls, method, sig);
failed++;
} else {
ok++;
}
(*env)->DeleteLocalRef(env, k);
}
guest_free(list);
if (ok || failed) bridge_log(ANDROID_LOG_INFO, "%s: %d Java_ functions registered, %d not", libname, ok, failed);
}
+22
View File
@@ -0,0 +1,22 @@
/* The stub: one copy per 32-bit library, renamed to that library's name (libX.so; the guest code is libX.a32.so).
* It only finds its own path and hands JNI_OnLoad / ANativeActivity_onCreate to the bridge. */
#include <dlfcn.h>
#include <stddef.h>
#include "a32bridge.h"
static const char *self_path(void)
{
Dl_info info;
return dladdr((void *)self_path, &info) && info.dli_fname ? info.dli_fname : "";
}
A32B_API jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
(void)reserved;
return a32b_jni_onload(vm, self_path());
}
A32B_API void ANativeActivity_onCreate(struct ANativeActivity *activity, void *saved, size_t saved_size)
{
a32b_native_activity_oncreate(activity, saved, saved_size, self_path());
}
+44
View File
@@ -0,0 +1,44 @@
/* Native method trampolines: ART calls a32b_tramp_table + 8 * n with the AAPCS64 JNI arguments; slot n says which
* guest function and shorty (natives.c). Every slot is "adr x16, . ; b common": common turns x16 into the slot
* number, saves the argument registers and calls a32b_native_call(n, gpr[8], fpr[8], stack args). The result comes
* back in x0 and is copied to d0 as well (float and double results use s0/d0). */
#define NTRAMP 4096
.text
.p2align 3
.global a32b_tramp_table
.hidden a32b_tramp_table
.type a32b_tramp_table, %function
a32b_tramp_table:
.rept NTRAMP
adr x16, .
b a32b_tramp_common
.endr
.size a32b_tramp_table, . - a32b_tramp_table
.type a32b_tramp_common, %function
a32b_tramp_common:
stp x29, x30, [sp, #-160]!
mov x29, sp
stp x0, x1, [sp, #16]
stp x2, x3, [sp, #32]
stp x4, x5, [sp, #48]
stp x6, x7, [sp, #64]
stp d0, d1, [sp, #80]
stp d2, d3, [sp, #96]
stp d4, d5, [sp, #112]
stp d6, d7, [sp, #128]
adrp x17, a32b_tramp_table
add x17, x17, :lo12:a32b_tramp_table
sub x0, x16, x17
lsr x0, x0, #3
add x1, sp, #16
add x2, sp, #80
add x3, sp, #160
bl a32b_native_call
fmov d0, x0
ldp x29, x30, [sp], #160
ret
.size a32b_tramp_common, . - a32b_tramp_common
.section .note.GNU-stack, "", %progbits
File diff suppressed because it is too large. Load diff
+183
View File
@@ -0,0 +1,183 @@
# Host functions guest libraries can call (libandroid, ...). One per line: [!] <result> <name>(<arguments>)
# Types: v void, I 32-bit int, J 64-bit int, f float, P guest pointer (passed through: guest memory is host memory),
# H host pointer handle (ANativeWindow*, ...: a 32-bit handle on the guest side), A ANativeActivity*, E JNIEnv*
# (the guest's -> the thread's own), O jobject (handle). Results also: S string (copied into guest memory).
# "!" = written by hand in host/android.c or host/input.c (input events) as imp_<name>(a32_cpu *c, argreader *R).
# The host functions are weak references: one the system lacks logs its name and returns 0.
! v ANativeActivity_finish(A)
v ANativeActivity_setWindowFormat(AI)
v ANativeActivity_setWindowFlags(AII)
v ANativeActivity_showSoftInput(AI)
v ANativeActivity_hideSoftInput(AI)
v ANativeWindow_acquire(H)
v ANativeWindow_release(H)
I ANativeWindow_getWidth(H)
I ANativeWindow_getHeight(H)
I ANativeWindow_getFormat(H)
I ANativeWindow_setBuffersGeometry(HIII)
H ANativeWindow_fromSurface(EO)
H AAssetManager_fromJava(EO)
! I AInputEvent_getType(H)
! I AInputEvent_getDeviceId(H)
! I AInputEvent_getSource(H)
! I AKeyEvent_getAction(H)
! I AKeyEvent_getKeyCode(H)
! I AKeyEvent_getMetaState(H)
! I AKeyEvent_getRepeatCount(H)
! I AKeyEvent_getFlags(H)
H ALooper_forThread()
H ALooper_prepare(I)
H ASensorManager_getInstance()
H ASensorManager_getInstanceForPackage(P)
H ASensorManager_getDefaultSensor(HI)
! I ASensorManager_getSensorList(HP)
! H ASensorManager_createEventQueue(HHIPP)
I ASensorManager_destroyEventQueue(HH)
I ASensorEventQueue_enableSensor(HH)
I ASensorEventQueue_disableSensor(HH)
I ASensorEventQueue_setEventRate(HHI)
I ASensorEventQueue_hasEvents(H)
I ASensorEventQueue_getEvents(HPI)
I ASensor_getMinDelay(H)
S ASensor_getName(H)
S ASensor_getVendor(H)
I ASensor_getType(H)
f ASensor_getResolution(H)
# VrApi 1.x (Gear VR era: vrapi_SubmitFrame/ovrFrameParms), translated to the 64-bit VrApi bridge (host/vrapi.c)
! I vrapi_Initialize(P)
! v vrapi_Shutdown()
! S vrapi_GetVersionString()
! v vrapi_GetTimeInSeconds()
! I vrapi_GetSystemPropertyInt(PI)
! f vrapi_GetSystemPropertyFloat(PI)
! S vrapi_GetSystemPropertyString(PI)
! I vrapi_GetSystemStatusInt(PI)
! f vrapi_GetSystemStatusFloat(PI)
! H vrapi_EnterVrMode(P)
! v vrapi_LeaveVrMode(H)
! v vrapi_GetPredictedDisplayTime(HJ)
! v vrapi_GetPredictedTracking(PH)
! v vrapi_RecenterPose(H)
! H vrapi_CreateTextureSwapChain(IIIIII)
! H vrapi_CreateTextureSwapChain2(IIIIII)
! v vrapi_DestroyTextureSwapChain(H)
! I vrapi_GetTextureSwapChainLength(H)
! I vrapi_GetTextureSwapChainHandle(HI)
! v vrapi_SetTextureSwapChainHandle(HII)
! v vrapi_SubmitFrame(HP)
! I vrapi_EnumerateInputDevices(HIP)
! I vrapi_GetInputDeviceCapabilities(HP)
! I vrapi_GetCurrentInputState(HIP)
! I vrapi_GetInputTrackingState(HIJP)
! v vrapi_RecenterInputPose(HI)
! I vrapi_SetRemoteEmulation(HI)
! v vrapi_SetPropertyInt(PII)
! v vrapi_SetPropertyFloat(PIf)
! I vrapi_GetPropertyInt(PI)
! I vrapi_ShowSystemUI(PI)
! I vrapi_ShowSystemUIWithExtra(PIP)
! v vrapi_ShowFatalError(PPPP)
! v vrapi_ReturnToHome(P)
! P ovr_GetLocalPreferenceValueForKey(PP)
! v ovr_SetLocalPreferenceValueForKey(PP)
# audio output for guest/opensles.c (AAudio)
! H a32_audio_open(III)
! I a32_audio_write(HPI)
! v a32_audio_start(H)
! v a32_audio_pause(H)
! v a32_audio_close(H)
# VrApi 1.2x-1.4x (Go/Quest era: vrapi_SubmitFrame2, WaitFrame/BeginFrame), same translation (host/vrapi.c)
! H vrapi_CreateTextureSwapChain3(IJIIII)
! v vrapi_GetPredictedTracking2(PHD)
! I vrapi_SubmitFrame2(HP)
! I vrapi_WaitFrame(HJ)
! I vrapi_BeginFrame(HJ)
! I vrapi_SetDisplayRefreshRate(Hf)
! I vrapi_PollEvent(P)
! I vrapi_GetSystemPropertyFloatArray(PIPI)
! I vrapi_SetTrackingSpace(HI)
! I vrapi_GetTrackingSpace(H)
! v vrapi_LocateTrackingSpace(PHI)
! v vrapi_GetTrackingTransform(PHI)
! v vrapi_SetTrackingTransform(Hfffffff)
! I vrapi_GetBoundaryGeometry(HIPP)
! I vrapi_GetBoundaryOrientedBoundingBox(HPP)
! I vrapi_TestPointIsInBoundary(HPPP)
! I vrapi_GetBoundaryTriggerState(HIP)
! I vrapi_RequestBoundaryVisible(HI)
! I vrapi_GetBoundaryVisible(HP)
! I vrapi_SetHapticVibrationSimple(HIf)
! I vrapi_SetHapticVibrationBuffer(HIP)
! I vrapi_SetClockLevels(HII)
! I vrapi_SetPerfThread(HII)
! I vrapi_SetExtraLatencyMode(HI)
! H vrapi_CreateAndroidSurfaceSwapChain(II)
! H vrapi_CreateAndroidSurfaceSwapChain2(IIIP)
! H vrapi_GetTextureSwapChainAndroidSurface(H)
! I vrapi_CreateSystemVulkan(P)
! v vrapi_DestroySystemVulkan()
! I vrapi_GetInstanceExtensionsVulkan(PP)
! I vrapi_GetDeviceExtensionsVulkan(PP)
! I vrapi_GetTextureSwapChainBufferVulkan(HI)
! I vrapi_GetTextureSwapChainBufferFoveationVulkan(HIPP)
# NativeActivity games built on android_native_app_glue (e.g. Unreal 4.10 Gear VR games): looper, input queue,
# configuration and assets
H AConfiguration_new()
v AConfiguration_delete(H)
v AConfiguration_fromAssetManager(HH)
v AConfiguration_getLanguage(HP)
v AConfiguration_getCountry(HP)
I AConfiguration_getOrientation(H)
I AConfiguration_getDensity(H)
I AConfiguration_getSdkVersion(H)
I AConfiguration_getMcc(H)
I AConfiguration_getMnc(H)
I AConfiguration_getTouchscreen(H)
I AConfiguration_getKeyboard(H)
I AConfiguration_getNavigation(H)
I AConfiguration_getKeysHidden(H)
I AConfiguration_getNavHidden(H)
I AConfiguration_getScreenSize(H)
I AConfiguration_getScreenLong(H)
I AConfiguration_getUiModeType(H)
I AConfiguration_getUiModeNight(H)
! I AMotionEvent_getAction(H)
! I AMotionEvent_getPointerCount(H)
! I AMotionEvent_getPointerId(HI)
! f AMotionEvent_getX(HI)
! f AMotionEvent_getY(HI)
! f AMotionEvent_getRawX(HI)
! f AMotionEvent_getRawY(HI)
! f AMotionEvent_getAxisValue(HII)
! I AMotionEvent_getButtonState(H)
! v AInputQueue_attachLooper(HHIPP)
! v AInputQueue_detachLooper(H)
! I AInputQueue_hasEvents(H)
! I AInputQueue_getEvent(HP)
! I AInputQueue_preDispatchEvent(HH)
! v AInputQueue_finishEvent(HHI)
! I ALooper_addFd(HIIIPP)
I ALooper_removeFd(HI)
! I ALooper_pollAll(IPPP)
! I ALooper_pollOnce(IPPP)
v ALooper_wake(H)
v ALooper_acquire(H)
v ALooper_release(H)
H AAssetManager_open(HPI)
H AAssetManager_openDir(HP)
! S AAssetDir_getNextFileName(H)
v AAssetDir_rewind(H)
v AAssetDir_close(H)
! v AAsset_close(H)
! P AAsset_getBuffer(H)
I AAsset_read(HPI)
I AAsset_seek(HII)
J AAsset_seek64(HJI)
I AAsset_getLength(H)
J AAsset_getLength64(H)
I AAsset_getRemainingLength(H)
J AAsset_getRemainingLength64(H)
! I AAsset_openFileDescriptor(HPP)
! I AAsset_openFileDescriptor64(HPP)
I AAsset_isAllocated(H)
+593
View File
@@ -0,0 +1,593 @@
/* Fake JVM (see fakejni.h). Objects are never freed; references are the object pointers. Only what the bridge and
* the test libraries use is implemented: everything else aborts with the function's index. */
#define _GNU_SOURCE
#include "fakejni.h"
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
enum { O_CLASS = 1, O_STRING, O_ARRAY, O_OBJECT, O_METHOD };
struct fclass {
char name[256]; /* dotted, as Class.getName() returns it */
fmethod *methods;
int nmethods;
};
typedef struct fobj {
int kind;
fclass *cls;
union {
fclass *klass; /* O_CLASS */
char *utf; /* O_STRING */
fmethod *m; /* O_METHOD */
int field; /* O_OBJECT */
struct { char type; int len; void *data; } arr;
};
} fobj;
static fclass *classes[256];
static int nclasses;
static __thread int attached;
static __thread char exc[256];
static __thread int exc_pending;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
#define O(x) ((fobj *)(x))
static void dotted(const char *in, char *out, size_t n)
{
snprintf(out, n, "%s", in);
for (char *p = out; *p; p++)
if (*p == '/') *p = '.';
}
static fclass *find_class(const char *dname)
{
for (int k = 0; k < nclasses; k++)
if (!strcmp(classes[k]->name, dname)) return classes[k];
return NULL;
}
static fclass *get_class(const char *dname)
{
pthread_mutex_lock(&lock);
fclass *c = find_class(dname);
if (!c) {
c = calloc(1, sizeof *c);
snprintf(c->name, sizeof c->name, "%s", dname);
classes[nclasses++] = c;
}
pthread_mutex_unlock(&lock);
return c;
}
static fobj *class_obj(fclass *k)
{
fobj *o = calloc(1, sizeof *o);
o->kind = O_CLASS;
o->cls = get_class("java.lang.Class");
o->klass = k;
return o;
}
fclass *fake_class(const char *name, const fmethod *methods)
{
char d[256];
dotted(name, d, sizeof d);
fclass *c = get_class(d);
int n = 0;
while (methods && methods[n].name) n++;
c->methods = calloc((size_t)n + 1, sizeof *c->methods);
memcpy(c->methods, methods, (size_t)n * sizeof *methods);
c->nmethods = n;
for (int k = 0; k < n; k++) c->methods[k].cls = c;
return c;
}
fmethod *fake_method(fclass *c, const char *name, const char *sig)
{
for (int k = 0; k < c->nmethods; k++)
if (!strcmp(c->methods[k].name, name) && (!sig || !strcmp(c->methods[k].sig, sig))) return &c->methods[k];
return NULL;
}
jstring fake_string(const char *utf)
{
fobj *o = calloc(1, sizeof *o);
o->kind = O_STRING;
o->cls = get_class("java.lang.String");
o->utf = strdup(utf);
return (jstring)o;
}
const char *fake_utf(jstring s) { return s ? O(s)->utf : NULL; }
static int esize(char t) { return t == 'Z' || t == 'B' ? 1 : t == 'C' || t == 'S' ? 2 : t == 'J' || t == 'D' ? 8 : 4; }
/* "heap" memory below 4 GiB, as ART's */
static void *low_alloc(size_t n)
{
static uint8_t *arena;
static size_t used;
pthread_mutex_lock(&lock);
if (!arena) {
arena = mmap((void *)0x30000000, 16 << 20, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE,
-1, 0);
if (arena == MAP_FAILED) abort();
}
void *p = arena + used;
used += (n + 15) & ~(size_t)15;
pthread_mutex_unlock(&lock);
return p;
}
static void *high_alloc(size_t n)
{
void *p = mmap((void *)0x7100000000, (n + 4095) & ~(size_t)4095, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED || (uintptr_t)p < 0x100000000ull) {
fprintf(stderr, "fake JNI: no memory above 4 GiB (%p)\n", p);
abort();
}
return p;
}
jarray fake_array(char type, int len, int low)
{
fobj *o = calloc(1, sizeof *o);
o->kind = O_ARRAY;
char cn[256];
if (type == 'L') snprintf(cn, sizeof cn, "[Ljava.lang.Object;");
else snprintf(cn, sizeof cn, "[%c", type);
o->cls = get_class(cn);
o->arr.type = type;
o->arr.len = len;
size_t n = (size_t)len * (type == 'L' ? sizeof(void *) : (size_t)esize(type));
o->arr.data = low ? low_alloc(n ? n : 1) : high_alloc(n ? n : 1);
memset(o->arr.data, 0, n);
return (jarray)o;
}
void *fake_array_data(jarray a) { return O(a)->arr.data; }
int fake_get_int_field(jobject o) { return O(o)->field; }
const char *fake_take_exception(void)
{
if (!exc_pending) return NULL;
exc_pending = 0;
return exc;
}
static void throw(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(exc, sizeof exc, fmt, ap);
va_end(ap);
exc_pending = 1;
}
/* ---------------------------------------------------------------- reflection (java.lang.Class / Method) */
static jvalue class_get_name(JNIEnv *env, jobject self, const jvalue *a)
{
(void)env, (void)a;
jvalue r;
r.l = fake_string(O(self)->klass->name);
return r;
}
/* the class object of one descriptor at *p (advances it) */
static fobj *descriptor_class(const char **p)
{
static const char *const prim[] = {"boolean", "byte", "char", "short", "int", "long", "float", "double", "void"};
static const char letters[] = "ZBCSIJFDV";
char name[256];
const char *s = *p;
if (*s == '[') {
const char *e = s;
while (*e == '[') e++;
e = *e == 'L' ? strchr(e, ';') + 1 : e + 1;
snprintf(name, sizeof name, "%.*s", (int)(e - s), s);
for (char *q = name; *q; q++)
if (*q == '/') *q = '.';
*p = e;
} else if (*s == 'L') {
const char *e = strchr(s, ';');
snprintf(name, sizeof name, "%.*s", (int)(e - s - 1), s + 1);
for (char *q = name; *q; q++)
if (*q == '/') *q = '.';
*p = e + 1;
} else {
snprintf(name, sizeof name, "%s", prim[strchr(letters, *s) - letters]);
*p = s + 1;
}
return class_obj(get_class(name));
}
static jvalue class_get_declared_methods(JNIEnv *env, jobject self, const jvalue *a)
{
(void)env, (void)a;
fclass *k = O(self)->klass;
jarray arr = fake_array('L', k->nmethods, 0);
O(arr)->cls = get_class("[Ljava.lang.reflect.Method;");
for (int i = 0; i < k->nmethods; i++) {
fobj *m = calloc(1, sizeof *m);
m->kind = O_METHOD;
m->cls = get_class("java.lang.reflect.Method");
m->m = &k->methods[i];
((fobj **)O(arr)->arr.data)[i] = m;
}
jvalue r;
r.l = arr;
return r;
}
static jvalue method_get_name(JNIEnv *env, jobject self, const jvalue *a)
{
(void)env, (void)a;
jvalue r;
r.l = fake_string(O(self)->m->name);
return r;
}
static jvalue method_get_modifiers(JNIEnv *env, jobject self, const jvalue *a)
{
(void)env, (void)a;
jvalue r;
r.i = (O(self)->m->is_native ? 0x100 : 0) | (O(self)->m->is_static ? 0x8 : 0) | 1;
return r;
}
static jvalue method_get_parameter_types(JNIEnv *env, jobject self, const jvalue *a)
{
(void)env, (void)a;
const char *p = O(self)->m->sig + 1;
fobj *tmp[64];
int n = 0;
while (*p != ')') tmp[n++] = descriptor_class(&p);
jarray arr = fake_array('L', n, 0);
O(arr)->cls = get_class("[Ljava.lang.Class;");
memcpy(O(arr)->arr.data, tmp, (size_t)n * sizeof *tmp);
jvalue r;
r.l = arr;
return r;
}
static jvalue method_get_return_type(JNIEnv *env, jobject self, const jvalue *a)
{
(void)env, (void)a;
const char *p = strchr(O(self)->m->sig, ')') + 1;
jvalue r;
r.l = descriptor_class(&p);
return r;
}
/* ---------------------------------------------------------------- JNIEnv */
static jint GetVersion(JNIEnv *env) { (void)env; return JNI_VERSION_1_6; }
static jclass FindClass(JNIEnv *env, const char *name)
{
(void)env;
char d[256];
dotted(name, d, sizeof d);
pthread_mutex_lock(&lock);
fclass *c = find_class(d);
pthread_mutex_unlock(&lock);
if (!c) {
throw("java.lang.NoClassDefFoundError: %s", name);
return NULL;
}
return (jclass)class_obj(c);
}
static jclass GetObjectClass(JNIEnv *env, jobject o) { (void)env; return (jclass)class_obj(O(o)->cls); }
static jboolean IsInstanceOf(JNIEnv *env, jobject o, jclass k) { (void)env; return o && O(o)->cls == O(k)->klass; }
static jboolean IsSameObject(JNIEnv *env, jobject a, jobject b) { (void)env; return a == b; }
static jobject NewRef(JNIEnv *env, jobject o) { (void)env; return o; }
static void DeleteRef(JNIEnv *env, jobject o) { (void)env, (void)o; }
static jint PushLocalFrame(JNIEnv *env, jint n) { (void)env, (void)n; return 0; }
static jobject PopLocalFrame(JNIEnv *env, jobject o) { (void)env; return o; }
static jint EnsureLocalCapacity(JNIEnv *env, jint n) { (void)env, (void)n; return 0; }
static jboolean ExceptionCheck(JNIEnv *env) { (void)env; return (jboolean)exc_pending; }
static void ExceptionClear(JNIEnv *env) { (void)env; exc_pending = 0; }
static jthrowable ExceptionOccurred(JNIEnv *env) { (void)env; return exc_pending ? (jthrowable)fake_string(exc) : NULL; }
static void ExceptionDescribe(JNIEnv *env) { (void)env; if (exc_pending) fprintf(stderr, "fake JNI exception: %s\n", exc); }
static jint ThrowNew(JNIEnv *env, jclass k, const char *msg)
{
(void)env;
throw("%s: %s", O(k)->klass->name, msg);
return 0;
}
static jmethodID GetMethodID(JNIEnv *env, jclass k, const char *name, const char *sig)
{
(void)env;
fmethod *m = fake_method(O(k)->klass, name, sig);
if (!m || m->is_static) {
throw("java.lang.NoSuchMethodError: %s%s", name, sig);
return NULL;
}
return (jmethodID)m;
}
static jmethodID GetStaticMethodID(JNIEnv *env, jclass k, const char *name, const char *sig)
{
(void)env;
fmethod *m = fake_method(O(k)->klass, name, sig);
if (!m || !m->is_static) {
throw("java.lang.NoSuchMethodError: %s%s", name, sig);
return NULL;
}
return (jmethodID)m;
}
static jfieldID GetFieldID(JNIEnv *env, jclass k, const char *name, const char *sig)
{
(void)env, (void)k, (void)sig;
return strcmp(name, "value") ? NULL : (jfieldID)1;
}
static jint GetIntField(JNIEnv *env, jobject o, jfieldID f) { (void)env, (void)f; return O(o)->field; }
static void SetIntField(JNIEnv *env, jobject o, jfieldID f, jint v) { (void)env, (void)f; O(o)->field = v; }
/* calls a Java method (impl) or a native one (through its registered pointer, ART style) */
jvalue fake_invoke(JNIEnv *env, fmethod *m, jobject self, const jvalue *a);
static jvalue call(JNIEnv *env, jobject self, jmethodID mid, const jvalue *a)
{
fmethod *m = (fmethod *)mid;
if (!m) {
fprintf(stderr, "fake JNI: call with a NULL method ID\n");
abort();
}
return fake_invoke(env, m, self, a);
}
/* "..." forms: used by the bridge only for methods without arguments */
static jobject CallObjectMethod(JNIEnv *env, jobject o, jmethodID m, ...)
{
if (((fmethod *)m)->sig[1] != ')') abort();
return call(env, o, m, NULL).l;
}
static jint CallIntMethod(JNIEnv *env, jobject o, jmethodID m, ...)
{
if (((fmethod *)m)->sig[1] != ')') abort();
return call(env, o, m, NULL).i;
}
static jobject CallObjectMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).l; }
static jboolean CallBooleanMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).z; }
static jbyte CallByteMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).b; }
static jchar CallCharMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).c; }
static jshort CallShortMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).s; }
static jint CallIntMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).i; }
static jlong CallLongMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).j; }
static jfloat CallFloatMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).f; }
static jdouble CallDoubleMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { return call(env, o, m, a).d; }
static void CallVoidMethodA(JNIEnv *env, jobject o, jmethodID m, const jvalue *a) { call(env, o, m, a); }
static jobject CallStaticObjectMethodA(JNIEnv *env, jclass k, jmethodID m, const jvalue *a) { (void)k; return call(env, NULL, m, a).l; }
static jint CallStaticIntMethodA(JNIEnv *env, jclass k, jmethodID m, const jvalue *a) { (void)k; return call(env, NULL, m, a).i; }
static jlong CallStaticLongMethodA(JNIEnv *env, jclass k, jmethodID m, const jvalue *a) { (void)k; return call(env, NULL, m, a).j; }
static jfloat CallStaticFloatMethodA(JNIEnv *env, jclass k, jmethodID m, const jvalue *a) { (void)k; return call(env, NULL, m, a).f; }
static jdouble CallStaticDoubleMethodA(JNIEnv *env, jclass k, jmethodID m, const jvalue *a) { (void)k; return call(env, NULL, m, a).d; }
static void CallStaticVoidMethodA(JNIEnv *env, jclass k, jmethodID m, const jvalue *a) { (void)k; call(env, NULL, m, a); }
static jboolean CallStaticBooleanMethodA(JNIEnv *env, jclass k, jmethodID m, const jvalue *a) { (void)k; return call(env, NULL, m, a).z; }
static jobject NewObjectA(JNIEnv *env, jclass k, jmethodID m, const jvalue *a)
{
fobj *o = calloc(1, sizeof *o);
o->kind = O_OBJECT;
o->cls = O(k)->klass;
call(env, (jobject)o, m, a);
return (jobject)o;
}
static jstring NewStringUTF(JNIEnv *env, const char *s) { (void)env; return fake_string(s); }
static jsize GetStringUTFLength(JNIEnv *env, jstring s) { (void)env; return (jsize)strlen(O(s)->utf); }
static jsize GetStringLength(JNIEnv *env, jstring s) { (void)env; return (jsize)strlen(O(s)->utf); } /* ASCII only */
static void GetStringRegion(JNIEnv *env, jstring s, jsize start, jsize len, jchar *buf)
{
(void)env;
for (jsize k = 0; k < len; k++) buf[k] = (jchar)O(s)->utf[start + k];
}
static const char *GetStringUTFChars(JNIEnv *env, jstring s, jboolean *is_copy)
{
(void)env;
if (is_copy) *is_copy = JNI_TRUE;
char *p = high_alloc(strlen(O(s)->utf) + 1); /* malloc'd copies live high on Android */
strcpy(p, O(s)->utf);
return p;
}
static void ReleaseStringUTFChars(JNIEnv *env, jstring s, const char *p) { (void)env, (void)s, (void)p; }
static jsize GetArrayLength(JNIEnv *env, jarray a) { (void)env; return O(a)->arr.len; }
static jobject GetObjectArrayElement(JNIEnv *env, jobjectArray a, jsize i) { (void)env; return ((jobject *)O(a)->arr.data)[i]; }
static void SetObjectArrayElement(JNIEnv *env, jobjectArray a, jsize i, jobject v) { (void)env; ((jobject *)O(a)->arr.data)[i] = v; }
static jintArray NewIntArray(JNIEnv *env, jsize n) { (void)env; return (jintArray)fake_array('I', n, 1); }
static void *GetElements(JNIEnv *env, jarray a, jboolean *is_copy)
{
(void)env;
if (is_copy) *is_copy = JNI_FALSE;
return O(a)->arr.data;
}
static void ReleaseElements(JNIEnv *env, jarray a, void *p, jint mode) { (void)env, (void)a, (void)p, (void)mode; }
static void GetIntArrayRegion(JNIEnv *env, jintArray a, jsize s, jsize n, jint *buf) { (void)env; memcpy(buf, (jint *)O(a)->arr.data + s, (size_t)n * 4); }
static void SetIntArrayRegion(JNIEnv *env, jintArray a, jsize s, jsize n, const jint *buf) { (void)env; memcpy((jint *)O(a)->arr.data + s, buf, (size_t)n * 4); }
static jint RegisterNatives(JNIEnv *env, jclass k, const JNINativeMethod *ms, jint n)
{
(void)env;
for (jint i = 0; i < n; i++) {
fmethod *m = fake_method(O(k)->klass, ms[i].name, ms[i].signature);
if (!m || !m->is_native) {
throw("java.lang.NoSuchMethodError: no native method %s%s", ms[i].name, ms[i].signature);
return JNI_ERR;
}
m->native_fn = ms[i].fnPtr;
}
return JNI_OK;
}
static jint GetJavaVM(JNIEnv *env, JavaVM **vm) { (void)env; *vm = fake_vm(); return 0; }
static void *GetDirectBufferAddress(JNIEnv *env, jobject b) { (void)env; return O(b)->arr.data; }
static jlong GetDirectBufferCapacity(JNIEnv *env, jobject b) { (void)env; return O(b)->arr.len; }
static struct JNINativeInterface env_table;
static JNIEnv env_obj = &env_table;
/* every function not implemented here: "mov w0, #index; b fake_unimplemented" */
__asm__(".text\n.p2align 3\nfake_unimpl_table:\n.set i, 0\n.rept 233\nmov w0, #i\nb fake_unimplemented\n"
".set i, i + 1\n.endr\n");
extern const char fake_unimpl_table[];
__attribute__((used)) void fake_unimplemented(int index)
{
fprintf(stderr, "fake JNI: JNIEnv function %d is not implemented\n", index);
abort();
}
static void init_env(void)
{
struct JNINativeInterface *t = &env_table;
void **slots = (void **)t;
for (int k = 0; k < 233; k++) slots[k] = (void *)(fake_unimpl_table + 8 * k);
t->GetVersion = GetVersion;
t->FindClass = FindClass;
t->GetObjectClass = GetObjectClass;
t->IsInstanceOf = IsInstanceOf;
t->IsSameObject = IsSameObject;
t->NewGlobalRef = NewRef;
t->NewLocalRef = NewRef;
t->NewWeakGlobalRef = NewRef;
t->DeleteGlobalRef = DeleteRef;
t->DeleteLocalRef = DeleteRef;
t->DeleteWeakGlobalRef = DeleteRef;
t->PushLocalFrame = PushLocalFrame;
t->PopLocalFrame = PopLocalFrame;
t->EnsureLocalCapacity = EnsureLocalCapacity;
t->ExceptionCheck = ExceptionCheck;
t->ExceptionClear = ExceptionClear;
t->ExceptionOccurred = ExceptionOccurred;
t->ExceptionDescribe = ExceptionDescribe;
t->ThrowNew = ThrowNew;
t->GetMethodID = GetMethodID;
t->GetStaticMethodID = GetStaticMethodID;
t->GetFieldID = GetFieldID;
t->GetIntField = GetIntField;
t->SetIntField = SetIntField;
t->CallObjectMethod = CallObjectMethod;
t->CallIntMethod = CallIntMethod;
t->CallObjectMethodA = CallObjectMethodA;
t->CallBooleanMethodA = CallBooleanMethodA;
t->CallByteMethodA = CallByteMethodA;
t->CallCharMethodA = CallCharMethodA;
t->CallShortMethodA = CallShortMethodA;
t->CallIntMethodA = CallIntMethodA;
t->CallLongMethodA = CallLongMethodA;
t->CallFloatMethodA = CallFloatMethodA;
t->CallDoubleMethodA = CallDoubleMethodA;
t->CallVoidMethodA = CallVoidMethodA;
t->CallStaticObjectMethodA = CallStaticObjectMethodA;
t->CallStaticBooleanMethodA = CallStaticBooleanMethodA;
t->CallStaticIntMethodA = CallStaticIntMethodA;
t->CallStaticLongMethodA = CallStaticLongMethodA;
t->CallStaticFloatMethodA = CallStaticFloatMethodA;
t->CallStaticDoubleMethodA = CallStaticDoubleMethodA;
t->CallStaticVoidMethodA = CallStaticVoidMethodA;
t->NewObjectA = NewObjectA;
t->NewStringUTF = NewStringUTF;
t->GetStringUTFLength = GetStringUTFLength;
t->GetStringLength = GetStringLength;
t->GetStringRegion = GetStringRegion;
t->GetStringUTFChars = GetStringUTFChars;
t->ReleaseStringUTFChars = ReleaseStringUTFChars;
t->GetArrayLength = GetArrayLength;
t->GetObjectArrayElement = GetObjectArrayElement;
t->SetObjectArrayElement = SetObjectArrayElement;
t->NewIntArray = NewIntArray;
t->GetIntArrayElements = (void *)GetElements;
t->ReleaseIntArrayElements = (void *)ReleaseElements;
t->GetFloatArrayElements = (void *)GetElements;
t->ReleaseFloatArrayElements = (void *)ReleaseElements;
t->GetByteArrayElements = (void *)GetElements;
t->ReleaseByteArrayElements = (void *)ReleaseElements;
t->GetPrimitiveArrayCritical = (void *)GetElements;
t->ReleasePrimitiveArrayCritical = (void *)ReleaseElements;
t->GetIntArrayRegion = GetIntArrayRegion;
t->SetIntArrayRegion = SetIntArrayRegion;
t->RegisterNatives = RegisterNatives;
t->GetJavaVM = GetJavaVM;
t->GetDirectBufferAddress = GetDirectBufferAddress;
t->GetDirectBufferCapacity = GetDirectBufferCapacity;
static const fmethod class_methods[] = {
{"getName", "()Ljava/lang/String;", 0, 0, class_get_name, NULL, NULL},
{"getDeclaredMethods", "()[Ljava/lang/reflect/Method;", 0, 0, class_get_declared_methods, NULL, NULL},
{NULL, NULL, 0, 0, NULL, NULL, NULL},
};
static const fmethod method_methods[] = {
{"getName", "()Ljava/lang/String;", 0, 0, method_get_name, NULL, NULL},
{"getModifiers", "()I", 0, 0, method_get_modifiers, NULL, NULL},
{"getParameterTypes", "()[Ljava/lang/Class;", 0, 0, method_get_parameter_types, NULL, NULL},
{"getReturnType", "()Ljava/lang/Class;", 0, 0, method_get_return_type, NULL, NULL},
{NULL, NULL, 0, 0, NULL, NULL, NULL},
};
fake_class("java/lang/Class", class_methods);
fake_class("java/lang/reflect/Method", method_methods);
fake_class("java/lang/String", NULL);
fake_class("java/lang/IllegalStateException", NULL);
}
JNIEnv *fake_env(void) { return &env_obj; }
/* ---------------------------------------------------------------- JavaVM */
static jint vm_get_env(JavaVM *vm, void **env, jint version)
{
(void)vm, (void)version;
if (!attached) {
*env = NULL;
return JNI_EDETACHED;
}
*env = &env_obj;
return JNI_OK;
}
static jint vm_attach(JavaVM *vm, JNIEnv **env, void *args)
{
(void)vm, (void)args;
attached = 1;
*env = &env_obj;
return JNI_OK;
}
static jint vm_detach(JavaVM *vm)
{
(void)vm;
attached = 0;
return JNI_OK;
}
static struct JNIInvokeInterface vm_table = {
.GetEnv = vm_get_env,
.AttachCurrentThread = vm_attach,
.AttachCurrentThreadAsDaemon = vm_attach,
.DetachCurrentThread = vm_detach,
};
static JavaVM vm_obj = &vm_table;
JavaVM *fake_vm(void)
{
static pthread_once_t once = PTHREAD_ONCE_INIT;
pthread_once(&once, init_env);
return &vm_obj;
}
void fake_attach(void) { attached = 1; }
@@ -0,0 +1,35 @@
/* A small fake JVM for testing the bridge without Android: classes and methods are C structs, Java methods are C
* functions, native methods are registered function pointers that the harness calls the way ART does. */
#ifndef FAKEJNI_H
#define FAKEJNI_H
#include <jni.h>
typedef struct fclass fclass;
typedef struct fmethod fmethod;
typedef jvalue (*fimpl)(JNIEnv *env, jobject self, const jvalue *args);
struct fmethod {
const char *name, *sig;
int is_static, is_native;
fimpl impl; /* Java methods */
void *native_fn; /* native methods: set by RegisterNatives */
fclass *cls;
};
JavaVM *fake_vm(void);
JNIEnv *fake_env(void);
void fake_attach(void); /* marks the calling thread as attached (ART threads are) */
/* defines a class with methods (name, sig, static, native, impl); NULL name ends the list */
fclass *fake_class(const char *name, const fmethod *methods);
fmethod *fake_method(fclass *c, const char *name, const char *sig);
jstring fake_string(const char *utf);
const char *fake_utf(jstring s);
/* a primitive array whose data lies below 4 GiB (like ART's heap) or above it */
jarray fake_array(char type, int len, int low);
void *fake_array_data(jarray a);
/* the pending exception's message (NULL if none); clears it */
const char *fake_take_exception(void);
int fake_get_int_field(jobject o);
#endif
+300
View File
@@ -0,0 +1,300 @@
/* Bridge test harness: plays ART for the guest test libraries (libbtest*.a32.so) with the fake JVM.
*
* harness <dir with liba32rt.so and the test libraries>
*
* Prints one line per check and "ALL OK" at the end (exit code 0), else the number of failed checks. */
#define _GNU_SOURCE
#include <android/native_activity.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include "a32bridge.h"
#include "fakejni.h"
static int failures;
#define CHECK(cond, ...) \
do { \
int ok_ = (cond); \
printf("%s ", ok_ ? "ok " : "FAIL"); \
printf(__VA_ARGS__); \
printf("\n"); \
fflush(stdout); \
if (!ok_) failures++; \
} while (0)
/* ---------------------------------------------------------------- the "Java" class */
static fclass *bridge_cls;
static jclass bridge_jcls; /* what ART passes static natives */
static jvalue j_add3(JNIEnv *env, jobject self, const jvalue *a)
{
jvalue r;
r.i = a[0].i + a[1].i + a[2].i;
return r;
}
static jvalue j_mix(JNIEnv *env, jobject self, const jvalue *a)
{
jvalue r;
r.d = a[0].i + (double)a[1].j + a[2].f + a[3].d + (double)strlen(fake_utf((jstring)a[4].l));
return r;
}
/* Java callBack(n) = nativeTwice(n) */
static jvalue j_callback(JNIEnv *env, jobject self, const jvalue *a)
{
jvalue r;
fmethod *m = fake_method(bridge_cls, "nativeTwice", "(I)I");
r.i = ((jint (*)(JNIEnv *, jclass, jint))m->native_fn)(env, bridge_jcls, a[0].i);
return r;
}
static jvalue j_ctor(JNIEnv *env, jobject self, const jvalue *a)
{
(*env)->SetIntField(env, self, (*env)->GetFieldID(env, bridge_jcls, "value", "I"), a[0].i);
jvalue r;
r.j = 0;
return r;
}
static jvalue j_greet(JNIEnv *env, jobject self, const jvalue *a)
{
char buf[128];
snprintf(buf, sizeof buf, "hello %s/%d", fake_utf((jstring)a[0].l), fake_get_int_field(self));
jvalue r;
r.l = fake_string(buf);
return r;
}
#define NATIVE(name, sig) {name, sig, 1, 1, NULL, NULL, NULL}
static const fmethod bridge_methods[] = {
{"add3", "(III)I", 1, 0, j_add3, NULL, NULL},
{"mix", "(IJFDLjava/lang/String;)D", 1, 0, j_mix, NULL, NULL},
{"callBack", "(I)I", 1, 0, j_callback, NULL, NULL},
{"<init>", "(I)V", 0, 0, j_ctor, NULL, NULL},
{"greet", "(Ljava/lang/String;)Ljava/lang/String;", 0, 0, j_greet, NULL, NULL},
NATIVE("nativeAdd", "(II)I"),
NATIVE("nativeMany", "(JDFZBCSIJDFI)J"),
NATIVE("nativeFloat", "(FF)F"),
NATIVE("nativeDouble", "(DD)D"),
NATIVE("nativeByte", "(B)B"),
NATIVE("nativeConcat", "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE("nativeSum", "([I)I"),
NATIVE("nativeCallJava", "()I"),
NATIVE("nativeNested", "(I)I"),
NATIVE("nativeTwice", "(I)I"),
NATIVE("nativeThread", "()I"),
NATIVE("nativeThrow", "()I"),
NATIVE("exported", "(I)I"),
NATIVE("over", "(I)J"),
NATIVE("over", "(J)J"),
NATIVE("under_score", "()I"),
NATIVE("unregistered", "()V"),
{NULL, NULL, 0, 0, NULL, NULL, NULL},
};
jvalue fake_invoke(JNIEnv *env, fmethod *m, jobject self, const jvalue *a)
{
if (m->impl) return m->impl(env, self, a);
fprintf(stderr, "harness: Java calls native %s%s, not supported by the fake\n", m->name, m->sig);
abort();
}
static void *nat(const char *name, const char *sig)
{
fmethod *m = fake_method(bridge_cls, name, sig);
return m ? m->native_fn : NULL;
}
/* ---------------------------------------------------------------- tests */
static void *other_thread(void *arg)
{
fake_attach(); /* an ART thread */
JNIEnv *env = fake_env();
jint (*add)(JNIEnv *, jclass, jint, jint) = nat("nativeAdd", "(II)I");
intptr_t r = 0;
for (int k = 0; k < 100; k++) r += add(env, bridge_jcls, k, 1);
jint (*nested)(JNIEnv *, jclass, jint) = nat("nativeNested", "(I)I");
r += nested(env, bridge_jcls, 1000); /* 2001 */
return (void *)r;
}
static void test_jni(const char *dir)
{
JavaVM *vm = fake_vm();
fake_attach();
JNIEnv *env = fake_env();
bridge_cls = fake_class("com/example/Bridge", bridge_methods);
bridge_jcls = (*env)->FindClass(env, "com/example/Bridge");
char stub[512];
snprintf(stub, sizeof stub, "%s/libbtest.so", dir);
jint ver = a32b_jni_onload(vm, stub);
CHECK(ver == JNI_VERSION_1_6, "JNI_OnLoad -> 0x%x", ver);
jint (*add)(JNIEnv *, jclass, jint, jint) = nat("nativeAdd", "(II)I");
CHECK(add && add(env, bridge_jcls, 40, 2) == 42, "RegisterNatives: nativeAdd(40, 2)");
CHECK(add && add(env, bridge_jcls, -5, 3) == -2, "nativeAdd(-5, 3)");
jlong (*many)(JNIEnv *, jclass, jlong, jdouble, jfloat, jboolean, jbyte, jchar, jshort, jint, jlong, jdouble,
jfloat, jint) = nat("nativeMany", "(JDFZBCSIJDFI)J");
jlong exp = 10000000000LL + 1500 + 25 + 1 + (-3) + 60000 + (-7) + 123456 + (-9000000000LL) + 75 + 25 + 77;
jlong got = many ? many(env, bridge_jcls, 10000000000LL, 1.5, 0.25f, 1, -3, 60000, -7, 123456, -9000000000LL, 7.5, 2.5f, 77)
: 0;
CHECK(got == exp, "12 mixed arguments (stack on both sides): %lld, expected %lld", (long long)got,
(long long)exp);
jfloat (*mulf)(JNIEnv *, jclass, jfloat, jfloat) = nat("nativeFloat", "(FF)F");
CHECK(mulf && mulf(env, bridge_jcls, 1.5f, -4.0f) == -6.0f, "float arguments and result");
jdouble (*divd)(JNIEnv *, jclass, jdouble, jdouble) = nat("nativeDouble", "(DD)D");
CHECK(divd && divd(env, bridge_jcls, 1.0, 8.0) == 0.125, "double arguments and result");
jbyte (*byte1)(JNIEnv *, jclass, jbyte) = nat("nativeByte", "(B)B");
CHECK(byte1 && byte1(env, bridge_jcls, -128) == 127 && byte1(env, bridge_jcls, 5) == 4, "byte argument and result");
jstring (*concat)(JNIEnv *, jclass, jstring) = nat("nativeConcat", "(Ljava/lang/String;)Ljava/lang/String;");
jstring s = concat ? concat(env, bridge_jcls, fake_string("frame")) : NULL;
CHECK(s && !strcmp(fake_utf(s), "frame-5"), "strings both ways: %s", s ? fake_utf(s) : "(null)");
jint (*sum)(JNIEnv *, jclass, jintArray) = nat("nativeSum", "([I)I");
for (int low = 1; low >= 0; low--) {
jintArray arr = fake_array('I', 5, low);
jint *d = fake_array_data(arr);
for (int k = 0; k < 5; k++) d[k] = k + 1;
jint r = sum ? sum(env, bridge_jcls, arr) : -1;
CHECK(r == 15 && d[0] == 99, "int[] elements %s 4 GiB (sum %d, written back %d)", low ? "below" : "above",
r, d[0]);
}
jint (*calljava)(JNIEnv *, jclass) = nat("nativeCallJava", "()I");
jint bits = calljava ? calljava(env, bridge_jcls) : 0;
CHECK(bits == 127, "Call*Method: ... / va_list / jvalue[], NewObject, fields, arrays (0x%x of 0x7f)", bits);
jint (*nested)(JNIEnv *, jclass, jint) = nat("nativeNested", "(I)I");
CHECK(nested && nested(env, bridge_jcls, 21) == 43, "nested calls: native -> Java -> native");
jint (*thr)(JNIEnv *, jclass) = nat("nativeThread", "()I");
CHECK(thr && thr(env, bridge_jcls) == 123, "guest thread: AttachCurrentThread + call Java");
pthread_t t[3];
for (int k = 0; k < 3; k++) pthread_create(&t[k], NULL, other_thread, NULL);
for (int k = 0; k < 3; k++) {
void *r = NULL;
pthread_join(t[k], &r);
CHECK((intptr_t)r == 4950 + 100 + 2001, "host thread %d gets a guest thread (%ld)", k, (long)(intptr_t)r);
}
jint (*throw_)(JNIEnv *, jclass) = nat("nativeThrow", "()I");
jint tr = throw_ ? throw_(env, bridge_jcls) : 0;
const char *e = fake_take_exception();
CHECK(tr == 7 && e && strstr(e, "boom"), "ThrowNew: %s", e ? e : "(no exception)");
jint (*exported)(JNIEnv *, jclass, jint) = nat("exported", "(I)I");
CHECK(exported && exported(env, bridge_jcls, 14) == 42, "Java_ export, short name");
jlong (*over_i)(JNIEnv *, jclass, jint) = nat("over", "(I)J");
jlong (*over_j)(JNIEnv *, jclass, jlong) = nat("over", "(J)J");
CHECK(over_i && over_j && over_i(env, bridge_jcls, 1) == 2 && over_j(env, bridge_jcls, 1LL << 40) == (1LL << 40) + 2,
"Java_ exports, long names (overloads)");
jint (*under)(JNIEnv *, jclass) = nat("under_score", "()I");
CHECK(under && under(env, bridge_jcls) == 5, "Java_ export with an escaped underscore");
}
/* ---------------------------------------------------------------- NativeActivity */
static int fake_window_marker;
#define FAKE_WINDOW ((ANativeWindow *)&fake_window_marker)
/* libandroid, as far as the imports need it */
void ANativeActivity_finish(ANativeActivity *a) {}
void ANativeActivity_setWindowFormat(ANativeActivity *a, int32_t f) {}
void ANativeActivity_setWindowFlags(ANativeActivity *a, uint32_t add, uint32_t rm) {}
void ANativeActivity_showSoftInput(ANativeActivity *a, uint32_t f) {}
void ANativeActivity_hideSoftInput(ANativeActivity *a, uint32_t f) {}
void ANativeWindow_acquire(ANativeWindow *w) {}
void ANativeWindow_release(ANativeWindow *w) {}
int32_t ANativeWindow_getWidth(ANativeWindow *w) { return w == FAKE_WINDOW ? 1234 : -1; }
int32_t ANativeWindow_getHeight(ANativeWindow *w) { return w == FAKE_WINDOW ? 567 : -1; }
int32_t ANativeWindow_getFormat(ANativeWindow *w) { return 1; }
int32_t ANativeWindow_setBuffersGeometry(ANativeWindow *w, int32_t x, int32_t y, int32_t f) { return 0; }
static int result2(uint32_t h, int which)
{
uint32_t fn = a32b_sym(h, "btest2_result");
uint32_t w = (uint32_t)which;
return fn ? (int)a32b_call(fn, &w, 1) : -999;
}
static void test_native_activity(const char *dir)
{
char stub[512];
snprintf(stub, sizeof stub, "%s/libbtest2.so", dir);
static ANativeActivityCallbacks cb;
static ANativeActivity act;
act.callbacks = &cb;
act.vm = fake_vm();
act.env = fake_env();
act.clazz = fake_string("activity");
act.internalDataPath = "/data/test/files";
act.externalDataPath = "/sdcard/test";
act.sdkVersion = 30;
a32b_native_activity_oncreate(&act, "abc", 3, stub);
uint32_t h = a32b_load(stub);
CHECK(h != 0, "NativeActivity library loaded (with its DT_NEEDED libbtest.so)");
cb.onStart(&act);
cb.onResume(&act);
cb.onWindowFocusChanged(&act, 1);
cb.onNativeWindowCreated(&act, FAKE_WINDOW);
size_t n = 0;
char *state = cb.onSaveInstanceState(&act, &n);
CHECK(result2(h, 0) == 1 && result2(h, 1) == 1, "onStart, onResume forwarded");
CHECK(result2(h, 3) == 1, "onWindowFocusChanged(1)");
CHECK(result2(h, 2) == 1234, "onNativeWindowCreated -> ANativeWindow_getWidth import (%d)", result2(h, 2));
CHECK(n == 6 && state && !strcmp(state, "state"), "onSaveInstanceState result copied out");
CHECK(result2(h, 4) == 1, "saved state passed in");
CHECK(result2(h, 5) == 30, "sdkVersion");
CHECK(result2(h, 6) == 1, "activity vm/env/paths");
CHECK(result2(h, 7) == (1 ^ 0x55), "symbol from the DT_NEEDED library");
cb.onDestroy(&act);
CHECK(result2(h, 8) == 1, "onDestroy forwarded");
free(state);
}
static void test_cxx(const char *dir, const char *name)
{
char stub[512];
snprintf(stub, sizeof stub, "%s/%s.so", dir, name);
uint32_t h = a32b_load(stub);
uint32_t fn = h ? a32b_sym(h, "cxx_test") : 0;
uint32_t w = 6;
int r = fn ? (int)a32b_call(fn, &w, 1) : -1;
CHECK(r == 303, "%s: C++ exceptions and static constructors in a guest library (%d)", name, r);
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: harness <dir>\n");
return 2;
}
/* the host process owns memory in the low 4 GiB, as ART's heap and boot image do: the guest must avoid it */
void *taken = mmap((void *)0x400000, 4 << 20, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
if (taken == MAP_FAILED) perror("mmap 0x400000");
extern int a32_vrapi_selftest(void);
CHECK(a32_vrapi_selftest() == 0, "VrApi ABI, render poses, tracking consistency and floor transforms");
test_jni(argv[1]);
test_native_activity(argv[1]);
test_cxx(argv[1], "libbtest3");
test_cxx(argv[1], "libbtest3_android");
test_cxx(argv[1], "libbtest3_standard");
CHECK(mprotect(taken, 4 << 20, PROT_NONE) == 0, "the host's low mapping is still there");
if (failures) {
printf("%d FAILED\n", failures);
return 1;
}
printf("ALL OK\n");
return 0;
}
@@ -0,0 +1,132 @@
/* Guest NativeActivity for the on-device test APK (make_apk.py): checks the bridge against the real ART in a
* Lepton container and logs "A32TEST ok|FAIL <check>" lines (logcat tag a32test), then "A32TEST done N failed". */
#include <android/log.h>
#include <android/native_activity.h>
#include <android/native_window.h>
#include <dlfcn.h>
#include <jni.h>
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "a32test", __VA_ARGS__)
static int failed;
static JavaVM *g_vm;
static void check(int ok, const char *what, const char *detail)
{
if (!ok) failed++;
LOG("A32TEST %s %s%s%s", ok ? "ok" : "FAIL", what, detail ? ": " : "", detail ? detail : "");
}
static jstring static_string(JNIEnv *env, const char *cls, const char *field)
{
jclass c = (*env)->FindClass(env, cls);
if (!c) return NULL;
jfieldID f = (*env)->GetStaticFieldID(env, c, field, "Ljava/lang/String;");
return f ? (jstring)(*env)->GetStaticObjectField(env, c, f) : NULL;
}
static void *thread_fn(void *arg)
{
JNIEnv *env = NULL;
if ((*g_vm)->AttachCurrentThread(g_vm, &env, NULL) != JNI_OK) return (void *)0;
jclass c = (*env)->FindClass(env, "android/os/SystemClock");
jmethodID m = c ? (*env)->GetStaticMethodID(env, c, "uptimeMillis", "()J") : NULL;
jlong t = m ? (*env)->CallStaticLongMethod(env, c, m) : 0;
(*g_vm)->DetachCurrentThread(g_vm);
return (void *)(intptr_t)(t > 0);
}
static void run_checks(ANativeActivity *a)
{
JNIEnv *env = NULL;
g_vm = a->vm;
check((*a->vm)->GetEnv(a->vm, (void **)&env, JNI_VERSION_1_6) == JNI_OK && env == a->env, "GetEnv", NULL);
jstring model = static_string(env, "android/os/Build", "MODEL");
const char *u = model ? (*env)->GetStringUTFChars(env, model, NULL) : NULL;
check(u && *u, "Build.MODEL", u);
if (u) (*env)->ReleaseStringUTFChars(env, model, u);
/* String.format("%d-%s", 42, "x") through a varargs Call with an Object[] built in JNI */
jclass sc = (*env)->FindClass(env, "java/lang/String");
jclass ic = (*env)->FindClass(env, "java/lang/Integer");
jmethodID valueof = (*env)->GetStaticMethodID(env, ic, "valueOf", "(I)Ljava/lang/Integer;");
jmethodID format = (*env)->GetStaticMethodID(env, sc, "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;");
jobjectArray args = (*env)->NewObjectArray(env, 2, (*env)->FindClass(env, "java/lang/Object"), NULL);
(*env)->SetObjectArrayElement(env, args, 0, (*env)->CallStaticObjectMethod(env, ic, valueof, 42));
(*env)->SetObjectArrayElement(env, args, 1, (*env)->NewStringUTF(env, "x"));
jstring s = (*env)->CallStaticObjectMethod(env, sc, format, (*env)->NewStringUTF(env, "%d-%s"), args);
u = s ? (*env)->GetStringUTFChars(env, s, NULL) : NULL;
check(u && !strcmp(u, "42-x"), "String.format via JNI", u);
if (u) (*env)->ReleaseStringUTFChars(env, s, u);
/* Math.hypot(3, 4): double arguments and result */
jclass mc = (*env)->FindClass(env, "java/lang/Math");
jmethodID hypot = (*env)->GetStaticMethodID(env, mc, "hypot", "(DD)D");
check((*env)->CallStaticDoubleMethod(env, mc, hypot, 3.0, 4.0) == 5.0, "Math.hypot", NULL);
/* int[] through Get/ReleaseIntArrayElements (ART's heap is below 4 GiB: shared, not copied) */
jintArray arr = (*env)->NewIntArray(env, 1000);
jboolean copy = 2;
jint *p = (*env)->GetIntArrayElements(env, arr, &copy);
for (int k = 0; k < 1000; k++) p[k] = k;
(*env)->ReleaseIntArrayElements(env, arr, p, 0);
jint back[2];
(*env)->GetIntArrayRegion(env, arr, 998, 2, back);
char d[64];
snprintf(d, sizeof d, "isCopy %d, at %p", copy, (void *)p);
check(back[0] == 998 && back[1] == 999, "int[] elements", d);
/* an exception thrown in Java, seen and cleared by guest code */
jclass ic2 = (*env)->FindClass(env, "java/lang/Integer");
jmethodID parse = (*env)->GetStaticMethodID(env, ic2, "parseInt", "(Ljava/lang/String;)I");
(*env)->CallStaticIntMethod(env, ic2, parse, (*env)->NewStringUTF(env, "not a number"));
int had = (*env)->ExceptionCheck(env);
(*env)->ExceptionClear(env);
check(had, "Java exception visible to guest code", NULL);
pthread_t t;
void *r = NULL;
pthread_create(&t, NULL, thread_fn, NULL);
pthread_join(t, &r);
check(r != NULL, "guest thread attaches and calls Java", NULL);
/* the C++ test library: dlopen from guest code, exceptions inside it */
void *h = dlopen("libbtest3.so", RTLD_NOW);
int (*cxx)(int) = h ? (int (*)(int))dlsym(h, "cxx_test") : NULL;
int cr = cxx ? cxx(6) : -1;
snprintf(d, sizeof d, "%d", cr);
check(cr == 303, "C++ library via dlopen", d);
check(a->internalDataPath && access(a->internalDataPath, F_OK) == 0, "internalDataPath exists",
a->internalDataPath);
LOG("A32TEST done %d failed", failed);
}
static void on_start(ANativeActivity *a) { LOG("onStart"); }
static void on_resume(ANativeActivity *a) { LOG("onResume"); }
static void on_pause(ANativeActivity *a) { LOG("onPause"); }
static void on_focus(ANativeActivity *a, int f) { LOG("onWindowFocusChanged %d", f); }
static void on_window(ANativeActivity *a, ANativeWindow *w)
{
LOG("onNativeWindowCreated %dx%d format %d", ANativeWindow_getWidth(w), ANativeWindow_getHeight(w),
ANativeWindow_getFormat(w));
}
static void on_window_destroyed(ANativeActivity *a, ANativeWindow *w) { LOG("onNativeWindowDestroyed"); }
void ANativeActivity_onCreate(ANativeActivity *a, void *saved, size_t n)
{
LOG("onCreate (32-bit guest code, sdk %d)", a->sdkVersion);
a->callbacks->onStart = on_start;
a->callbacks->onResume = on_resume;
a->callbacks->onPause = on_pause;
a->callbacks->onWindowFocusChanged = on_focus;
a->callbacks->onNativeWindowCreated = on_window;
a->callbacks->onNativeWindowDestroyed = on_window_destroyed;
run_checks(a);
}
+153
View File
@@ -0,0 +1,153 @@
/* Guest test library (armv7, Thumb): what a game's JNI library does. JNI_OnLoad registers natives with
* RegisterNatives; Java_* exports are found by name. The natives call back into "Java" with every argument style. */
#include <android/log.h>
#include <jni.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define TAG "btest"
static JavaVM *g_vm;
static jclass g_cls;
static jmethodID m_add3, m_mix, m_callback, m_ctor, m_greet;
static jint nativeAdd(JNIEnv *env, jclass c, jint a, jint b) { return a + b; }
/* 12 arguments: host-side some go on the stack (gpr and fpr overflow differ from ARM's) */
static jlong nativeMany(JNIEnv *env, jclass c, jlong a, jdouble b, jfloat f, jboolean z, jbyte by, jchar ch,
jshort s, jint i, jlong l2, jdouble d2, jfloat f2, jint i2)
{
return a + (jlong)(b * 1000) + (jlong)(f * 100) + z + by + ch + s + i + l2 + (jlong)(d2 * 10) + (jlong)(f2 * 10) +
i2;
}
static jfloat nativeFloat(JNIEnv *env, jclass c, jfloat a, jfloat b) { return a * b; }
static jdouble nativeDouble(JNIEnv *env, jclass c, jdouble a, jdouble b) { return a / b; }
static jbyte nativeByte(JNIEnv *env, jclass c, jbyte a) { return (jbyte)(a - 1); }
static jstring nativeConcat(JNIEnv *env, jclass c, jstring s)
{
const char *u = (*env)->GetStringUTFChars(env, s, NULL);
char buf[128];
snprintf(buf, sizeof buf, "%s-%d", u, (int)(*env)->GetStringUTFLength(env, s));
(*env)->ReleaseStringUTFChars(env, s, u);
return (*env)->NewStringUTF(env, buf);
}
/* sums the array and writes element 0 back (shared or copied, both must work) */
static jint nativeSum(JNIEnv *env, jclass c, jintArray a)
{
jint n = (*env)->GetArrayLength(env, a), sum = 0;
jint *p = (*env)->GetIntArrayElements(env, a, NULL);
for (jint k = 0; k < n; k++) sum += p[k];
p[0] = 99;
(*env)->ReleaseIntArrayElements(env, a, p, 0);
return sum;
}
static jint call_v(JNIEnv *env, jclass c, jmethodID m, ...)
{
va_list ap;
va_start(ap, m);
jint r = (*env)->CallStaticIntMethodV(env, c, m, ap);
va_end(ap);
return r;
}
/* calls Java in every style; returns a bit per passed check */
static jint nativeCallJava(JNIEnv *env, jclass c)
{
jint ok = 0;
if ((*env)->CallStaticIntMethod(env, c, m_add3, 1, 2, 3) == 6) ok |= 1;
jdouble d = (*env)->CallStaticDoubleMethod(env, c, m_mix, 4, (jlong)5000000000LL, (jfloat)1.5f, 2.25,
(*env)->NewStringUTF(env, "abc"));
if (d == 4 + 5000000000.0 + 1.5 + 2.25 + 3) ok |= 2;
jvalue v[3];
v[0].i = 10, v[1].i = 20, v[2].i = 30;
if ((*env)->CallStaticIntMethodA(env, c, m_add3, v) == 60) ok |= 4;
if (call_v(env, c, m_add3, 7, 8, 9) == 24) ok |= 8;
jobject o = (*env)->NewObject(env, c, m_ctor, 41);
jfieldID f = (*env)->GetFieldID(env, c, "value", "I");
if (o && (*env)->GetIntField(env, o, f) == 41) ok |= 16;
jstring g = (*env)->CallObjectMethod(env, o, m_greet, (*env)->NewStringUTF(env, "abc"));
const char *u = g ? (*env)->GetStringUTFChars(env, g, NULL) : NULL;
if (u && !strcmp(u, "hello abc/41")) ok |= 32;
if (u) (*env)->ReleaseStringUTFChars(env, g, u);
jintArray arr = (*env)->NewIntArray(env, 4);
jint in[4] = {1, 2, 3, 4}, out[4];
(*env)->SetIntArrayRegion(env, arr, 0, 4, in);
(*env)->GetIntArrayRegion(env, arr, 1, 3, out);
if (out[0] == 2 && out[2] == 4) ok |= 64;
return ok;
}
/* Java -> native -> Java -> native: nested calls on one thread */
static jint nativeNested(JNIEnv *env, jclass c, jint n) { return (*env)->CallStaticIntMethod(env, c, m_callback, n) + 1; }
static jint nativeTwice(JNIEnv *env, jclass c, jint n) { return 2 * n; }
static void *thread_fn(void *arg)
{
JNIEnv *env = NULL;
if ((*g_vm)->AttachCurrentThread(g_vm, &env, NULL) != JNI_OK) return (void *)(intptr_t)-1;
jint r = (*env)->CallStaticIntMethod(env, g_cls, m_add3, 100, 20, 3);
(*g_vm)->DetachCurrentThread(g_vm);
return (void *)(intptr_t)r;
}
/* a guest thread attaches itself and calls Java */
static jint nativeThread(JNIEnv *env, jclass c)
{
pthread_t t;
void *r = NULL;
if (pthread_create(&t, NULL, thread_fn, NULL)) return -1;
pthread_join(t, &r);
return (jint)(intptr_t)r;
}
static jint nativeThrow(JNIEnv *env, jclass c)
{
(*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/IllegalStateException"), "boom");
return 7;
}
JNIEXPORT jint JNICALL Java_com_example_Bridge_exported(JNIEnv *env, jclass c, jint x) { return x * 3; }
JNIEXPORT jlong JNICALL Java_com_example_Bridge_over__I(JNIEnv *env, jclass c, jint x) { return x + 1; }
JNIEXPORT jlong JNICALL Java_com_example_Bridge_over__J(JNIEnv *env, jclass c, jlong x) { return x + 2; }
JNIEXPORT jint JNICALL Java_com_example_Bridge_under_1score(JNIEnv *env, jclass c) { return 5; }
int btest_helper(int x) { return x ^ 0x55; }
JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
g_vm = vm;
JNIEnv *env;
if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) return JNI_ERR;
jclass c = (*env)->FindClass(env, "com/example/Bridge");
if (!c) return JNI_ERR;
g_cls = (*env)->NewGlobalRef(env, c);
m_add3 = (*env)->GetStaticMethodID(env, c, "add3", "(III)I");
m_mix = (*env)->GetStaticMethodID(env, c, "mix", "(IJFDLjava/lang/String;)D");
m_callback = (*env)->GetStaticMethodID(env, c, "callBack", "(I)I");
m_ctor = (*env)->GetMethodID(env, c, "<init>", "(I)V");
m_greet = (*env)->GetMethodID(env, c, "greet", "(Ljava/lang/String;)Ljava/lang/String;");
static const JNINativeMethod natives[] = {
{"nativeAdd", "(II)I", (void *)nativeAdd},
{"nativeMany", "(JDFZBCSIJDFI)J", (void *)nativeMany},
{"nativeFloat", "(FF)F", (void *)nativeFloat},
{"nativeDouble", "(DD)D", (void *)nativeDouble},
{"nativeByte", "(B)B", (void *)nativeByte},
{"nativeConcat", "(Ljava/lang/String;)Ljava/lang/String;", (void *)nativeConcat},
{"nativeSum", "([I)I", (void *)nativeSum},
{"nativeCallJava", "()I", (void *)nativeCallJava},
{"nativeNested", "(I)I", (void *)nativeNested},
{"nativeTwice", "(I)I", (void *)nativeTwice},
{"nativeThread", "()I", (void *)nativeThread},
{"nativeThrow", "()I", (void *)nativeThrow},
};
if ((*env)->RegisterNatives(env, c, natives, sizeof natives / sizeof *natives)) return JNI_ERR;
__android_log_print(ANDROID_LOG_INFO, TAG, "JNI_OnLoad done (%s)", m_add3 && m_mix ? "methods found" : "?");
return JNI_VERSION_1_6;
}
@@ -0,0 +1,57 @@
/* Guest test library (armv7, ARM): a NativeActivity. Needs libbtest.so (DT_NEEDED) and libandroid. */
#include <android/log.h>
#include <android/native_activity.h>
#include <android/native_window.h>
#include <jni.h>
#include <stdlib.h>
#include <string.h>
int btest_helper(int x); /* libbtest.so */
static int started, resumed, width, focus, saved_ok, sdk, env_ok, destroyed;
static void on_start(ANativeActivity *a) { started++; }
static void on_resume(ANativeActivity *a) { resumed++; }
static void on_focus(ANativeActivity *a, int f) { focus = f; }
static void on_window(ANativeActivity *a, ANativeWindow *w) { width = ANativeWindow_getWidth(w); }
static void on_destroy(ANativeActivity *a) { destroyed++; }
static void *on_save(ANativeActivity *a, size_t *len)
{
char *p = malloc(6);
memcpy(p, "state", 6);
*len = 6;
return p;
}
void ANativeActivity_onCreate(ANativeActivity *a, void *saved, size_t n)
{
a->callbacks->onStart = on_start;
a->callbacks->onResume = on_resume;
a->callbacks->onWindowFocusChanged = on_focus;
a->callbacks->onNativeWindowCreated = on_window;
a->callbacks->onSaveInstanceState = on_save;
a->callbacks->onDestroy = on_destroy;
saved_ok = n == 3 && !memcmp(saved, "abc", 3);
sdk = a->sdkVersion;
JNIEnv *env = NULL;
env_ok = (*a->vm)->GetEnv(a->vm, (void **)&env, JNI_VERSION_1_6) == JNI_OK && env == a->env &&
a->internalDataPath && !strcmp(a->internalDataPath, "/data/test/files");
__android_log_print(ANDROID_LOG_INFO, "btest2", "onCreate: sdk %d, saved %d", sdk, saved_ok);
}
int btest2_result(int which)
{
switch (which) {
case 0: return started;
case 1: return resumed;
case 2: return width;
case 3: return focus;
case 4: return saved_ok;
case 5: return sdk;
case 6: return env_ok;
case 7: return btest_helper(1);
case 8: return destroyed;
}
return -1;
}
@@ -0,0 +1,26 @@
// Guest test library (armv7, C++, static libc++): exceptions thrown and caught inside a guest library unwind
// through the runtime's dl_unwind_find_exidx; static constructors run at load.
#include <stdexcept>
#include <string>
#include <vector>
static std::vector<int> g_init{1, 2, 3}; // a static constructor
static int thrower(int x)
{
if (x > 2) throw std::runtime_error("too big: " + std::to_string(x));
return x;
}
extern "C" int cxx_test(int n)
{
int caught = 0;
for (int k = 0; k < n; k++) {
try {
thrower(k);
} catch (const std::runtime_error &e) {
if (std::string(e.what()).find("too big") == 0) caught++;
}
}
return caught * 100 + (int)g_init.size();
}
Loaded 100 of 228 files, more files were not shown because too many files have changed in this diff. Show more