Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f69833c7af | ||
|
|
22413e21e9 | ||
|
|
4d5c5fa091 | ||
|
|
5007ad26a2 | ||
|
|
927dae5ff8 | ||
|
|
57bb69f79c | ||
|
|
a87ccf4c7b | ||
|
|
6b8605a83e | ||
|
|
bef42dfd1b | ||
|
|
c29c3a3fe2 | ||
|
|
2a608e92f4 | ||
|
|
90ebabab01 | ||
|
|
5f2dd4bf27 | ||
|
|
2e2fac2348 | ||
|
|
5b1f09e79a | ||
|
|
fb0fe55c6d | ||
|
|
84ae3c1ce0 | ||
|
|
2ee1dcbfcb | ||
|
|
14f026c529 | ||
|
|
30a71a1ad4 | ||
|
|
a2515f13a7 | ||
|
|
5d6072e11e | ||
|
|
0e588f74f7 | ||
|
|
13a350b3bf | ||
|
|
36dbbe0de7 | ||
|
|
eb251c45b5 | ||
|
|
df0cc6a34f | ||
|
|
3b018b6976 | ||
|
|
7c066b5fea | ||
|
|
095281fca5 | ||
|
|
8453408d24 | ||
|
|
f5368d73ea | ||
|
|
bd92c25a09 | ||
|
|
05024e02bf | ||
|
|
56e122d85f | ||
|
|
d7a26ca181 | ||
|
|
3fcb901f8c | ||
|
|
faea99e837 | ||
|
|
05c4f5603b | ||
|
|
60fa213862 | ||
|
|
b67c403447 | ||
|
|
21e2693568 | ||
|
|
8d8a5dab59 | ||
|
|
185a947ba1 | ||
|
|
8622f8bc5c | ||
|
|
70d722063e | ||
|
|
e9ab42bcab | ||
|
|
6d9944844a | ||
|
|
11c52636c3 | ||
|
|
f251129c11 | ||
|
|
5acf9f1d7a | ||
|
|
88dd4a99a6 | ||
|
|
e30c9735dc | ||
|
|
f237f64d84 | ||
|
|
a37c75aec8 | ||
|
|
536fba2145 | ||
|
|
a7b5acbd14 | ||
|
|
a305ecc43b | ||
|
|
2acfd64f7f | ||
|
|
324b3401f7 | ||
|
|
694621c71f | ||
|
|
9df1d35003 | ||
|
|
a86a86df3d | ||
|
|
626950e52e | ||
|
|
4be8e3be37 | ||
|
|
98b16b211a | ||
|
|
4f042f7225 |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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).
|
||||
@@ -643,7 +703,9 @@ reaches its OVRInput cleanly (probe: both Touch connected 0x63, individual butto
|
||||
"outside of frame bounds" warnings stay (~2/frame) and are harmless.
|
||||
Steam library (GitHub #4/#21/#27, agent v38): shortcuts go to every Steam account (signed-in first; MostRecent isn't
|
||||
always the account on the Frame); stop_steam also waits for Steam's helpers; after the restart the agent re-reads
|
||||
shortcuts.vdf and writes once more if Steam put its old copy back (`shortcuts_lost`), else reports it. 0.6.3's Play
|
||||
shortcuts.vdf and writes once more if Steam put its old copy back (`shortcuts_lost`); lost again (agent v89): Steam
|
||||
ignores FramePort's entries on that Frame, so `add_devkit_entry` adds the devkit entry instead (`added` gets `via:
|
||||
devkit`) and only reports an error if that fails too. 0.6.3's Play
|
||||
auto-repair (`_add_then_play`) crashed (its job got a Job, not a reporter). Uploads resume on a transient OSError.
|
||||
Lepton's Android 11 has no clipboard service (134 services; checked with `podman exec … service check clipboard`):
|
||||
SDL/LÖVE apps crashed at start → `frame.sdl_clipboard` (`apk/dex.py`: in-place dex edit, nops one invoke, fixes
|
||||
@@ -741,6 +803,22 @@ own context and saved as `files/fb_snap_0-7.ppm` (quarter size) — headless lau
|
||||
shows what the game draws. Vader: Lucasfilm logo (an OBB mp4: video works), then its loading card (portrait + segmented
|
||||
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).
|
||||
**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), so the keeper doesn't catch every failure.
|
||||
**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).
|
||||
**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
|
||||
|
||||
@@ -44,7 +44,7 @@ try:
|
||||
except ImportError: # Windows: pc_revive loads this file for its VDF code only (GitHub #131)
|
||||
fcntl = None
|
||||
|
||||
AGENT_VERSION = 86
|
||||
AGENT_VERSION = 90
|
||||
HOME = os.path.expanduser("~")
|
||||
STEAM = os.path.join(HOME, ".local/share/Steam")
|
||||
ANCHORS = os.path.join(HOME, "Applications/quest-frame")
|
||||
@@ -1256,7 +1256,7 @@ def _shortcuts_worker(payload):
|
||||
if service or args.get("restart", True):
|
||||
start_steam(service)
|
||||
lost = shortcuts_lost(users, args["packages"])
|
||||
if lost: # Steam wrote its old copy back over ours (it was still saving): once more, then report
|
||||
if lost: # Steam wrote its old copy back over ours (it was still saving): once more, then the devkit entry
|
||||
result["retried"] = lost
|
||||
service = stop_steam()
|
||||
for user in users:
|
||||
@@ -1264,7 +1264,7 @@ def _shortcuts_worker(payload):
|
||||
start_steam(service)
|
||||
for pkg in shortcuts_lost(users, lost):
|
||||
result["added"] = [a for a in result["added"] if a["package"] != pkg]
|
||||
result["errors"].append(f"{pkg}: Steam removed the new library entry again after restarting")
|
||||
add_devkit_entry(pkg, result)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["state"] = "failed"
|
||||
result["errors"].append(str(exc))
|
||||
@@ -1274,6 +1274,19 @@ def _shortcuts_worker(payload):
|
||||
json.dump(result, f)
|
||||
|
||||
|
||||
def add_devkit_entry(pkg, result):
|
||||
"""Steam dropped the game's shortcuts.vdf entry twice: this Frame's Steam ignores FramePort's entries (GitHub #41),
|
||||
so add it the way Valve's devkit tool does (Steam is running again). That entry is the one Steam keeps."""
|
||||
try:
|
||||
appid = devkit_register(pkg)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result["errors"].append(f"{pkg}: Steam removed the new library entry again after restarting, and the devkit "
|
||||
f"entry failed too: {exc}")
|
||||
return
|
||||
result["added"].append({"package": pkg, "appid": appid, "expected": (deployment(pkg) or {}).get("appid"),
|
||||
"via": "devkit"})
|
||||
|
||||
|
||||
def remove_from_library(user, remove, result):
|
||||
"""Remove uninstalled games' shortcuts + grid art from one Steam account (Steam is closed)."""
|
||||
vdf = os.path.join(STEAM, "userdata", user, "config/shortcuts.vdf")
|
||||
@@ -1526,10 +1539,17 @@ def is_overlay(dep):
|
||||
return bool(isinstance(dep, dict) and dep.get("overlay"))
|
||||
|
||||
|
||||
def deployment_summary(dep):
|
||||
"""Keep routine connection/monitor samples small; detailed data manifests are fetched only for an update."""
|
||||
return {key: value for key, value in dep.items()
|
||||
if key not in ("data_manifest", "configuration", "managed_config_files")}
|
||||
|
||||
|
||||
def cmd_list_installed(args):
|
||||
games = []
|
||||
table = mounts()
|
||||
for dep_path in sorted(glob.glob(os.path.join(ANCHORS, "*/deployment.json"))):
|
||||
selected = check_pkg(args["package"]) if args.get("package") else "*"
|
||||
for dep_path in sorted(glob.glob(os.path.join(ANCHORS, selected, "deployment.json"))):
|
||||
try:
|
||||
dep = json.load(open(dep_path))
|
||||
except (OSError, ValueError):
|
||||
@@ -1566,7 +1586,7 @@ def cmd_list_installed(args):
|
||||
dep["apk_present"] = os.path.exists(apk)
|
||||
dep["apk_size"] = os.path.getsize(apk) if dep["apk_present"] else 0
|
||||
dep["last_play"] = last_play(dep["anchor"]) # agent v70: the PC triages a finished play session's log
|
||||
games.append(dep)
|
||||
games.append(dep if args.get("details") else deployment_summary(dep))
|
||||
return {"games": games}
|
||||
|
||||
|
||||
@@ -3023,7 +3043,7 @@ setsid {lepton_q} start >"$app_dir/launch.log" 2>&1 &
|
||||
child=$!
|
||||
{dashboard}
|
||||
{logcat}
|
||||
wait "$child"
|
||||
{restart}
|
||||
""")
|
||||
|
||||
|
||||
@@ -3068,6 +3088,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__)))
|
||||
|
||||
@@ -3119,6 +3204,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
|
||||
@@ -3511,7 +3605,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:
|
||||
@@ -3828,7 +3922,7 @@ def cmd_finalize(args):
|
||||
pkg = check_pkg(args["package"])
|
||||
title = args["title"]
|
||||
prep = cmd_prepare({"package": pkg, "title": title, "dest": args.get("dest")})
|
||||
base, anchor, appid, incoming = prep["base"], prep["anchor"], prep["appid"], prep["incoming"]
|
||||
base, anchor, incoming = prep["base"], prep["anchor"], prep["incoming"]
|
||||
lepton = prep["lepton"]
|
||||
if not lepton:
|
||||
raise AgentError("Lepton is not installed (Developer Mode → install/launch 'Lepton Development' once)")
|
||||
@@ -3849,6 +3943,10 @@ def cmd_finalize(args):
|
||||
bad = [k for k, v in expected.items() if have.get(k) != v]
|
||||
if bad:
|
||||
raise AgentError(f"{len(bad)} data file(s) missing or incomplete, e.g. {bad[0]}")
|
||||
if args.get("existing_only") and os.path.exists(new_apk):
|
||||
raise AgentError("an interrupted APK upload is pending; finish that install before updating data")
|
||||
if args.get("existing_only"):
|
||||
verify_installed_apk(deployment(pkg), args.get("apk_sha256"))
|
||||
if os.path.exists(new_apk):
|
||||
if args.get("apk_sha256") and sha256_file(new_apk) != args["apk_sha256"]:
|
||||
raise AgentError("uploaded APK checksum mismatch (transfer corrupted?)")
|
||||
@@ -3859,16 +3957,67 @@ def cmd_finalize(args):
|
||||
elif not os.path.exists(os.path.join(app, "game.apk")):
|
||||
raise AgentError("no APK uploaded and none installed")
|
||||
moved = 0
|
||||
for root, _, files in os.walk(inc_obb):
|
||||
for name in files:
|
||||
if name.endswith(".part"):
|
||||
continue
|
||||
src = os.path.join(root, name)
|
||||
dst = os.path.join(app, "obb", os.path.relpath(src, inc_obb))
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
os.replace(src, dst)
|
||||
moved += 1
|
||||
shutil.rmtree(incoming, ignore_errors=True)
|
||||
if not args.get("preserve_data"):
|
||||
for root, _, files in os.walk(inc_obb):
|
||||
for name in files:
|
||||
if name.endswith(".part"):
|
||||
continue
|
||||
src = os.path.join(root, name)
|
||||
rel = os.path.relpath(src, inc_obb)
|
||||
if expected is not None and rel not in expected:
|
||||
continue # an older interrupted upload is not part of this install
|
||||
dst = os.path.join(app, "obb", rel)
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
os.replace(src, dst)
|
||||
moved += 1
|
||||
shutil.rmtree(incoming, ignore_errors=True)
|
||||
return configure_install({**args, "consume_artwork": args.get("consume_artwork", True)}, prep, moved)
|
||||
|
||||
|
||||
def verify_installed_apk(dep, expected):
|
||||
apk = os.path.join(dep["base"], "lepton-app", "game.apk")
|
||||
if not expected or dep.get("sha256") != expected or not os.path.isfile(apk):
|
||||
raise AgentError("installed APK is missing or changed; refresh and reinstall it")
|
||||
st = os.stat(apk)
|
||||
identity = {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
|
||||
if identity != dep.get("apk_stat") and sha256_file(apk) != expected:
|
||||
raise AgentError("installed APK content changed; reinstall it")
|
||||
|
||||
|
||||
def cmd_configure(args):
|
||||
"""Apply runtime configuration to an existing, matching APK without staging/replacing game files."""
|
||||
pkg = check_pkg(args["package"])
|
||||
dep = deployment(pkg)
|
||||
if not dep or dep.get("kind", "quest") != "quest":
|
||||
raise AgentError(f"{pkg} is not an installed Quest/Android app")
|
||||
base, _ = new_base(args, pkg, dep) # validates a removable drive; never silently falls back
|
||||
verify_installed_apk(dep, args.get("apk_sha256"))
|
||||
if container_running(dep["appid"]):
|
||||
raise AgentError("Close the game before updating its configuration")
|
||||
lepton, _ = lepton_path()
|
||||
if not lepton:
|
||||
raise AgentError("Lepton is not installed")
|
||||
return configure_install({**args, "title": dep["title"]},
|
||||
{"base": base, "anchor": os.path.join(ANCHORS, pkg),
|
||||
"appid": dep["appid"], "lepton": lepton}, 0)
|
||||
|
||||
|
||||
def configure_install(args, prep, moved):
|
||||
pkg, title = check_pkg(args["package"]), args["title"]
|
||||
base, anchor, appid, lepton = prep["base"], prep["anchor"], prep["appid"], prep["lepton"]
|
||||
app = os.path.join(base, "lepton-app")
|
||||
previous = deployment(pkg) or {}
|
||||
files_dir = data_files_dir(base, pkg)
|
||||
for rel in set(args.get("files") or {}) | set(previous.get("managed_config_files") or {}):
|
||||
target = os.path.realpath(os.path.join(files_dir, rel))
|
||||
if not _inside(target, os.path.realpath(files_dir)) or target == os.path.realpath(files_dir):
|
||||
raise AgentError(f"refusing to write outside the game's files dir: {rel}")
|
||||
backup = os.path.join(files_dir, rel) + ".frameport-config-backup"
|
||||
if os.path.islink(backup):
|
||||
raise AgentError(f"refusing a linked configuration backup: {rel}")
|
||||
for key, value in (args.get("settings") or {}).items():
|
||||
if not re.fullmatch(r"[a-z_]+", key) or any(c in str(value) for c in "\r\n\x00"):
|
||||
raise AgentError(f"bad setting {key}")
|
||||
if "flatscreen" in args: # older clients don't send it: leave the marker as it is
|
||||
set_flatscreen(app, args["flatscreen"])
|
||||
# settings: settings.conf (read by the adapter via LEPTON_ENV_FRAMEBRIDGE_CONFIG) + framebridge.conf copy
|
||||
@@ -3885,13 +4034,37 @@ def cmd_finalize(args):
|
||||
f.write(text)
|
||||
with open(os.path.join(files_dir, "framebridge.conf"), "w") as f:
|
||||
f.write(text)
|
||||
managed = previous.get("managed_config_files") or {}
|
||||
wanted = args.get("files") or {}
|
||||
for rel, record in managed.items():
|
||||
if rel in wanted:
|
||||
continue
|
||||
target = os.path.realpath(os.path.join(files_dir, rel))
|
||||
if not _inside(target, os.path.realpath(files_dir)):
|
||||
raise AgentError(f"invalid previously managed path: {rel}")
|
||||
if os.path.isfile(target) and sha256_file(target) == record["sha256"]:
|
||||
backup = target + ".frameport-config-backup"
|
||||
if record.get("backup") and os.path.isfile(backup):
|
||||
os.replace(backup, target)
|
||||
else:
|
||||
os.unlink(target)
|
||||
new_managed = {}
|
||||
for rel, content in (args.get("files") or {}).items():
|
||||
target = os.path.normpath(os.path.join(files_dir, rel))
|
||||
if not target.startswith(files_dir + os.sep):
|
||||
raise AgentError(f"refusing to write outside the game's files dir: {rel}")
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
record = managed.get(rel)
|
||||
backup = target + ".frameport-config-backup"
|
||||
# no record: an existing file is the user's, unless it already has exactly this content (written by
|
||||
# FramePort before agent v86 kept records; backing it up would bring it back when the recipe drops it)
|
||||
had_original = bool(record.get("backup")) if record else os.path.isfile(target) and \
|
||||
open(target, "rb").read() != content.encode()
|
||||
if not record and had_original:
|
||||
shutil.copy2(target, backup)
|
||||
with open(target, "w") as f:
|
||||
f.write(content)
|
||||
new_managed[rel] = {"sha256": sha256_file(target), "backup": had_original}
|
||||
models = install_controller_models(files_dir, str(settings.get("controller_models", 0)) not in ("0", "0.0"))
|
||||
recipe = args.get("recipe") if isinstance(args.get("recipe"), dict) else {}
|
||||
hw_video = HW_VIDEO_PATCH in (recipe.get("patches") or []) # the shared codec (install_video_codec)
|
||||
@@ -3901,22 +4074,40 @@ def cmd_finalize(args):
|
||||
config_sync = args.get("config_sync") if isinstance(args.get("config_sync"), dict) else {}
|
||||
write_launcher(anchor, base, pkg, title, appid, lepton, args.get("env"), hw_video, gamepad, bool(config_sync))
|
||||
art_in = os.path.join(base, "incoming-artwork")
|
||||
if os.path.isdir(art_in):
|
||||
art_moved = False
|
||||
if args.get("consume_artwork") and os.path.isdir(art_in):
|
||||
shutil.rmtree(os.path.join(anchor, "artwork"), ignore_errors=True)
|
||||
shutil.move(art_in, os.path.join(anchor, "artwork"))
|
||||
previous = deployment(pkg) or {}
|
||||
dep = {"package": pkg, "appid": int(appid), "base": base, "title": title, "tags": args.get("tags") or [],
|
||||
"apk": args.get("apk_name", "game.apk"),
|
||||
"sha256": args.get("apk_sha256"), "recipe": args.get("recipe"), "installed_by": "frameport",
|
||||
art_moved = True
|
||||
dep = {**previous, "package": pkg, "appid": int(appid), "base": base, "title": title,
|
||||
"tags": args.get("tags", previous.get("tags")) or [],
|
||||
"apk": args.get("apk_name", previous.get("apk", "game.apk")),
|
||||
"sha256": args.get("apk_sha256") or previous.get("sha256"),
|
||||
"recipe": args.get("recipe"), "installed_by": "frameport",
|
||||
"hw_video_decode": hw_video, "steam_gamepad": gamepad, "config_sync": config_sync,
|
||||
"agent_version": AGENT_VERSION, "time": time.time()}
|
||||
if previous.get("eye_base"): # the runtime's eye size learned from an earlier start (device.config_sync)
|
||||
dep["eye_base"] = previous["eye_base"]
|
||||
with open(os.path.join(anchor, "deployment.json"), "w") as f:
|
||||
json.dump(dep, f, indent=2)
|
||||
dep["managed_config_files"] = new_managed
|
||||
# An app before agent v86 records none of these: what it installed is unknown, so a newer PC mustn't skip work
|
||||
# on the strength of an older record. Art the agent didn't replace keeps its record.
|
||||
art_replaced = bool(args.get("consume_artwork")) and art_moved
|
||||
for key in ("configuration", "configuration_fp", "apk_recipe_fp", "source_version", "artwork_manifest"):
|
||||
if key in args:
|
||||
dep[key] = args[key]
|
||||
elif key != "artwork_manifest" or art_replaced:
|
||||
dep.pop(key, None)
|
||||
if args.get("obb_manifest") is not None:
|
||||
dep["data_manifest"] = args["obb_manifest"]
|
||||
if "data_manifest" in dep:
|
||||
dep["data_fp"] = hashlib.sha256(json.dumps(dep["data_manifest"], sort_keys=True).encode()).hexdigest()[:32]
|
||||
st = os.stat(os.path.join(app, "game.apk"))
|
||||
dep["apk_size"] = st.st_size
|
||||
dep["apk_stat"] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
|
||||
synced = sync_game_config(pkg, dep)
|
||||
write_deployment(pkg, dep)
|
||||
return {"ok": True, "base": base, "appid": appid, "moved_data_files": moved, "controller_models": models,
|
||||
"config_sync": synced}
|
||||
"config_sync": synced, "deployment": deployment_summary(dep)}
|
||||
|
||||
|
||||
# --------------------------------------------------------------- Steam Frame controller models (XR_FB_render_model)
|
||||
@@ -5175,8 +5366,8 @@ def cmd_set_settings(args):
|
||||
if k:
|
||||
current[k] = v
|
||||
for k, v in (args.get("settings") or {}).items():
|
||||
if not re.fullmatch(r"[a-z_]+", k) or not re.fullmatch(r"-?[0-9.]+", str(v)):
|
||||
raise AgentError(f"bad setting {k}={v}")
|
||||
if not re.fullmatch(r"[a-z_]+", k) or not re.fullmatch(r"-?(?:[0-9]+\.?[0-9]*|\.[0-9]+)", str(v)):
|
||||
raise AgentError(f"bad setting {k}={v}") # checked before anything is written
|
||||
current[k] = str(v)
|
||||
text = "".join(f"{k}={v}\n" for k, v in current.items())
|
||||
with open(conf, "w") as f:
|
||||
@@ -5186,7 +5377,19 @@ def cmd_set_settings(args):
|
||||
with open(os.path.join(files_dir, "framebridge.conf"), "w") as f:
|
||||
f.write(text)
|
||||
models = install_controller_models(files_dir, current.get("controller_models", "0") not in ("0", "0.0"))
|
||||
return {"settings": current, "controller_models": models, "config_sync": sync_game_config(pkg, dep)}
|
||||
synced = sync_game_config(pkg, dep)
|
||||
if isinstance(dep.get("configuration"), dict):
|
||||
applied = dep["configuration"]
|
||||
settings = applied.get("settings") or {}
|
||||
for key, value in (args.get("settings") or {}).items():
|
||||
if key in settings:
|
||||
number = float(value)
|
||||
# keep the recorded type (the PC's fingerprint uses it); an int setting given 1.5 stays 1.5
|
||||
settings[key] = number if isinstance(settings[key], float) or not number.is_integer() \
|
||||
else int(number)
|
||||
dep["configuration_fp"] = hashlib.sha256(json.dumps(applied, sort_keys=True).encode()).hexdigest()[:32]
|
||||
write_deployment(pkg, dep)
|
||||
return {"settings": current, "controller_models": models, "config_sync": synced}
|
||||
|
||||
|
||||
TITLE_MAX = 128
|
||||
@@ -5200,6 +5403,26 @@ def clean_title(title):
|
||||
return text[:TITLE_MAX]
|
||||
|
||||
|
||||
def cmd_record_artwork(args):
|
||||
"""Record artwork only after verifying the files actually uploaded to the game's anchor."""
|
||||
pkg = check_pkg(args["package"])
|
||||
dep = deployment(pkg)
|
||||
if not dep:
|
||||
raise AgentError(f"{pkg} is not installed")
|
||||
manifest = args.get("manifest") or {}
|
||||
root = os.path.join(ANCHORS, pkg, "artwork")
|
||||
for name, digest in manifest.items():
|
||||
if (not re.fullmatch(r"(?:portrait|landscape|hero|logo|icon)\.[a-zA-Z0-9]+|\.icon-source", name)
|
||||
or not re.fullmatch(r"[a-f0-9]{64}", str(digest))):
|
||||
raise AgentError("invalid artwork manifest")
|
||||
path = os.path.join(root, name)
|
||||
if not os.path.isfile(path) or sha256_file(path) != digest:
|
||||
raise AgentError(f"artwork missing or checksum mismatch: {name}")
|
||||
dep["artwork_manifest"] = manifest
|
||||
write_deployment(pkg, dep)
|
||||
return {"verified": True}
|
||||
|
||||
|
||||
def cmd_rename(args):
|
||||
"""Rename an installed game (agent v77): deployment.json's title is what its Steam shortcut shows. The shortcut
|
||||
keeps its appid (upsert_shortcut matches by Exe, deployment.json keeps the appid), so Play, its grid art, launch
|
||||
@@ -7636,6 +7859,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
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
1a4dce5c4a6d0dfc5f20e55ac29e70c73cc2cc124c21ca6a7e1b316e6afb1c79 ./arm64-v8a/libVkLayer_fdm_darken.so
|
||||
5becb96ee86fbda0ce98c0e0fd064f8ba092314aceaa400e3dcc785705dc3c23 ./arm64-v8a/libVkLayer_fp_shaderfix.so
|
||||
e7554c6343ee2989b0a273ee6230e65c25bfe6499eefd00de19f5f0fee58754f ./arm64-v8a/libfp_langpack.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
|
||||
40defdaddcda53bd2649eb48076fae1622bfc2bfc88e9e03c94fc8b45af2a4f2 ./arm64-v8a/libfp_ovrtrace.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
|
||||
e44ded778758de33ad87bb31398281d7ec94c1ecd43dcf55b1dc99311f011859 ./arm64-v8a/libopenxr_loader_generic.so
|
||||
51f5e0c5b3d3556baab27ece2936257782d6b590183ae59601cc6d8158c96ee2 ./arm64-v8a/libopenxr_loader_generic.so
|
||||
1feaeafad467c4cafdf2b018a4d84b0bee200c3f711697b4ce97e66a3ba256ca ./arm64-v8a/libovrplatformcompat.so
|
||||
7f30861c770361a4e311e3f486dcd2e48cd99a7f907961829ce68e24af17d775 ./arm64-v8a/libvrapi.so
|
||||
7f30861c770361a4e311e3f486dcd2e48cd99a7f907961829ce68e24af17d775 ./arm64-v8a/libvrapi_foveation.so
|
||||
d2361ee8b6ff62d2ff6b3f59f7b15730b95bdbe0e9dcee469ffa1117411e7288 ./armeabi-v7a/libopenxr_loader_generic.so
|
||||
a4ed80ae45ca90758239f152ea5a2e8c127d491e1e697ea5680db6fd7f72db07 ./arm64-v8a/libvrapi.so
|
||||
a4ed80ae45ca90758239f152ea5a2e8c127d491e1e697ea5680db6fd7f72db07 ./arm64-v8a/libvrapi_foveation.so
|
||||
6927f100536283a8c26b784af73ee400140dd910e9294e4a9d55f855547ffaf2 ./armeabi-v7a/libopenxr_loader_generic.so
|
||||
1871eae093432d277da4bc751bf5f3269dfcf11f9168260b0c3caadb0dedb19d ./dex/oculusos-stubs.dex
|
||||
b634ab5640e258563c536e658cad87080553df6f34f62269a21d554844e58bfe ./hevc/COPYING.FFmpeg
|
||||
141de01f0d40b97d4f9a720db5ab8ea442f6aa35db5272048899292884994a1c ./hevc/libstagefrighthw.so
|
||||
|
||||
@@ -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
|
||||
@@ -13,8 +13,9 @@ details: Unreal Engine 4 (GLES). Found and verified in gameplay on a Frame by Kl
|
||||
the captured modules are from Lepton 2.8.14 and stop matching if a Frame update changes the driver's output -
|
||||
the layer logs that). OVRPlugin asks for poses at its own clock (pose_time_fix). Unreal's Oculus input animates the
|
||||
thumbs from near-touch, which the Frame never reports (frame.unreal_thumb_touch reads the touches instead; binding
|
||||
the proximity to the touch inputs in FrameBridge didn't reach the game). The Frame's SteamVR runtime
|
||||
leaks about 20 MB a second while the game runs (reported to Valve).
|
||||
the proximity to the touch inputs in FrameBridge didn't reach the game). The game leaves GL errors
|
||||
pending; the runtime's GL check took one as its own failure and then allocated a command buffer every frame
|
||||
(~20 MB a second until the frame rate collapsed). gl_error_clear clears them first (GitHub #285).
|
||||
tested_version: 1.1.1+667256.cl.387770
|
||||
engine: Unreal
|
||||
xr: VrApi
|
||||
@@ -27,10 +28,11 @@ frame:
|
||||
- frame.zink_shader_fix
|
||||
adapter:
|
||||
pose_time_fix: 1
|
||||
gl_error_clear: 1
|
||||
zink_shader_fix: 12016:b2919629761ad268e0b21c72ac8520f81b76e72c3adc26897f97eae9a3e70a66:3092:0x0003003e,166,82,0x0003003e,177,82,0x0003003e,183,82,0x0003003e,189,82,0x0003003e,256,82,0x0003003e,266,82,0x0003003e,272,82,0x0003003e,278,82,0x0003003e,318,82,0x0003003e,328,82,0x0003003e,334,82,0x0003003e,340,82;11436:6f18be49f2aaa2452f962eb16f7af744c5c22a7b25f37ce681e0d6399e35a869:2932:0x0003003e,164,80,0x0003003e,175,80,0x0003003e,181,80,0x0003003e,187,80,0x0003003e,254,80,0x0003003e,264,80,0x0003003e,270,80,0x0003003e,276,80,0x0003003e,316,80,0x0003003e,326,80,0x0003003e,332,80,0x0003003e,338,80
|
||||
verified:
|
||||
date: '2026-10-09'
|
||||
issue: 49
|
||||
updated: '2026-10-09'
|
||||
updated: '2026-10-14'
|
||||
min_app: 0.12.1
|
||||
source_hint: Vader Immortal- Episode I
|
||||
@@ -18,7 +18,9 @@ frame:
|
||||
- frame.unreal_thumb_touch
|
||||
adapter:
|
||||
pose_time_fix: 1
|
||||
gl_error_clear: 1
|
||||
verified:
|
||||
date: '2026-10-09'
|
||||
updated: '2026-10-14'
|
||||
min_app: 0.12.1
|
||||
source_hint: Vader Immortal- Episode II
|
||||
@@ -18,7 +18,9 @@ frame:
|
||||
- frame.unreal_thumb_touch
|
||||
adapter:
|
||||
pose_time_fix: 1
|
||||
gl_error_clear: 1
|
||||
verified:
|
||||
date: '2026-10-09'
|
||||
updated: '2026-10-14'
|
||||
min_app: 0.12.1
|
||||
source_hint: Vader Immortal- Episode III
|
||||
@@ -0,0 +1,19 @@
|
||||
package: com.NiVision.RacketPinball
|
||||
title: RacketPinball
|
||||
status: works
|
||||
tested_version: '2.06'
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
adapter:
|
||||
haptic_fix: 1
|
||||
verified:
|
||||
date: '2026-10-13'
|
||||
known_good_sha256: 80e850f81c24112e8c35a560a333846163a3e783da391290db7663b9015ca58f
|
||||
app: 1.0.4
|
||||
overport_cli: 1.2.5
|
||||
issue: 262
|
||||
source_hint: RacketPinball
|
||||
@@ -4,9 +4,9 @@ tested_version: MAIN.450412.207706.final
|
||||
source_hint: Assassins Creed Nexus VR
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
status: issues
|
||||
notes: Some launch warning text is still upside down; the rest of the UI is fixed by flip emulation. Ubisoft login
|
||||
may not work.
|
||||
status: works
|
||||
notes: FrameBridge turns its upside-down UI panels upright (flip emulation, in place since FramePort 1.1.2). 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.
|
||||
overport_extra:
|
||||
@@ -17,3 +17,6 @@ verified:
|
||||
overport_runtime: 3.4.3-23204ea
|
||||
known_good_sha256: 89644a12bf8df956fa3d3a9a40540ba9e1fb62f63494714a05c9f05984383ac8
|
||||
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
|
||||
@@ -0,0 +1,25 @@
|
||||
package: com.arkio.arkio
|
||||
title: Arkio
|
||||
status: works
|
||||
notes: The quest version allows for passthrough mode
|
||||
tested_version: 2.3.1
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
overport_extra:
|
||||
- patch_force_passthrough
|
||||
frame:
|
||||
- frame.meta_permissions
|
||||
- frame.unity_text_input
|
||||
device:
|
||||
- device.text_input_window
|
||||
adapter:
|
||||
scene_emul: 1
|
||||
verified:
|
||||
date: '2026-10-13'
|
||||
known_good_sha256: e17f9b2dc56cb49b4469d81f2e075ca5953f73152804ff1a00fba0931048e103
|
||||
app: 1.1.0
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20261007.6125817'
|
||||
agent: 85
|
||||
issue: 266
|
||||
source_hint: com.arkio.arkio
|
||||
@@ -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)
|
||||
@@ -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.1.2
|
||||
@@ -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
|
||||
@@ -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,20 @@
|
||||
package: com.fulldivegames.majorasmaskvr
|
||||
title: Majora's Mask VR
|
||||
status: issues
|
||||
notes: Audio on the file select screen sounds crunchy. Controls may need rebinding in the game. Quest build from https://github.com/fulldivegames/Majoras-Mask-VR.
|
||||
tested_version: '0.36'
|
||||
engine: Other
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- frame.sdl_clipboard
|
||||
adapter:
|
||||
refresh_rate: 144.0
|
||||
verified:
|
||||
date: '2026-10-13'
|
||||
known_good_sha256: 220096c70fb515ec7b8db1cc7a9075836b4d09f7df63026908af3c30e9fdb7e5
|
||||
app: 1.1.0
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20261007.6125817'
|
||||
agent: 85
|
||||
issue: 268
|
||||
source_hint: MMVR-Quest-0.36
|
||||
@@ -0,0 +1,26 @@
|
||||
package: com.nDreams.Ghostbusters
|
||||
title: 'Ghostbusters: Rise of the Ghost Lord'
|
||||
status: works
|
||||
notes: 'Needs the game''s offline mode: it is built for online play, and without a profile the player name is a random
|
||||
number. The flat loading screen floats in front of you instead of following your head, so assets can be seen loading
|
||||
in behind it.'
|
||||
tested_version: 1.325635.prod.shipping
|
||||
engine: Unreal
|
||||
xr: OpenXR
|
||||
alt_overport:
|
||||
- patch_remove_unreal_force_quit
|
||||
frame:
|
||||
- frame.unreal_ovrp_entrypoints
|
||||
- frame.hw_video_decode
|
||||
adapter:
|
||||
haptic_fix: 1
|
||||
scene_emul: 1
|
||||
verified:
|
||||
date: '2026-10-14'
|
||||
known_good_sha256: 7556a78c8772aed70c38fc4781677c0900e9dfd4be085a79c421a31323af7888
|
||||
app: 1.1.0
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20261007.6125817'
|
||||
agent: 85
|
||||
issue: 279
|
||||
source_hint: GBRotgl
|
||||
@@ -0,0 +1,23 @@
|
||||
package: com.notdead.COMPOUNDQUEST
|
||||
title: COMPOUND
|
||||
status: works
|
||||
tested_version: 1.0.12
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
frame:
|
||||
- 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-13'
|
||||
known_good_sha256: 5da7aac9863412daec7ba909dcfd2d5cfa6cb5d078150011c006165058cd76bd
|
||||
app: 1.1.0
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20261007.6125817'
|
||||
agent: 85
|
||||
issue: 260
|
||||
source_hint: COMPOUND
|
||||
@@ -0,0 +1,22 @@
|
||||
package: com.polyarc.Moss2
|
||||
title: 'Moss: Book II'
|
||||
status: works
|
||||
notes: Just played the very begining but controlls worked. Did nothing other than install it.
|
||||
tested_version: 1.0.3.149619
|
||||
engine: Unreal
|
||||
xr: VrApi
|
||||
alt_overport:
|
||||
- patch_remove_unreal_force_quit
|
||||
frame:
|
||||
- frame.hw_video_decode
|
||||
adapter:
|
||||
haptic_fix: 1
|
||||
verified:
|
||||
date: '2026-10-12'
|
||||
known_good_sha256: 686db536ced97d8a151c82955174ec01d67987c466ecd326d3deb557d8c4fd1d
|
||||
app: 1.0.4
|
||||
overport_cli: 1.2.5
|
||||
frame_build: '20261007.6125817'
|
||||
agent: 79
|
||||
issue: 248
|
||||
source_hint: Moss- Book II
|
||||
@@ -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.1.2
|
||||
@@ -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
|
||||
@@ -1,11 +1,16 @@
|
||||
package: quest.eleven.forfunlabs
|
||||
title: Eleven Table Tennis
|
||||
status: unsupported
|
||||
notes: Stops at the splash screen. The game needs Meta's online services after start, which aren't available on
|
||||
the Frame.
|
||||
status: works
|
||||
notes: Works great for me, tried the tutorial and an online match. Quest 2 apk.
|
||||
tested_version: 0.436.37_2026.9.4.18.35.33.415
|
||||
engine: Unity
|
||||
xr: OpenXR
|
||||
pcvr_alternative: The PC VR (Rift) version works on the Frame through FramePort.
|
||||
adapter:
|
||||
haptic_fix: 1
|
||||
verified:
|
||||
date: '2026-10-10'
|
||||
issue: 160
|
||||
date: '2026-10-13'
|
||||
known_good_sha256: f4d996db1c913639f8b981bf87834e053ee2d9267383da3c1a8372ba755e5ac8
|
||||
app: 1.1.0
|
||||
overport_cli: 1.2.5
|
||||
issue: 267
|
||||
source_hint: quest.eleven.forfunlabs
|
||||
@@ -6,6 +6,11 @@
|
||||
# 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:
|
||||
- id: meta-asset-status-error
|
||||
pattern: 'Asset status error\s+\(code 100\)'
|
||||
severity: error
|
||||
diagnosis: A DLC manager reports a Meta asset-file status error after VR starts (e.g. PixelRipped 1995). The asset-file check failed; the log does not identify the native call or asset ID. Try the experimental asset-file bypass (empty list, installed status with no file path); this does not supply DLC and has not been verified in the game.
|
||||
suggest: [frame.asset_files_stub]
|
||||
- id: lua-lightuserdata-pointer
|
||||
pattern: 'bad light userdata pointer'
|
||||
severity: fatal
|
||||
@@ -44,8 +49,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
|
||||
@@ -263,6 +268,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]
|
||||
@@ -375,10 +381,13 @@ 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. If the game still stops
|
||||
here, the OBB doesn't match this APK version - copy the APK and the OBB from the same install, add the game
|
||||
again and reinstall.
|
||||
suggest: [frame.unreal_skip_obb_check]
|
||||
on an error screen. "Unreal - start without the OBB check" skips the content check. 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
|
||||
(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.
|
||||
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)'
|
||||
severity: error
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -10,7 +10,9 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
| Accounting+ | Quest | ✅ Works | |
|
||||
| AgeOfJoy | Quest | ✅ Works | |
|
||||
| AllInOneSports | Quest | ✅ Works | |
|
||||
| Arkio | Quest | ✅ Works | |
|
||||
| Asgard's Wrath 2 | Quest | ✅ Works | |
|
||||
| Assassin's Creed Nexus | Quest | ✅ Works | |
|
||||
| Audica | Quest | ✅ Works | |
|
||||
| BAM | Quest | ✅ Works | |
|
||||
| BARTENDER VR SIMULATOR | Quest | ✅ Works | |
|
||||
@@ -28,6 +30,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
| Carve Snowboarding | Quest | ✅ Works | |
|
||||
| Caves | Quest | ✅ Works | |
|
||||
| Clockwork | Quest | ✅ Works | |
|
||||
| COMPOUND | Quest | ✅ Works | |
|
||||
| Cook-Out | Quest | ✅ Works | |
|
||||
| Cosmodread | Quest | ✅ Works | |
|
||||
| Creed | Quest | ✅ Works | |
|
||||
@@ -40,14 +43,17 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
| Down the Rabbit Hole | Quest | ✅ Works | |
|
||||
| Drunkn Bar Fight | Quest | ✅ Works | |
|
||||
| Drunkn Bar Fight 2 - Early Access | Quest | ✅ Works | |
|
||||
| Eleven Table Tennis | Quest | ✅ Works | |
|
||||
| Eleven: Table Tennis VR | PC VR | ✅ Works | |
|
||||
| Espire 2 | Quest | ✅ Works | |
|
||||
| FrenzyVR | Quest | ✅ Works | |
|
||||
| Fruit Ninja | Quest | ✅ Works | |
|
||||
| Fruit Salon | Quest | ✅ Works | |
|
||||
| Genotype | Quest | ✅ Works | |
|
||||
| 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 | |
|
||||
@@ -68,6 +74,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
| Medieval Dynasty New Settlement | Quest | ✅ Works | |
|
||||
| Metro Awakening | Quest | ✅ Works | |
|
||||
| Mobile Suit Gundam: Silver Phantom | Quest | ✅ Works | |
|
||||
| Moss: Book II | Quest | ✅ Works | |
|
||||
| Munkr Funkr (The Legacy Days) | Quest | ✅ Works | |
|
||||
| Nano | Quest | ✅ Works | |
|
||||
| NEX Player | Quest | ✅ Works | |
|
||||
@@ -81,6 +88,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
| PowerWash Simulator VR | Quest | ✅ Works | |
|
||||
| QuestCraft | Quest | ✅ Works | |
|
||||
| Racket: Nx | Quest | ✅ Works | |
|
||||
| RacketPinball | Quest | ✅ Works | |
|
||||
| RC Pilot Trainer | Quest | ✅ Works | |
|
||||
| Retronika | Quest | ✅ Works | |
|
||||
| Retropolis | Quest | ✅ Works | |
|
||||
@@ -89,11 +97,13 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
| Riven | Quest | ✅ Works | |
|
||||
| Robo Recall | Quest | ✅ Works | |
|
||||
| RUINSMAGUS | Quest | ✅ Works | |
|
||||
| Shoot The Zombirds VR | Quest | ✅ Works | |
|
||||
| Shores of Loci | Quest | ✅ Works | |
|
||||
| SilentSlayer | Quest | ✅ Works | |
|
||||
| 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 | |
|
||||
@@ -125,9 +135,9 @@ 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). |
|
||||
| Assassin's Creed Nexus | Quest | ⚠️ Works with issues | Some launch warning text is still upside down; the rest of the UI is fixed by flip emulation. |
|
||||
| Does it Stack? | Quest | ⚠️ Works with issues | Mixed reality mode does not work (works on Demeo), everything else seems to be OK |
|
||||
| Dungeons of Eternity | Quest | ⚠️ Works with issues | It can not connect to servers |
|
||||
| End Space | Quest | ⚠️ Works with issues | Controls stop responding after the first mission loads. |
|
||||
@@ -135,21 +145,22 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
|
||||
| Fisherman | Quest | ⚠️ Works with issues | Loading screens have corruption, but everything works otherwise. |
|
||||
| Freedom | Quest | ⚠️ Works with issues | Volume can't be changed in the game. |
|
||||
| MacacoVR | Quest | ⚠️ Works with issues | 2d loading screens are glitchy, otherwise main gameplay is fine |
|
||||
| Majora's Mask VR | Quest | ⚠️ Works with issues | Audio on the file select screen sounds crunchy. |
|
||||
| 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. |
|
||||
| Time Stall | Quest | ⚠️ Works with issues | Both eyes distort during movement (unresolved). |
|
||||
| Vermillion | Quest | ⚠️ Works with issues | Runs. |
|
||||
| WiiCompiled VR | Quest | ⚠️ Works with issues | To add a game: in FramePort's Files tab, upload your .wcgame file to this game's storage, folder Android/data/org.wiicompiled.quest/files/WiiCompiledOpenXRVR… |
|
||||
| Eleven Table Tennis | Quest | ❌ Doesn't run | Stops at the splash screen. |
|
||||
| Espire 1: VR Operative (Quest Edition) | Quest | ❌ Doesn't run | Mesa GL driver crash during texture upload. |
|
||||
| GOLF+ | Quest | ❌ Doesn't run | Black screen. |
|
||||
| HITMAN 3 VR: Reloaded | Quest | ❌ Doesn't run | Vulkan driver crash (freedreno), even without Valve layers. |
|
||||
| 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. |
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# Patches
|
||||
|
||||
Every patch and game setting FramePort knows: 164 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,8 +11,8 @@ 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) (52)
|
||||
- [Game settings](#group-adapter) (66)
|
||||
- [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)
|
||||
|
||||
@@ -30,7 +30,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
|
||||
| [Disable application space warp if used](#patch_disable_space_warp) | `patch_disable_space_warp` | Patches from OVRPort | 3 |
|
||||
| [Fix minimal Android SDK](#patch_fix_min_android_sdk) | `patch_fix_min_android_sdk` | Patches from OVRPort | default |
|
||||
| [Fix UE4 crash with Unity stub](#patch_fix_unreal_crash) | `patch_fix_unreal_crash` | Patches from OVRPort | default |
|
||||
| [Force enable passthrough](#patch_force_passthrough) | `patch_force_passthrough` | Patches from OVRPort | 2 |
|
||||
| [Force enable passthrough](#patch_force_passthrough) | `patch_force_passthrough` | Patches from OVRPort | 3 |
|
||||
| [Generate OVRPort config](#patch_generate_config) | `patch_generate_config` | Patches from OVRPort | default |
|
||||
| [Fix launcher icon entry](#patch_launcher_entry) | `patch_launcher_entry` | Patches from OVRPort | default |
|
||||
| [Mark application to allow backup](#patch_mark_allow_backup) | `patch_mark_allow_backup` | Patches from OVRPort | default |
|
||||
@@ -39,14 +39,16 @@ 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 | 34 |
|
||||
| [Remove Unreal's ForceQuit](#patch_remove_unreal_force_quit) | `patch_remove_unreal_force_quit` | Patches from OVRPort | 35 |
|
||||
| [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 | |
|
||||
| [BlazeRush: controllers without Meta avatars, own shader cache](#frame-blazerush) | `frame.blazerush` | Steam Frame patches | 1 |
|
||||
@@ -54,12 +56,12 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
|
||||
| [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 | 6 |
|
||||
| [Hardware video decoding (H.264, HEVC, VP9)](#frame-hw_video_decode) | `frame.hw_video_decode` | Steam Frame patches | 9 |
|
||||
| [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 |
|
||||
| [Fix Lua startup crashes on Frame](#frame-luajit_pointers) | `frame.luajit_pointers` | Steam Frame patches | |
|
||||
| [Declare Meta-only permissions](#frame-meta_permissions) | `frame.meta_permissions` | Steam Frame patches | 1 |
|
||||
| [Declare Meta-only permissions](#frame-meta_permissions) | `frame.meta_permissions` | Steam Frame patches | 2 |
|
||||
| [Meta XR Audio: skip Quest telemetry class](#frame-metaxr_telemetry) | `frame.metaxr_telemetry` | Steam Frame patches | default |
|
||||
| [Clear android:debuggable](#frame-nodebug) | `frame.nodebug` | Steam Frame patches | 3 |
|
||||
| [Oculus OS telemetry class stubs](#frame-oculusos) | `frame.oculusos` | Steam Frame patches | 15 |
|
||||
@@ -69,26 +71,27 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
|
||||
| [Platform compat (ovrMessageType_ToString)](#frame-ovrplatformcompat) | `frame.ovrplatformcompat` | Steam Frame patches | default |
|
||||
| [Stub missing Meta platform functions](#frame-ovrstubs) | `frame.ovrstubs` | Steam Frame patches | default |
|
||||
| [Unpaired pointer-authentication checks](#frame-pac_hints) | `frame.pac_hints` | Steam Frame patches | 1 |
|
||||
| [SDL apps: start without a clipboard service](#frame-sdl_clipboard) | `frame.sdl_clipboard` | Steam Frame patches | 3 |
|
||||
| [SDL apps: start without a clipboard service](#frame-sdl_clipboard) | `frame.sdl_clipboard` | Steam Frame patches | 4 |
|
||||
| [Stress Level Zero: let Unity start Vulkan itself](#frame-slz_vulkan_hooks) | `frame.slz_vulkan_hooks` | Steam Frame patches | 1 |
|
||||
| [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 | 18 |
|
||||
| [GL shim for Unity (no multisampled render-to-texture)](#frame-unity_gl_shim) | `frame.unity_gl_shim` | Steam Frame patches | 19 |
|
||||
| [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: 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 | 23 |
|
||||
| [Make Unity text fields work](#frame-unity_text_input) | `frame.unity_text_input` | Steam Frame patches | 70 |
|
||||
| [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: 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 |
|
||||
| [Unreal: match multiview depth to the eye size](#frame-unreal_multiview_depth) | `frame.unreal_multiview_depth` | Steam Frame patches | 1 |
|
||||
| [Unreal: stand-ins for OVRPlugin functions OVRPort lacks](#frame-unreal_ovrp_entrypoints) | `frame.unreal_ovrp_entrypoints` | Steam Frame patches | 1 |
|
||||
| [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: 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 |
|
||||
@@ -112,17 +115,19 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
|
||||
| [360° 3D](#adapter-equirect_stereo) | `adapter.equirect_stereo` | Game settings | |
|
||||
| [Per-eye diagnostics (log)](#adapter-eye_debug) | `adapter.eye_debug` | Game settings | |
|
||||
| [Draw fades over the picture](#adapter-fade_quad) | `adapter.fade_quad` | Game settings | 2 |
|
||||
| [Upside-down panel images (diagnostics)](#adapter-flip_dump) | `adapter.flip_dump` | Game settings | |
|
||||
| [Fix upside-down menus](#adapter-flip_emul) | `adapter.flip_emul` | Game settings | |
|
||||
| [Rotate panels 180°](#adapter-flip_quads) | `adapter.flip_quads` | Game settings | |
|
||||
| [Don't pause on short interruptions](#adapter-focus_hold) | `adapter.focus_hold` | Game settings | 4 |
|
||||
| [Ignore focus dips up to](#adapter-focus_hold_ms) | `adapter.focus_hold_ms` | Game settings | 2 |
|
||||
| [Hide Quest foveation](#adapter-foveation_fix) | `adapter.foveation_fix` | Game settings | |
|
||||
| [Clear the game's GL errors (GLES)](#adapter-gl_error_clear) | `adapter.gl_error_clear` | Game settings | 3 |
|
||||
| [Hide fast anti-aliasing (OpenGL ES)](#adapter-gl_hide_msrtt) | `adapter.gl_hide_msrtt` | Game settings | 1 |
|
||||
| [Draw each eye separately (OpenGL ES)](#adapter-gl_hide_multiview) | `adapter.gl_hide_multiview` | Game settings | 1 |
|
||||
| [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 | 61 |
|
||||
| [Fix freezes when controllers vibrate](#adapter-haptic_fix) | `adapter.haptic_fix` | Game settings | 66 |
|
||||
| [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,12 +143,12 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
|
||||
| [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 | |
|
||||
| [Refresh rate](#adapter-refresh_rate) | `adapter.refresh_rate` | Game settings | 2 |
|
||||
| [Refresh rate](#adapter-refresh_rate) | `adapter.refresh_rate` | Game settings | 3 |
|
||||
| [Wait for the game's GPU](#adapter-release_wait) | `adapter.release_wait` | Game settings | |
|
||||
| [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 | 2 |
|
||||
| [Pretend room layout](#adapter-scene_emul) | `adapter.scene_emul` | Game settings | 4 |
|
||||
| [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,7 +175,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
|
||||
| [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 | 70 |
|
||||
| [Show the app's Android window (for typing)](#device-text_input_window) | `device.text_input_window` | Files and settings on the Frame | 76 |
|
||||
| [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) | |
|
||||
@@ -313,7 +318,7 @@ Lets mixed-reality games start even though they insist on a camera view of your
|
||||
- `patch_force_passthrough`
|
||||
- **Changes:** Changes the APK (during the OVRPort conversion).
|
||||
- **Suggested (on):** Mixed-reality-only game (passthrough required, no guardian): force passthrough on.
|
||||
- **Catalog games (2):** BAM, Demeter.
|
||||
- **Catalog games (3):** Arkio, BAM, Demeter.
|
||||
- **Suggested by launch-test signatures:**
|
||||
- `passthrough-missing` (error): The game needs Meta passthrough (the camera view), which the Frame lacks; the adapter emulates it.
|
||||
- **Source:** [patches/overport.py](../src/frameport/patches/overport.py)
|
||||
@@ -415,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 (34):** Asgard's Wrath 2, BARTENDER VR SIMULATOR, Carve Snowboarding, Creed, Dance Central, Espire 1: VR Operative (Quest Edition), Espire 2, ExploreVR and 26 more.
|
||||
- **Catalog games (35):** Asgard's Wrath 2, BARTENDER VR SIMULATOR, Carve Snowboarding, Creed, Dance Central, Espire 1: VR Operative (Quest Edition), Espire 2, ExploreVR and 27 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)
|
||||
@@ -483,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.
|
||||
@@ -511,6 +530,19 @@ Lets the game find extra content it keeps next to its data (for example Star War
|
||||
|
||||
> Some games keep content in separate files next to their OBB (for example Star Wars: Tales from the Galaxy's Edge: its seasons and sound banks) and ask Meta's platform for them as asset files. OVRPort's platform loader doesn't know them, so the game waits for content that never arrives (black screen after loading). Lists the content files shipped with the game's data (*.pak) as installed and answers their download request at once with the file's path; nothing is copied or downloaded. Shares the language-pack library.
|
||||
|
||||
### <a id="frame-asset_files_stub"></a>Asset-file service bypass
|
||||
|
||||
Experimental bypass for a failed Meta asset-file check at startup. Reports an empty asset list and installed status without a file path; does not provide DLC. Experimental.
|
||||
|
||||
- `frame.asset_files_stub` · experimental
|
||||
- **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.
|
||||
- **Suggested by launch-test signatures:**
|
||||
- `meta-asset-status-error` (error): A DLC manager reports a Meta asset-file status error after VR starts (e.g.
|
||||
- **Source:** [patches/frame/langpack.py](../src/frameport/patches/frame/langpack.py)
|
||||
|
||||
> Experimental bypass for a DLC manager blocked on Meta asset-file service errors at startup (e.g. PixelRipped 1995: Asset status error (code 100)). Returns an empty successful asset list and reports requested asset IDs as installed, with an empty file path. Does not supply DLC or change download requests. Enable only to test this startup failure; disable with FRAMEPORT_ASSET_FILES_STUB=0. Shares the language-pack library and needs no language packs.
|
||||
|
||||
### <a id="frame-avatar_stub"></a>Skip Meta avatars
|
||||
|
||||
Lets games start that would stop at Meta's avatars (for example BlazeRush). No Meta avatars.
|
||||
@@ -611,7 +643,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 (6):** 4XVR Video Player, Batman: Arkham Shadow, Dance Central, Fruit Ninja, Kill It With Fire VR, MacacoVR.
|
||||
- **Catalog games (9):** 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 and 1 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.
|
||||
@@ -672,7 +704,7 @@ Declares Meta's permissions some mixed-reality games ask for, so they don't stop
|
||||
- `frame.meta_permissions`
|
||||
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
|
||||
- **Suggested (on):** Mixed-reality game that needs the room model: its 'use spatial data' permission must be granted (for example Demeter).
|
||||
- **Catalog games (1):** Demeter.
|
||||
- **Catalog games (2):** Arkio, Demeter.
|
||||
- **Source:** [patches/frame/manifest_fixes.py](../src/frameport/patches/frame/manifest_fixes.py)
|
||||
|
||||
> Declares com.oculus.permission.* / horizonos.permission.* that the app uses, so Android grants them at install (for example the 'use spatial data' permission of mixed-reality games like Demeter).
|
||||
@@ -804,7 +836,7 @@ Lets SDL and LÖVE games start on the Frame (they'd crash looking for a clipboar
|
||||
- `frame.sdl_clipboard` · also for 2D apps
|
||||
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
|
||||
- **Suggested (on):** SDL app: it crashes at start in Lepton, which has no clipboard service.
|
||||
- **Catalog games (3):** Time Crisis II VR (Test), Time Crisis VR (Experimental), WiiCompiled VR.
|
||||
- **Catalog games (4):** Majora's Mask VR, Time Crisis II VR (Test), Time Crisis VR (Experimental), WiiCompiled VR.
|
||||
- **Suggested by launch-test signatures:**
|
||||
- `sdl-no-clipboard` (fatal): The app crashed at start because the Frame's Android has no clipboard.
|
||||
- **Source:** [patches/frame/sdl_clipboard.py](../src/frameport/patches/frame/sdl_clipboard.py)
|
||||
@@ -855,7 +887,7 @@ Allows very large pictures (8K video, theaters) instead of quitting.
|
||||
|
||||
Lets Team Beef ports (for example Lambda1VR) start on the Frame.
|
||||
|
||||
- `frame.tbxr_vendor`
|
||||
- `frame.tbxr_vendor` · revision 2
|
||||
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
|
||||
- **Suggested (on):** Team Beef port: it picks its OpenXR setup by headset maker, which the Frame reports as "valve".
|
||||
- **Catalog games (1):** Lambda1VR.
|
||||
@@ -870,7 +902,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 (18):** Audica, BattleSisters, Beat Saber, Clockwork, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight, End Space and 10 more.
|
||||
- **Catalog games (19):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 11 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)
|
||||
@@ -939,7 +971,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 (23):** Audica, BattleSisters, Beat Saber, Clockwork, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight, End Space and 15 more.
|
||||
- **Catalog games (24):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 16 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.
|
||||
@@ -955,7 +987,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 (70):** AgeOfJoy, AllInOneSports, Ancient_Dungeon, Audica, BattleSisters, Beat Saber, Beat Saber (co-existence build), Blade & Sorcery: Nomad and 62 more.
|
||||
- **Catalog games (73):** AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arkio, Audica, BattleSisters, Beat Saber, Beat Saber (co-existence build) and 65 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 -> false and isKeyboardUsingEvents (TMP) / InPlaceEditing (uGUI) -> 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.
|
||||
@@ -1021,7 +1053,7 @@ Lets older Unreal games start VR on the Frame (for example Star Wars Pinball VR)
|
||||
- `frame.unreal_ovrp_entrypoints`
|
||||
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
|
||||
- **Suggested (on):** Unreal looks up OVRPlugin function(s) OVRPort's OVRPlugin lacks: ……. Without them Unreal starts no VR.
|
||||
- **Catalog games (1):** Star Wars Pinball VR.
|
||||
- **Catalog games (2):** Ghostbusters: Rise of the Ghost Lord, Star Wars Pinball VR.
|
||||
- **Source:** [patches/frame/unreal_ovrp.py](../src/frameport/patches/frame/unreal_ovrp.py)
|
||||
|
||||
> Unreal's Oculus module looks up every OVRPlugin function it was built against and starts no VR when one is missing; OVRPort's OpenXR OVRPlugin lacks some old ones (for example ovrp_GetPTWNear, which Unreal 4.25 builds like Star Wars Pinball VR look up). The game then never starts an OpenXR session and crashes a few seconds in. Adds a generated library to libOVRPlugin.so with a stand-in for each missing function that reports failure (ovrpFailure), so Unreal's Oculus support starts. The functions OVRPort has are untouched.
|
||||
@@ -1064,6 +1096,19 @@ Starts Unreal games without re-checking their data file (they'd seem to hang on
|
||||
|
||||
> Unreal games can check their whole data file (.obb) before starting (bVerifyOBBOnStartUp). On the Frame that check's progress and error screens are invisible (Lepton runs VR games without an Android window), so the game seems to hang on its DownloaderActivity, for example Contractors. This turns the check off in the manifest; Unreal still checks that the OBB is there with the right size, so a missing or wrong-version OBB still stops the game.
|
||||
|
||||
### <a id="frame-unreal_skip_obb_delivery"></a>Unreal: skip the OBB delivery check
|
||||
|
||||
Skips a separate data-file check when an Unreal game still hangs at startup with the content check off. Experimental; the game still needs its data.
|
||||
|
||||
- `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.
|
||||
- **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.
|
||||
|
||||
### <a id="frame-unreal_splash_bypass"></a>Unreal: bypass the stalled loading splash
|
||||
|
||||
Lets the game finish loading when its separate loading splash stalls the render thread.
|
||||
@@ -1397,6 +1442,20 @@ For games whose fades to black don't show, so you see the level loading (for exa
|
||||
|
||||
> Games that fade to black by dimming their picture with a layer color scale (XR_KHR_composition_layer_color_scale_bias, for example Batman: Arkham Shadow's loading screens) can show the level loading instead of black on the Frame. FrameBridge then draws the fade itself: a black quad in front of the eyes whose opacity follows the game's dimming. 2 also removes the game's own dimming (if both show, the fade is doubled).
|
||||
|
||||
### <a id="adapter-flip_dump"></a>Upside-down panel images (diagnostics)
|
||||
|
||||
Saves a few UI panels before and after FrameBridge turns them upright, for testing without the headset.
|
||||
|
||||
- `adapter.flip_dump`
|
||||
- **Changes:** Game setting: stored in the build and on the Frame (settings.conf); can be changed without a rebuild.
|
||||
- **Suggested:** not automatically; set on the game page (Customize), by a recipe or after a launch test.
|
||||
- **Options:**
|
||||
- Value: int, default `0`.
|
||||
- Game settings → Troubleshooting → "Upside-down panel images (diagnostics)" (advanced).
|
||||
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
|
||||
|
||||
> Saves the first N UI panels that FrameBridge turns upright (Vulkan games whose panels are stored upside down), before and after the flip, as fb_flip_<n>_raw.ppm / fb_flip_<n>_upright.ppm in the game's files folder on the Frame. Shows what the runtime gets without anyone wearing the headset.
|
||||
|
||||
### <a id="adapter-flip_emul"></a>Fix upside-down menus
|
||||
|
||||
Turns menus and text the right way up.
|
||||
@@ -1471,6 +1530,21 @@ Hides a Quest-only way of saving GPU power that the Frame lacks. Leave it on.
|
||||
|
||||
> Hides Quest foveation extensions the Frame runtime lacks.
|
||||
|
||||
### <a id="adapter-gl_error_clear"></a>Clear the game's GL errors (GLES)
|
||||
|
||||
For OpenGL ES games whose memory use keeps growing (e.g. Vader Immortal).
|
||||
|
||||
- `adapter.gl_error_clear`
|
||||
- **Changes:** Game setting: stored in the build and on the Frame (settings.conf); can be changed without a rebuild.
|
||||
- **Suggested:** not automatically; set on the game page (Customize), by a recipe or after a launch test.
|
||||
- **Options:**
|
||||
- Value: int, default `0`.
|
||||
- Game settings → Troubleshooting → "Clear the game's GL errors (GLES)" (advanced).
|
||||
- **Catalog games (3):** Vader Immortal: Episode I, Vader Immortal: Episode II, Vader Immortal: Episode III.
|
||||
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
|
||||
|
||||
> Clears OpenGL errors the game left pending before FrameBridge calls the Frame's runtime. The runtime's GL code fails on any pending error; after one such failure at the start it allocated GPU memory every frame without freeing it (e.g. Vader Immortal, ~20 MB a second).
|
||||
|
||||
### <a id="adapter-gl_hide_msrtt"></a>Hide fast anti-aliasing (OpenGL ES)
|
||||
|
||||
For Unity games that crash when they turn on anti-aliasing (for example The Room VR).
|
||||
@@ -1555,7 +1629,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 (61):** AgeOfJoy, Ancient_Dungeon, Audica, BattleSisters, Beat Saber, Caves, Clockwork, Cosmodread and 53 more.
|
||||
- **Catalog games (66):** AgeOfJoy, Ancient_Dungeon, Audica, BattleSisters, Beat Saber, Caves, Clockwork, COMPOUND and 58 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.
|
||||
@@ -1790,7 +1864,7 @@ How often the picture updates. Higher is smoother if the game can keep up.
|
||||
- **Options:**
|
||||
- Value: float, default `0.0`.
|
||||
- Game settings → Picture → "Refresh rate": Game's choice (`0`), 72 Hz (`72`), 80 Hz (`80`), 90 Hz (`90`), 96 Hz (`96`), 108 Hz (`108`), 120 Hz (`120`), 144 Hz (`144`).
|
||||
- **Catalog games (2):** Does it Stack?, Vacation Simulator.
|
||||
- **Catalog games (3):** Does it Stack?, Majora's Mask VR, Vacation Simulator.
|
||||
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
|
||||
|
||||
> Display refresh rate for this game (72, 80, 90, 96, 108, 120 or 144; 0 = the game's choice). A video's frame rate that divides the refresh rate plays smoothest (for example 30 fps at 90 Hz, 24 fps at 72 Hz).
|
||||
@@ -1863,7 +1937,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 (2):** Demeter, Vermillion.
|
||||
- **Catalog games (4):** Arkio, Demeter, Ghostbusters: Rise of the Ghost Lord, Vermillion.
|
||||
- **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)
|
||||
@@ -1929,7 +2003,7 @@ For games whose menus or screens jump to wherever you look.
|
||||
|
||||
### <a id="adapter-strip_color_bias"></a>Drop layer color fades
|
||||
|
||||
For games whose memory use keeps growing (for example Vader Immortal). Some fades no longer show.
|
||||
Diagnostics: removes layer color fades. Some fades no longer show.
|
||||
|
||||
- `adapter.strip_color_bias`
|
||||
- **Changes:** Game setting: stored in the build and on the Frame (settings.conf); can be changed without a rebuild.
|
||||
@@ -1939,7 +2013,7 @@ For games whose memory use keeps growing (for example Vader Immortal). Some fade
|
||||
- Game settings → Troubleshooting → "Drop layer color fades" (advanced).
|
||||
- **Source:** [patches/settings.py](../src/frameport/patches/settings.py)
|
||||
|
||||
> Removes the color scale/bias (XR_KHR_composition_layer_color_scale_bias) from the game's layers, so the runtime doesn't apply it. The Frame's runtime allocates GPU memory for it every frame without freeing it, for example Vader Immortal leaked ~20 MB/s on its loading screen. Fades done this way no longer show.
|
||||
> Removes the color scale/bias (XR_KHR_composition_layer_color_scale_bias) from the game's layers, so the runtime doesn't apply it (diagnostics). Fades done this way no longer show.
|
||||
|
||||
### <a id="adapter-strip_depth"></a>Strip depth layers
|
||||
|
||||
@@ -2256,7 +2330,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 (70):** AgeOfJoy, AllInOneSports, Ancient_Dungeon, Audica, Beat Saber, Beat Saber (co-existence build), Blade & Sorcery: Nomad, BodyCombat and 62 more.
|
||||
- **Catalog games (76):** AFFECTED: The Manor, AgeOfJoy, AllInOneSports, Ancient_Dungeon, Arkio, Audica, Beat Saber, Beat Saber (co-existence build) and 68 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".
|
||||
|
||||
@@ -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.
|
||||
@@ -24,6 +24,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|
||||
| A Unity OpenXR game closes right after the OpenXR instance is created: `F VrApiLoader: vrapi_SetPropertyInt was called before vrapi_Initialize()!`, SIGABRT on UnityMain (GitHub #62, Jurassic World Aftermath) | the APK still ships Meta's VrApi loader; OVRPlugin (1.89, on OpenXR) calls it without starting VrApi and Meta's loader aborts. The VrApi bridge can't replace it (39 of the loader's 114 functions: OVRPlugin wouldn't link) | `frame.vrapi_stub` (same exports, each returns 0); triage `vrapi-before-init` |
|
||||
| A VrApi game exits at once: `UnsatisfiedLinkError … dlopen failed: cannot locate symbol "vrapi_PollEvent"` (GitHub #57, BlazeRush) | the engine imports a VrApi function the VrApi bridge didn't implement | the bridge has `vrapi_PollEvent`, `RecenterPose`, `SetDisplayRefreshRate`, `GetSystemPropertyFloatArray` (rebuild the game); the static check "VrApi functions resolvable" names any other missing one; triage `vrapi-symbol-missing` |
|
||||
| A Team Beef port (Lambda1VR, RTCWQuest, …) exits at once: `UnsatisfiedLinkError: dlopen failed: library "libopenxr_loader_valve.so" not found` (GitHub #59) | TBXR loads `openxr_loader_<Build.MANUFACTURER>` (Lepton: valve) and takes the Meta path only when `strstr(OPENXR_HMD, "meta")` matches, else Pico's | `frame.tbxr_vendor` (empty `libopenxr_loader_valve.so` + the "meta" literal → "alve"). Game data (`xash/`, …) goes to /sdcard: upload it with the Files tab to the game's storage. Black eyes with `TBXR: Incomplete frame buffer object: GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE`: TBXR always uses multisampled render-to-texture (even `--msaa 1`); `frame.tbxr_vendor` links the GL shim, which hands it single-sampled versions (log `GL shim: multisampled render-to-texture … drawn single-sampled`) |
|
||||
| Black screen after VR starts; `Asset status error (code 100)` in `DLC_Manager:AssetStatusCallback` (GitHub #203, e.g. PixelRipped 1995) | Meta asset-file status fails after entitlement succeeds; the log does not identify the native call or asset ID | Try `frame.asset_files_stub` (opt-in, triage-only): native/langpack answers GetList with an empty successful list and StatusById with installed status, an empty path and the requested ID. No DLC files are supplied; download requests retain their existing behavior. Disable with `FRAMEPORT_ASSET_FILES_STUB=0`. Host-tested only; whether this fixes startup needs a game/device test |
|
||||
| Missing sound or extra content in a game whose OBB folder has separate `*.pak` files (GitHub #61, Star Wars: Tales from the Galaxy's Edge: seasons + Wwise banks) | the game asks Meta's platform for these asset files (`ovr_AssetFile_GetList` / `DownloadById`); OVRPort's loader doesn't list them | copy every content/sound-bank PAK and use `frame.asset_files` (native/langpack lists the data's `*.pak` as installed `default` assets, IAP `free`, and answers DownloadById at once with the path; off: env FRAMEPORT_ASSET_FILES=0). Tales also needs the splash and depth-size fixes below |
|
||||
| A SideQuest backup has `apk/` and a sibling `obb/` with content/sound-bank PAKs, but the Frame only has the main OBB (GitHub #61, Tales from the Galaxy's Edge) | older scans treated that layout as loose expansion files and selected only the named OBBs; the asset-file patch then found no PAKs | the scanner chooses the OBB folder by version first, then keeps the whole sibling data folder when all its expansion files are selected for this APK; app updates repair affected library entries and refresh asset/language-pack detection. Reinstall to copy the missing files, or scan the backup again first. Folders with other packages or unselected OBB versions still send only the selected OBBs |
|
||||
| Tales from the Galaxy's Edge stops during map loading (GitHub #61): game thread in `FlushRenderingCommands` / `UEngine::LoadMap`, render thread in `FSplash::RenderFrame_RenderThread` / `ovrp_WaitToBeginFrame` / SteamVR `WaitFrame` | the separate Oculus loading splash waits for an unbegun frame while map travel waits for rendering | `frame.unreal_splash_bypass`: returns from the splash renderer, with a checked symbol, size and prologue. The last image stays visible during loading; the normal renderer and menu layers continue. Headset test with the depth-size fix: gameplay, both eyes, controller input and sound work |
|
||||
@@ -60,7 +61,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|
||||
| Oculus Rift game won't run on the Frame | Oculus/LibOVR game: needs Revive, whose hooks don't work under Proton-arm64, and FramePort won't defeat the Oculus runtime signature check | Play it on this PC (SteamVR + Revive). Only OpenVR/OpenXR-native Rift games run on the Frame |
|
||||
| Un-cracked Oculus PC VR game: "Initializing OVR session" then exits / signature check on the runtime | Revive's hooks don't install on Proton-arm64; the Oculus shim rejects the unsigned Revive runtime | Not runnable on the Frame without the repack's crack extracted (not done by FramePort); use the PC version |
|
||||
| PC VR game: `Failed to initialize Oculus API (-3001)` / `Unable to load LibOVRRT DLL` | Revive's LoadLibrary hook doesn't work under Proton arm64 (ARM64EC kernelbase); the game's LibOVR shim finds no runtime DLL | Symlink `LibOVRRT64_1.dll` → Revive's DLL in the prefix's system32 (manual so far) → then -3021 (runtime signature check; open) |
|
||||
| Uploads to the Frame are slow (~15 MB/s) | PC and Frame both on Wi-Fi through the home router | Connect the PC to the Frame's own hotspot (or a USB cable): FramePort uses the direct link automatically (~80-100 MB/s); job log line "Transfer link" |
|
||||
| Uploads to the Frame are slow | The link, storage or transfer backend can limit throughput | Check the job's "Transfer link"; try the Frame's hotspot or USB cable. Large install files prefer system OpenSSH SFTP, retaining paired-host checks and `.part` resume; unavailable or failed native uploads fall back to Paramiko. The log names the backend. Settings → Installing → Parallel uploads accepts 1–8 (default 3; saved preferences are preserved). More is not always faster. Measure the production path with `scripts/upload_bench.py --methods app-files-3 --check-resume` (three repetitions, checksum verification) |
|
||||
| PC VR game exits right away: `Unhandled Exception: 0xc06d007e` (after `FOnlineSubsystemOculus::InitWithWindowsPlatform`) | Delay-loaded `LibOVRPlatform64_1.dll` (Oculus Platform SDK, installed with the Oculus app) is missing | None on the Frame (entitlement check; FramePort doesn't replace it). PC mode with the Oculus app |
|
||||
| Unity PC VR game (Oculus + SteamVR build: `OVRPlugin.dll` and `openvr_api.dll` in `<Name>_Data/Plugins`) opens a window and quits after ~20 s; no VR Vulkan instance after the game's DXVK device in launch.log; Unity log (`unity log … Player.log`, agent v67): `OpenVR failed initialization` / `Initialization of device … failed` | Unity's built-in VR tries its SDKs in list order (Oculus first) unless `-vrmode` picks one; a catalog recipe verified with another build of the game (for example SUPERHOT VR's OpenXR build, GitHub #105) used to drop the build's own arguments | `pcvr.launch_args` = `-vrmode OpenVR` (detected for such builds; kept when the catalog's `xr` differs from the build's). A game's Electron launcher next to it (SHVR.exe) is ranked below the game |
|
||||
| Unreal PC VR game opens the crash reporter instead of closing | UE starts CrashReportClient.exe on a crash | `pcvr.no_crash_reporter` (default for Unreal Rift games): `-nocrashreports` + CrashReportClient.exe renamed `.disabled` in the Frame copy |
|
||||
@@ -72,7 +73,14 @@ 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 |
|
||||
| `INSTALL_FAILED_NO_MATCHING_ABIS` | 32-bit-only APK; Frame has no AArch32 | None. PC/Rift version via Revive |
|
||||
| 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 (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) |
|
||||
@@ -80,6 +88,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) |
|
||||
@@ -94,6 +103,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 |
|
||||
@@ -146,6 +156,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
|
||||
| Unreal game (ILMxLAB, for example Vader Immortal): controllers track but grip/trigger do nothing, grabbing never works (Unreal's own input values move, the game's stay 0) | `URPOCKeyMapManagerComponent` picks the Quest or the Gear VR key set by `IsRunningOnSantaCruz()`; on the Frame it takes Gear VR, empty in a Quest build | `frame.unreal_quest_keymap` (the Oculus case keeps the Quest set, for action and axis mappings; found by Klownicle, GitHub #49) |
|
||||
| The hands' thumbs never move when you touch the thumbstick or buttons (Unreal `ThumbUp` stays 1, for example Vader Immortal) | OVRPlugin reports thumb proximity from XR_FB_touch_controller_proximity, which the Frame's runtime lacks; OVRPort's loader offers it anyway and the proximity actions never get a binding | adapter `proximity_emul=1` (thumb proximity from the touch inputs: thumbstick, face buttons, thumb rest; 2 = also the index finger from trigger touch); log `proximity_emul: finger proximity bound to touch`. **For UE4 Oculus games this didn't animate the thumbs** (Vader, GitHub #49): use `frame.unreal_thumb_touch` (found by Klownicle): `OculusInput::FOculusInput::SendControllerEvents` computes ThumbUp from NearTouches (masks 0x2/0x8); the patch makes it read Touches (the slot 4 bytes before) with masks 0x0f00 (X/Y/stick/thumb rest) / 0x000f (A/B/stick/thumb rest), keeping the inversion; three instructions, matched exactly (build note `OculusInput ThumbUp: from the capacitive touches`). Matches Vader Immortal Ep. I, Robo Recall, Phantom: Covert Ops, Time Stall, Star Wars: Tales from the Galaxy's Edge; newer UE4 builds (for example Asgard's Wrath 2, RE4, In Death) compile it differently (shared mask registers) and aren't matched |
|
||||
| Vulkan game (Unreal / own engine with the Vulkan shim): the GPU hangs at one effect or cutscene (kernel `hangcheck detected gpu lockup`, freeze/exit; for example a VR4 cutscene, GitHub #140) | a SPIR-V shader reads a loop counter/accumulator before setting it (VR4's campaign shader, GitHub #10) | adapter `vk_shader_dump=1` (`frame.vk_sanitize`'s shim; log `vk shim: dumping SPIR-V modules to …`) writes every distinct module once to `files/fp_vk_shaders/<size>_<sha256>.spv` + `index.txt` (`<seq> <ms> <unix ms> <name> new\|known\|again`); play to the hang, collect diagnostics (`target/shaders/fp_vk_shaders/`, newest 4 MB) and take the modules first created (`new`) shortly before the kernel's hangcheck time; disassemble (`spirv-dis`), find the variable read before its first store, write a `vk_shader_fix` (`<size>:<sha256>:<byte offset>:<words>` = inserted OpStores; log `vk shim: fixed shader module`); switch the dump off again |
|
||||
| OpenGL ES game: memory and GPU mappings grow every frame (~20 MB/s, `/dev/dri/renderD128` mappings ~6 per frame) until the frame rate collapses; the game's `xrclient_<package>.txt` (Steam logs) has one `SXR_GL_CHECK: error:0x502 ... glGenTextures` before the session starts (GitHub #285, Vader Immortal) | The game leaves GL errors pending on its context; the runtime's GL interop reads glGetError after its own calls and takes the stale error as its own failure. From then on `CVRCompositorSharedTextures::BeginCommandBuffer` allocates a new command buffer every frame instead of reusing one (perf page-fault stacks) | Adapter `gl_error_clear=1` (GLES only) clears pending GL errors before xrCreateSwapchain/xrBeginFrame/xrEndFrame; Vader's catalog recipes set it. Verified headless 2026-10-14: 191 GPU mappings and ~1.07 GB flat over 100 s (before: +430 mappings/s, +22 MB/s), no SXR_GL_CHECK |
|
||||
| OpenGL ES game: the GPU hangs at one effect (freeze/exit, compositor watchdog, for example Vader Immortal's lightspeed jump) | a shader (as Zink compiles it) reads loop counters/accumulators before setting them | capture the SPIR-V (adapter `zink_shader_dump=1` writes every module to `files/fp_spirv/`, or a GPU capture), then a `zink_shader_fix` entry (same format as `vk_shader_fix`) + `frame.zink_shader_fix` (Vulkan layer under Zink, activated through GraphicsEnv's debug layer list); log `shader fix layer: fixed shader module N`; triage `zink-shader-fix-mismatch` when a Frame update changed the driver's output |
|
||||
| 2D Android app: Steam says it's running but nothing shows | Lepton runs apps headless unless the app folder has `lepton-show-flatscreen` | FramePort adds it for apps without VR (agent v28+); reinstall apps installed before |
|
||||
| A phone/tablet app shows nothing in the headset, or a VR app opens as a flat window | FramePort's VR/2D guess (`vr_kind`) is wrong for this app | patch `device.display_mode` → **Flat window** or **VR** (Customize → "Show as VR or as a flat window"), then Update on Frame |
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
# Transfer measurements and incremental installs
|
||||
|
||||
## Production OpenSSH follow-up
|
||||
|
||||
OpenSSH is now the preferred installer backend for files >=8 MiB. The new default is three workers (range 1–8),
|
||||
with saved preferences preserved. Fresh files use `put`; existing partial files use `reput`. Each worker keeps
|
||||
one SFTP batch session. Progress is polled through a separate bounded SFTP channel. Native failures resume via
|
||||
Paramiko; cancellation stops the owned SFTP/SSH process trees and does not trigger fallback.
|
||||
|
||||
Windows matched production comparison: eight 64 MiB files, 512 MiB total, three shuffled repetitions per backend,
|
||||
three workers, same home Wi-Fi/internal storage. OpenSSH median **15.51 MB/s**, Paramiko median **11.08 MB/s**
|
||||
(about 40% faster). All six checksums passed. OpenSSH trials ranged 9.5–16.8 MB/s, so link variability still
|
||||
matters; it was slower than Paramiko in one pass. Native credential/progress setup took 0.12–0.13 seconds.
|
||||
|
||||
The separate Windows 128 MiB production test also passed every checksum. Native cancellation left a partial file
|
||||
of 74,752,000 bytes; resuming with OpenSSH produced the expected SHA-256. The log confirmed no fallback for the
|
||||
resumed production upload. Reports:
|
||||
`/mnt/c/Users/Austin/AppData/Local/Temp/frameport-upload-native-production-comparison-windows.json` and
|
||||
`/mnt/c/Users/Austin/AppData/Local/Temp/frameport-upload-native-production-windows.json`.
|
||||
|
||||
The earlier sections below preserve measurements made before the production backend switch.
|
||||
|
||||
The WSL production validation (128 MiB, three workers, three repetitions) measured 14.1 / 19.1 / 15.0 MB/s,
|
||||
with every checksum passing and native backend logs recorded. Production cancellation left a 72,330,240-byte
|
||||
partial file; OpenSSH resumed it in 4.23 seconds with the expected SHA-256 and no Paramiko fallback. Report:
|
||||
`/tmp/frameport-upload-native-production-wsl.json`.
|
||||
|
||||
## Measurements (2026-10-14)
|
||||
|
||||
Both runs used the same paired Frame, the home-router connection and internal ext4 storage under the paired user's
|
||||
home. Each large-file trial sent the same 128 MiB random payload; each small-file trial sent 512 files of 64 KiB
|
||||
(32 MiB total). Methods were shuffled for each of three repetitions. Windows and WSL runs were sequential, not
|
||||
concurrent. Every completed transfer passed SHA-256 verification. Rates below include connection/setup and transfer
|
||||
completion, but exclude checksum verification and cleanup; MB/s uses decimal bytes.
|
||||
|
||||
| Method | WSL2 median MB/s | Windows 11 native median MB/s |
|
||||
|---|---:|---:|
|
||||
| FramePort pipelined SFTP | 10.4 | 6.1 |
|
||||
| Paramiko SFTP, 64 MiB window | 17.1 | 4.5 |
|
||||
| OpenSSH SFTP | 16.8 | 15.4 |
|
||||
| OpenSSH SCP (default protocol) | 11.1 | 10.1 |
|
||||
| OpenSSH `ssh` + streamed file | 9.9 | 8.1 |
|
||||
| FramePort tar stream | 14.9 | 6.8 |
|
||||
| OpenSSH tar stream | 15.0 | 7.2 |
|
||||
|
||||
The network varied considerably: WSL's application trials ranged from 9.6–12.8 MB/s, native SFTP from
|
||||
16.2–17.3 MB/s, and some other methods dropped below 5 MB/s. Windows application trials ranged from 5.6–6.4 MB/s;
|
||||
native SFTP ranged from 9.1–16.5 MB/s. These are useful end-to-end comparisons on this setup, not a measurement of
|
||||
the maximum throughput each transport can achieve. Window tuning did not help the Windows run.
|
||||
|
||||
Cancellation/resume checks interrupted the application upload at 64 MiB, then independently resumed that partial
|
||||
file with the application and with OpenSSH SFTP `reput`. All four resumed files passed SHA-256 verification. This
|
||||
checks application cancellation and both resume paths; native SFTP cancellation itself remains unmeasured.
|
||||
|
||||
The Frame's USB and hotspot interfaces were up, but neither direct endpoint was reachable from the PC. No removable
|
||||
storage was mounted. USB, hotspot and microSD performance remain **unmeasured** in this round. The Frame's router
|
||||
connection used 5 GHz / 80 MHz Wi-Fi, with roughly -56 dBm signal during a read-only probe. This does not reproduce
|
||||
the 6 GHz direct-hotspot setup in [discussion #242](https://github.com/spoopyghosty0/frameport/discussions/242), where
|
||||
the reporter measured about 114 MB/s with OpenSSH versus 23 MB/s with Paramiko.
|
||||
|
||||
**Recommendation:** prototype an optional OpenSSH SFTP backend for large files, retaining `.part`/`reput`,
|
||||
cancellation, retries, strict paired-host verification and Paramiko fallback. Validate it on a fast direct link
|
||||
before making it the default. On this Windows run SFTP was about 2.5 times faster than the current application,
|
||||
and it beat SCP. The small-file tar measurements do not justify selecting a new tar transport yet. Production
|
||||
transport selection remains Paramiko pending that decision. The bounded parallel-file setting described below
|
||||
uses independent Paramiko connections.
|
||||
|
||||
## Parallel-file uploads
|
||||
|
||||
### Matched native OpenSSH comparison
|
||||
|
||||
The later comparison tested both backends sequentially on Windows and WSL, with three shuffled repetitions of
|
||||
the same eight 16 MiB files per worker count. Native `sftp-files-N` balances files across N persistent OpenSSH
|
||||
SFTP batch processes. Setup and completion are included; checksum verification is excluded. All 60 transfers
|
||||
passed SHA-256 checks. This is benchmark code; the production uploader still uses Paramiko.
|
||||
|
||||
| Workers | Windows Paramiko MB/s | Windows OpenSSH MB/s | WSL Paramiko MB/s | WSL OpenSSH MB/s |
|
||||
|---|---:|---:|---:|---:|
|
||||
| 1 | 6.22 | 14.96 | 6.17 | 14.64 |
|
||||
| 2 | 10.61 | 17.73 | 14.41 | 14.45 |
|
||||
| 3 | 8.90 | 18.89 | 13.65 | 17.75 |
|
||||
| 4 | 14.90 | 16.80 | 15.67 | 16.63 |
|
||||
| 8 | 13.50 | 20.16 | 17.03 | 16.82 |
|
||||
|
||||
Three is a reasonable default candidate for a future OpenSSH backend: versus two it improved median throughput
|
||||
by 6.5% on Windows and 22.8% on WSL. Eight was faster on Windows but slower on WSL. The production Paramiko
|
||||
default remains two because three regressed by 16.1% on Windows and 5.3% on WSL in this matched comparison.
|
||||
Link variability remains substantial, and no fast hotspot/USB result is claimed.
|
||||
|
||||
Reports: `/mnt/c/Users/Austin/AppData/Local/Temp/frameport-upload-native-parallel-windows.json` and
|
||||
`/tmp/frameport-upload-native-parallel-wsl.json`.
|
||||
|
||||
Settings → Installing → **Parallel uploads** accepts **1–8**, default **2**. It controls large files within one
|
||||
install; the FIFO still runs one install job at a time. A single APK is not split into chunks. Large files are
|
||||
scheduled largest first, with at most one authenticated SSH connection per active worker and never more workers
|
||||
than files. Small files still use tar batches after the large-file uploads. Choose 1 on a busy network; a higher
|
||||
count can consume all available bandwidth and is not automatically faster.
|
||||
|
||||
The parallel comparison uses the same eight 16 MiB OBB-shaped files (128 MiB total) for every worker count, with
|
||||
three shuffled repetitions. The production uploader is used by `app-files-N`, including its aggregate progress,
|
||||
resume baselines, cancellation checks and connection cleanup. A failed or cancelled cohort stops queued work and
|
||||
closes only its worker transports; completed files and interrupted `.part` files remain resumable.
|
||||
|
||||
| Workers | WSL2 production median MB/s | Windows 11 production median MB/s |
|
||||
|---|---:|---:|
|
||||
| 1 | 9.6 | 5.6 |
|
||||
| 2 (default) | 9.1 | 10.9 |
|
||||
| 3 | 6.5 | Not measured in the final production run |
|
||||
| 4 | 12.4 | 14.8 |
|
||||
| 8 | 11.2 | 17.3 |
|
||||
|
||||
On Windows, the production uploader improved from 5.6 to 10.9 MB/s with 2 workers (**1.95 times faster**), and
|
||||
17.3 MB/s with 8 (**3.08 times faster**). All twelve Windows production transfers passed SHA-256 verification.
|
||||
The preceding Windows prototype also tested 3 workers (12.2 MB/s median), before aggregate progress/cancellation
|
||||
were integrated; that is not included as a production measurement in the table.
|
||||
|
||||
WSL was noisy: four workers improved its median by about 29%, but 2 did not improve its median, and 3 was slower.
|
||||
There is no evidence that a particular worker count is universally fastest. The option is retained because it
|
||||
produced a repeatable benefit on Windows and higher counts improved the WSL median. Default 2 limits competing
|
||||
transfers while retaining a measured Windows benefit; users can measure higher counts or select 1 in their own
|
||||
environment. Production code, including cleanup and progress checks, was used for both final comparisons.
|
||||
|
||||
```sh
|
||||
uv run python scripts/upload_bench.py --mib 128 --repeat 3 --methods app-files-1,app-files-2,app-files-3,app-files-4,app-files-8 --json parallel.json
|
||||
```
|
||||
|
||||
`install.upload_threads` persists the setting. Malformed values use 2 and numeric values are clamped to 1–8.
|
||||
The serial setting reuses the existing control connection; parallel workers verify that the new transport reaches
|
||||
the same paired headset before sending any files.
|
||||
|
||||
## Reproducing the measurements
|
||||
|
||||
Run from the checkout using the Python environment for the platform being measured:
|
||||
|
||||
```sh
|
||||
uv run python scripts/upload_bench.py --mib 512 --repeat 3 --check-resume --json uploads.json
|
||||
uv run python scripts/upload_bench.py --fast-link --probe
|
||||
uv run python scripts/upload_bench.py --fast-link --remote-dir /path/on/card --mib 512 --repeat 3 --json card.json
|
||||
```
|
||||
|
||||
`--host` selects a specific paired endpoint; `--fast-link` uses the same authenticated direct-link discovery as an
|
||||
install. Inspect the reported endpoint and link before comparing methods. Join the Frame's hotspot or connect its
|
||||
USB cable before testing those paths; the benchmark does not change PC networking. Keep the headset awake and avoid
|
||||
other network traffic. A 512 MiB payload is preferred for follow-up tests on fast links; the available-link runs
|
||||
above used 128 MiB.
|
||||
|
||||
The script creates a unique scratch directory on the selected filesystem, checks content outside the timed upload,
|
||||
and removes its own temporary remote files and temporary key copy. It never modifies the pairing key's ACL. Windows
|
||||
OpenSSH rejects an `OWNER RIGHTS` ACL entry; the temporary copy grants only the current user, without Python's
|
||||
Windows `chmod` behaviour that can introduce that entry. Native clients use the application's key and known-hosts
|
||||
file with strict host verification.
|
||||
|
||||
JSON rows contain bytes, total seconds, separately measured setup seconds where available, payload and total rates,
|
||||
verification duration and checksums. SCP/SFTP's setup is included in total time because their command-line clients
|
||||
do not expose its completion separately. On POSIX, CPU includes the Python parent and child processes; on Windows,
|
||||
`os.times()` measures only the parent, so native subprocess CPU numbers must not be compared with Paramiko's CPU.
|
||||
An error is recorded rather than counted as a successful trial. `--methods` can restrict the run; `--small-files`
|
||||
controls the tar corpus. Cipher comparisons are available as `ssh-gcm` and `ssh-chacha`.
|
||||
|
||||
## Incremental install behaviour
|
||||
|
||||
`game_update.plan_update` is the shared, I/O-free Quest/Android classifier used by badges and installation. Recipe
|
||||
source, notes and catalog revision do not affect it. A newer tested catalog recipe remains a separate suggestion
|
||||
when the user customized their recipe.
|
||||
|
||||
- Build records keep an APK recipe fingerprint, source hash/stat, selected native-asset identities, converter
|
||||
identity and the existing validated APK hashes. Reusable local APKs are checksum-checked before installation.
|
||||
- Deployment records keep applied runtime configuration and its fingerprint, APK stat/hash, source version,
|
||||
data manifest/digest and artwork hashes. Routine device samples carry only the digest, and updates fetch a
|
||||
detailed manifest only when necessary. Live numeric settings writes update only the applied runtime configuration,
|
||||
leaving APK build identity intact. Desired data manifests are cached locally for badges, without render-path I/O.
|
||||
- Runtime-only updates use agent v87 `configure`: no conversion, signing, APK transfer, artwork, Steam restart or
|
||||
automatic launch test. They still require the installed APK identity and an available destination, and refuse
|
||||
changes while the game is running. Defaults explicitly reset overrides embedded in an older APK. Generated
|
||||
configuration files are restored or removed only when they still match FramePort's last write; user edits survive.
|
||||
- Build support dependencies remain conservative: controller models/native surfaces/haptic support, Zink-layer
|
||||
selection, mixed foveation patches and revised adapter support can require a new APK. A recorded alternate
|
||||
variant can be reused when switching variants.
|
||||
- Data-only updates transfer missing/different-size data using the resumable uploader. Recipe/APK updates skip
|
||||
data synchronization when the source data manifest is unchanged, preserving Frame-side mods; explicit forced
|
||||
reinstalls still check/repair data. Artwork-only
|
||||
updates send changed slots; unchanged artwork avoids a Steam refresh. APK/data changes retain the configured
|
||||
automatic launch test. Settings/artwork changes skip it.
|
||||
- APK-only updates preserve installed OBBs, including mods, and do not apply old staged OBBs or artwork from an
|
||||
interrupted upload. Ordinary data comparison still uses sizes, matching existing behaviour; equal-size content
|
||||
replacement is not detected automatically. Explicit rebuild/reinstall remains available (`install --force`).
|
||||
- Legacy build identities take the full path once because their original build inputs cannot be established
|
||||
safely. Converted-copy cleanup and `build.keep_copies` remain in effect; a configuration/data update does not
|
||||
require the deleted converted APK.
|
||||
|
||||
Install results record `stage_seconds` in the library's install history. This includes planning, conversion,
|
||||
validation, transfer and finalization stages reached by that operation; the GUI's subsequent optional launch test
|
||||
is separate. Use these timings to distinguish build cost, network transfer and device/Steam work when reviewing a
|
||||
slow install. Configuration success is recorded after writing the configuration and completing its sync; a failed
|
||||
operation leaves the prior applied fingerprint so it remains retryable.
|
||||
|
Before Width: | Height: | Size: 85 KiB After Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 668 KiB After Width: | Height: | Size: 663 KiB |
|
Before Width: | Height: | Size: 217 KiB After Width: | Height: | Size: 215 KiB |
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 6.8 MiB After Width: | Height: | Size: 6.4 MiB |
|
Before Width: | Height: | Size: 288 KiB After Width: | Height: | Size: 287 KiB |
@@ -0,0 +1,6 @@
|
||||
out/
|
||||
out-dev/
|
||||
*.core
|
||||
# generated by bridge/gen_stubs.py at every build
|
||||
bridge/guest/gen/
|
||||
bridge/host/gen/
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -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) {}
|
||||
@@ -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; }
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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; }
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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, ©);
|
||||
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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Builds the on-device test APK org.frameport.a32test: a NativeActivity without Java code whose library is 32-bit
|
||||
ARM code (libapktest.a32.so) run by the bridge. Build the bridge first (python bridge/build.py --test).
|
||||
|
||||
uv run python native/a32translator/bridge/test/make_apk.py [--out FILE]
|
||||
|
||||
The APK is signed with FramePort's key for the package (created on first use). Install it with
|
||||
`frameport install org.frameport.a32test --apk FILE` after `frameport scan` of its folder, or by hand.
|
||||
"""
|
||||
import argparse
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parents[1]
|
||||
OUT = ROOT / "out" / "bridge"
|
||||
NDK_BIN = ROOT.parent / ".cache/ndk-27.2.12479018/toolchains/llvm/prebuilt/linux-x86_64/bin"
|
||||
PACKAGE = "org.frameport.a32test"
|
||||
ANDROID_NS = "http://schemas.android.com/apk/res/android"
|
||||
ATTR_IDS = { # android: attributes used here (framework resource IDs)
|
||||
"label": 0x01010001, "name": 0x01010003, "hasCode": 0x0101000C, "debuggable": 0x0101000F,
|
||||
"exported": 0x01010010, "value": 0x01010024, "minSdkVersion": 0x0101020C, "versionCode": 0x0101021B,
|
||||
"versionName": 0x0101021C, "targetSdkVersion": 0x01010270, "extractNativeLibs": 0x010104EA,
|
||||
}
|
||||
T_STRING, T_INT, T_BOOL = 0x03, 0x10, 0x12
|
||||
|
||||
# (element, [(attribute, value)], children); android attributes are the ATTR_IDS keys, others have no namespace
|
||||
MANIFEST = ("manifest", [("package", PACKAGE), ("versionCode", 1), ("versionName", "1.0")], [
|
||||
("uses-sdk", [("minSdkVersion", 24), ("targetSdkVersion", 30)], []),
|
||||
("application", [("label", "A32 bridge test"), ("hasCode", False), ("debuggable", True),
|
||||
("extractNativeLibs", True)], [
|
||||
("activity", [("name", "android.app.NativeActivity"), ("label", "A32 bridge test"), ("exported", True)], [
|
||||
("meta-data", [("name", "android.app.lib_name"), ("value", "apktest")], []),
|
||||
("intent-filter", [], [
|
||||
("action", [("name", "android.intent.action.MAIN")], []),
|
||||
("category", [("name", "android.intent.category.LAUNCHER")], []),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
])
|
||||
|
||||
|
||||
def axml(root) -> bytes:
|
||||
"""Android binary XML for the tree above (UTF-8 string pool; attribute names with IDs first, as aapt does)."""
|
||||
attr_names = sorted({a for _, attrs, _ in walk(root) for a, _ in attrs if a in ATTR_IDS}, key=ATTR_IDS.get)
|
||||
strings = list(attr_names)
|
||||
|
||||
def idx(s):
|
||||
if s not in strings:
|
||||
strings.append(s)
|
||||
return strings.index(s)
|
||||
|
||||
for s in ("android", ANDROID_NS):
|
||||
idx(s)
|
||||
body = bytearray()
|
||||
ns_chunk = struct.pack("<IIII", 1, 0xFFFFFFFF, idx("android"), idx(ANDROID_NS))
|
||||
body += struct.pack("<HHI", 0x0100, 16, 24) + ns_chunk
|
||||
|
||||
def emit(node):
|
||||
name, attrs, children = node
|
||||
recs = []
|
||||
for a, v in sorted(attrs, key=lambda av: ATTR_IDS.get(av[0], 0)):
|
||||
ns = idx(ANDROID_NS) if a in ATTR_IDS else 0xFFFFFFFF
|
||||
if isinstance(v, bool):
|
||||
raw, typ, data = 0xFFFFFFFF, T_BOOL, 0xFFFFFFFF if v else 0
|
||||
elif isinstance(v, int):
|
||||
raw, typ, data = 0xFFFFFFFF, T_INT, v
|
||||
else:
|
||||
raw, typ, data = idx(v), T_STRING, idx(v)
|
||||
recs.append(struct.pack("<IIIHBBI", ns, idx(a), raw, 8, 0, typ, data))
|
||||
n = idx(name)
|
||||
start = struct.pack("<IIIIHHHHHH", 1, 0xFFFFFFFF, 0xFFFFFFFF, n, 20, 20, len(recs), 0, 0, 0)
|
||||
body.extend(struct.pack("<HHI", 0x0102, 16, 8 + len(start) + 20 * len(recs)) + start + b"".join(recs))
|
||||
for c in children:
|
||||
emit(c)
|
||||
body.extend(struct.pack("<HHI", 0x0103, 16, 24) + struct.pack("<IIII", 1, 0xFFFFFFFF, 0xFFFFFFFF, n))
|
||||
|
||||
emit(root)
|
||||
body += struct.pack("<HHI", 0x0101, 16, 24) + ns_chunk
|
||||
|
||||
data = bytearray()
|
||||
offsets = []
|
||||
for s in strings:
|
||||
offsets.append(len(data))
|
||||
b = s.encode()
|
||||
assert len(s) < 0x80 and len(b) < 0x80
|
||||
data += bytes([len(s), len(b)]) + b + b"\0"
|
||||
while len(data) % 4:
|
||||
data += b"\0"
|
||||
hdr = 28
|
||||
pool = struct.pack("<HHIIIIII", 0x0001, hdr, hdr + 4 * len(strings) + len(data), len(strings), 0, 0x100,
|
||||
hdr + 4 * len(strings), 0)
|
||||
pool += struct.pack(f"<{len(offsets)}I", *offsets) + data
|
||||
resmap = struct.pack("<HHI", 0x0180, 8, 8 + 4 * len(attr_names)) + b"".join(
|
||||
struct.pack("<I", ATTR_IDS[a]) for a in attr_names)
|
||||
total = 8 + len(pool) + len(resmap) + len(body)
|
||||
return struct.pack("<HHI", 0x0003, 8, total) + pool + resmap + bytes(body)
|
||||
|
||||
|
||||
def walk(node):
|
||||
yield node
|
||||
for c in node[2]:
|
||||
yield from walk(c)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--out", default=str(OUT / "a32test.apk"))
|
||||
a = ap.parse_args()
|
||||
test = OUT / "test"
|
||||
cc = NDK_BIN / "armv7a-linux-androideabi30-clang"
|
||||
subprocess.run([str(cc), "-O2", "-g", "-mthumb", "-shared", "-fPIC", str(HERE / "libapktest.c"), "-landroid",
|
||||
"-llog", "-ldl", "-o", str(test / "libapktest.a32.so")], check=True)
|
||||
libs = {
|
||||
"libapktest.so": OUT / "liba32stub.so", # the stub, under the 32-bit library's name
|
||||
"liba32bridge.so": OUT / "liba32bridge.so",
|
||||
"liba32rt.so": OUT / "liba32rt.so",
|
||||
"libapktest.a32.so": test / "libapktest.a32.so",
|
||||
"libbtest3.a32.so": test / "libbtest3.a32.so",
|
||||
}
|
||||
manifest = axml(MANIFEST)
|
||||
sys.path.insert(0, str(ROOT.parents[1] / "src"))
|
||||
from frameport.apk import axml as fp_axml
|
||||
from frameport.apk import sign
|
||||
|
||||
x = fp_axml.Axml(manifest) # FramePort's own parser must read it
|
||||
assert fp_axml.MAIN in x.strings() and fp_axml.LAUNCHER in x.strings()
|
||||
assert fp_axml.categories(manifest) == {fp_axml.LAUNCHER}
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
unsigned = Path(td) / "unsigned.apk"
|
||||
with zipfile.ZipFile(unsigned, "w") as z:
|
||||
z.writestr(zipfile.ZipInfo("AndroidManifest.xml", (2026, 1, 1, 0, 0, 0)), manifest, zipfile.ZIP_DEFLATED)
|
||||
for name, src in libs.items():
|
||||
z.write(src, f"lib/arm64-v8a/{name}", zipfile.ZIP_STORED)
|
||||
sign.sign(unsigned, Path(a.out), PACKAGE)
|
||||
print(a.out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Runs the bridge test harness (build it first: python bridge/build.py --test).
|
||||
|
||||
python bridge/test/run.py [--runner "qemu-aarch64"] [--interp] [--strace] [--timeout 300]
|
||||
|
||||
On x86_64 the harness runs under qemu-aarch64; on an AArch64 Linux machine pass --runner "". Like the program tests,
|
||||
it runs in a fresh user+pid namespace (32-bit bionic refuses pids above 65535). Exit code 0 = every check passed.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import resource
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
DIR = Path(__file__).resolve().parents[2] / "out" / "bridge" / "test"
|
||||
|
||||
|
||||
def no_core():
|
||||
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) # qemu-user hangs writing a multi-threaded core
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--runner", default="qemu-aarch64")
|
||||
ap.add_argument("--interp", action="store_true", help="interpreter only (A32_INTERP=1)")
|
||||
ap.add_argument("--strace", action="store_true", help="log guest syscalls (A32_STRACE=1)")
|
||||
ap.add_argument("--timeout", type=int, default=300)
|
||||
a = ap.parse_args()
|
||||
if not (DIR / "harness").exists():
|
||||
sys.exit(f"{DIR / 'harness'} missing: run python bridge/build.py --test")
|
||||
env = dict(os.environ)
|
||||
if a.interp:
|
||||
env["A32_INTERP"] = "1"
|
||||
if a.strace:
|
||||
env["A32_STRACE"] = "1"
|
||||
cmd = ["timeout", "-s", "KILL", str(a.timeout), "unshare", "-Urpf", "--kill-child", *shlex.split(a.runner),
|
||||
"./harness", "."]
|
||||
p = subprocess.run(cmd, cwd=DIR, env=env, preexec_fn=no_core)
|
||||
sys.exit(p.returncode)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,171 @@
|
||||
/* Linked only into the qemu host harness. Exercise the real AAPCS readers and thunks with a fake 64-bit API. */
|
||||
#include <sys/mman.h>
|
||||
static int test_tracking_calls, test_submit_calls;
|
||||
static int test_tracked = 1, test_identity, test_current_only;
|
||||
static posef64 test_set_pose;
|
||||
static tracking2 test_tracking(void *m, double t)
|
||||
{
|
||||
tracking2 tr = {0};
|
||||
tr.Status = test_tracked && (!test_current_only || t == 0) ? 143 : 0;
|
||||
tr.HeadPose.Orientation[3] = 1;
|
||||
++test_tracking_calls;
|
||||
tr.HeadPose.Position[1] = (!tr.Status || test_identity) ? 1.6f : (float)test_tracking_calls;
|
||||
tr.HeadPose.TimeInSeconds = t == 0 ? 42.75 : t;
|
||||
return tr;
|
||||
}
|
||||
static posef64 test_transform(void *m, int which)
|
||||
{
|
||||
posef64 pose = {{0,0,0,1}, {0, which == 3 ? -1.6f : 0, 0}};
|
||||
return pose;
|
||||
}
|
||||
static void test_set_transform(void *m, posef64 pose) { test_set_pose = pose; }
|
||||
static double test_display(void *m, int64_t index) { return 42.25; }
|
||||
static pose64 test_submit_pose;
|
||||
static uint64_t test_submit_index;
|
||||
static unsigned test_submit_layers;
|
||||
static double test_submit_time;
|
||||
static int test_submit(void *m, const submit2 *d)
|
||||
{
|
||||
++test_submit_calls;
|
||||
test_submit_layers = d->LayerCount;
|
||||
test_submit_index = d->FrameIndex;
|
||||
test_submit_time = d->DisplayTime;
|
||||
if (d->LayerCount == 1) test_submit_pose = ((const projection2 *)d->Layers[0])->HeadPose;
|
||||
return 0;
|
||||
}
|
||||
int a32_vrapi_selftest(void)
|
||||
{
|
||||
int failed = 0;
|
||||
#define VT(x) do { if (!(x)) { fprintf(stderr, "FAIL vrapi: %s\n", #x); ++failed; } } while (0)
|
||||
uint8_t *buf = mmap((void *)0x30000000, 8192, PROT_READ|PROT_WRITE,
|
||||
MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED_NOREPLACE, -1, 0);
|
||||
if (buf == MAP_FAILED) return 1;
|
||||
uint32_t g = p2g(buf);
|
||||
a32_cpu cpu = {0};
|
||||
argreader r;
|
||||
cpu.r[0] = 123; cpu.r[1] = 0xdeadbeef; cpu.r[2] = 0x89abcdef; cpu.r[3] = 0x01234567;
|
||||
ar_init(&r, &cpu, 0, g);
|
||||
VT(rd32(&r) == 123); VT(rd64(&r) == UINT64_C(0x0123456789abcdef));
|
||||
bridge(); /* finish pthread_once (the static harness has no real bridge DSO) */
|
||||
__typeof__(B) saved = B;
|
||||
int saved_ok = bridge_ok;
|
||||
B.GetPredictedTracking2 = test_tracking;
|
||||
B.GetTrackingTransform = test_transform; B.SetTrackingTransform = test_set_transform;
|
||||
B.GetPredictedDisplayTime = test_display; B.SubmitFrame2 = test_submit;
|
||||
bridge_ok = 1;
|
||||
void *m = &test_set_pose;
|
||||
uint32_t mh = ptr2h(m);
|
||||
tracking_reset();
|
||||
tracking2 a = tracking_of(m, 42.25), b = tracking_of(m, 42.25);
|
||||
VT(!memcmp(&a, &b, sizeof a)); VT(test_tracking_calls == 1);
|
||||
tracking_of(m, 42.5); VT(test_tracking_calls == 2);
|
||||
cpu.r[0]=g; cpu.r[1]=mh; double requested=42.25; memcpy(&cpu.r[2],&requested,8);
|
||||
ar_init(&r,&cpu,0,g+4096); imp_vrapi_GetPredictedTracking(&cpu,&r);
|
||||
VT(!memcmp(buf,&a,104)); VT(cpu.r[0] == g);
|
||||
cpu.r[0]=g; cpu.r[1]=mh;
|
||||
ar_init(&r,&cpu,0,g+4096); imp_vrapi_GetPredictedTracking2(&cpu,&r);
|
||||
VT(!memcmp(buf,&a,sizeof a)); VT(test_tracking_calls == 2);
|
||||
tracking_reset(); test_tracked = 0;
|
||||
tracking_of(m, 42.25); tracking_of(m, 42.25); VT(test_tracking_calls == 4);
|
||||
test_tracked = 1;
|
||||
cpu.r[0] = g; cpu.r[1] = mh; cpu.r[2] = 3;
|
||||
ar_init(&r, &cpu, 0, g+4096); imp_vrapi_GetTrackingTransform(&cpu, &r);
|
||||
posef64 floor; memcpy(&floor, buf, sizeof floor);
|
||||
VT(floor.Orientation[3] == 1 && floor.Position[1] == -1.6f); VT(cpu.r[0] == g);
|
||||
posef64 wanted = {{0.1f,0.2f,0.3f,0.9f}, {2,-1.6f,4}};
|
||||
cpu.r[0] = mh;
|
||||
memcpy(&cpu.r[1], &wanted, 12); memcpy(buf+4096, (uint8_t *)&wanted+12, 16);
|
||||
ar_init(&r, &cpu, 0, g+4096); imp_vrapi_SetTrackingTransform(&cpu, &r);
|
||||
VT(!memcmp(&wanted, &test_set_pose, sizeof wanted));
|
||||
tracking_of(m, 42.25); VT(test_tracking_calls == 5); /* transform invalidated the cache */
|
||||
/* Projection2: pointer widening and 88 -> 96 byte texture stride; HeadPose is ABI-identical. */
|
||||
memset(buf, 0, 4096);
|
||||
uint32_t layer = g+128, array = g+1024;
|
||||
uint32_t chain_object = 0; uint32_t ch = ptr2h(&chain_object);
|
||||
pose64 render = {0}; render.Orientation[3] = 1; render.Position[1] = 1.75f;
|
||||
render.AngularVelocity[1] = 0.25f; render.LinearAcceleration[2] = 0.75f;
|
||||
render.TimeInSeconds = 42.25; render.PredictionInSeconds = 0.0125;
|
||||
st32(g+32,1); st32(g+36,array); st32(array,layer);
|
||||
st32(layer,1); memcpy(g2p(layer+40), &render, sizeof render);
|
||||
st32(layer+136,ch); st32(layer+224,ch);
|
||||
uint64_t index = UINT64_C(0x123456789);
|
||||
memcpy(buf+8,&index,8); double time=42.25; memcpy(buf+16,&time,8);
|
||||
cpu.r[0] = mh; cpu.r[1] = g;
|
||||
ar_init(&r,&cpu,0,g+4096); imp_vrapi_SubmitFrame2(&cpu,&r);
|
||||
VT(test_submit_calls == 1); VT(test_submit_index == index && test_submit_time == time);
|
||||
VT(!memcmp(&render,&test_submit_pose,sizeof render));
|
||||
/* Legacy VrApi 1.5: 200-byte eye textures and 432-byte layers. */
|
||||
memset(buf,0,4096); st32(g,3); st32(g+1736,1);
|
||||
st32(g+8,ch); st32(g+208,ch); memcpy(buf+8+96,&render,sizeof render);
|
||||
memcpy(buf+1744,&index,8);
|
||||
cpu.r[0]=mh; cpu.r[1]=g;
|
||||
ar_init(&r,&cpu,0,g+4096); imp_vrapi_SubmitFrame(&cpu,&r);
|
||||
VT(test_submit_calls == 2); VT(test_submit_index == index && test_submit_time == time);
|
||||
VT(!memcmp(&render,&test_submit_pose,sizeof render));
|
||||
/* The early loader's 140-byte prefix shifts the otherwise identical legacy layout. */
|
||||
memset(buf,0,4096); st32(g,0x10000001); st32(g+1876,1);
|
||||
st32(g+148,ch); st32(g+348,ch); memcpy(buf+148+96,&render,sizeof render);
|
||||
memcpy(buf+1884,&index,8);
|
||||
cpu.r[0]=mh; cpu.r[1]=g;
|
||||
ar_init(&r,&cpu,0,g+4096); imp_vrapi_SubmitFrame(&cpu,&r);
|
||||
VT(test_submit_calls == 3); VT(test_submit_index == index && test_submit_time == time);
|
||||
VT(!memcmp(&render,&test_submit_pose,sizeof render));
|
||||
/* Runtime tracking loss: hold head and eyes together for <=100 ms, while
|
||||
* keeping repeated answers consistent without renewing the original sample age. */
|
||||
tracking2 good = tracking_of(m, 42.25);
|
||||
test_tracked = 0;
|
||||
int calls = test_tracking_calls;
|
||||
tracking2 held = tracking_of(m, 42.26);
|
||||
VT(held.Status == good.Status && held.HeadPose.Position[1] == good.HeadPose.Position[1]);
|
||||
VT(held.HeadPose.TimeInSeconds == 42.26);
|
||||
VT(!memcmp(held.Eye, good.Eye, sizeof held.Eye));
|
||||
tracking_of(m, 42.26); VT(test_tracking_calls == calls+1);
|
||||
VT(tracking_of(m, 42.36).Status == 0); /* held .26 did not renew .25 */
|
||||
VT(tracking_of(m, 42.5).Status == 0);
|
||||
test_tracked = 1;
|
||||
/* Default submitted without a matching tracking request: repair at display time.
|
||||
* Both conversion paths use this gate; preserve valid arbitrary render poses. */
|
||||
projection2 projection = {0}; projection.Header.Type = 1;
|
||||
projection.HeadPose.Orientation[3] = 1; projection.HeadPose.Position[1] = 1.6f;
|
||||
projection.HeadPose.TimeInSeconds = 42.26;
|
||||
const header2 *headers[] = {&projection.Header};
|
||||
submit2 desc = {0}; desc.DisplayTime = 42.25; desc.LayerCount = 1; desc.Layers = headers;
|
||||
submit_prepare(m, &desc);
|
||||
VT(desc.LayerCount == 1 && projection.HeadPose.Position[1] == good.HeadPose.Position[1]);
|
||||
VT(projection.HeadPose.TimeInSeconds == 42.26); /* exact render-time held answer */
|
||||
/* Genuine tracked identity and head-locked identity must remain unchanged. */
|
||||
tracking_reset(); test_identity = 1;
|
||||
tracking2 identity = tracking_of(m, 42.25);
|
||||
projection.HeadPose = identity.HeadPose; submit_prepare(m, &desc);
|
||||
VT(!memcmp(&projection.HeadPose, &identity.HeadPose, sizeof(pose64)));
|
||||
tracking_reset(); test_tracked = 0;
|
||||
projection.Header.Flags = 4; submit_prepare(m, &desc); VT(desc.LayerCount == 1);
|
||||
projection.Header.Flags = 0; submit_prepare(m, &desc); VT(desc.LayerCount == 0);
|
||||
/* Check the real SubmitFrame2 thunk ends an empty frame with no tracked fallback. */
|
||||
memset(buf, 0, 4096);
|
||||
st32(g+32,1); st32(g+36,array); st32(array,layer); st32(layer,1);
|
||||
st32(layer+136,ch); st32(layer+224,ch);
|
||||
memcpy(g2p(layer+40), &identity.HeadPose, sizeof(pose64)); memcpy(buf+16,&time,8);
|
||||
cpu.r[0]=mh; cpu.r[1]=g;
|
||||
ar_init(&r,&cpu,0,g+4096); imp_vrapi_SubmitFrame2(&cpu,&r);
|
||||
VT(test_submit_calls == 4 && test_submit_layers == 0);
|
||||
test_tracked = 1; test_identity = 0; test_current_only = 1;
|
||||
desc.LayerCount = 1; projection.HeadPose = identity.HeadPose;
|
||||
submit_prepare(m, &desc);
|
||||
VT(desc.LayerCount == 1 && projection.HeadPose.TimeInSeconds == 42.75);
|
||||
VT(desc.DisplayTime == 42.25); /* no extra WaitFrame or display-time advance */
|
||||
test_current_only = 0;
|
||||
/* Keep an update/render pair across more than the old 16 cache entries. */
|
||||
tracking_reset();
|
||||
good = tracking_of(m, 42.25);
|
||||
for (int j = 1; j <= 40; ++j) tracking_of(m, 42.25+j*0.001);
|
||||
calls = test_tracking_calls;
|
||||
held = tracking_of(m, 42.25);
|
||||
VT(test_tracking_calls == calls && !memcmp(&held, &good, sizeof held));
|
||||
test_tracked = 1; test_identity = 0;
|
||||
tracking_reset(); B = saved; bridge_ok = saved_ok;
|
||||
munmap(buf,8192);
|
||||
fprintf(stderr, "vrapi ABI/cache/transform tests: %s\n", failed ? "FAILED" : "OK");
|
||||
#undef VT
|
||||
return failed;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Builds a32run (the AArch32 -> AArch64 translator) with the NDK's clang as a static AArch64 executable.
|
||||
|
||||
python native/a32translator/build.py [--debug] [--ndk PATH] [--out DIR]
|
||||
|
||||
The NDK comes from native/.cache (python native/build.py downloads it). The binary is static bionic, linked at a
|
||||
high image base so the guest's low 4 GiB stay free; it runs on any AArch64 Linux (SteamOS, Android) or under
|
||||
qemu-aarch64.
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
NDK_DEFAULT = HERE.parent / ".cache" / "ndk-27.2.12479018"
|
||||
SOURCES = ["main.c", "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"]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--debug", action="store_true")
|
||||
ap.add_argument("--ndk", default=str(NDK_DEFAULT))
|
||||
ap.add_argument("--out", default=str(HERE / "out"))
|
||||
a = ap.parse_args()
|
||||
cc = Path(a.ndk) / "toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android29-clang"
|
||||
if not cc.exists():
|
||||
sys.exit(f"{cc} not found (run python native/build.py once to fetch the NDK)")
|
||||
out = Path(a.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
srcs = [HERE / "src" / s for s in SOURCES if (HERE / "src" / s).exists()]
|
||||
flags = ["-std=gnu11", "-Wall", "-Wextra", "-Wno-unused-parameter", "-Wno-missing-field-initializers",
|
||||
"-march=armv8-a+crypto", f"-ffile-prefix-map={HERE}=a32translator", "-fno-strict-aliasing"]
|
||||
flags += ["-O0", "-g"] if a.debug else ["-O2", "-g"]
|
||||
cmd = [str(cc), *flags, *map(str, srcs), "-static", "-Wl,--image-base=0x7000000000", "-lm",
|
||||
"-o", str(out / "a32run")]
|
||||
print(" ".join(cmd[:1] + ["..."] + cmd[-2:]))
|
||||
r = subprocess.run(cmd)
|
||||
sys.exit(r.returncode)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,688 @@
|
||||
/* A32 (ARM state) decoder, following the ARMv7-A/R ARM (DDI 0406C) chapter A5 plus the ARMv8 AArch32 additions
|
||||
* that user code meets (LDA/STL, CRC32, VSEL & co. live in vfp_neon_decode.c). */
|
||||
#include <string.h>
|
||||
#include "insn.h"
|
||||
|
||||
static void shift_imm(insn_t *i, uint32_t w)
|
||||
{
|
||||
unsigned type = BITS(w, 6, 5), amt = BITS(w, 11, 7);
|
||||
i->rm = BITS(w, 3, 0);
|
||||
i->form = F_REG;
|
||||
i->shtype = type;
|
||||
i->shimm = amt;
|
||||
if (type == SH_LSR || type == SH_ASR) {
|
||||
if (amt == 0) i->shimm = 32;
|
||||
} else if (type == SH_ROR && amt == 0) {
|
||||
i->shtype = SH_RRX;
|
||||
i->shimm = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* The condition is kept: a conditional UNDEFINED instruction that fails its condition is skipped
|
||||
* (IMPLEMENTATION DEFINED; qemu and many cores do this). The unconditional space has cond = AL already. */
|
||||
static int undef(insn_t *i)
|
||||
{
|
||||
i->op = OP_UNDEF;
|
||||
return 4;
|
||||
}
|
||||
|
||||
static int dp(uint32_t w, insn_t *i, int form)
|
||||
{
|
||||
unsigned opc = BITS(w, 24, 21);
|
||||
i->op = OP_DP;
|
||||
i->sub = opc;
|
||||
i->s = BIT(w, 20);
|
||||
i->rn = BITS(w, 19, 16);
|
||||
i->rd = BITS(w, 15, 12);
|
||||
if (form == F_IMM) {
|
||||
unsigned rot = BITS(w, 11, 8) * 2;
|
||||
i->form = F_IMM;
|
||||
i->imm = ror32(BITS(w, 7, 0), rot);
|
||||
i->immcarry = rot != 0;
|
||||
} else if (form == F_REG) {
|
||||
shift_imm(i, w);
|
||||
} else {
|
||||
i->form = F_RSR;
|
||||
i->rm = BITS(w, 3, 0);
|
||||
i->rs = BITS(w, 11, 8);
|
||||
i->shtype = BITS(w, 6, 5);
|
||||
if (i->rd == 15 || i->rn == 15 || i->rm == 15 || i->rs == 15) i->unpred = 1;
|
||||
}
|
||||
if (opc >= A_TST && opc <= A_CMN) {
|
||||
/* S must be 1 (else it is a misc/halfword-multiply encoding, handled by the caller) */
|
||||
if (i->rd != 0) i->unpred = 1; /* Rd should be zero */
|
||||
i->rd = 0;
|
||||
} else if (i->rd == 15) {
|
||||
i->writes_pc = 1;
|
||||
if (i->s) i->unpred = 1; /* SUBS PC, LR and friends: exception return, not in user mode */
|
||||
}
|
||||
if (opc == A_MOV || opc == A_MVN) {
|
||||
if (i->rn != 0) i->unpred = 1; /* Rn should be zero */
|
||||
i->rn = 0;
|
||||
}
|
||||
return 4;
|
||||
}
|
||||
|
||||
/* Miscellaneous instructions (op 10xx0, bit 7 = 0) */
|
||||
static int misc(uint32_t w, insn_t *i)
|
||||
{
|
||||
unsigned op = BITS(w, 22, 21), op2 = BITS(w, 6, 4);
|
||||
switch (op2) {
|
||||
case 0:
|
||||
if (BIT(w, 9)) { /* banked register MRS/MSR: UNPREDICTABLE in user mode */
|
||||
i->unpred = 1;
|
||||
return undef(i);
|
||||
}
|
||||
if (!(op & 1)) { /* MRS */
|
||||
if (BIT(w, 22)) return undef(i); /* SPSR */
|
||||
i->op = OP_MRS;
|
||||
i->rd = BITS(w, 15, 12);
|
||||
if (i->rd == 15 || BITS(w, 19, 16) != 15 || BITS(w, 11, 0) != 0) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (op == 1) { /* MSR APSR, Rn */
|
||||
i->op = OP_MSR;
|
||||
i->imm = BITS(w, 19, 18) << 2;
|
||||
i->rn = BITS(w, 3, 0);
|
||||
i->form = F_REG;
|
||||
if (i->rn == 15 || i->imm == 0 || BITS(w, 15, 12) != 15 || BITS(w, 11, 4) != 0) i->unpred = 1;
|
||||
if (BITS(w, 17, 16)) i->imm |= 0x100; /* system fields: ignored in user mode */
|
||||
return 4;
|
||||
}
|
||||
return undef(i); /* MSR SPSR */
|
||||
case 1:
|
||||
if (op == 1) {
|
||||
i->op = OP_BX;
|
||||
i->rm = BITS(w, 3, 0);
|
||||
i->writes_pc = 1;
|
||||
if (BITS(w, 19, 8) != 0xfff) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (op == 3) {
|
||||
i->op = OP_CLZ;
|
||||
i->rd = BITS(w, 15, 12);
|
||||
i->rm = BITS(w, 3, 0);
|
||||
if (i->rd == 15 || i->rm == 15 || BITS(w, 19, 16) != 15 || BITS(w, 11, 8) != 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
return undef(i);
|
||||
case 2:
|
||||
if (op == 1) { /* BXJ: no Jazelle, behaves as BX */
|
||||
i->op = OP_BX;
|
||||
i->rm = BITS(w, 3, 0);
|
||||
i->writes_pc = 1;
|
||||
if (BITS(w, 19, 8) != 0xfff) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
return undef(i);
|
||||
case 3:
|
||||
if (op == 1) {
|
||||
i->op = OP_BLX_REG;
|
||||
i->rm = BITS(w, 3, 0);
|
||||
if (i->rm == 15 || BITS(w, 19, 8) != 0xfff) i->unpred = 1;
|
||||
i->writes_pc = 1;
|
||||
return 4;
|
||||
}
|
||||
return undef(i);
|
||||
case 4: /* CRC32 (ARMv8) */
|
||||
i->op = OP_CRC32;
|
||||
i->size = 1u << op;
|
||||
if (BIT(w, 9)) i->flags |= MF_CRC32C;
|
||||
i->rn = BITS(w, 19, 16);
|
||||
i->rd = BITS(w, 15, 12);
|
||||
i->rm = BITS(w, 3, 0);
|
||||
if (op == 3 || i->cond != C_AL || BITS(w, 11, 10) || BIT(w, 8)) i->unpred = 1;
|
||||
if (op == 3) return undef(i);
|
||||
return 4;
|
||||
case 5:
|
||||
i->op = OP_QADDSUB;
|
||||
i->sub = op;
|
||||
i->rn = BITS(w, 19, 16);
|
||||
i->rd = BITS(w, 15, 12);
|
||||
i->rm = BITS(w, 3, 0);
|
||||
if (i->rd == 15 || i->rn == 15 || i->rm == 15 || BITS(w, 11, 8)) i->unpred = 1;
|
||||
return 4;
|
||||
case 7:
|
||||
if (op == 1) {
|
||||
if (i->cond != C_AL) i->unpred = 1;
|
||||
i->op = OP_BKPT;
|
||||
i->imm = BITS(w, 19, 8) << 4 | BITS(w, 3, 0);
|
||||
return 4;
|
||||
}
|
||||
return undef(i); /* SMC, HVC */
|
||||
default:
|
||||
return undef(i);
|
||||
}
|
||||
}
|
||||
|
||||
static int halfword_mul(uint32_t w, insn_t *i)
|
||||
{
|
||||
unsigned op1 = BITS(w, 22, 21);
|
||||
i->op = OP_MULXY;
|
||||
i->rd = BITS(w, 19, 16);
|
||||
i->ra = BITS(w, 15, 12);
|
||||
i->rm = BITS(w, 11, 8);
|
||||
i->rn = BITS(w, 3, 0);
|
||||
if (BIT(w, 5)) i->flags |= MF_NHI;
|
||||
if (BIT(w, 6)) i->flags |= MF_MHI;
|
||||
switch (op1) {
|
||||
case 0: i->sub = MX_SMLA; break;
|
||||
case 1:
|
||||
/* SMLAWy (bit 5 = 0) / SMULWy (bit 5 = 1); y is bit 6 */
|
||||
i->sub = BIT(w, 5) ? MX_SMULW : MX_SMLAW;
|
||||
i->flags &= ~MF_NHI;
|
||||
break;
|
||||
case 2: i->sub = MX_SMLAL; break; /* ra = RdLo, rd = RdHi */
|
||||
case 3: i->sub = MX_SMUL; break;
|
||||
}
|
||||
if (i->rd == 15 || i->rn == 15 || i->rm == 15 || (i->sub != MX_SMUL && i->sub != MX_SMULW && i->ra == 15))
|
||||
i->unpred = 1;
|
||||
if (i->sub == MX_SMLAL && i->ra == i->rd) i->unpred = 1;
|
||||
if ((i->sub == MX_SMUL || i->sub == MX_SMULW) && i->ra != 0) i->unpred = 1; /* Ra should be zero */
|
||||
return 4;
|
||||
}
|
||||
|
||||
static int multiply(uint32_t w, insn_t *i)
|
||||
{
|
||||
static const signed char ops[8] = {M_MUL, M_MLA, M_UMAAL, M_MLS, M_UMULL, M_UMLAL, M_SMULL, M_SMLAL};
|
||||
unsigned op = BITS(w, 23, 21);
|
||||
i->op = OP_MUL;
|
||||
i->sub = ops[op];
|
||||
i->s = BIT(w, 20);
|
||||
i->rd = BITS(w, 19, 16); /* Rd or RdHi */
|
||||
i->ra = BITS(w, 15, 12); /* Ra or RdLo */
|
||||
i->rm = BITS(w, 11, 8);
|
||||
i->rn = BITS(w, 3, 0);
|
||||
if ((op == 2 || op == 3) && i->s) return undef(i); /* 0101 / 0111 unallocated */
|
||||
if (i->rd == 15 || i->rn == 15 || i->rm == 15) i->unpred = 1;
|
||||
if (op == 0 && i->ra != 0) i->unpred = 1; /* MUL: Ra should be zero */
|
||||
if (op >= 4 || op == 2) {
|
||||
/* long multiplies: rd = RdHi, ra = RdLo */
|
||||
if (i->ra == 15 || i->ra == i->rd) i->unpred = 1;
|
||||
} else if ((op == 1 || op == 3) && i->ra == 15) {
|
||||
i->unpred = 1;
|
||||
}
|
||||
return 4;
|
||||
}
|
||||
|
||||
static int sync_prim(uint32_t w, insn_t *i)
|
||||
{
|
||||
unsigned op = BITS(w, 23, 20);
|
||||
i->rn = BITS(w, 19, 16);
|
||||
if (!(op & 8)) {
|
||||
/* SWP / SWPB */
|
||||
if (op & 3) return undef(i);
|
||||
i->op = OP_SWP;
|
||||
i->size = BIT(w, 22) ? 1 : 4;
|
||||
i->rd = BITS(w, 15, 12);
|
||||
i->rm = BITS(w, 3, 0);
|
||||
if (i->rd == 15 || i->rn == 15 || i->rm == 15 || i->rn == i->rd || i->rn == i->rm || BITS(w, 11, 8))
|
||||
i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
static const uint8_t sizes[4] = {4, 8, 1, 2};
|
||||
unsigned l = op & 1, sz = sizes[BITS(op, 2, 1)];
|
||||
unsigned ex = BITS(w, 9, 8); /* 11 exclusive (v7 and v8), 10 acquire/release exclusive, 00 acquire/release */
|
||||
i->size = sz;
|
||||
if (ex == 1) return undef(i);
|
||||
if (ex != 3) i->flags |= MF_ACQREL;
|
||||
if (ex == 0) {
|
||||
/* LDA/STL (no exclusive), only words, bytes and halfwords */
|
||||
if (sz == 8) return undef(i);
|
||||
if (l) {
|
||||
i->op = OP_LDA;
|
||||
i->rd = BITS(w, 15, 12);
|
||||
if (BITS(w, 3, 0) != 15) i->unpred = 1;
|
||||
} else {
|
||||
i->op = OP_STL;
|
||||
i->rm = BITS(w, 3, 0);
|
||||
if (BITS(w, 15, 12) != 15) i->unpred = 1;
|
||||
}
|
||||
return 4;
|
||||
}
|
||||
if (l) {
|
||||
i->op = OP_LDREX;
|
||||
i->rd = BITS(w, 15, 12);
|
||||
if (BITS(w, 3, 0) != 15) i->unpred = 1;
|
||||
if (sz == 8) {
|
||||
i->ra = i->rd + 1;
|
||||
if ((i->rd & 1) || i->rd == 14) i->unpred = 1;
|
||||
}
|
||||
if (i->rd == 15 || i->rn == 15) i->unpred = 1;
|
||||
} else {
|
||||
i->op = OP_STREX;
|
||||
i->rd = BITS(w, 15, 12);
|
||||
i->rm = BITS(w, 3, 0);
|
||||
if (sz == 8) {
|
||||
i->ra = i->rm + 1;
|
||||
if ((i->rm & 1) || i->rm == 14) i->unpred = 1;
|
||||
}
|
||||
if (i->rd == 15 || i->rm == 15 || i->rn == 15 || i->rd == i->rn || i->rd == i->rm ||
|
||||
(sz == 8 && i->rd == i->ra))
|
||||
i->unpred = 1;
|
||||
}
|
||||
return 4;
|
||||
}
|
||||
|
||||
/* LDRH/STRH/LDRD/STRD/LDRSB/LDRSH */
|
||||
static int extra_ldst(uint32_t w, insn_t *i)
|
||||
{
|
||||
unsigned op2 = BITS(w, 6, 5), l = BIT(w, 20);
|
||||
i->op = OP_LDST;
|
||||
i->p = BIT(w, 24);
|
||||
i->u = BIT(w, 23);
|
||||
i->w = !i->p || BIT(w, 21);
|
||||
if (!i->p && BIT(w, 21)) i->flags |= MF_USER;
|
||||
i->rn = BITS(w, 19, 16);
|
||||
i->rd = BITS(w, 15, 12);
|
||||
if (BIT(w, 22)) {
|
||||
i->form = F_IMM;
|
||||
i->imm = BITS(w, 11, 8) << 4 | BITS(w, 3, 0);
|
||||
} else {
|
||||
i->form = F_REG;
|
||||
i->rm = BITS(w, 3, 0);
|
||||
i->shtype = SH_LSL;
|
||||
i->shimm = 0;
|
||||
if (BITS(w, 11, 8)) i->unpred = 1;
|
||||
}
|
||||
if (op2 == 1) {
|
||||
i->size = 2;
|
||||
if (l) i->flags |= MF_LOAD;
|
||||
} else if (!l) {
|
||||
/* LDRD (op2 = 10) / STRD (op2 = 11) */
|
||||
i->size = 8;
|
||||
if (op2 == 2) i->flags |= MF_LOAD;
|
||||
if (i->flags & MF_USER) return undef(i);
|
||||
if (i->rd & 1) i->unpred = 1;
|
||||
i->ra = i->rd + 1;
|
||||
if (i->ra == 15) i->unpred = 1;
|
||||
if (i->form == F_REG && (i->rm == i->rd || i->rm == i->ra) && (i->flags & MF_LOAD)) i->unpred = 1;
|
||||
if (i->w && (i->rn == i->rd || i->rn == i->ra)) i->unpred = 1;
|
||||
} else {
|
||||
i->size = op2 == 2 ? 1 : 2;
|
||||
i->sign = 1;
|
||||
i->flags |= MF_LOAD;
|
||||
}
|
||||
if (i->rd == 15) i->unpred = 1;
|
||||
if (i->form == F_REG && i->rm == 15) i->unpred = 1;
|
||||
if (i->w && (i->rn == 15 || i->rn == i->rd)) i->unpred = 1;
|
||||
if (i->w && i->form == F_REG && i->rm == i->rn) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
|
||||
static int dp_misc(uint32_t w, insn_t *i)
|
||||
{
|
||||
unsigned op = BITS(w, 24, 20);
|
||||
if (BIT(w, 25)) {
|
||||
if (op == 0x10 || op == 0x14) {
|
||||
i->op = op == 0x10 ? OP_MOVW : OP_MOVT;
|
||||
i->rd = BITS(w, 15, 12);
|
||||
i->imm = BITS(w, 19, 16) << 12 | BITS(w, 11, 0);
|
||||
if (i->rd == 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if ((op & 0x1b) == 0x12) {
|
||||
/* MSR immediate and hints */
|
||||
unsigned mask = BITS(w, 19, 16);
|
||||
if (op == 0x12 && mask == 0) {
|
||||
i->op = OP_NOP; /* NOP, YIELD, WFE, WFI, SEV, CSDB, DBG */
|
||||
if (BITS(w, 15, 8) != 0xf0) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (op & 4) {
|
||||
i->unpred = 1; /* MSR SPSR: UNPREDICTABLE in user mode */
|
||||
return undef(i);
|
||||
}
|
||||
i->op = OP_MSR;
|
||||
i->imm = BITS(w, 19, 18) << 2;
|
||||
if (mask & 3) i->imm |= 0x100;
|
||||
if (BITS(w, 15, 12) != 15 || !(mask & 0xc)) i->unpred = 1;
|
||||
i->form = F_IMM;
|
||||
i->reglist = ror32(BITS(w, 7, 0), BITS(w, 11, 8) * 2);
|
||||
return 4;
|
||||
}
|
||||
if ((op & 0x19) == 0x10) return undef(i); /* TST..CMN without S: unallocated (covered above) */
|
||||
return dp(w, i, F_IMM);
|
||||
}
|
||||
if (!BIT(w, 4)) {
|
||||
if ((op & 0x19) == 0x10) return BIT(w, 7) ? halfword_mul(w, i) : misc(w, i);
|
||||
return dp(w, i, F_REG);
|
||||
}
|
||||
if (!BIT(w, 7)) {
|
||||
if ((op & 0x19) == 0x10) return misc(w, i);
|
||||
return dp(w, i, F_RSR);
|
||||
}
|
||||
if (BITS(w, 6, 5) == 0) return BIT(w, 24) ? sync_prim(w, i) : multiply(w, i);
|
||||
return extra_ldst(w, i);
|
||||
}
|
||||
|
||||
static int ldst_word(uint32_t w, insn_t *i)
|
||||
{
|
||||
i->op = OP_LDST;
|
||||
i->p = BIT(w, 24);
|
||||
i->u = BIT(w, 23);
|
||||
i->w = !i->p || BIT(w, 21);
|
||||
if (!i->p && BIT(w, 21)) i->flags |= MF_USER;
|
||||
i->size = BIT(w, 22) ? 1 : 4;
|
||||
if (BIT(w, 20)) i->flags |= MF_LOAD;
|
||||
i->rn = BITS(w, 19, 16);
|
||||
i->rd = BITS(w, 15, 12);
|
||||
if (BIT(w, 25)) {
|
||||
shift_imm(i, w);
|
||||
if (i->rm == 15) i->unpred = 1;
|
||||
if (i->w && i->rm == i->rn) i->unpred = 1;
|
||||
} else {
|
||||
i->form = F_IMM;
|
||||
i->imm = BITS(w, 11, 0);
|
||||
}
|
||||
if ((i->flags & MF_LOAD) && i->rd == 15) {
|
||||
i->writes_pc = 1;
|
||||
if (i->size == 1) i->unpred = 1;
|
||||
}
|
||||
if (!(i->flags & MF_LOAD) && i->size == 1 && i->rd == 15) i->unpred = 1;
|
||||
if (i->w && (i->rn == 15 || i->rn == i->rd)) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
|
||||
static int media(uint32_t w, insn_t *i)
|
||||
{
|
||||
unsigned op1 = BITS(w, 24, 20), op2 = BITS(w, 7, 5);
|
||||
unsigned rn = BITS(w, 19, 16), rd = BITS(w, 15, 12), rm = BITS(w, 3, 0), ra = BITS(w, 15, 12);
|
||||
i->rn = rn;
|
||||
i->rd = rd;
|
||||
i->rm = rm;
|
||||
if ((op1 & 0x18) == 0x00) {
|
||||
/* parallel addition and subtraction */
|
||||
static const signed char prefix[8] = {-1, PP_S, PP_Q, PP_SH, -1, PP_U, PP_UQ, PP_UH};
|
||||
static const signed char pop[8] = {PO_ADD16, PO_ASX, PO_SAX, PO_SUB16, PO_ADD8, -1, -1, PO_SUB8};
|
||||
if (prefix[op1 & 7] < 0 || pop[op2] < 0) return undef(i);
|
||||
i->op = OP_PARALLEL;
|
||||
i->sub = prefix[op1 & 7] << 4 | pop[op2];
|
||||
if (rd == 15 || rn == 15 || rm == 15 || BITS(w, 11, 8) != 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if ((op1 & 0x18) == 0x08) {
|
||||
unsigned o = op1 & 7;
|
||||
if (o == 0 && !(op2 & 1)) { /* PKH */
|
||||
i->op = OP_PKH;
|
||||
i->sub = BIT(w, 6);
|
||||
i->shimm = BITS(w, 11, 7);
|
||||
if (i->sub && i->shimm == 0) i->shimm = 32;
|
||||
if (rd == 15 || rn == 15 || rm == 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if ((o & 2) && !(op2 & 1)) { /* SSAT / USAT */
|
||||
i->op = OP_SAT;
|
||||
i->sign = !(o & 4);
|
||||
i->imm = BITS(w, 20, 16) + (i->sign ? 1 : 0);
|
||||
i->rn = rm;
|
||||
i->shtype = BIT(w, 6) ? SH_ASR : SH_LSL;
|
||||
i->shimm = BITS(w, 11, 7);
|
||||
if (i->shtype == SH_ASR && i->shimm == 0) i->shimm = 32;
|
||||
if (rd == 15 || rm == 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if ((o == 2 || o == 6) && op2 == 1) { /* SSAT16 / USAT16 */
|
||||
i->op = OP_SAT16;
|
||||
i->sign = o == 2;
|
||||
i->imm = BITS(w, 19, 16) + (i->sign ? 1 : 0);
|
||||
i->rn = rm;
|
||||
if (rd == 15 || rm == 15 || BITS(w, 11, 8) != 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (op2 == 3) { /* extend (and add) */
|
||||
static const signed char ext[8] = {E_SXTB16, -1, E_SXTB, E_SXTH, E_UXTB16, -1, E_UXTB, E_UXTH};
|
||||
if (ext[o] < 0) return undef(i);
|
||||
i->op = OP_EXTEND;
|
||||
i->sub = ext[o];
|
||||
i->shimm = BITS(w, 11, 10) * 8;
|
||||
if (rd == 15 || rm == 15 || BITS(w, 9, 8)) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (o == 0 && op2 == 5) {
|
||||
i->op = OP_SEL;
|
||||
if (rd == 15 || rn == 15 || rm == 15 || BITS(w, 11, 8) != 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (op2 == 1 && (o == 3 || o == 7)) {
|
||||
i->op = o == 3 ? OP_REV : OP_RBIT;
|
||||
if (rd == 15 || rm == 15 || rn != 15 || BITS(w, 11, 8) != 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (op2 == 5 && (o == 3 || o == 7)) {
|
||||
i->op = o == 3 ? OP_REV16 : OP_REVSH;
|
||||
if (rd == 15 || rm == 15 || rn != 15 || BITS(w, 11, 8) != 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
return undef(i);
|
||||
}
|
||||
if ((op1 & 0x18) == 0x10) {
|
||||
/* signed multiplies, divide; rd is bits 19:16 here, ra bits 15:12, rm bits 11:8, rn bits 3:0 */
|
||||
unsigned o = op1 & 7;
|
||||
i->rd = rn;
|
||||
i->ra = ra;
|
||||
i->rm = BITS(w, 11, 8);
|
||||
i->rn = rm;
|
||||
if (BIT(w, 5)) i->flags |= MF_SWAP;
|
||||
if (i->rd == 15 || i->rn == 15 || i->rm == 15) i->unpred = 1;
|
||||
if (o == 0 && op2 < 4) {
|
||||
i->op = OP_DUALMUL;
|
||||
i->sub = op2 & 2 ? DM_SMLSD : DM_SMLAD;
|
||||
return 4;
|
||||
}
|
||||
if ((o == 1 || o == 3) && op2 == 0) {
|
||||
i->op = OP_DIV;
|
||||
i->sign = o == 1;
|
||||
if (ra != 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (o == 4 && op2 < 4) {
|
||||
i->op = OP_DUALMUL;
|
||||
i->sub = op2 & 2 ? DM_SMLSLD : DM_SMLALD;
|
||||
if (i->ra == 15 || i->ra == i->rd) i->unpred = 1; /* ra = RdLo, rd = RdHi */
|
||||
return 4;
|
||||
}
|
||||
if (o == 5 && (op2 < 2 || op2 >= 6)) {
|
||||
i->op = OP_SMMUL;
|
||||
i->sub = op2 >= 6 ? 2 : (ra == 15 ? 0 : 1);
|
||||
if (op2 >= 6 && ra == 15) i->unpred = 1;
|
||||
i->flags &= ~MF_SWAP;
|
||||
if (BIT(w, 5)) i->flags |= MF_ROUND;
|
||||
return 4;
|
||||
}
|
||||
return undef(i);
|
||||
}
|
||||
/* op1 = 11xxx */
|
||||
if (op1 == 0x18 && op2 == 0) {
|
||||
i->op = OP_USAD8;
|
||||
i->rd = rn;
|
||||
i->ra = ra;
|
||||
i->rm = BITS(w, 11, 8);
|
||||
i->rn = rm;
|
||||
if (i->rd == 15 || i->rn == 15 || i->rm == 15) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if ((op1 & 0x1e) == 0x1a && (op2 & 3) == 2) {
|
||||
i->op = OP_BFX;
|
||||
i->sign = 1;
|
||||
goto bfx;
|
||||
}
|
||||
if ((op1 & 0x1e) == 0x1e && (op2 & 3) == 2) {
|
||||
i->op = OP_BFX;
|
||||
i->sign = 0;
|
||||
bfx:
|
||||
i->rn = rm;
|
||||
i->imm = BITS(w, 11, 7);
|
||||
i->shimm = BITS(w, 20, 16) + 1;
|
||||
if (rd == 15 || rm == 15 || i->imm + i->shimm > 32) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if ((op1 & 0x1e) == 0x1c && (op2 & 3) == 0) {
|
||||
i->op = OP_BFI;
|
||||
i->rn = rm; /* 15 = BFC */
|
||||
i->imm = BITS(w, 11, 7);
|
||||
i->shimm = BITS(w, 20, 16);
|
||||
if (rd == 15 || i->shimm < i->imm) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
if (op1 == 0x1f && op2 == 7) { /* UDF */
|
||||
i->op = OP_UNDEF;
|
||||
i->cond = C_AL;
|
||||
if (BITS(w, 31, 28) != C_AL) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
return undef(i);
|
||||
}
|
||||
|
||||
static int ldm_stm(uint32_t w, insn_t *i)
|
||||
{
|
||||
/* ^ (user registers / exception return) is UNPREDICTABLE in user mode; like qemu and real cores, run it as a
|
||||
* plain LDM/STM */
|
||||
if (BIT(w, 22)) i->unpred = 1;
|
||||
i->op = BIT(w, 20) ? OP_LDM : OP_STM;
|
||||
i->p = BIT(w, 24);
|
||||
i->u = BIT(w, 23);
|
||||
i->w = BIT(w, 21);
|
||||
i->rn = BITS(w, 19, 16);
|
||||
i->reglist = BITS(w, 15, 0);
|
||||
if (i->rn == 15 || i->reglist == 0) i->unpred = 1;
|
||||
if (i->op == OP_LDM) {
|
||||
if (i->reglist & 0x8000) i->writes_pc = 1;
|
||||
if (i->w && (i->reglist & (1u << i->rn))) i->unpred = 1;
|
||||
} else {
|
||||
/* STM with writeback and the base in the list (not lowest) stores an UNKNOWN value; PC in the list is
|
||||
* IMPLEMENTATION DEFINED (PC + 8 here) */
|
||||
if (i->w && (i->reglist & (1u << i->rn)) && (i->reglist & ((1u << i->rn) - 1))) i->unpred = 1;
|
||||
if (i->reglist & 0x8000) i->unpred = 1;
|
||||
}
|
||||
/* ARMv7: fewer than 2 registers is fine for ARM encodings except an empty list */
|
||||
return 4;
|
||||
}
|
||||
|
||||
static int coproc(uint32_t w, insn_t *i)
|
||||
{
|
||||
unsigned cp = BITS(w, 11, 8);
|
||||
if (BITS(w, 27, 24) == 15) {
|
||||
i->op = OP_SVC;
|
||||
i->imm = BITS(w, 23, 0);
|
||||
i->writes_pc = 1;
|
||||
return 4;
|
||||
}
|
||||
if ((cp & 0xe) == 0xa) {
|
||||
vfp_neon_decode(w, i);
|
||||
return 4;
|
||||
}
|
||||
if (cp == 15 && BITS(w, 27, 24) == 14 && BIT(w, 4)) {
|
||||
/* MRC/MCR p15 */
|
||||
unsigned opc1 = BITS(w, 23, 21), crn = BITS(w, 19, 16), crm = BITS(w, 3, 0), opc2 = BITS(w, 7, 5);
|
||||
i->rd = BITS(w, 15, 12);
|
||||
i->op = BIT(w, 20) ? OP_MRC : OP_MCR;
|
||||
if (opc1 == 0 && crn == 13 && crm == 0 && (opc2 == 2 || opc2 == 3)) {
|
||||
i->imm = opc2 == 3 ? CP15_TPIDRURO : CP15_TPIDRURW;
|
||||
if (i->op == OP_MCR && opc2 == 3) return undef(i);
|
||||
} else if (opc1 == 0 && crn == 14 && crm == 0 && opc2 == 0 && i->op == OP_MRC) {
|
||||
i->imm = CP15_CNTFRQ;
|
||||
} else if (opc1 == 0 && crn == 7 && ((crm == 10 && (opc2 == 4 || opc2 == 5)) || (crm == 5 && opc2 == 4))) {
|
||||
/* CP15DSB/CP15DMB/CP15ISB (deprecated barriers, still allowed at EL0) */
|
||||
if (i->op != OP_MCR) return undef(i);
|
||||
i->op = OP_BARRIER;
|
||||
return 4;
|
||||
} else {
|
||||
return undef(i);
|
||||
}
|
||||
if (i->rd == 15) {
|
||||
if (i->op == OP_MCR) i->unpred = 1;
|
||||
else return undef(i); /* APSR_nzcv form: not for these registers */
|
||||
}
|
||||
return 4;
|
||||
}
|
||||
if (cp == 15 && BITS(w, 27, 21) == 0x62 && BIT(w, 20)) {
|
||||
/* MRRC p15: generic timer counters */
|
||||
unsigned opc1 = BITS(w, 7, 4), crm = BITS(w, 3, 0);
|
||||
if (crm != 14 || opc1 > 1) return undef(i);
|
||||
i->op = OP_MRRC;
|
||||
i->rd = BITS(w, 15, 12);
|
||||
i->ra = BITS(w, 19, 16);
|
||||
i->imm = opc1 ? CP15_CNTVCT : CP15_CNTPCT;
|
||||
if (i->rd == 15 || i->ra == 15 || i->rd == i->ra) i->unpred = 1;
|
||||
return 4;
|
||||
}
|
||||
return undef(i);
|
||||
}
|
||||
|
||||
static int uncond(uint32_t w, insn_t *i)
|
||||
{
|
||||
i->cond = C_AL;
|
||||
if ((w & 0x0e000000) == 0x02000000) { /* Advanced SIMD data processing */
|
||||
vfp_neon_decode(w, i);
|
||||
return 4;
|
||||
}
|
||||
if ((w & 0x0f100000) == 0x04000000) { /* Advanced SIMD element or structure load/store */
|
||||
vfp_neon_decode(w, i);
|
||||
return 4;
|
||||
}
|
||||
if ((w & 0x0e000000) == 0x0a000000) {
|
||||
i->op = OP_BLX_IMM;
|
||||
int32_t off = (int32_t)(w << 8) >> 6;
|
||||
i->imm = i->pc + 8 + off + (BIT(w, 24) << 1);
|
||||
i->writes_pc = 1;
|
||||
return 4;
|
||||
}
|
||||
if ((w & 0xfffffdff) == 0xf1010000) {
|
||||
i->op = OP_SETEND;
|
||||
i->imm = BIT(w, 9);
|
||||
return 4;
|
||||
}
|
||||
if (w == 0xf57ff01f) {
|
||||
i->op = OP_CLREX;
|
||||
return 4;
|
||||
}
|
||||
if ((w & 0xffffff00) == 0xf57ff000 && BITS(w, 7, 4) >= 4 && BITS(w, 7, 4) <= 6) {
|
||||
i->op = OP_BARRIER;
|
||||
return 4;
|
||||
}
|
||||
if ((w & 0x0f700000) == 0x04500000 || (w & 0x0f300000) == 0x05100000 || (w & 0x0f300010) == 0x07100000 ||
|
||||
(w & 0x0f700010) == 0x06500000) {
|
||||
i->op = OP_NOP; /* PLI / PLD / PLDW */
|
||||
return 4;
|
||||
}
|
||||
if ((w & 0x0e000000) == 0x0c000000 || (w & 0x0f000000) == 0x0e000000) {
|
||||
/* unconditional coprocessor space: VSEL, VMAXNM, VRINT{A,N,P,M}, VCVT{A,N,P,M} use cp 10/11 */
|
||||
if ((BITS(w, 11, 8) & 0xe) == 0xa && (w & 0x0f000010) == 0x0e000000) {
|
||||
vfp_neon_decode(w, i);
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
return undef(i);
|
||||
}
|
||||
|
||||
int a32_decode(uint32_t w, uint32_t pc, insn_t *i)
|
||||
{
|
||||
memset(i, 0, sizeof *i);
|
||||
i->pc = pc;
|
||||
i->pcval = pc + 8;
|
||||
i->raw = w;
|
||||
i->len = 4;
|
||||
i->cond = w >> 28;
|
||||
if (i->cond == C_NV) return uncond(w, i);
|
||||
switch (BITS(w, 27, 25)) {
|
||||
case 0:
|
||||
case 1:
|
||||
return dp_misc(w, i);
|
||||
case 2:
|
||||
return ldst_word(w, i);
|
||||
case 3:
|
||||
return BIT(w, 4) ? media(w, i) : ldst_word(w, i);
|
||||
case 4:
|
||||
return ldm_stm(w, i);
|
||||
case 5: {
|
||||
int32_t off = (int32_t)(w << 8) >> 6;
|
||||
i->op = BIT(w, 24) ? OP_BL : OP_B;
|
||||
i->imm = pc + 8 + off;
|
||||
i->writes_pc = 1;
|
||||
return 4;
|
||||
}
|
||||
default:
|
||||
return coproc(w, i);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
/* A64 instruction encoders used by the JIT. Register numbers are 0..31 (31 = WZR/XZR or SP depending on the
|
||||
* instruction); sf selects the 64-bit form. Checked against llvm-mc by tests/test_a64.py. */
|
||||
#ifndef A32_A64_H
|
||||
#define A32_A64_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
uint32_t *start, *p, *end;
|
||||
int overflow;
|
||||
} cbuf;
|
||||
|
||||
static inline void emit(cbuf *b, uint32_t w)
|
||||
{
|
||||
if (b->p < b->end) *b->p++ = w;
|
||||
else b->overflow = 1;
|
||||
}
|
||||
|
||||
enum { A64_EQ, A64_NE, A64_CS, A64_CC, A64_MI, A64_PL, A64_VS, A64_VC, A64_HI, A64_LS, A64_GE, A64_LT, A64_GT, A64_LE,
|
||||
A64_AL };
|
||||
enum { SHIFT_LSL, SHIFT_LSR, SHIFT_ASR, SHIFT_ROR };
|
||||
#define XZR 31
|
||||
#define SPREG 31
|
||||
|
||||
/* ---------------------------------------------------------------- integer */
|
||||
|
||||
static inline uint32_t a64_addsub_imm(int sf, int sub, int s, int rd, int rn, uint32_t imm12, int sh12)
|
||||
{
|
||||
return 0x11000000u | (uint32_t)sf << 31 | (uint32_t)sub << 30 | (uint32_t)s << 29 | (uint32_t)sh12 << 22 |
|
||||
(imm12 & 0xfff) << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_addsub_reg(int sf, int sub, int s, int rd, int rn, int rm, int shift, int amt)
|
||||
{
|
||||
return 0x0b000000u | (uint32_t)sf << 31 | (uint32_t)sub << 30 | (uint32_t)s << 29 | (uint32_t)shift << 22 |
|
||||
(uint32_t)rm << 16 | (uint32_t)(amt & 63) << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* extended register: option 0..7 = UXTB UXTH UXTW UXTX SXTB SXTH SXTW SXTX */
|
||||
static inline uint32_t a64_addsub_ext(int sf, int sub, int s, int rd, int rn, int rm, int option, int amt)
|
||||
{
|
||||
return 0x0b200000u | (uint32_t)sf << 31 | (uint32_t)sub << 30 | (uint32_t)s << 29 | (uint32_t)rm << 16 |
|
||||
(uint32_t)option << 13 | (uint32_t)amt << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_adc(int sf, int sub, int s, int rd, int rn, int rm)
|
||||
{
|
||||
return 0x1a000000u | (uint32_t)sf << 31 | (uint32_t)sub << 30 | (uint32_t)s << 29 | (uint32_t)rm << 16 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* opc: 0 AND, 1 ORR, 2 EOR, 3 ANDS; n: invert rm (BIC, ORN, EON, BICS) */
|
||||
static inline uint32_t a64_logic_reg(int sf, int opc, int n, int rd, int rn, int rm, int shift, int amt)
|
||||
{
|
||||
return 0x0a000000u | (uint32_t)sf << 31 | (uint32_t)opc << 29 | (uint32_t)shift << 22 | (uint32_t)n << 21 |
|
||||
(uint32_t)rm << 16 | (uint32_t)(amt & 63) << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_logic_imm(int sf, int opc, int rd, int rn, uint32_t nimms /* N:immr:imms */)
|
||||
{
|
||||
return 0x12000000u | (uint32_t)sf << 31 | (uint32_t)opc << 29 | nimms << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* opc: 0 MOVN, 2 MOVZ, 3 MOVK */
|
||||
static inline uint32_t a64_movw(int sf, int opc, int rd, uint32_t imm16, int hw)
|
||||
{
|
||||
return 0x12800000u | (uint32_t)sf << 31 | (uint32_t)opc << 29 | (uint32_t)hw << 21 | (imm16 & 0xffff) << 5 |
|
||||
(uint32_t)rd;
|
||||
}
|
||||
/* opc: 0 SBFM, 1 BFM, 2 UBFM */
|
||||
static inline uint32_t a64_bfm(int sf, int opc, int rd, int rn, int immr, int imms)
|
||||
{
|
||||
return 0x13000000u | (uint32_t)sf << 31 | (uint32_t)opc << 29 | (uint32_t)sf << 22 | (uint32_t)immr << 16 |
|
||||
(uint32_t)imms << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_extr(int sf, int rd, int rn, int rm, int lsb)
|
||||
{
|
||||
return 0x13800000u | (uint32_t)sf << 31 | (uint32_t)sf << 22 | (uint32_t)rm << 16 | (uint32_t)lsb << 10 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* 2-source: 2 UDIV, 3 SDIV, 8 LSLV, 9 LSRV, 10 ASRV, 11 RORV */
|
||||
static inline uint32_t a64_dp2(int sf, int opcode, int rd, int rn, int rm)
|
||||
{
|
||||
return 0x1ac00000u | (uint32_t)sf << 31 | (uint32_t)rm << 16 | (uint32_t)opcode << 10 | (uint32_t)rn << 5 |
|
||||
(uint32_t)rd;
|
||||
}
|
||||
/* 1-source: 0 RBIT, 1 REV16, 2 REV(32) / REV32(64), 3 REV(64), 4 CLZ, 5 CLS */
|
||||
static inline uint32_t a64_dp1(int sf, int opcode, int rd, int rn)
|
||||
{
|
||||
return 0x5ac00000u | (uint32_t)sf << 31 | (uint32_t)opcode << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_madd(int sf, int sub, int rd, int rn, int rm, int ra)
|
||||
{
|
||||
return 0x1b000000u | (uint32_t)sf << 31 | (uint32_t)rm << 16 | (uint32_t)sub << 15 | (uint32_t)ra << 10 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* SMADDL/SMSUBL/UMADDL/UMSUBL: xd = xa +/- wn * wm */
|
||||
static inline uint32_t a64_maddl(int u, int sub, int rd, int rn, int rm, int ra)
|
||||
{
|
||||
return 0x9b200000u | (uint32_t)u << 23 | (uint32_t)rm << 16 | (uint32_t)sub << 15 | (uint32_t)ra << 10 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_mulh(int u, int rd, int rn, int rm)
|
||||
{
|
||||
return 0x9b407c00u | (uint32_t)u << 23 | (uint32_t)rm << 16 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* op: 0 CSEL, 1 CSINC, 2 CSINV, 3 CSNEG */
|
||||
static inline uint32_t a64_csel(int sf, int op, int rd, int rn, int rm, int cond)
|
||||
{
|
||||
return 0x1a800000u | (uint32_t)sf << 31 | (uint32_t)(op >> 1) << 30 | (uint32_t)rm << 16 | (uint32_t)cond << 12 |
|
||||
(uint32_t)(op & 1) << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_ccmp_imm(int sf, int neg, int rn, int imm5, int nzcv, int cond)
|
||||
{
|
||||
return 0x7a400800u | (uint32_t)sf << 31 | (uint32_t)(!neg) << 30 | (uint32_t)imm5 << 16 | (uint32_t)cond << 12 |
|
||||
(uint32_t)rn << 5 | (uint32_t)nzcv;
|
||||
}
|
||||
|
||||
#define SYS_NZCV 0x5a10u /* op0 3, op1 3, CRn 4, CRm 2, op2 0 */
|
||||
#define SYS_FPCR 0x5a20u
|
||||
#define SYS_FPSR 0x5a21u
|
||||
#define SYS_CNTVCT 0x5f02u
|
||||
#define SYS_CNTFRQ 0x5f00u
|
||||
static inline uint32_t a64_mrs(int rt, uint32_t sysreg) { return 0xd5300000u | sysreg << 5 | (uint32_t)rt; }
|
||||
static inline uint32_t a64_msr(int rt, uint32_t sysreg) { return 0xd5100000u | sysreg << 5 | (uint32_t)rt; }
|
||||
|
||||
/* loads/stores, unsigned scaled immediate. size: 0 B, 1 H, 2 W, 3 X; opc: 0 store, 1 load, 2 load signed 64,
|
||||
* 3 load signed 32 */
|
||||
static inline uint32_t a64_ldst_imm(int size, int opc, int rt, int rn, uint32_t byte_off)
|
||||
{
|
||||
return 0x39000000u | (uint32_t)size << 30 | (uint32_t)opc << 22 | ((byte_off >> size) & 0xfff) << 10 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
/* unscaled signed 9-bit offset (LDUR/STUR) */
|
||||
static inline uint32_t a64_ldst_unscaled(int size, int opc, int rt, int rn, int off)
|
||||
{
|
||||
return 0x38000000u | (uint32_t)size << 30 | (uint32_t)opc << 22 | ((uint32_t)off & 0x1ff) << 12 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
/* register offset: option 2 UXTW, 3 LSL, 6 SXTW, 7 SXTX; s: scale by access size */
|
||||
static inline uint32_t a64_ldst_reg(int size, int opc, int rt, int rn, int rm, int option, int s)
|
||||
{
|
||||
return 0x38200800u | (uint32_t)size << 30 | (uint32_t)opc << 22 | (uint32_t)rm << 16 | (uint32_t)option << 13 |
|
||||
(uint32_t)s << 12 | (uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
/* LDP/STP signed offset; sf 0: W registers (offset multiple of 4), 1: X */
|
||||
static inline uint32_t a64_ldstp(int sf, int load, int rt, int rt2, int rn, int off)
|
||||
{
|
||||
int sc = sf ? 3 : 2;
|
||||
return 0x29000000u | (uint32_t)sf << 31 | (uint32_t)load << 22 | ((uint32_t)(off >> sc) & 0x7f) << 15 |
|
||||
(uint32_t)rt2 << 10 | (uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
/* FP/SIMD register load/store, unsigned scaled offset. size: 2 S, 3 D, 4 Q */
|
||||
static inline uint32_t a64_ldst_fp(int size, int load, int rt, int rn, uint32_t byte_off)
|
||||
{
|
||||
uint32_t sz = size == 4 ? 0 : (uint32_t)size, opc = (size == 4 ? 2u : 0u) | (uint32_t)load;
|
||||
return 0x3d000000u | sz << 30 | opc << 22 | ((byte_off >> size) & 0xfff) << 10 | (uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
/* FP/SIMD register offset (Xn + Xm, unscaled) */
|
||||
static inline uint32_t a64_ldst_fp_reg(int size, int load, int rt, int rn, int rm)
|
||||
{
|
||||
uint32_t sz = size == 4 ? 0 : (uint32_t)size, opc = (size == 4 ? 2u : 0u) | (uint32_t)load;
|
||||
return 0x3c206800u | sz << 30 | opc << 22 | (uint32_t)rm << 16 | (uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
static inline uint32_t a64_ldst_fp_unscaled(int size, int load, int rt, int rn, int off)
|
||||
{
|
||||
uint32_t sz = size == 4 ? 0 : (uint32_t)size, opc = (size == 4 ? 2u : 0u) | (uint32_t)load;
|
||||
return 0x3c000000u | sz << 30 | opc << 22 | ((uint32_t)off & 0x1ff) << 12 | (uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
|
||||
static inline uint32_t a64_b(int32_t words) { return 0x14000000u | ((uint32_t)words & 0x3ffffff); }
|
||||
static inline uint32_t a64_bl(int32_t words) { return 0x94000000u | ((uint32_t)words & 0x3ffffff); }
|
||||
static inline uint32_t a64_bcond(int cond, int32_t words) { return 0x54000000u | ((uint32_t)words & 0x7ffff) << 5 | (uint32_t)cond; }
|
||||
static inline uint32_t a64_cbz(int sf, int nz, int rt, int32_t words)
|
||||
{
|
||||
return 0x34000000u | (uint32_t)sf << 31 | (uint32_t)nz << 24 | ((uint32_t)words & 0x7ffff) << 5 | (uint32_t)rt;
|
||||
}
|
||||
static inline uint32_t a64_tbz(int nz, int rt, int bit, int32_t words)
|
||||
{
|
||||
return 0x36000000u | (uint32_t)(bit >> 5) << 31 | (uint32_t)nz << 24 | (uint32_t)(bit & 31) << 19 |
|
||||
((uint32_t)words & 0x3fff) << 5 | (uint32_t)rt;
|
||||
}
|
||||
static inline uint32_t a64_br(int rn) { return 0xd61f0000u | (uint32_t)rn << 5; }
|
||||
static inline uint32_t a64_blr(int rn) { return 0xd63f0000u | (uint32_t)rn << 5; }
|
||||
static inline uint32_t a64_ret(void) { return 0xd65f03c0u; }
|
||||
static inline uint32_t a64_adr(int rd, int32_t off)
|
||||
{
|
||||
return 0x10000000u | ((uint32_t)off & 3) << 29 | (((uint32_t)off >> 2) & 0x7ffff) << 5 | (uint32_t)rd;
|
||||
}
|
||||
#define A64_NOP 0xd503201fu
|
||||
#define A64_DMB_ISH 0xd5033bbfu
|
||||
#define A64_DSB_ISH 0xd5033b9fu
|
||||
#define A64_ISB 0xd5033fdfu
|
||||
|
||||
/* exclusives (size 0..3): LDXR/LDAXR Rt, [Xn]; STXR/STLXR Ws, Rt, [Xn] */
|
||||
static inline uint32_t a64_ldxr(int size, int acq, int rt, int rn)
|
||||
{
|
||||
return 0x085f7c00u | (uint32_t)size << 30 | (uint32_t)acq << 15 | (uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
static inline uint32_t a64_stxr(int size, int rel, int rs, int rt, int rn)
|
||||
{
|
||||
return 0x08007c00u | (uint32_t)size << 30 | (uint32_t)rs << 16 | (uint32_t)rel << 15 | (uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
#define A64_CLREX 0xd5033f5fu
|
||||
/* load-acquire / store-release (size 0..3) */
|
||||
static inline uint32_t a64_ldar(int size, int rt, int rn) { return 0x08dffc00u | (uint32_t)size << 30 | (uint32_t)rn << 5 | (uint32_t)rt; }
|
||||
static inline uint32_t a64_stlr(int size, int rt, int rn) { return 0x089ffc00u | (uint32_t)size << 30 | (uint32_t)rn << 5 | (uint32_t)rt; }
|
||||
|
||||
/* ---------------------------------------------------------------- scalar floating point (type 0 = S, 1 = D) */
|
||||
|
||||
/* opcode: 0 FMUL, 1 FDIV, 2 FADD, 3 FSUB, 4 FMAX, 5 FMIN, 6 FMAXNM, 7 FMINNM, 8 FNMUL */
|
||||
static inline uint32_t a64_fp2(int type, int opcode, int rd, int rn, int rm)
|
||||
{
|
||||
return 0x1e200800u | (uint32_t)type << 22 | (uint32_t)rm << 16 | (uint32_t)opcode << 12 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* opcode: 0 FMOV, 1 FABS, 2 FNEG, 3 FSQRT, 4 FCVT->S, 5 FCVT->D, 7 FCVT->H, 8 FRINTN, 9 FRINTP, 10 FRINTM,
|
||||
* 11 FRINTZ, 12 FRINTA, 14 FRINTX, 15 FRINTI */
|
||||
static inline uint32_t a64_fp1(int type, int opcode, int rd, int rn)
|
||||
{
|
||||
return 0x1e204000u | (uint32_t)type << 22 | (uint32_t)opcode << 15 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* o1:o0: 0 FMADD, 1 FMSUB, 2 FNMADD, 3 FNMSUB */
|
||||
static inline uint32_t a64_fp3(int type, int op, int rd, int rn, int rm, int ra)
|
||||
{
|
||||
return 0x1f000000u | (uint32_t)type << 22 | (uint32_t)(op >> 1) << 21 | (uint32_t)rm << 16 | (uint32_t)(op & 1) << 15 |
|
||||
(uint32_t)ra << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_fcmp(int type, int e, int zero, int rn, int rm)
|
||||
{
|
||||
return 0x1e202000u | (uint32_t)type << 22 | (uint32_t)(zero ? 0 : rm) << 16 | (uint32_t)rn << 5 |
|
||||
(uint32_t)e << 4 | (uint32_t)zero << 3;
|
||||
}
|
||||
/* int <-> fp. rmode:opcode as in the ARM ARM: SCVTF 0x02, UCVTF 0x03, FCVTZS 0x18, FCVTZU 0x19, FCVTNS 0x00,
|
||||
* FCVTNU 0x01, FCVTPS 0x08, FCVTPU 0x09, FCVTMS 0x10, FCVTMU 0x11, FCVTAS 0x04, FCVTAU 0x05, FMOV W<-S 0x06,
|
||||
* FMOV S<-W 0x07 */
|
||||
static inline uint32_t a64_fcvt_int(int sf, int type, int rmode_op, int rd, int rn)
|
||||
{
|
||||
return 0x1e200000u | (uint32_t)sf << 31 | (uint32_t)type << 22 | (uint32_t)rmode_op << 16 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* fixed point: SCVTF 0x02, UCVTF 0x03, FCVTZS 0x18, FCVTZU 0x19; fbits 1..32 (sf = 0) */
|
||||
static inline uint32_t a64_fcvt_fix(int sf, int type, int rmode_op, int rd, int rn, int fbits)
|
||||
{
|
||||
return 0x1e000000u | (uint32_t)sf << 31 | (uint32_t)type << 22 | (uint32_t)rmode_op << 16 |
|
||||
(uint32_t)(64 - fbits) << 10 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_fcsel(int type, int rd, int rn, int rm, int cond)
|
||||
{
|
||||
return 0x1e200c00u | (uint32_t)type << 22 | (uint32_t)rm << 16 | (uint32_t)cond << 12 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Advanced SIMD (subset) */
|
||||
|
||||
/* three same: opcode 5 bits, size 2 bits */
|
||||
static inline uint32_t a64_simd3(int q, int u, int size, int opcode, int rd, int rn, int rm)
|
||||
{
|
||||
return 0x0e200400u | (uint32_t)q << 30 | (uint32_t)u << 29 | (uint32_t)size << 22 | (uint32_t)rm << 16 |
|
||||
(uint32_t)opcode << 11 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* two-register misc: opcode 5 bits */
|
||||
static inline uint32_t a64_simd2(int q, int u, int size, int opcode, int rd, int rn)
|
||||
{
|
||||
return 0x0e200800u | (uint32_t)q << 30 | (uint32_t)u << 29 | (uint32_t)size << 22 | (uint32_t)opcode << 12 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* shift by immediate: immh:immb encodes element size and amount; opcode 5 bits */
|
||||
static inline uint32_t a64_simd_shift(int q, int u, int immhb, int opcode, int rd, int rn)
|
||||
{
|
||||
return 0x0f000400u | (uint32_t)q << 30 | (uint32_t)u << 29 | (uint32_t)immhb << 16 | (uint32_t)opcode << 11 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* DUP (element): imm5 encodes size and index */
|
||||
static inline uint32_t a64_dup_elem(int q, int rd, int rn, int imm5)
|
||||
{
|
||||
return 0x0e000400u | (uint32_t)q << 30 | (uint32_t)imm5 << 16 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* DUP (general) */
|
||||
static inline uint32_t a64_dup_gen(int q, int rd, int rn, int imm5)
|
||||
{
|
||||
return 0x0e000c00u | (uint32_t)q << 30 | (uint32_t)imm5 << 16 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* INS (general): Vd.T[idx] = Rn */
|
||||
static inline uint32_t a64_ins_gen(int rd, int rn, int imm5) { return 0x4e001c00u | (uint32_t)imm5 << 16 | (uint32_t)rn << 5 | (uint32_t)rd; }
|
||||
/* UMOV / SMOV (to W) */
|
||||
static inline uint32_t a64_umov(int sf, int rd, int rn, int imm5) { return 0x0e003c00u | (uint32_t)sf << 30 | (uint32_t)imm5 << 16 | (uint32_t)rn << 5 | (uint32_t)rd; }
|
||||
static inline uint32_t a64_smov(int rd, int rn, int imm5) { return 0x0e002c00u | (uint32_t)imm5 << 16 | (uint32_t)rn << 5 | (uint32_t)rd; }
|
||||
/* INS (element): Vd.T[i1] = Vn.T[i2] */
|
||||
static inline uint32_t a64_ins_elem(int rd, int rn, int imm5, int imm4)
|
||||
{
|
||||
return 0x6e000400u | (uint32_t)imm5 << 16 | (uint32_t)imm4 << 11 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* MOVI/MVNI/ORR/BIC (vector, immediate) */
|
||||
static inline uint32_t a64_movi(int q, int op, int cmode, int rd, uint32_t imm8)
|
||||
{
|
||||
return 0x0f000400u | (uint32_t)q << 30 | (uint32_t)op << 29 | (imm8 >> 5) << 16 | (uint32_t)cmode << 12 |
|
||||
(imm8 & 31) << 5 | (uint32_t)rd;
|
||||
}
|
||||
static inline uint32_t a64_ext(int q, int rd, int rn, int rm, int idx)
|
||||
{
|
||||
return 0x2e000000u | (uint32_t)q << 30 | (uint32_t)rm << 16 | (uint32_t)idx << 11 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* three different (long/wide/narrow): opcode 4 bits */
|
||||
static inline uint32_t a64_simd3diff(int q, int u, int size, int opcode, int rd, int rn, int rm)
|
||||
{
|
||||
return 0x0e200000u | (uint32_t)q << 30 | (uint32_t)u << 29 | (uint32_t)size << 22 | (uint32_t)rm << 16 |
|
||||
(uint32_t)opcode << 12 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* by element: opcode 4 bits, L/M/H index bits supplied */
|
||||
static inline uint32_t a64_simd_elem(int q, int u, int size, int opcode, int rd, int rn, int rm, int l, int m, int h)
|
||||
{
|
||||
return 0x0f000000u | (uint32_t)q << 30 | (uint32_t)u << 29 | (uint32_t)size << 22 | (uint32_t)l << 21 |
|
||||
(uint32_t)m << 20 | (uint32_t)(rm & 15) << 16 | (uint32_t)opcode << 12 | (uint32_t)h << 11 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* permute: opcode 1 UZP1, 2 TRN1, 3 ZIP1, 5 UZP2, 6 TRN2, 7 ZIP2 */
|
||||
static inline uint32_t a64_perm(int q, int size, int opcode, int rd, int rn, int rm)
|
||||
{
|
||||
return 0x0e000800u | (uint32_t)q << 30 | (uint32_t)size << 22 | (uint32_t)rm << 16 | (uint32_t)opcode << 12 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* vector register copy (ORR Vd, Vn, Vn) */
|
||||
static inline uint32_t a64_mov_v(int q, int rd, int rn)
|
||||
{
|
||||
return 0x0ea01c00u | (uint32_t)q << 30 | (uint32_t)rn << 16 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* LDP/STP of Q registers, signed offset (multiple of 16) */
|
||||
static inline uint32_t a64_ldstp_q(int load, int rt, int rt2, int rn, int off)
|
||||
{
|
||||
return 0xad000000u | (uint32_t)load << 22 | ((uint32_t)(off >> 4) & 0x7f) << 15 | (uint32_t)rt2 << 10 |
|
||||
(uint32_t)rn << 5 | (uint32_t)rt;
|
||||
}
|
||||
/* DUP (element, scalar): Sd/Dd/... = Vn.T[i] ("mov s0, v1.s[2]") */
|
||||
static inline uint32_t a64_dup_scalar(int rd, int rn, int imm5)
|
||||
{
|
||||
return 0x5e000400u | (uint32_t)imm5 << 16 | (uint32_t)rn << 5 | (uint32_t)rd;
|
||||
}
|
||||
/* LD1/ST1 (single structure, one lane) {Vt.T}[idx], [Xn]; es = log2 element bytes */
|
||||
static inline uint32_t a64_ld1_lane(int load, int es, int idx, int rt, int rn)
|
||||
{
|
||||
uint32_t opcode, q, s, size;
|
||||
switch (es) {
|
||||
case 0: opcode = 0; q = idx >> 3; s = (idx >> 2) & 1; size = idx & 3; break;
|
||||
case 1: opcode = 2; q = idx >> 2; s = (idx >> 1) & 1; size = (idx & 1) << 1; break;
|
||||
case 2: opcode = 4; q = idx >> 1; s = idx & 1; size = 0; break;
|
||||
default: opcode = 4; q = idx & 1; s = 0; size = 1; break;
|
||||
}
|
||||
return 0x0d000000u | q << 30 | (uint32_t)load << 22 | opcode << 13 | s << 12 | size << 10 | (uint32_t)rn << 5 |
|
||||
(uint32_t)rt;
|
||||
}
|
||||
/* lane encodings: imm5 for element size log2 es and index i; imm4 for INS (element) source index */
|
||||
static inline int a64_imm5(int es, int idx) { return ((idx << 1) | 1) << es; }
|
||||
static inline int a64_imm4(int es, int idx) { return idx << es; }
|
||||
|
||||
/* Encodes a 32- or 64-bit logical immediate (N:immr:imms), or returns -1. */
|
||||
static inline int a64_bitmask(uint64_t v, int sf)
|
||||
{
|
||||
if (!sf) v = (v & 0xffffffffull) | (v << 32);
|
||||
if (v == 0 || v == ~0ull) return -1;
|
||||
int size = 64;
|
||||
for (; size > 2; size >>= 1) {
|
||||
uint64_t mask = (1ull << (size / 2)) - 1;
|
||||
if ((v & mask) != ((v >> (size / 2)) & mask)) break;
|
||||
}
|
||||
uint64_t emask = size == 64 ? ~0ull : (1ull << size) - 1, e = v & emask;
|
||||
/* rotate e right until it is of the form 0..01..1 */
|
||||
int rot;
|
||||
for (rot = 0; rot < size; rot++) {
|
||||
uint64_t r = ((e >> rot) | (e << (size - rot))) & emask;
|
||||
if (rot == 0) r = e;
|
||||
if ((r & (r + 1)) == 0 && (r & 1)) {
|
||||
int ones = __builtin_popcountll(r);
|
||||
int immr = (size - rot) % size, imms = ((~(size - 1) << 1) & 0x3f) | (ones - 1);
|
||||
int n = size == 64;
|
||||
if (!sf && n) return -1;
|
||||
return n << 12 | immr << 6 | (imms & 0x3f);
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,849 @@
|
||||
/* Generated by tools/gen_syscalls.py from the NDK's arm asm/unistd-eabi.h: guest syscall numbers. */
|
||||
#ifndef A32_ARM_SYSCALLS_H
|
||||
#define A32_ARM_SYSCALLS_H
|
||||
|
||||
#define G_NR_restart_syscall 0
|
||||
#define G_NR_exit 1
|
||||
#define G_NR_fork 2
|
||||
#define G_NR_read 3
|
||||
#define G_NR_write 4
|
||||
#define G_NR_open 5
|
||||
#define G_NR_close 6
|
||||
#define G_NR_creat 8
|
||||
#define G_NR_link 9
|
||||
#define G_NR_unlink 10
|
||||
#define G_NR_execve 11
|
||||
#define G_NR_chdir 12
|
||||
#define G_NR_mknod 14
|
||||
#define G_NR_chmod 15
|
||||
#define G_NR_lchown 16
|
||||
#define G_NR_lseek 19
|
||||
#define G_NR_getpid 20
|
||||
#define G_NR_mount 21
|
||||
#define G_NR_setuid 23
|
||||
#define G_NR_getuid 24
|
||||
#define G_NR_ptrace 26
|
||||
#define G_NR_pause 29
|
||||
#define G_NR_access 33
|
||||
#define G_NR_nice 34
|
||||
#define G_NR_sync 36
|
||||
#define G_NR_kill 37
|
||||
#define G_NR_rename 38
|
||||
#define G_NR_mkdir 39
|
||||
#define G_NR_rmdir 40
|
||||
#define G_NR_dup 41
|
||||
#define G_NR_pipe 42
|
||||
#define G_NR_times 43
|
||||
#define G_NR_brk 45
|
||||
#define G_NR_setgid 46
|
||||
#define G_NR_getgid 47
|
||||
#define G_NR_geteuid 49
|
||||
#define G_NR_getegid 50
|
||||
#define G_NR_acct 51
|
||||
#define G_NR_umount2 52
|
||||
#define G_NR_ioctl 54
|
||||
#define G_NR_fcntl 55
|
||||
#define G_NR_setpgid 57
|
||||
#define G_NR_umask 60
|
||||
#define G_NR_chroot 61
|
||||
#define G_NR_ustat 62
|
||||
#define G_NR_dup2 63
|
||||
#define G_NR_getppid 64
|
||||
#define G_NR_getpgrp 65
|
||||
#define G_NR_setsid 66
|
||||
#define G_NR_sigaction 67
|
||||
#define G_NR_setreuid 70
|
||||
#define G_NR_setregid 71
|
||||
#define G_NR_sigsuspend 72
|
||||
#define G_NR_sigpending 73
|
||||
#define G_NR_sethostname 74
|
||||
#define G_NR_setrlimit 75
|
||||
#define G_NR_getrusage 77
|
||||
#define G_NR_gettimeofday 78
|
||||
#define G_NR_settimeofday 79
|
||||
#define G_NR_getgroups 80
|
||||
#define G_NR_setgroups 81
|
||||
#define G_NR_symlink 83
|
||||
#define G_NR_readlink 85
|
||||
#define G_NR_uselib 86
|
||||
#define G_NR_swapon 87
|
||||
#define G_NR_reboot 88
|
||||
#define G_NR_munmap 91
|
||||
#define G_NR_truncate 92
|
||||
#define G_NR_ftruncate 93
|
||||
#define G_NR_fchmod 94
|
||||
#define G_NR_fchown 95
|
||||
#define G_NR_getpriority 96
|
||||
#define G_NR_setpriority 97
|
||||
#define G_NR_statfs 99
|
||||
#define G_NR_fstatfs 100
|
||||
#define G_NR_syslog 103
|
||||
#define G_NR_setitimer 104
|
||||
#define G_NR_getitimer 105
|
||||
#define G_NR_stat 106
|
||||
#define G_NR_lstat 107
|
||||
#define G_NR_fstat 108
|
||||
#define G_NR_vhangup 111
|
||||
#define G_NR_wait4 114
|
||||
#define G_NR_swapoff 115
|
||||
#define G_NR_sysinfo 116
|
||||
#define G_NR_fsync 118
|
||||
#define G_NR_sigreturn 119
|
||||
#define G_NR_clone 120
|
||||
#define G_NR_setdomainname 121
|
||||
#define G_NR_uname 122
|
||||
#define G_NR_adjtimex 124
|
||||
#define G_NR_mprotect 125
|
||||
#define G_NR_sigprocmask 126
|
||||
#define G_NR_init_module 128
|
||||
#define G_NR_delete_module 129
|
||||
#define G_NR_quotactl 131
|
||||
#define G_NR_getpgid 132
|
||||
#define G_NR_fchdir 133
|
||||
#define G_NR_bdflush 134
|
||||
#define G_NR_sysfs 135
|
||||
#define G_NR_personality 136
|
||||
#define G_NR_setfsuid 138
|
||||
#define G_NR_setfsgid 139
|
||||
#define G_NR__llseek 140
|
||||
#define G_NR_getdents 141
|
||||
#define G_NR__newselect 142
|
||||
#define G_NR_flock 143
|
||||
#define G_NR_msync 144
|
||||
#define G_NR_readv 145
|
||||
#define G_NR_writev 146
|
||||
#define G_NR_getsid 147
|
||||
#define G_NR_fdatasync 148
|
||||
#define G_NR__sysctl 149
|
||||
#define G_NR_mlock 150
|
||||
#define G_NR_munlock 151
|
||||
#define G_NR_mlockall 152
|
||||
#define G_NR_munlockall 153
|
||||
#define G_NR_sched_setparam 154
|
||||
#define G_NR_sched_getparam 155
|
||||
#define G_NR_sched_setscheduler 156
|
||||
#define G_NR_sched_getscheduler 157
|
||||
#define G_NR_sched_yield 158
|
||||
#define G_NR_sched_get_priority_max 159
|
||||
#define G_NR_sched_get_priority_min 160
|
||||
#define G_NR_sched_rr_get_interval 161
|
||||
#define G_NR_nanosleep 162
|
||||
#define G_NR_mremap 163
|
||||
#define G_NR_setresuid 164
|
||||
#define G_NR_getresuid 165
|
||||
#define G_NR_poll 168
|
||||
#define G_NR_nfsservctl 169
|
||||
#define G_NR_setresgid 170
|
||||
#define G_NR_getresgid 171
|
||||
#define G_NR_prctl 172
|
||||
#define G_NR_rt_sigreturn 173
|
||||
#define G_NR_rt_sigaction 174
|
||||
#define G_NR_rt_sigprocmask 175
|
||||
#define G_NR_rt_sigpending 176
|
||||
#define G_NR_rt_sigtimedwait 177
|
||||
#define G_NR_rt_sigqueueinfo 178
|
||||
#define G_NR_rt_sigsuspend 179
|
||||
#define G_NR_pread64 180
|
||||
#define G_NR_pwrite64 181
|
||||
#define G_NR_chown 182
|
||||
#define G_NR_getcwd 183
|
||||
#define G_NR_capget 184
|
||||
#define G_NR_capset 185
|
||||
#define G_NR_sigaltstack 186
|
||||
#define G_NR_sendfile 187
|
||||
#define G_NR_vfork 190
|
||||
#define G_NR_ugetrlimit 191
|
||||
#define G_NR_mmap2 192
|
||||
#define G_NR_truncate64 193
|
||||
#define G_NR_ftruncate64 194
|
||||
#define G_NR_stat64 195
|
||||
#define G_NR_lstat64 196
|
||||
#define G_NR_fstat64 197
|
||||
#define G_NR_lchown32 198
|
||||
#define G_NR_getuid32 199
|
||||
#define G_NR_getgid32 200
|
||||
#define G_NR_geteuid32 201
|
||||
#define G_NR_getegid32 202
|
||||
#define G_NR_setreuid32 203
|
||||
#define G_NR_setregid32 204
|
||||
#define G_NR_getgroups32 205
|
||||
#define G_NR_setgroups32 206
|
||||
#define G_NR_fchown32 207
|
||||
#define G_NR_setresuid32 208
|
||||
#define G_NR_getresuid32 209
|
||||
#define G_NR_setresgid32 210
|
||||
#define G_NR_getresgid32 211
|
||||
#define G_NR_chown32 212
|
||||
#define G_NR_setuid32 213
|
||||
#define G_NR_setgid32 214
|
||||
#define G_NR_setfsuid32 215
|
||||
#define G_NR_setfsgid32 216
|
||||
#define G_NR_getdents64 217
|
||||
#define G_NR_pivot_root 218
|
||||
#define G_NR_mincore 219
|
||||
#define G_NR_madvise 220
|
||||
#define G_NR_fcntl64 221
|
||||
#define G_NR_gettid 224
|
||||
#define G_NR_readahead 225
|
||||
#define G_NR_setxattr 226
|
||||
#define G_NR_lsetxattr 227
|
||||
#define G_NR_fsetxattr 228
|
||||
#define G_NR_getxattr 229
|
||||
#define G_NR_lgetxattr 230
|
||||
#define G_NR_fgetxattr 231
|
||||
#define G_NR_listxattr 232
|
||||
#define G_NR_llistxattr 233
|
||||
#define G_NR_flistxattr 234
|
||||
#define G_NR_removexattr 235
|
||||
#define G_NR_lremovexattr 236
|
||||
#define G_NR_fremovexattr 237
|
||||
#define G_NR_tkill 238
|
||||
#define G_NR_sendfile64 239
|
||||
#define G_NR_futex 240
|
||||
#define G_NR_sched_setaffinity 241
|
||||
#define G_NR_sched_getaffinity 242
|
||||
#define G_NR_io_setup 243
|
||||
#define G_NR_io_destroy 244
|
||||
#define G_NR_io_getevents 245
|
||||
#define G_NR_io_submit 246
|
||||
#define G_NR_io_cancel 247
|
||||
#define G_NR_exit_group 248
|
||||
#define G_NR_lookup_dcookie 249
|
||||
#define G_NR_epoll_create 250
|
||||
#define G_NR_epoll_ctl 251
|
||||
#define G_NR_epoll_wait 252
|
||||
#define G_NR_remap_file_pages 253
|
||||
#define G_NR_set_tid_address 256
|
||||
#define G_NR_timer_create 257
|
||||
#define G_NR_timer_settime 258
|
||||
#define G_NR_timer_gettime 259
|
||||
#define G_NR_timer_getoverrun 260
|
||||
#define G_NR_timer_delete 261
|
||||
#define G_NR_clock_settime 262
|
||||
#define G_NR_clock_gettime 263
|
||||
#define G_NR_clock_getres 264
|
||||
#define G_NR_clock_nanosleep 265
|
||||
#define G_NR_statfs64 266
|
||||
#define G_NR_fstatfs64 267
|
||||
#define G_NR_tgkill 268
|
||||
#define G_NR_utimes 269
|
||||
#define G_NR_arm_fadvise64_64 270
|
||||
#define G_NR_pciconfig_iobase 271
|
||||
#define G_NR_pciconfig_read 272
|
||||
#define G_NR_pciconfig_write 273
|
||||
#define G_NR_mq_open 274
|
||||
#define G_NR_mq_unlink 275
|
||||
#define G_NR_mq_timedsend 276
|
||||
#define G_NR_mq_timedreceive 277
|
||||
#define G_NR_mq_notify 278
|
||||
#define G_NR_mq_getsetattr 279
|
||||
#define G_NR_waitid 280
|
||||
#define G_NR_socket 281
|
||||
#define G_NR_bind 282
|
||||
#define G_NR_connect 283
|
||||
#define G_NR_listen 284
|
||||
#define G_NR_accept 285
|
||||
#define G_NR_getsockname 286
|
||||
#define G_NR_getpeername 287
|
||||
#define G_NR_socketpair 288
|
||||
#define G_NR_send 289
|
||||
#define G_NR_sendto 290
|
||||
#define G_NR_recv 291
|
||||
#define G_NR_recvfrom 292
|
||||
#define G_NR_shutdown 293
|
||||
#define G_NR_setsockopt 294
|
||||
#define G_NR_getsockopt 295
|
||||
#define G_NR_sendmsg 296
|
||||
#define G_NR_recvmsg 297
|
||||
#define G_NR_semop 298
|
||||
#define G_NR_semget 299
|
||||
#define G_NR_semctl 300
|
||||
#define G_NR_msgsnd 301
|
||||
#define G_NR_msgrcv 302
|
||||
#define G_NR_msgget 303
|
||||
#define G_NR_msgctl 304
|
||||
#define G_NR_shmat 305
|
||||
#define G_NR_shmdt 306
|
||||
#define G_NR_shmget 307
|
||||
#define G_NR_shmctl 308
|
||||
#define G_NR_add_key 309
|
||||
#define G_NR_request_key 310
|
||||
#define G_NR_keyctl 311
|
||||
#define G_NR_semtimedop 312
|
||||
#define G_NR_vserver 313
|
||||
#define G_NR_ioprio_set 314
|
||||
#define G_NR_ioprio_get 315
|
||||
#define G_NR_inotify_init 316
|
||||
#define G_NR_inotify_add_watch 317
|
||||
#define G_NR_inotify_rm_watch 318
|
||||
#define G_NR_mbind 319
|
||||
#define G_NR_get_mempolicy 320
|
||||
#define G_NR_set_mempolicy 321
|
||||
#define G_NR_openat 322
|
||||
#define G_NR_mkdirat 323
|
||||
#define G_NR_mknodat 324
|
||||
#define G_NR_fchownat 325
|
||||
#define G_NR_futimesat 326
|
||||
#define G_NR_fstatat64 327
|
||||
#define G_NR_unlinkat 328
|
||||
#define G_NR_renameat 329
|
||||
#define G_NR_linkat 330
|
||||
#define G_NR_symlinkat 331
|
||||
#define G_NR_readlinkat 332
|
||||
#define G_NR_fchmodat 333
|
||||
#define G_NR_faccessat 334
|
||||
#define G_NR_pselect6 335
|
||||
#define G_NR_ppoll 336
|
||||
#define G_NR_unshare 337
|
||||
#define G_NR_set_robust_list 338
|
||||
#define G_NR_get_robust_list 339
|
||||
#define G_NR_splice 340
|
||||
#define G_NR_arm_sync_file_range 341
|
||||
#define G_NR_tee 342
|
||||
#define G_NR_vmsplice 343
|
||||
#define G_NR_move_pages 344
|
||||
#define G_NR_getcpu 345
|
||||
#define G_NR_epoll_pwait 346
|
||||
#define G_NR_kexec_load 347
|
||||
#define G_NR_utimensat 348
|
||||
#define G_NR_signalfd 349
|
||||
#define G_NR_timerfd_create 350
|
||||
#define G_NR_eventfd 351
|
||||
#define G_NR_fallocate 352
|
||||
#define G_NR_timerfd_settime 353
|
||||
#define G_NR_timerfd_gettime 354
|
||||
#define G_NR_signalfd4 355
|
||||
#define G_NR_eventfd2 356
|
||||
#define G_NR_epoll_create1 357
|
||||
#define G_NR_dup3 358
|
||||
#define G_NR_pipe2 359
|
||||
#define G_NR_inotify_init1 360
|
||||
#define G_NR_preadv 361
|
||||
#define G_NR_pwritev 362
|
||||
#define G_NR_rt_tgsigqueueinfo 363
|
||||
#define G_NR_perf_event_open 364
|
||||
#define G_NR_recvmmsg 365
|
||||
#define G_NR_accept4 366
|
||||
#define G_NR_fanotify_init 367
|
||||
#define G_NR_fanotify_mark 368
|
||||
#define G_NR_prlimit64 369
|
||||
#define G_NR_name_to_handle_at 370
|
||||
#define G_NR_open_by_handle_at 371
|
||||
#define G_NR_clock_adjtime 372
|
||||
#define G_NR_syncfs 373
|
||||
#define G_NR_sendmmsg 374
|
||||
#define G_NR_setns 375
|
||||
#define G_NR_process_vm_readv 376
|
||||
#define G_NR_process_vm_writev 377
|
||||
#define G_NR_kcmp 378
|
||||
#define G_NR_finit_module 379
|
||||
#define G_NR_sched_setattr 380
|
||||
#define G_NR_sched_getattr 381
|
||||
#define G_NR_renameat2 382
|
||||
#define G_NR_seccomp 383
|
||||
#define G_NR_getrandom 384
|
||||
#define G_NR_memfd_create 385
|
||||
#define G_NR_bpf 386
|
||||
#define G_NR_execveat 387
|
||||
#define G_NR_userfaultfd 388
|
||||
#define G_NR_membarrier 389
|
||||
#define G_NR_mlock2 390
|
||||
#define G_NR_copy_file_range 391
|
||||
#define G_NR_preadv2 392
|
||||
#define G_NR_pwritev2 393
|
||||
#define G_NR_pkey_mprotect 394
|
||||
#define G_NR_pkey_alloc 395
|
||||
#define G_NR_pkey_free 396
|
||||
#define G_NR_statx 397
|
||||
#define G_NR_rseq 398
|
||||
#define G_NR_io_pgetevents 399
|
||||
#define G_NR_migrate_pages 400
|
||||
#define G_NR_kexec_file_load 401
|
||||
#define G_NR_clock_gettime64 403
|
||||
#define G_NR_clock_settime64 404
|
||||
#define G_NR_clock_adjtime64 405
|
||||
#define G_NR_clock_getres_time64 406
|
||||
#define G_NR_clock_nanosleep_time64 407
|
||||
#define G_NR_timer_gettime64 408
|
||||
#define G_NR_timer_settime64 409
|
||||
#define G_NR_timerfd_gettime64 410
|
||||
#define G_NR_timerfd_settime64 411
|
||||
#define G_NR_utimensat_time64 412
|
||||
#define G_NR_pselect6_time64 413
|
||||
#define G_NR_ppoll_time64 414
|
||||
#define G_NR_io_pgetevents_time64 416
|
||||
#define G_NR_recvmmsg_time64 417
|
||||
#define G_NR_mq_timedsend_time64 418
|
||||
#define G_NR_mq_timedreceive_time64 419
|
||||
#define G_NR_semtimedop_time64 420
|
||||
#define G_NR_rt_sigtimedwait_time64 421
|
||||
#define G_NR_futex_time64 422
|
||||
#define G_NR_sched_rr_get_interval_time64 423
|
||||
#define G_NR_pidfd_send_signal 424
|
||||
#define G_NR_io_uring_setup 425
|
||||
#define G_NR_io_uring_enter 426
|
||||
#define G_NR_io_uring_register 427
|
||||
#define G_NR_open_tree 428
|
||||
#define G_NR_move_mount 429
|
||||
#define G_NR_fsopen 430
|
||||
#define G_NR_fsconfig 431
|
||||
#define G_NR_fsmount 432
|
||||
#define G_NR_fspick 433
|
||||
#define G_NR_pidfd_open 434
|
||||
#define G_NR_clone3 435
|
||||
#define G_NR_close_range 436
|
||||
#define G_NR_openat2 437
|
||||
#define G_NR_pidfd_getfd 438
|
||||
#define G_NR_faccessat2 439
|
||||
#define G_NR_process_madvise 440
|
||||
#define G_NR_epoll_pwait2 441
|
||||
#define G_NR_mount_setattr 442
|
||||
#define G_NR_quotactl_fd 443
|
||||
#define G_NR_landlock_create_ruleset 444
|
||||
#define G_NR_landlock_add_rule 445
|
||||
#define G_NR_landlock_restrict_self 446
|
||||
#define G_NR_process_mrelease 448
|
||||
#define G_NR_futex_waitv 449
|
||||
#define G_NR_set_mempolicy_home_node 450
|
||||
#define G_NR_cachestat 451
|
||||
#define G_NR_fchmodat2 452
|
||||
#define G_NR_map_shadow_stack 453
|
||||
#define G_NR_futex_wake 454
|
||||
#define G_NR_futex_wait 455
|
||||
#define G_NR_futex_requeue 456
|
||||
#define G_NR_statmount 457
|
||||
#define G_NR_listmount 458
|
||||
#define G_NR_lsm_get_self_attr 459
|
||||
#define G_NR_lsm_set_self_attr 460
|
||||
#define G_NR_lsm_list_modules 461
|
||||
#define G_NR_ARM_breakpoint 983041
|
||||
#define G_NR_ARM_cacheflush 983042
|
||||
#define G_NR_ARM_usr26 983043
|
||||
#define G_NR_ARM_usr32 983044
|
||||
#define G_NR_ARM_set_tls 983045
|
||||
#define G_NR_ARM_get_tls 983046
|
||||
|
||||
static const struct { int nr; const char *name; } g_syscall_names[] = {
|
||||
{0, "restart_syscall"},
|
||||
{1, "exit"},
|
||||
{2, "fork"},
|
||||
{3, "read"},
|
||||
{4, "write"},
|
||||
{5, "open"},
|
||||
{6, "close"},
|
||||
{8, "creat"},
|
||||
{9, "link"},
|
||||
{10, "unlink"},
|
||||
{11, "execve"},
|
||||
{12, "chdir"},
|
||||
{14, "mknod"},
|
||||
{15, "chmod"},
|
||||
{16, "lchown"},
|
||||
{19, "lseek"},
|
||||
{20, "getpid"},
|
||||
{21, "mount"},
|
||||
{23, "setuid"},
|
||||
{24, "getuid"},
|
||||
{26, "ptrace"},
|
||||
{29, "pause"},
|
||||
{33, "access"},
|
||||
{34, "nice"},
|
||||
{36, "sync"},
|
||||
{37, "kill"},
|
||||
{38, "rename"},
|
||||
{39, "mkdir"},
|
||||
{40, "rmdir"},
|
||||
{41, "dup"},
|
||||
{42, "pipe"},
|
||||
{43, "times"},
|
||||
{45, "brk"},
|
||||
{46, "setgid"},
|
||||
{47, "getgid"},
|
||||
{49, "geteuid"},
|
||||
{50, "getegid"},
|
||||
{51, "acct"},
|
||||
{52, "umount2"},
|
||||
{54, "ioctl"},
|
||||
{55, "fcntl"},
|
||||
{57, "setpgid"},
|
||||
{60, "umask"},
|
||||
{61, "chroot"},
|
||||
{62, "ustat"},
|
||||
{63, "dup2"},
|
||||
{64, "getppid"},
|
||||
{65, "getpgrp"},
|
||||
{66, "setsid"},
|
||||
{67, "sigaction"},
|
||||
{70, "setreuid"},
|
||||
{71, "setregid"},
|
||||
{72, "sigsuspend"},
|
||||
{73, "sigpending"},
|
||||
{74, "sethostname"},
|
||||
{75, "setrlimit"},
|
||||
{77, "getrusage"},
|
||||
{78, "gettimeofday"},
|
||||
{79, "settimeofday"},
|
||||
{80, "getgroups"},
|
||||
{81, "setgroups"},
|
||||
{83, "symlink"},
|
||||
{85, "readlink"},
|
||||
{86, "uselib"},
|
||||
{87, "swapon"},
|
||||
{88, "reboot"},
|
||||
{91, "munmap"},
|
||||
{92, "truncate"},
|
||||
{93, "ftruncate"},
|
||||
{94, "fchmod"},
|
||||
{95, "fchown"},
|
||||
{96, "getpriority"},
|
||||
{97, "setpriority"},
|
||||
{99, "statfs"},
|
||||
{100, "fstatfs"},
|
||||
{103, "syslog"},
|
||||
{104, "setitimer"},
|
||||
{105, "getitimer"},
|
||||
{106, "stat"},
|
||||
{107, "lstat"},
|
||||
{108, "fstat"},
|
||||
{111, "vhangup"},
|
||||
{114, "wait4"},
|
||||
{115, "swapoff"},
|
||||
{116, "sysinfo"},
|
||||
{118, "fsync"},
|
||||
{119, "sigreturn"},
|
||||
{120, "clone"},
|
||||
{121, "setdomainname"},
|
||||
{122, "uname"},
|
||||
{124, "adjtimex"},
|
||||
{125, "mprotect"},
|
||||
{126, "sigprocmask"},
|
||||
{128, "init_module"},
|
||||
{129, "delete_module"},
|
||||
{131, "quotactl"},
|
||||
{132, "getpgid"},
|
||||
{133, "fchdir"},
|
||||
{134, "bdflush"},
|
||||
{135, "sysfs"},
|
||||
{136, "personality"},
|
||||
{138, "setfsuid"},
|
||||
{139, "setfsgid"},
|
||||
{140, "_llseek"},
|
||||
{141, "getdents"},
|
||||
{142, "_newselect"},
|
||||
{143, "flock"},
|
||||
{144, "msync"},
|
||||
{145, "readv"},
|
||||
{146, "writev"},
|
||||
{147, "getsid"},
|
||||
{148, "fdatasync"},
|
||||
{149, "_sysctl"},
|
||||
{150, "mlock"},
|
||||
{151, "munlock"},
|
||||
{152, "mlockall"},
|
||||
{153, "munlockall"},
|
||||
{154, "sched_setparam"},
|
||||
{155, "sched_getparam"},
|
||||
{156, "sched_setscheduler"},
|
||||
{157, "sched_getscheduler"},
|
||||
{158, "sched_yield"},
|
||||
{159, "sched_get_priority_max"},
|
||||
{160, "sched_get_priority_min"},
|
||||
{161, "sched_rr_get_interval"},
|
||||
{162, "nanosleep"},
|
||||
{163, "mremap"},
|
||||
{164, "setresuid"},
|
||||
{165, "getresuid"},
|
||||
{168, "poll"},
|
||||
{169, "nfsservctl"},
|
||||
{170, "setresgid"},
|
||||
{171, "getresgid"},
|
||||
{172, "prctl"},
|
||||
{173, "rt_sigreturn"},
|
||||
{174, "rt_sigaction"},
|
||||
{175, "rt_sigprocmask"},
|
||||
{176, "rt_sigpending"},
|
||||
{177, "rt_sigtimedwait"},
|
||||
{178, "rt_sigqueueinfo"},
|
||||
{179, "rt_sigsuspend"},
|
||||
{180, "pread64"},
|
||||
{181, "pwrite64"},
|
||||
{182, "chown"},
|
||||
{183, "getcwd"},
|
||||
{184, "capget"},
|
||||
{185, "capset"},
|
||||
{186, "sigaltstack"},
|
||||
{187, "sendfile"},
|
||||
{190, "vfork"},
|
||||
{191, "ugetrlimit"},
|
||||
{192, "mmap2"},
|
||||
{193, "truncate64"},
|
||||
{194, "ftruncate64"},
|
||||
{195, "stat64"},
|
||||
{196, "lstat64"},
|
||||
{197, "fstat64"},
|
||||
{198, "lchown32"},
|
||||
{199, "getuid32"},
|
||||
{200, "getgid32"},
|
||||
{201, "geteuid32"},
|
||||
{202, "getegid32"},
|
||||
{203, "setreuid32"},
|
||||
{204, "setregid32"},
|
||||
{205, "getgroups32"},
|
||||
{206, "setgroups32"},
|
||||
{207, "fchown32"},
|
||||
{208, "setresuid32"},
|
||||
{209, "getresuid32"},
|
||||
{210, "setresgid32"},
|
||||
{211, "getresgid32"},
|
||||
{212, "chown32"},
|
||||
{213, "setuid32"},
|
||||
{214, "setgid32"},
|
||||
{215, "setfsuid32"},
|
||||
{216, "setfsgid32"},
|
||||
{217, "getdents64"},
|
||||
{218, "pivot_root"},
|
||||
{219, "mincore"},
|
||||
{220, "madvise"},
|
||||
{221, "fcntl64"},
|
||||
{224, "gettid"},
|
||||
{225, "readahead"},
|
||||
{226, "setxattr"},
|
||||
{227, "lsetxattr"},
|
||||
{228, "fsetxattr"},
|
||||
{229, "getxattr"},
|
||||
{230, "lgetxattr"},
|
||||
{231, "fgetxattr"},
|
||||
{232, "listxattr"},
|
||||
{233, "llistxattr"},
|
||||
{234, "flistxattr"},
|
||||
{235, "removexattr"},
|
||||
{236, "lremovexattr"},
|
||||
{237, "fremovexattr"},
|
||||
{238, "tkill"},
|
||||
{239, "sendfile64"},
|
||||
{240, "futex"},
|
||||
{241, "sched_setaffinity"},
|
||||
{242, "sched_getaffinity"},
|
||||
{243, "io_setup"},
|
||||
{244, "io_destroy"},
|
||||
{245, "io_getevents"},
|
||||
{246, "io_submit"},
|
||||
{247, "io_cancel"},
|
||||
{248, "exit_group"},
|
||||
{249, "lookup_dcookie"},
|
||||
{250, "epoll_create"},
|
||||
{251, "epoll_ctl"},
|
||||
{252, "epoll_wait"},
|
||||
{253, "remap_file_pages"},
|
||||
{256, "set_tid_address"},
|
||||
{257, "timer_create"},
|
||||
{258, "timer_settime"},
|
||||
{259, "timer_gettime"},
|
||||
{260, "timer_getoverrun"},
|
||||
{261, "timer_delete"},
|
||||
{262, "clock_settime"},
|
||||
{263, "clock_gettime"},
|
||||
{264, "clock_getres"},
|
||||
{265, "clock_nanosleep"},
|
||||
{266, "statfs64"},
|
||||
{267, "fstatfs64"},
|
||||
{268, "tgkill"},
|
||||
{269, "utimes"},
|
||||
{270, "arm_fadvise64_64"},
|
||||
{271, "pciconfig_iobase"},
|
||||
{272, "pciconfig_read"},
|
||||
{273, "pciconfig_write"},
|
||||
{274, "mq_open"},
|
||||
{275, "mq_unlink"},
|
||||
{276, "mq_timedsend"},
|
||||
{277, "mq_timedreceive"},
|
||||
{278, "mq_notify"},
|
||||
{279, "mq_getsetattr"},
|
||||
{280, "waitid"},
|
||||
{281, "socket"},
|
||||
{282, "bind"},
|
||||
{283, "connect"},
|
||||
{284, "listen"},
|
||||
{285, "accept"},
|
||||
{286, "getsockname"},
|
||||
{287, "getpeername"},
|
||||
{288, "socketpair"},
|
||||
{289, "send"},
|
||||
{290, "sendto"},
|
||||
{291, "recv"},
|
||||
{292, "recvfrom"},
|
||||
{293, "shutdown"},
|
||||
{294, "setsockopt"},
|
||||
{295, "getsockopt"},
|
||||
{296, "sendmsg"},
|
||||
{297, "recvmsg"},
|
||||
{298, "semop"},
|
||||
{299, "semget"},
|
||||
{300, "semctl"},
|
||||
{301, "msgsnd"},
|
||||
{302, "msgrcv"},
|
||||
{303, "msgget"},
|
||||
{304, "msgctl"},
|
||||
{305, "shmat"},
|
||||
{306, "shmdt"},
|
||||
{307, "shmget"},
|
||||
{308, "shmctl"},
|
||||
{309, "add_key"},
|
||||
{310, "request_key"},
|
||||
{311, "keyctl"},
|
||||
{312, "semtimedop"},
|
||||
{313, "vserver"},
|
||||
{314, "ioprio_set"},
|
||||
{315, "ioprio_get"},
|
||||
{316, "inotify_init"},
|
||||
{317, "inotify_add_watch"},
|
||||
{318, "inotify_rm_watch"},
|
||||
{319, "mbind"},
|
||||
{320, "get_mempolicy"},
|
||||
{321, "set_mempolicy"},
|
||||
{322, "openat"},
|
||||
{323, "mkdirat"},
|
||||
{324, "mknodat"},
|
||||
{325, "fchownat"},
|
||||
{326, "futimesat"},
|
||||
{327, "fstatat64"},
|
||||
{328, "unlinkat"},
|
||||
{329, "renameat"},
|
||||
{330, "linkat"},
|
||||
{331, "symlinkat"},
|
||||
{332, "readlinkat"},
|
||||
{333, "fchmodat"},
|
||||
{334, "faccessat"},
|
||||
{335, "pselect6"},
|
||||
{336, "ppoll"},
|
||||
{337, "unshare"},
|
||||
{338, "set_robust_list"},
|
||||
{339, "get_robust_list"},
|
||||
{340, "splice"},
|
||||
{341, "arm_sync_file_range"},
|
||||
{342, "tee"},
|
||||
{343, "vmsplice"},
|
||||
{344, "move_pages"},
|
||||
{345, "getcpu"},
|
||||
{346, "epoll_pwait"},
|
||||
{347, "kexec_load"},
|
||||
{348, "utimensat"},
|
||||
{349, "signalfd"},
|
||||
{350, "timerfd_create"},
|
||||
{351, "eventfd"},
|
||||
{352, "fallocate"},
|
||||
{353, "timerfd_settime"},
|
||||
{354, "timerfd_gettime"},
|
||||
{355, "signalfd4"},
|
||||
{356, "eventfd2"},
|
||||
{357, "epoll_create1"},
|
||||
{358, "dup3"},
|
||||
{359, "pipe2"},
|
||||
{360, "inotify_init1"},
|
||||
{361, "preadv"},
|
||||
{362, "pwritev"},
|
||||
{363, "rt_tgsigqueueinfo"},
|
||||
{364, "perf_event_open"},
|
||||
{365, "recvmmsg"},
|
||||
{366, "accept4"},
|
||||
{367, "fanotify_init"},
|
||||
{368, "fanotify_mark"},
|
||||
{369, "prlimit64"},
|
||||
{370, "name_to_handle_at"},
|
||||
{371, "open_by_handle_at"},
|
||||
{372, "clock_adjtime"},
|
||||
{373, "syncfs"},
|
||||
{374, "sendmmsg"},
|
||||
{375, "setns"},
|
||||
{376, "process_vm_readv"},
|
||||
{377, "process_vm_writev"},
|
||||
{378, "kcmp"},
|
||||
{379, "finit_module"},
|
||||
{380, "sched_setattr"},
|
||||
{381, "sched_getattr"},
|
||||
{382, "renameat2"},
|
||||
{383, "seccomp"},
|
||||
{384, "getrandom"},
|
||||
{385, "memfd_create"},
|
||||
{386, "bpf"},
|
||||
{387, "execveat"},
|
||||
{388, "userfaultfd"},
|
||||
{389, "membarrier"},
|
||||
{390, "mlock2"},
|
||||
{391, "copy_file_range"},
|
||||
{392, "preadv2"},
|
||||
{393, "pwritev2"},
|
||||
{394, "pkey_mprotect"},
|
||||
{395, "pkey_alloc"},
|
||||
{396, "pkey_free"},
|
||||
{397, "statx"},
|
||||
{398, "rseq"},
|
||||
{399, "io_pgetevents"},
|
||||
{400, "migrate_pages"},
|
||||
{401, "kexec_file_load"},
|
||||
{403, "clock_gettime64"},
|
||||
{404, "clock_settime64"},
|
||||
{405, "clock_adjtime64"},
|
||||
{406, "clock_getres_time64"},
|
||||
{407, "clock_nanosleep_time64"},
|
||||
{408, "timer_gettime64"},
|
||||
{409, "timer_settime64"},
|
||||
{410, "timerfd_gettime64"},
|
||||
{411, "timerfd_settime64"},
|
||||
{412, "utimensat_time64"},
|
||||
{413, "pselect6_time64"},
|
||||
{414, "ppoll_time64"},
|
||||
{416, "io_pgetevents_time64"},
|
||||
{417, "recvmmsg_time64"},
|
||||
{418, "mq_timedsend_time64"},
|
||||
{419, "mq_timedreceive_time64"},
|
||||
{420, "semtimedop_time64"},
|
||||
{421, "rt_sigtimedwait_time64"},
|
||||
{422, "futex_time64"},
|
||||
{423, "sched_rr_get_interval_time64"},
|
||||
{424, "pidfd_send_signal"},
|
||||
{425, "io_uring_setup"},
|
||||
{426, "io_uring_enter"},
|
||||
{427, "io_uring_register"},
|
||||
{428, "open_tree"},
|
||||
{429, "move_mount"},
|
||||
{430, "fsopen"},
|
||||
{431, "fsconfig"},
|
||||
{432, "fsmount"},
|
||||
{433, "fspick"},
|
||||
{434, "pidfd_open"},
|
||||
{435, "clone3"},
|
||||
{436, "close_range"},
|
||||
{437, "openat2"},
|
||||
{438, "pidfd_getfd"},
|
||||
{439, "faccessat2"},
|
||||
{440, "process_madvise"},
|
||||
{441, "epoll_pwait2"},
|
||||
{442, "mount_setattr"},
|
||||
{443, "quotactl_fd"},
|
||||
{444, "landlock_create_ruleset"},
|
||||
{445, "landlock_add_rule"},
|
||||
{446, "landlock_restrict_self"},
|
||||
{448, "process_mrelease"},
|
||||
{449, "futex_waitv"},
|
||||
{450, "set_mempolicy_home_node"},
|
||||
{451, "cachestat"},
|
||||
{452, "fchmodat2"},
|
||||
{453, "map_shadow_stack"},
|
||||
{454, "futex_wake"},
|
||||
{455, "futex_wait"},
|
||||
{456, "futex_requeue"},
|
||||
{457, "statmount"},
|
||||
{458, "listmount"},
|
||||
{459, "lsm_get_self_attr"},
|
||||
{460, "lsm_set_self_attr"},
|
||||
{461, "lsm_list_modules"},
|
||||
{983041, "ARM_breakpoint"},
|
||||
{983042, "ARM_cacheflush"},
|
||||
{983043, "ARM_usr26"},
|
||||
{983044, "ARM_usr32"},
|
||||
{983045, "ARM_set_tls"},
|
||||
{983046, "ARM_get_tls"},
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,99 @@
|
||||
/* Guest (AArch32, user mode) CPU state.
|
||||
*
|
||||
* Layout notes:
|
||||
* - nzcv uses the CPSR/A64 NZCV bit positions (31..28), so the JIT can MSR it into the host flags unchanged.
|
||||
* - fpcr/fpsr use the A64 FPCR/FPSR layouts, which match the AArch32 FPSCR bit positions (AHP 26, DN 25, FZ 24,
|
||||
* RMode 23:22; QC 27, IDC 7, IXC 4, UFC 3, OFC 2, DZC 1, IOC 0). FPSCR = fpscr_nzcv | fpcr | fpsr.
|
||||
* - d[] is the VFP/NEON register file. On a little-endian host S<n> is ((uint32_t *)d)[n] and Q<n> is d[2n]:d[2n+1],
|
||||
* exactly the AArch32 aliasing.
|
||||
* - The JIT addresses fields by offset (cpu_offsets.h checks them at compile time), so keep the order. */
|
||||
#ifndef A32_CPU_H
|
||||
#define A32_CPU_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#define CPSR_N (1u << 31)
|
||||
#define CPSR_Z (1u << 30)
|
||||
#define CPSR_C (1u << 29)
|
||||
#define CPSR_V (1u << 28)
|
||||
|
||||
#define FPCR_AHP (1u << 26)
|
||||
#define FPCR_DN (1u << 25)
|
||||
#define FPCR_FZ (1u << 24)
|
||||
#define FPCR_RMODE_SHIFT 22
|
||||
#define FPCR_MASK (FPCR_AHP | FPCR_DN | FPCR_FZ | (3u << FPCR_RMODE_SHIFT))
|
||||
#define FPSR_QC (1u << 27)
|
||||
#define FPSR_MASK (FPSR_QC | 0x9fu)
|
||||
/* "Standard FPSCR value" used by every Advanced SIMD floating-point operation: DN=1, FZ=1, round to nearest. */
|
||||
#define FPCR_STANDARD (FPCR_DN | FPCR_FZ)
|
||||
|
||||
enum exit_reason {
|
||||
EXIT_NONE = 0, /* block ended normally, continue at r[15] */
|
||||
EXIT_SVC, /* supervisor call, r[15] already points after it */
|
||||
EXIT_UNDEF, /* undefined instruction at r[15] */
|
||||
EXIT_BKPT, /* breakpoint at r[15] */
|
||||
EXIT_FLUSH, /* code cache must be flushed (cacheflush, SMC), continue at r[15] */
|
||||
EXIT_SEGV, /* guest memory fault (fault_addr) at r[15] */
|
||||
};
|
||||
|
||||
typedef struct a32_cpu {
|
||||
uint32_t r[16]; /* 0x000 */
|
||||
uint32_t nzcv; /* 0x040 */
|
||||
uint32_t q; /* 0x044 sticky saturation flag (0/1) */
|
||||
uint32_t ge; /* 0x048 GE[3:0] */
|
||||
uint32_t thumb; /* 0x04c 0 = ARM, 1 = Thumb */
|
||||
uint32_t itstate; /* 0x050 ITSTATE[7:0] */
|
||||
uint32_t fpscr_nzcv; /* 0x054 FPSCR[31:28] */
|
||||
uint32_t fpcr; /* 0x058 guest FPSCR control bits, A64 FPCR layout */
|
||||
uint32_t fpsr; /* 0x05c guest cumulative flags, A64 FPSR layout */
|
||||
uint32_t tpidruro; /* 0x060 TLS register (set_tls), read by MRC p15,0,Rt,c13,c0,3 */
|
||||
uint32_t tpidrurw; /* 0x064 */
|
||||
uint32_t excl_addr; /* 0x068 exclusive monitor (LDREX/STREX), emulated as compare-and-swap */
|
||||
uint32_t excl_valid; /* 0x06c */
|
||||
uint64_t excl_val; /* 0x070 */
|
||||
uint64_t exit_reason; /* 0x078 */
|
||||
uint32_t svc_imm; /* 0x080 */
|
||||
uint32_t fault_addr; /* 0x084 */
|
||||
uint64_t host_sp; /* 0x088 host stack pointer saved by jit_enter */
|
||||
uint64_t exit_stub; /* 0x090 address of jit_exit (JIT code branches there through a register) */
|
||||
uint64_t helper_tab; /* 0x098 address of the JIT helper table */
|
||||
uint64_t lookup_tab; /* 0x0a0 block lookup hash table (direct-mapped) */
|
||||
uint64_t host_fpcr; /* 0x0a8 host FPCR at jit_enter, restored at exit */
|
||||
uint32_t interrupt; /* 0x0b0 set asynchronously (signal, code flush): JIT code leaves at the next block */
|
||||
uint32_t pad1; /* 0x0b4 */
|
||||
uint64_t last_exit; /* 0x0b8 chainable exit taken (struct jit_site *), 0 if none */
|
||||
uint64_t d[32] __attribute__((aligned(16))); /* 0x0c0 VFP/NEON registers */
|
||||
/* Not touched by JIT code directly. */
|
||||
struct a32_thread *thread;
|
||||
uint64_t insn_count;
|
||||
} a32_cpu;
|
||||
|
||||
static inline uint32_t *cpu_s(a32_cpu *c) { return (uint32_t *)c->d; }
|
||||
|
||||
#define OFF_R(n) (offsetof(a32_cpu, r) + 4 * (n))
|
||||
#define OFF_D(n) (offsetof(a32_cpu, d) + 8 * (n))
|
||||
|
||||
_Static_assert(offsetof(a32_cpu, nzcv) == 0x40, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, exit_reason) == 0x78, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, host_sp) == 0x88, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, exit_stub) == 0x90, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, helper_tab) == 0x98, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, lookup_tab) == 0xa0, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, host_fpcr) == 0xa8, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, interrupt) == 0xb0, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, last_exit) == 0xb8, "layout");
|
||||
_Static_assert(offsetof(a32_cpu, d) == 0xc0, "layout");
|
||||
|
||||
static inline uint32_t cpu_fpscr(const a32_cpu *c) { return c->fpscr_nzcv | c->fpcr | c->fpsr; }
|
||||
static inline void cpu_set_fpscr(a32_cpu *c, uint32_t v)
|
||||
{
|
||||
c->fpscr_nzcv = v & 0xf0000000u;
|
||||
c->fpcr = v & FPCR_MASK;
|
||||
c->fpsr = v & FPSR_MASK;
|
||||
}
|
||||
|
||||
/* APSR as read by MRS: NZCVQ + GE. */
|
||||
static inline uint32_t cpu_apsr(const a32_cpu *c) { return c->nzcv | (c->q << 27) | (c->ge << 16); }
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,168 @@
|
||||
/* Run loop: executes guest code (interpreter, or JIT blocks once jit.c is linked in), handles syscalls, kuser
|
||||
* helpers, signals and faults. */
|
||||
#define _GNU_SOURCE
|
||||
#include <stdarg.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include "interp.h"
|
||||
#include "runtime.h"
|
||||
#include "signals.h"
|
||||
|
||||
int opt_interp, opt_strace, opt_trace, opt_verbose, opt_bridge;
|
||||
|
||||
_Noreturn void fatal(const char *fmt, ...)
|
||||
{
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
fprintf(stderr, "a32: ");
|
||||
vfprintf(stderr, fmt, ap);
|
||||
fprintf(stderr, "\n");
|
||||
va_end(ap);
|
||||
fflush(stderr);
|
||||
if (opt_bridge) usleep(300000); /* see signals.c default_action */
|
||||
exit(127);
|
||||
}
|
||||
|
||||
void a32_dump_state(FILE *f, const a32_cpu *c)
|
||||
{
|
||||
for (int r = 0; r < 16; r++) fprintf(f, "%sr%-2d %08x%s", r % 4 ? " " : " ", r, c->r[r], r % 4 == 3 ? "\n" : "");
|
||||
fprintf(f, " nzcv %x q %u ge %x %s it %02x fpscr %08x\n", c->nzcv >> 28, c->q, c->ge, c->thumb ? "Thumb" : "ARM",
|
||||
c->itstate, cpu_fpscr(c));
|
||||
}
|
||||
|
||||
int kuser_helper(a32_cpu *c)
|
||||
{
|
||||
uint32_t pc = c->r[15];
|
||||
switch (pc) {
|
||||
case 0xffff0fe0: /* __kuser_get_tls */
|
||||
c->r[0] = c->tpidruro;
|
||||
break;
|
||||
case 0xffff0fc0: { /* __kuser_cmpxchg: r0 = oldval, r1 = newval, r2 = ptr; r0 = 0 and C set on success */
|
||||
uint32_t expected = c->r[0];
|
||||
int ok = __atomic_compare_exchange_n((uint32_t *)g2h(c->r[2]), &expected, c->r[1], 0, __ATOMIC_SEQ_CST,
|
||||
__ATOMIC_SEQ_CST);
|
||||
c->r[0] = ok ? 0 : 1;
|
||||
c->nzcv = ok ? (CPSR_Z | CPSR_C) : 0;
|
||||
c->r[3] = c->r[0];
|
||||
break;
|
||||
}
|
||||
case 0xffff0fa0: /* __kuser_memory_barrier */
|
||||
__atomic_thread_fence(__ATOMIC_SEQ_CST);
|
||||
break;
|
||||
case 0xffff0f60: { /* __kuser_cmpxchg64: r0 = &oldval, r1 = &newval, r2 = ptr */
|
||||
uint64_t expected = ld64(c->r[0]), nv = ld64(c->r[1]);
|
||||
int ok = __atomic_compare_exchange_n((uint64_t *)g2h(c->r[2]), &expected, nv, 0, __ATOMIC_SEQ_CST,
|
||||
__ATOMIC_SEQ_CST);
|
||||
c->r[0] = ok ? 0 : 1;
|
||||
c->nzcv = ok ? (CPSR_Z | CPSR_C) : 0;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
uint32_t lr = c->r[14];
|
||||
c->thumb = lr & 1;
|
||||
c->r[15] = lr & ~1u;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* JIT hooks (jit.c); weak so the interpreter-only build links without it */
|
||||
__attribute__((weak)) int jit_run(a32_cpu *c) { (void)c; return -1; }
|
||||
__attribute__((weak)) void jit_invalidate(uint32_t addr, uint32_t len) { (void)addr, (void)len; }
|
||||
__attribute__((weak)) void jit_fault_cleanup(a32_thread *t) { (void)t; }
|
||||
|
||||
void code_invalidate(uint32_t addr, uint32_t len) { jit_invalidate(addr, len); }
|
||||
|
||||
static int handle_exit(a32_cpu *c, int r, const insn_t *in)
|
||||
{
|
||||
switch (r) {
|
||||
case EXIT_NONE:
|
||||
case EXIT_FLUSH:
|
||||
return 0;
|
||||
case EXIT_SVC:
|
||||
do_syscall(c);
|
||||
return 0;
|
||||
case EXIT_SEGV: { /* instruction fetch from an unreadable address */
|
||||
siginfo_t si;
|
||||
memset(&si, 0, sizeof si);
|
||||
si.si_signo = SIGSEGV;
|
||||
si.si_code = SEGV_MAPERR;
|
||||
si.si_addr = g2h(c->fault_addr);
|
||||
deliver_fault(c, SIGSEGV, &si);
|
||||
return 0;
|
||||
}
|
||||
case EXIT_BKPT: {
|
||||
siginfo_t si;
|
||||
memset(&si, 0, sizeof si);
|
||||
si.si_signo = SIGTRAP;
|
||||
si.si_code = 1; /* TRAP_BRKPT */
|
||||
si.si_addr = g2h(c->r[15]);
|
||||
deliver_fault(c, SIGTRAP, &si);
|
||||
return 0;
|
||||
}
|
||||
default: {
|
||||
siginfo_t si;
|
||||
memset(&si, 0, sizeof si);
|
||||
si.si_signo = SIGILL;
|
||||
si.si_code = ILL_ILLOPC;
|
||||
si.si_addr = g2h(c->r[15]);
|
||||
if (opt_verbose) {
|
||||
fprintf(stderr, "a32: undefined instruction %0*x at 0x%08x (%s)\n", in && in->len == 2 ? 4 : 8,
|
||||
in ? in->raw : 0, c->r[15], c->thumb ? "Thumb" : "ARM");
|
||||
}
|
||||
deliver_fault(c, SIGILL, &si);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void interp_loop(a32_cpu *c, a32_thread *t)
|
||||
{
|
||||
insn_t in;
|
||||
while (!t->stop) {
|
||||
if (signal_pending(t)) deliver_signals(c);
|
||||
uint32_t pc = c->r[15];
|
||||
if (pc >= 0xffff0f60u && kuser_helper(c)) continue;
|
||||
t->fault_pc = pc;
|
||||
t->in_guest = 1;
|
||||
a32_decode_at(c, pc, &in);
|
||||
if (opt_trace) {
|
||||
fprintf(stderr, "%08x: %0*x %s\n", pc, in.len == 2 ? 4 : 8, in.raw, in.thumb ? "T" : "A");
|
||||
}
|
||||
int r = a32_exec(c, &in);
|
||||
t->in_guest = 0;
|
||||
c->insn_count++;
|
||||
if (r) handle_exit(c, r, &in);
|
||||
}
|
||||
}
|
||||
|
||||
int run_guest(a32_cpu *c)
|
||||
{
|
||||
a32_thread *t = g_self;
|
||||
/* the fault recovery point of an outer run (this one is nested inside a hypercall) */
|
||||
sigjmp_buf outer;
|
||||
memcpy(&outer, &t->fault_jmp, sizeof outer);
|
||||
if (sigsetjmp(t->fault_jmp, 1)) {
|
||||
/* a guest memory access faulted; the faulting instruction has not completed */
|
||||
t->in_guest = 0;
|
||||
jit_fault_cleanup(t);
|
||||
siginfo_t si;
|
||||
memcpy(&si, (const void *)&t->fault_info, sizeof si);
|
||||
deliver_fault(c, t->fault_sig, &si);
|
||||
}
|
||||
if (!opt_interp) {
|
||||
while (!t->stop) {
|
||||
int r = jit_run(c);
|
||||
if (r < 0) break; /* no JIT: fall back to the interpreter */
|
||||
handle_exit(c, r, NULL);
|
||||
if (t->stop) break;
|
||||
if (signal_pending(t)) deliver_signals(c);
|
||||
}
|
||||
if (!t->stop) opt_interp = 1;
|
||||
}
|
||||
if (!t->stop) interp_loop(c, t);
|
||||
t->stop = 0;
|
||||
memcpy(&t->fault_jmp, &outer, sizeof outer);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
/* Host (A64) floating-point primitives. AArch32 VFP/NEON and A64 share the IEEE operations, NaN propagation,
|
||||
* flush-to-zero, default-NaN and exception flags, and FPCR/FPSR use the FPSCR bit positions, so each guest
|
||||
* operation is the matching A64 instruction run with the guest's control bits in FPCR. Everything is volatile
|
||||
* inline asm so the compiler can neither fold, reorder nor commute operands (NaN propagation is order dependent). */
|
||||
#ifndef A32_FP_HOST_H
|
||||
#define A32_FP_HOST_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include "cpu.h"
|
||||
|
||||
static inline uint64_t host_fpcr(void) { uint64_t v; __asm__ volatile("mrs %0, fpcr" : "=r"(v)); return v; }
|
||||
static inline void set_host_fpcr(uint64_t v) { __asm__ volatile("msr fpcr, %0" ::"r"(v)); }
|
||||
static inline uint64_t host_fpsr(void) { uint64_t v; __asm__ volatile("mrs %0, fpsr" : "=r"(v)); return v; }
|
||||
static inline void set_host_fpsr(uint64_t v) { __asm__ volatile("msr fpsr, %0" ::"r"(v)); }
|
||||
|
||||
/* Runs guest FP operations with the given control value; flags are collected into the guest's FPSR. */
|
||||
typedef struct { uint64_t fpcr, fpsr; } fp_saved;
|
||||
static inline fp_saved fp_begin(uint32_t ctl)
|
||||
{
|
||||
fp_saved s = {host_fpcr(), host_fpsr()};
|
||||
if (s.fpcr != ctl) set_host_fpcr(ctl);
|
||||
set_host_fpsr(0);
|
||||
return s;
|
||||
}
|
||||
static inline uint32_t fp_end(fp_saved s)
|
||||
{
|
||||
uint32_t f = (uint32_t)host_fpsr() & FPSR_MASK;
|
||||
set_host_fpcr(s.fpcr);
|
||||
set_host_fpsr(s.fpsr);
|
||||
return f;
|
||||
}
|
||||
|
||||
#define FP2(name, ins, T, reg) \
|
||||
static inline T name(T a, T b) \
|
||||
{ \
|
||||
T r; \
|
||||
__asm__ volatile(ins " %" reg "0, %" reg "1, %" reg "2" : "=w"(r) : "w"(a), "w"(b)); \
|
||||
return r; \
|
||||
}
|
||||
#define FP1(name, ins, T, reg) \
|
||||
static inline T name(T a) \
|
||||
{ \
|
||||
T r; \
|
||||
__asm__ volatile(ins " %" reg "0, %" reg "1" : "=w"(r) : "w"(a)); \
|
||||
return r; \
|
||||
}
|
||||
#define FP3(name, ins, T, reg) \
|
||||
static inline T name(T n, T m, T a) \
|
||||
{ \
|
||||
T r; \
|
||||
__asm__ volatile(ins " %" reg "0, %" reg "1, %" reg "2, %" reg "3" : "=w"(r) : "w"(n), "w"(m), "w"(a)); \
|
||||
return r; \
|
||||
}
|
||||
|
||||
typedef float f32;
|
||||
typedef double f64;
|
||||
|
||||
FP2(fadd_s, "fadd", f32, "s") FP2(fadd_d, "fadd", f64, "d")
|
||||
FP2(fsub_s, "fsub", f32, "s") FP2(fsub_d, "fsub", f64, "d")
|
||||
FP2(fmul_s, "fmul", f32, "s") FP2(fmul_d, "fmul", f64, "d")
|
||||
FP2(fdiv_s, "fdiv", f32, "s") FP2(fdiv_d, "fdiv", f64, "d")
|
||||
FP2(fnmul_s, "fnmul", f32, "s") FP2(fnmul_d, "fnmul", f64, "d")
|
||||
FP2(fmax_s, "fmax", f32, "s") FP2(fmax_d, "fmax", f64, "d")
|
||||
FP2(fmin_s, "fmin", f32, "s") FP2(fmin_d, "fmin", f64, "d")
|
||||
FP2(fmaxnm_s, "fmaxnm", f32, "s") FP2(fmaxnm_d, "fmaxnm", f64, "d")
|
||||
FP2(fminnm_s, "fminnm", f32, "s") FP2(fminnm_d, "fminnm", f64, "d")
|
||||
FP2(fabd_s, "fabd", f32, "s")
|
||||
FP2(frecps_s, "frecps", f32, "s") FP2(frsqrts_s, "frsqrts", f32, "s")
|
||||
FP1(fneg_s, "fneg", f32, "s") FP1(fneg_d, "fneg", f64, "d")
|
||||
FP1(fabs_s, "fabs", f32, "s") FP1(fabs_d, "fabs", f64, "d")
|
||||
FP1(fsqrt_s, "fsqrt", f32, "s") FP1(fsqrt_d, "fsqrt", f64, "d")
|
||||
FP1(frintn_s, "frintn", f32, "s") FP1(frintn_d, "frintn", f64, "d")
|
||||
FP1(frintp_s, "frintp", f32, "s") FP1(frintp_d, "frintp", f64, "d")
|
||||
FP1(frintm_s, "frintm", f32, "s") FP1(frintm_d, "frintm", f64, "d")
|
||||
FP1(frintz_s, "frintz", f32, "s") FP1(frintz_d, "frintz", f64, "d")
|
||||
FP1(frinta_s, "frinta", f32, "s") FP1(frinta_d, "frinta", f64, "d")
|
||||
FP1(frinti_s, "frinti", f32, "s") FP1(frinti_d, "frinti", f64, "d")
|
||||
FP1(frintx_s, "frintx", f32, "s") FP1(frintx_d, "frintx", f64, "d")
|
||||
FP1(frecpe_s, "frecpe", f32, "s") FP1(frsqrte_s, "frsqrte", f32, "s")
|
||||
FP3(fmadd_s, "fmadd", f32, "s") FP3(fmadd_d, "fmadd", f64, "d")
|
||||
FP3(fmsub_s, "fmsub", f32, "s") FP3(fmsub_d, "fmsub", f64, "d")
|
||||
FP3(fnmadd_s, "fnmadd", f32, "s") FP3(fnmadd_d, "fnmadd", f64, "d")
|
||||
FP3(fnmsub_s, "fnmsub", f32, "s") FP3(fnmsub_d, "fnmsub", f64, "d")
|
||||
|
||||
static inline f32 u2f(uint32_t v) { union { uint32_t u; f32 f; } x = {v}; return x.f; }
|
||||
static inline uint32_t f2u(f32 v) { union { f32 f; uint32_t u; } x = {v}; return x.u; }
|
||||
static inline f64 u2d(uint64_t v) { union { uint64_t u; f64 f; } x = {v}; return x.f; }
|
||||
static inline uint64_t d2u(f64 v) { union { f64 f; uint64_t u; } x = {v}; return x.u; }
|
||||
|
||||
/* NZCV of an FP compare (A64 FCMP/FCMPE set the same flags as AArch32 VCMP). */
|
||||
static inline uint32_t fcmp_s(f32 a, f32 b, int e)
|
||||
{
|
||||
uint64_t f;
|
||||
if (e) __asm__ volatile("fcmpe %s1, %s2\n\tmrs %0, nzcv" : "=r"(f) : "w"(a), "w"(b) : "cc");
|
||||
else __asm__ volatile("fcmp %s1, %s2\n\tmrs %0, nzcv" : "=r"(f) : "w"(a), "w"(b) : "cc");
|
||||
return (uint32_t)f;
|
||||
}
|
||||
static inline uint32_t fcmp_d(f64 a, f64 b, int e)
|
||||
{
|
||||
uint64_t f;
|
||||
if (e) __asm__ volatile("fcmpe %d1, %d2\n\tmrs %0, nzcv" : "=r"(f) : "w"(a), "w"(b) : "cc");
|
||||
else __asm__ volatile("fcmp %d1, %d2\n\tmrs %0, nzcv" : "=r"(f) : "w"(a), "w"(b) : "cc");
|
||||
return (uint32_t)f;
|
||||
}
|
||||
static inline uint32_t fcmp0_s(f32 a, int e)
|
||||
{
|
||||
uint64_t f;
|
||||
if (e) __asm__ volatile("fcmpe %s1, #0.0\n\tmrs %0, nzcv" : "=r"(f) : "w"(a) : "cc");
|
||||
else __asm__ volatile("fcmp %s1, #0.0\n\tmrs %0, nzcv" : "=r"(f) : "w"(a) : "cc");
|
||||
return (uint32_t)f;
|
||||
}
|
||||
static inline uint32_t fcmp0_d(f64 a, int e)
|
||||
{
|
||||
uint64_t f;
|
||||
if (e) __asm__ volatile("fcmpe %d1, #0.0\n\tmrs %0, nzcv" : "=r"(f) : "w"(a) : "cc");
|
||||
else __asm__ volatile("fcmp %d1, #0.0\n\tmrs %0, nzcv" : "=r"(f) : "w"(a) : "cc");
|
||||
return (uint32_t)f;
|
||||
}
|
||||
|
||||
/* Conversions. rmode: 0 RN, 1 RP, 2 RM, 3 RZ, 6 RA (ties away). */
|
||||
#define CVT_TO_INT(name, T, reg, wreg) \
|
||||
static inline uint32_t name(T a, int rmode, int sgn) \
|
||||
{ \
|
||||
uint32_t r; \
|
||||
switch (rmode * 2 + sgn) { \
|
||||
case 0: __asm__ volatile("fcvtnu %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
case 1: __asm__ volatile("fcvtns %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
case 2: __asm__ volatile("fcvtpu %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
case 3: __asm__ volatile("fcvtps %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
case 4: __asm__ volatile("fcvtmu %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
case 5: __asm__ volatile("fcvtms %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
case 6: __asm__ volatile("fcvtzu %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
case 7: __asm__ volatile("fcvtzs %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
case 12: __asm__ volatile("fcvtau %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
default: __asm__ volatile("fcvtas %w0, %" reg "1" : "=r"(r) : "w"(a)); break; \
|
||||
} \
|
||||
return r; \
|
||||
}
|
||||
CVT_TO_INT(cvt_s2i, f32, "s", "w")
|
||||
CVT_TO_INT(cvt_d2i, f64, "d", "w")
|
||||
|
||||
static inline f32 cvt_i2s(uint32_t v, int sgn)
|
||||
{
|
||||
f32 r;
|
||||
if (sgn) __asm__ volatile("scvtf %s0, %w1" : "=w"(r) : "r"(v));
|
||||
else __asm__ volatile("ucvtf %s0, %w1" : "=w"(r) : "r"(v));
|
||||
return r;
|
||||
}
|
||||
static inline f64 cvt_i2d(uint32_t v, int sgn)
|
||||
{
|
||||
f64 r;
|
||||
if (sgn) __asm__ volatile("scvtf %d0, %w1" : "=w"(r) : "r"(v));
|
||||
else __asm__ volatile("ucvtf %d0, %w1" : "=w"(r) : "r"(v));
|
||||
return r;
|
||||
}
|
||||
static inline f64 cvt_s2d(f32 a) { f64 r; __asm__ volatile("fcvt %d0, %s1" : "=w"(r) : "w"(a)); return r; }
|
||||
static inline f32 cvt_d2s(f64 a) { f32 r; __asm__ volatile("fcvt %s0, %d1" : "=w"(r) : "w"(a)); return r; }
|
||||
static inline uint16_t cvt_s2h(f32 a)
|
||||
{
|
||||
uint32_t r;
|
||||
__asm__ volatile("fcvt h16, %s1\n\tfmov %w0, s16" : "=r"(r) : "w"(a) : "v16");
|
||||
return (uint16_t)r;
|
||||
}
|
||||
static inline uint16_t cvt_d2h(f64 a)
|
||||
{
|
||||
uint32_t r;
|
||||
__asm__ volatile("fcvt h16, %d1\n\tfmov %w0, s16" : "=r"(r) : "w"(a) : "v16");
|
||||
return (uint16_t)r;
|
||||
}
|
||||
static inline f32 cvt_h2s(uint16_t h)
|
||||
{
|
||||
f32 r;
|
||||
__asm__ volatile("fmov s16, %w1\n\tfcvt %s0, h16" : "=w"(r) : "r"((uint32_t)h) : "v16");
|
||||
return r;
|
||||
}
|
||||
static inline f64 cvt_h2d(uint16_t h)
|
||||
{
|
||||
f64 r;
|
||||
__asm__ volatile("fmov s16, %w1\n\tfcvt %d0, h16" : "=w"(r) : "r"((uint32_t)h) : "v16");
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Fixed point with 1..32 fraction bits (0 = plain integer conversion). Round towards zero (to fixed) and with
|
||||
* FPCR rounding (from fixed), like the guest. */
|
||||
static inline uint32_t cvt_s2fix(f32 a, int fbits, int sgn)
|
||||
{
|
||||
f32 scaled = a;
|
||||
if (fbits) {
|
||||
/* multiplying by 2^fbits is exact unless it overflows/underflows, which the integer conversion handles the
|
||||
* same way as FPToFixed (saturation / tiny values truncating to 0) except for flush-to-zero corner cases;
|
||||
* use the A64 fixed-point form instead to stay exact. */
|
||||
uint32_t r;
|
||||
switch (fbits) {
|
||||
#define FB(n) \
|
||||
case n: \
|
||||
if (sgn) __asm__ volatile("fcvtzs %w0, %s1, #" #n : "=r"(r) : "w"(a)); \
|
||||
else __asm__ volatile("fcvtzu %w0, %s1, #" #n : "=r"(r) : "w"(a)); \
|
||||
return r;
|
||||
FB(1) FB(2) FB(3) FB(4) FB(5) FB(6) FB(7) FB(8) FB(9) FB(10) FB(11) FB(12) FB(13) FB(14) FB(15) FB(16)
|
||||
FB(17) FB(18) FB(19) FB(20) FB(21) FB(22) FB(23) FB(24) FB(25) FB(26) FB(27) FB(28) FB(29) FB(30)
|
||||
FB(31) FB(32)
|
||||
#undef FB
|
||||
}
|
||||
}
|
||||
return cvt_s2i(scaled, 3, sgn);
|
||||
}
|
||||
static inline uint32_t cvt_d2fix(f64 a, int fbits, int sgn)
|
||||
{
|
||||
if (fbits) {
|
||||
uint32_t r;
|
||||
switch (fbits) {
|
||||
#define FB(n) \
|
||||
case n: \
|
||||
if (sgn) __asm__ volatile("fcvtzs %w0, %d1, #" #n : "=r"(r) : "w"(a)); \
|
||||
else __asm__ volatile("fcvtzu %w0, %d1, #" #n : "=r"(r) : "w"(a)); \
|
||||
return r;
|
||||
FB(1) FB(2) FB(3) FB(4) FB(5) FB(6) FB(7) FB(8) FB(9) FB(10) FB(11) FB(12) FB(13) FB(14) FB(15) FB(16)
|
||||
FB(17) FB(18) FB(19) FB(20) FB(21) FB(22) FB(23) FB(24) FB(25) FB(26) FB(27) FB(28) FB(29) FB(30)
|
||||
FB(31) FB(32)
|
||||
#undef FB
|
||||
}
|
||||
}
|
||||
return cvt_d2i(a, 3, sgn);
|
||||
}
|
||||
static inline f32 cvt_fix2s(uint32_t v, int fbits, int sgn)
|
||||
{
|
||||
if (fbits) {
|
||||
f32 r;
|
||||
switch (fbits) {
|
||||
#define FB(n) \
|
||||
case n: \
|
||||
if (sgn) __asm__ volatile("scvtf %s0, %w1, #" #n : "=w"(r) : "r"(v)); \
|
||||
else __asm__ volatile("ucvtf %s0, %w1, #" #n : "=w"(r) : "r"(v)); \
|
||||
return r;
|
||||
FB(1) FB(2) FB(3) FB(4) FB(5) FB(6) FB(7) FB(8) FB(9) FB(10) FB(11) FB(12) FB(13) FB(14) FB(15) FB(16)
|
||||
FB(17) FB(18) FB(19) FB(20) FB(21) FB(22) FB(23) FB(24) FB(25) FB(26) FB(27) FB(28) FB(29) FB(30)
|
||||
FB(31) FB(32)
|
||||
#undef FB
|
||||
}
|
||||
}
|
||||
return cvt_i2s(v, sgn);
|
||||
}
|
||||
static inline f64 cvt_fix2d(uint32_t v, int fbits, int sgn)
|
||||
{
|
||||
if (fbits) {
|
||||
f64 r;
|
||||
switch (fbits) {
|
||||
#define FB(n) \
|
||||
case n: \
|
||||
if (sgn) __asm__ volatile("scvtf %d0, %w1, #" #n : "=w"(r) : "r"(v)); \
|
||||
else __asm__ volatile("ucvtf %d0, %w1, #" #n : "=w"(r) : "r"(v)); \
|
||||
return r;
|
||||
FB(1) FB(2) FB(3) FB(4) FB(5) FB(6) FB(7) FB(8) FB(9) FB(10) FB(11) FB(12) FB(13) FB(14) FB(15) FB(16)
|
||||
FB(17) FB(18) FB(19) FB(20) FB(21) FB(22) FB(23) FB(24) FB(25) FB(26) FB(27) FB(28) FB(29) FB(30)
|
||||
FB(31) FB(32)
|
||||
#undef FB
|
||||
}
|
||||
}
|
||||
return cvt_i2d(v, sgn);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,207 @@
|
||||
/* Decoded instruction: the common form of A32 and T32 instructions. Both decoders produce it, the interpreter
|
||||
* executes it and the JIT translates it, so ARM and Thumb share all semantics.
|
||||
*
|
||||
* VFP and Advanced SIMD (NEON) instructions are first rewritten to their A32 encoding (T32 differs only in the
|
||||
* prefix bits), then decoded once by vfp_neon_decode.c. */
|
||||
#ifndef A32_INSN_H
|
||||
#define A32_INSN_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define BITS(x, hi, lo) (((x) >> (lo)) & ((1u << ((hi) - (lo) + 1)) - 1))
|
||||
#define BIT(x, n) (((x) >> (n)) & 1u)
|
||||
|
||||
enum cond { C_EQ, C_NE, C_CS, C_CC, C_MI, C_PL, C_VS, C_VC, C_HI, C_LS, C_GE, C_LT, C_GT, C_LE, C_AL, C_NV };
|
||||
|
||||
enum alu { A_AND, A_EOR, A_SUB, A_RSB, A_ADD, A_ADC, A_SBC, A_RSC, A_TST, A_TEQ, A_CMP, A_CMN, A_ORR, A_MOV, A_BIC,
|
||||
A_MVN, A_ORN };
|
||||
|
||||
enum shift { SH_LSL, SH_LSR, SH_ASR, SH_ROR, SH_RRX };
|
||||
|
||||
enum form {
|
||||
F_IMM, /* immediate operand (imm, immcarry) */
|
||||
F_REG, /* register rm shifted by an immediate (shtype, shimm; LSR/ASR #32 decoded as 32, ROR #0 as RRX) */
|
||||
F_RSR, /* register rm shifted by register rs */
|
||||
};
|
||||
|
||||
enum op {
|
||||
OP_UNDEF, OP_NOP,
|
||||
OP_DP, /* data processing: sub = enum alu, s, rd, rn, form + operand */
|
||||
OP_MOVW, OP_MOVT,
|
||||
OP_MUL, /* sub = enum mul; rd = Rd / RdLo, ra = Ra / RdHi */
|
||||
OP_MULXY, /* halfword multiplies: sub = enum mulxy, flags MF_NHI/MF_MHI */
|
||||
OP_DUALMUL, /* SMUAD/SMUSD/SMLAD/SMLSD/SMLALD/SMLSLD: sub = enum dualmul, flags MF_SWAP */
|
||||
OP_SMMUL, /* SMMUL/SMMLA/SMMLS: sub 0 = mul, 1 = mla, 2 = mls; flags MF_ROUND */
|
||||
OP_USAD8, /* ra == 15: USAD8, else USADA8 */
|
||||
OP_DIV, /* sign: SDIV/UDIV */
|
||||
OP_CLZ, OP_REV, OP_REV16, OP_REVSH, OP_RBIT,
|
||||
OP_EXTEND, /* sub = enum ext, shimm = rotation, rn == 15: no add */
|
||||
OP_PKH, /* sub 0 = PKHBT (LSL), 1 = PKHTB (ASR); shimm */
|
||||
OP_BFX, /* sign; imm = lsb, shimm = width */
|
||||
OP_BFI, /* rn == 15: BFC; imm = lsb, shimm = msb */
|
||||
OP_SAT, /* sign: SSAT/USAT; imm = saturate_to, shtype/shimm = LSL/ASR amount */
|
||||
OP_SAT16, /* sign; imm */
|
||||
OP_QADDSUB, /* sub 0 QADD, 1 QSUB, 2 QDADD, 3 QDSUB */
|
||||
OP_PARALLEL, /* sub = prefix (enum par_prefix) << 4 | op (enum par_op) */
|
||||
OP_SEL,
|
||||
OP_LDST, /* single load/store: flags MF_LOAD, size 1/2/4/8 (LDRD/STRD: ra = Rt2), sign, p/u/w, form */
|
||||
OP_LDM, /* p, u, w, reglist */
|
||||
OP_STM,
|
||||
OP_LDREX, /* size 1/2/4/8 (ra = Rt2); flags MF_ACQREL */
|
||||
OP_STREX, /* rd = status, rm = Rt, ra = Rt2 */
|
||||
OP_LDA, OP_STL, /* load-acquire / store-release (ARMv8): size, rd = Rt (LDA) / rm = Rt (STL) */
|
||||
OP_SWP, /* size 1/4; rd = Rt, rm = Rt2, rn = address */
|
||||
OP_B, /* imm = target address */
|
||||
OP_BL, /* imm = target, stays in the current instruction set */
|
||||
OP_BLX_IMM, /* imm = target, switches instruction set */
|
||||
OP_BX, /* rm */
|
||||
OP_BLX_REG, /* rm */
|
||||
OP_CBZ, /* rn, imm = target, flags MF_NONZERO */
|
||||
OP_TB, /* TBB/TBH: rn, rm, size 1/2 */
|
||||
OP_IT, /* imm = firstcond:mask */
|
||||
OP_SVC, /* imm */
|
||||
OP_BKPT,
|
||||
OP_MRS, /* rd */
|
||||
OP_MSR, /* imm = mask (bit 3 nzcvq, bit 2 g), form F_IMM (imm in reglist field) or rn */
|
||||
OP_MRC, /* rd = Rt, imm = cp15 register id (see CP15_*) */
|
||||
OP_MCR,
|
||||
OP_MRRC, /* rd, ra; imm = id */
|
||||
OP_BARRIER,
|
||||
OP_CLREX,
|
||||
OP_SETEND, /* imm = E bit */
|
||||
OP_CRC32, /* size 1/2/4, flags MF_CRC32C */
|
||||
OP_VFP, /* sub = enum vop; see vfp_neon_decode.c for fields */
|
||||
OP_NEON, /* sub = enum nop */
|
||||
OP_COUNT
|
||||
};
|
||||
|
||||
/* insn.flags */
|
||||
#define MF_LOAD 0x01
|
||||
#define MF_NHI 0x02 /* SMULxy: use top half of Rn */
|
||||
#define MF_MHI 0x04 /* SMULxy/SMLAWy: use top half of Rm */
|
||||
#define MF_SWAP 0x08 /* dual multiply: swap Rm halves (X suffix) */
|
||||
#define MF_ROUND 0x10 /* SMMUL R suffix */
|
||||
#define MF_NONZERO 0x20 /* CBNZ */
|
||||
#define MF_ACQREL 0x40 /* acquire/release variants */
|
||||
#define MF_CRC32C 0x80
|
||||
#define MF_SETFLAGS_IT 0x100 /* (T16) set flags only outside an IT block: resolved by the decoder */
|
||||
#define MF_USER 0x200 /* LDRT/STRT etc. (user mode access, same as normal in user mode) */
|
||||
|
||||
enum mul { M_MUL, M_MLA, M_MLS, M_UMULL, M_UMLAL, M_SMULL, M_SMLAL, M_UMAAL };
|
||||
enum mulxy { MX_SMLA, MX_SMLAW, MX_SMULW, MX_SMLAL, MX_SMUL };
|
||||
enum dualmul { DM_SMLAD, DM_SMLSD, DM_SMLALD, DM_SMLSLD }; /* SMUAD/SMUSD = SMLAD/SMLSD with ra == 15 */
|
||||
enum ext { E_SXTB16, E_SXTB, E_SXTH, E_UXTB16, E_UXTB, E_UXTH };
|
||||
enum par_prefix { PP_S, PP_Q, PP_SH, PP_U, PP_UQ, PP_UH };
|
||||
enum par_op { PO_ADD16, PO_ASX, PO_SAX, PO_SUB16, PO_ADD8, PO_SUB8 };
|
||||
|
||||
enum cp15 { CP15_TPIDRURW, CP15_TPIDRURO, CP15_CNTFRQ, CP15_CNTVCT, CP15_CNTPCT };
|
||||
|
||||
/* VFP operations (insn.sub when op == OP_VFP). dp = double precision. */
|
||||
enum vop {
|
||||
V_MLA, V_MLS, V_NMLA, V_NMLS, V_MUL, V_NMUL, V_ADD, V_SUB, V_DIV, V_FNMA, V_FNMS, V_FMA, V_FMS,
|
||||
V_MOVI, V_MOV, V_ABS, V_NEG, V_SQRT,
|
||||
V_CVT_HALF, /* VCVTB/VCVTT: flags VF_TOP (T), VF_TOHALF (to half precision); dp = double <-> half */
|
||||
V_CMP, /* flags VF_E (VCMPE), VF_ZERO (compare with 0) */
|
||||
V_RINT, /* imm = rounding: 0..3 = RN RP RM RZ, 4 = FPSCR (VRINTR), 5 = exact FPSCR (VRINTX), 6 = ties away (VRINTA) */
|
||||
V_CVT_DS, /* dp: double -> single, else single -> double */
|
||||
V_CVT_I2F, /* VF_SIGNED */
|
||||
V_CVT_F2I, /* VF_SIGNED; imm = rounding as V_RINT (3 = RZ for VCVT, 4 = FPSCR for VCVTR, 6/0/1/2 for VCVTA/N/P/M) */
|
||||
V_CVT_FIX, /* VF_SIGNED, VF_TOFIX, imm = fraction bits, size = 16/32 */
|
||||
V_SEL, /* imm = cond (EQ, VS, GE, GT) */
|
||||
V_MAXNM, V_MINNM,
|
||||
V_MOV_CS, /* core <-> S: rd = Rt, vn = S index, VF_TOCORE */
|
||||
V_MOV_CSS, /* two core <-> two consecutive S: rd = Rt, ra = Rt2, vm = S index */
|
||||
V_MOV_CD, /* two core <-> D: rd = Rt, ra = Rt2, vm = D index */
|
||||
V_MOV_SCALAR, /* core <-> scalar: rd = Rt, vd/vn = D index, imm = lane, size = 1/2/4 bytes, VF_SIGNED, VF_TOCORE */
|
||||
V_DUP, /* core -> all lanes: rd = Rt, vd = D index, q, size = 1/2/4 */
|
||||
V_MSR, /* VMSR FPSCR (imm = system register id), rd = Rt */
|
||||
V_MRS, /* VMRS, rd = Rt (15 = APSR_nzcv) */
|
||||
V_LDST, /* VLDR/VSTR: flags VF_LOAD, rn, imm (signed offset), vd = S or D index */
|
||||
V_LDSTM, /* VLDM/VSTM: VF_LOAD, rn, p/u/w, vd, nregs (count of S or D registers) */
|
||||
V_COUNT
|
||||
};
|
||||
#define VF_E 0x01
|
||||
#define VF_ZERO 0x02
|
||||
#define VF_SIGNED 0x04
|
||||
#define VF_TOFIX 0x08
|
||||
#define VF_TOCORE 0x10
|
||||
#define VF_LOAD 0x20
|
||||
#define VF_TOP 0x40
|
||||
#define VF_TOHALF 0x80
|
||||
|
||||
/* Advanced SIMD operations (insn.sub when op == OP_NEON). Field use is documented per group in
|
||||
* vfp_neon_decode.c; registers vd/vn/vm are D register numbers (a Q register n is D 2n). */
|
||||
enum nop {
|
||||
/* 3 registers, same length (size = log2 element bytes, VF_SIGNED unless U) */
|
||||
N_VHADD, N_VQADD, N_VRHADD, N_VAND, N_VBIC, N_VORR, N_VORN, N_VEOR, N_VBSL, N_VBIT, N_VBIF, N_VHSUB, N_VQSUB,
|
||||
N_VCGT, N_VCGE, N_VSHL, N_VQSHL, N_VRSHL, N_VQRSHL, N_VMAX, N_VMIN, N_VABD, N_VABA, N_VADD, N_VSUB, N_VTST,
|
||||
N_VCEQ, N_VMLA, N_VMLS, N_VMUL, N_VMULP, N_VPMAX, N_VPMIN, N_VQDMULH, N_VQRDMULH, N_VPADD,
|
||||
N_FADD, N_FSUB, N_FPADD, N_FABD, N_FMUL, N_FMLA, N_FMLS, N_FCEQ, N_FCGE, N_FCGT, N_FACGE, N_FACGT, N_FMAX,
|
||||
N_FMIN, N_FPMAX, N_FPMIN, N_FRECPS, N_FRSQRTS, N_FMA, N_FMS, N_FMAXNM, N_FMINNM,
|
||||
/* 3 registers, different lengths (long/wide/narrow) */
|
||||
N_VADDL, N_VADDW, N_VSUBL, N_VSUBW, N_VADDHN, N_VRADDHN, N_VABAL, N_VSUBHN, N_VRSUBHN, N_VABDL, N_VMLAL,
|
||||
N_VMLSL, N_VQDMLAL, N_VQDMLSL, N_VMULL, N_VQDMULL, N_VMULLP,
|
||||
/* 2 registers and a scalar (imm = scalar lane, vm = D register of the scalar) */
|
||||
N_VMLA_S, N_VMLS_S, N_VMLAL_S, N_VMLSL_S, N_VQDMLAL_S, N_VQDMLSL_S, N_VMUL_S, N_VMULL_S, N_VQDMULL_S,
|
||||
N_VQDMULH_S, N_VQRDMULH_S, N_FMLA_S, N_FMLS_S, N_FMUL_S,
|
||||
/* 2 registers and a shift amount (imm) */
|
||||
N_VSHR, N_VSRA, N_VRSHR, N_VRSRA, N_VSRI, N_VSHL_I, N_VSLI, N_VQSHLU_I, N_VQSHL_I, N_VSHRN, N_VRSHRN,
|
||||
N_VQSHRUN, N_VQRSHRUN, N_VQSHRN, N_VQRSHRN, N_VSHLL, N_VMOVL, N_VCVT_FIXF /* float<->fixed, VF_TOFIX */,
|
||||
/* 1 register and a modified immediate (imm64) */
|
||||
N_VMOV_I, N_VORR_I, N_VMVN_I, N_VBIC_I,
|
||||
/* 2 registers, miscellaneous */
|
||||
N_VREV64, N_VREV32, N_VREV16, N_VPADDL, N_VCLS, N_VCLZ, N_VCNT, N_VMVN, N_VPADAL, N_VQABS, N_VQNEG,
|
||||
N_VCGT0, N_VCGE0, N_VCEQ0, N_VCLE0, N_VCLT0, N_VABS, N_VNEG, N_FCGT0, N_FCGE0, N_FCEQ0, N_FCLE0, N_FCLT0,
|
||||
N_FABS, N_FNEG, N_VSWP, N_VTRN, N_VUZP, N_VZIP, N_VMOVN, N_VQMOVUN, N_VQMOVN, N_VSHLL_MAX, N_VCVT_HS
|
||||
/* VF_TOHALF: f32 -> f16 narrow, else widen */, N_VRECPE, N_VRSQRTE, N_FRECPE, N_FRSQRTE,
|
||||
N_VCVT_FI /* float <-> int: VF_SIGNED, VF_TOFIX = to integer */, N_FRINT /* imm = rounding */,
|
||||
N_VCVT_RND /* VCVTA/N/P/M: imm = rounding, VF_SIGNED */,
|
||||
N_AESE, N_AESD, N_AESMC, N_AESIMC, N_SHA1H, N_SHA1SU1, N_SHA256SU0,
|
||||
/* other */
|
||||
N_VEXT, /* imm = byte offset */
|
||||
N_VTBL, /* VF_E = VTBX, nregs = list length, vn = first table register */
|
||||
N_VDUP_S, /* imm = lane, size = log2 element */
|
||||
/* 3-same crypto (ARMv8) */
|
||||
N_SHA1C, N_SHA1P, N_SHA1M, N_SHA1SU0, N_SHA256H, N_SHA256H2, N_SHA256SU1,
|
||||
/* element/structure load/store: VF_LOAD; rn, rm (15 = no writeback, 13 = writeback by size, else by Rm);
|
||||
nregs = number of registers, imm = structure type (1-4), size = log2 element, imm2 = lane or -1 for all
|
||||
lanes (VLDn to all lanes uses flags NF_ALL), inc = register spacing */
|
||||
N_VLDST_MULTI, N_VLDST_LANE, N_VLD_ALL,
|
||||
N_COUNT
|
||||
};
|
||||
#define NF_ALL 0x100
|
||||
|
||||
typedef struct insn {
|
||||
uint32_t pc; /* address of the instruction */
|
||||
uint32_t pcval; /* value read from r15 by this instruction (pc + 8, pc + 4, or Align(pc + 4, 4)) */
|
||||
uint32_t raw; /* A32: the word; T32: hw1 << 16 | hw2, or hw1 for 16-bit; VFP/NEON: A32 form */
|
||||
uint16_t op; /* enum op */
|
||||
uint16_t sub;
|
||||
uint16_t flags; /* MF_* or VF_* */
|
||||
uint8_t cond; /* enum cond; Thumb instructions in an IT block get the block's condition */
|
||||
uint8_t len; /* 2 or 4 */
|
||||
uint8_t thumb;
|
||||
uint8_t s; /* sets flags */
|
||||
uint8_t rd, rn, rm, rs, ra;
|
||||
uint8_t shtype, shimm, form, immcarry;
|
||||
uint8_t p, u, w, size, sign;
|
||||
uint8_t unpred; /* encoding is UNPREDICTABLE / CONSTRAINED UNPREDICTABLE (executed best effort) */
|
||||
uint8_t writes_pc; /* instruction can write r15 (ends a block) */
|
||||
/* VFP / NEON */
|
||||
uint8_t vd, vn, vm, q, dp, nregs, inc, esize;
|
||||
uint32_t imm;
|
||||
uint32_t reglist;
|
||||
int32_t imm2;
|
||||
uint64_t imm64;
|
||||
} insn_t;
|
||||
|
||||
int a32_decode(uint32_t w, uint32_t pc, insn_t *i);
|
||||
/* in_it: inside an IT block (Thumb 16-bit flag setting depends on it), itcond: condition from ITSTATE */
|
||||
int t32_decode(const uint16_t *code, uint32_t pc, int in_it, int itcond, insn_t *i);
|
||||
int t32_insn_len(uint16_t hw1);
|
||||
void vfp_neon_decode(uint32_t a32, insn_t *i); /* fills op/sub/fields for a VFP or Advanced SIMD A32 word */
|
||||
const char *op_name(const insn_t *i);
|
||||
|
||||
static inline uint32_t ror32(uint32_t x, unsigned n) { n &= 31; return n ? (x >> n) | (x << (32 - n)) : x; }
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,790 @@
|
||||
/* Integer instruction semantics (ARMv7-A ARM pseudocode). */
|
||||
#include <stdint.h>
|
||||
#include "interp.h"
|
||||
|
||||
static inline uint32_t rreg(const a32_cpu *c, const insn_t *i, unsigned n)
|
||||
{
|
||||
return n == 15 ? i->pcval : c->r[n];
|
||||
}
|
||||
|
||||
static inline unsigned carry(const a32_cpu *c) { return (c->nzcv >> 29) & 1; }
|
||||
|
||||
static void set_nz(a32_cpu *c, uint32_t r)
|
||||
{
|
||||
c->nzcv = (c->nzcv & 0x30000000u) | (r & CPSR_N) | (r ? 0 : CPSR_Z);
|
||||
}
|
||||
|
||||
static void set_nzc(a32_cpu *c, uint32_t r, unsigned cy)
|
||||
{
|
||||
c->nzcv = (c->nzcv & CPSR_V) | (r & CPSR_N) | (r ? 0 : CPSR_Z) | (cy << 29);
|
||||
}
|
||||
|
||||
static uint32_t add_with_carry(a32_cpu *c, uint32_t x, uint32_t y, unsigned cin, int setflags)
|
||||
{
|
||||
uint64_t us = (uint64_t)x + y + cin;
|
||||
int64_t ss = (int64_t)(int32_t)x + (int32_t)y + cin;
|
||||
uint32_t r = (uint32_t)us;
|
||||
if (setflags) {
|
||||
c->nzcv = (r & CPSR_N) | (r ? 0 : CPSR_Z) | ((uint32_t)(us >> 32) << 29) |
|
||||
((int64_t)(int32_t)r != ss ? CPSR_V : 0);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
static void branch_write(a32_cpu *c, uint32_t a)
|
||||
{
|
||||
c->r[15] = c->thumb ? a & ~1u : a & ~3u;
|
||||
}
|
||||
|
||||
static void bx_write(a32_cpu *c, uint32_t a)
|
||||
{
|
||||
c->thumb = a & 1;
|
||||
c->r[15] = a & ~1u;
|
||||
}
|
||||
|
||||
static void alu_write_pc(a32_cpu *c, uint32_t a)
|
||||
{
|
||||
if (c->thumb) branch_write(c, a);
|
||||
else bx_write(c, a);
|
||||
}
|
||||
|
||||
/* Shift with carry out; amount already decoded for immediate shifts (LSR/ASR 1..32, RRX). */
|
||||
static uint32_t shift_c(uint32_t v, unsigned type, unsigned amt, unsigned cin, unsigned *cout)
|
||||
{
|
||||
*cout = cin;
|
||||
if (type == SH_RRX) {
|
||||
*cout = v & 1;
|
||||
return (cin << 31) | (v >> 1);
|
||||
}
|
||||
if (amt == 0) return v;
|
||||
switch (type) {
|
||||
case SH_LSL:
|
||||
if (amt < 32) { *cout = (v >> (32 - amt)) & 1; return v << amt; }
|
||||
*cout = amt == 32 ? (v & 1) : 0;
|
||||
return 0;
|
||||
case SH_LSR:
|
||||
if (amt < 32) { *cout = (v >> (amt - 1)) & 1; return v >> amt; }
|
||||
*cout = amt == 32 ? v >> 31 : 0;
|
||||
return 0;
|
||||
case SH_ASR:
|
||||
if (amt < 32) { *cout = (v >> (amt - 1)) & 1; return (uint32_t)((int32_t)v >> amt); }
|
||||
*cout = v >> 31;
|
||||
return (uint32_t)((int32_t)v >> 31);
|
||||
default: { /* ROR */
|
||||
unsigned a = amt & 31;
|
||||
uint32_t r = a ? ror32(v, a) : v;
|
||||
*cout = r >> 31;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Second operand of data processing with its shifter carry out. */
|
||||
static uint32_t operand2(const a32_cpu *c, const insn_t *i, unsigned *cout)
|
||||
{
|
||||
if (i->form == F_IMM) {
|
||||
*cout = i->immcarry ? i->imm >> 31 : carry(c);
|
||||
return i->imm;
|
||||
}
|
||||
uint32_t m = rreg(c, i, i->rm);
|
||||
if (i->form == F_REG) return shift_c(m, i->shtype, i->shimm, carry(c), cout);
|
||||
return shift_c(m, i->shtype, rreg(c, i, i->rs) & 0xff, carry(c), cout);
|
||||
}
|
||||
|
||||
static int exec_dp(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned cy;
|
||||
uint32_t op2 = operand2(c, i, &cy), n = rreg(c, i, i->rn), r;
|
||||
int s = i->s, logical = 0, write = 1;
|
||||
switch (i->sub) {
|
||||
case A_AND: r = n & op2; logical = 1; break;
|
||||
case A_EOR: r = n ^ op2; logical = 1; break;
|
||||
case A_SUB: r = add_with_carry(c, n, ~op2, 1, s); break;
|
||||
case A_RSB: r = add_with_carry(c, ~n, op2, 1, s); break;
|
||||
case A_ADD: r = add_with_carry(c, n, op2, 0, s); break;
|
||||
case A_ADC: r = add_with_carry(c, n, op2, carry(c), s); break;
|
||||
case A_SBC: r = add_with_carry(c, n, ~op2, carry(c), s); break;
|
||||
case A_RSC: r = add_with_carry(c, ~n, op2, carry(c), s); break;
|
||||
case A_TST: r = n & op2; logical = 1; write = 0; break;
|
||||
case A_TEQ: r = n ^ op2; logical = 1; write = 0; break;
|
||||
case A_CMP: r = add_with_carry(c, n, ~op2, 1, 1); write = 0; break;
|
||||
case A_CMN: r = add_with_carry(c, n, op2, 0, 1); write = 0; break;
|
||||
case A_ORR: r = n | op2; logical = 1; break;
|
||||
case A_MOV: r = op2; logical = 1; break;
|
||||
case A_BIC: r = n & ~op2; logical = 1; break;
|
||||
case A_MVN: r = ~op2; logical = 1; break;
|
||||
default: r = n | ~op2; logical = 1; break; /* ORN */
|
||||
}
|
||||
if (logical && s) set_nzc(c, r, cy);
|
||||
if (write) {
|
||||
if (i->rd == 15) {
|
||||
alu_write_pc(c, r);
|
||||
return 1;
|
||||
}
|
||||
c->r[i->rd] = r;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int32_t sat_s(int64_t v, unsigned bits, int *sat)
|
||||
{
|
||||
int64_t hi = ((int64_t)1 << (bits - 1)) - 1, lo = -((int64_t)1 << (bits - 1));
|
||||
if (v > hi) { *sat = 1; return (int32_t)hi; }
|
||||
if (v < lo) { *sat = 1; return (int32_t)lo; }
|
||||
return (int32_t)v;
|
||||
}
|
||||
|
||||
static uint32_t sat_u(int64_t v, unsigned bits, int *sat)
|
||||
{
|
||||
int64_t hi = bits >= 32 ? 0xffffffffll : (((int64_t)1 << bits) - 1);
|
||||
if (v > hi) { *sat = 1; return (uint32_t)hi; }
|
||||
if (v < 0) { *sat = 1; return 0; }
|
||||
return (uint32_t)v;
|
||||
}
|
||||
|
||||
static void exec_mul(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t n = c->r[i->rn], m = c->r[i->rm];
|
||||
switch (i->sub) {
|
||||
case M_MUL: case M_MLA: case M_MLS: {
|
||||
uint32_t r = n * m;
|
||||
if (i->sub == M_MLA) r += c->r[i->ra];
|
||||
if (i->sub == M_MLS) r = c->r[i->ra] - r;
|
||||
c->r[i->rd] = r;
|
||||
if (i->s) set_nz(c, r);
|
||||
return;
|
||||
}
|
||||
default: {
|
||||
uint64_t r;
|
||||
switch (i->sub) {
|
||||
case M_UMULL: r = (uint64_t)n * m; break;
|
||||
case M_SMULL: r = (uint64_t)((int64_t)(int32_t)n * (int32_t)m); break;
|
||||
case M_UMLAL: r = (uint64_t)n * m + ((uint64_t)c->r[i->rd] << 32 | c->r[i->ra]); break;
|
||||
case M_SMLAL: r = (uint64_t)((int64_t)(int32_t)n * (int32_t)m) + ((uint64_t)c->r[i->rd] << 32 | c->r[i->ra]); break;
|
||||
default: r = (uint64_t)n * m + c->r[i->rd] + c->r[i->ra]; break; /* UMAAL */
|
||||
}
|
||||
c->r[i->ra] = (uint32_t)r;
|
||||
c->r[i->rd] = (uint32_t)(r >> 32);
|
||||
if (i->s) {
|
||||
c->nzcv = (c->nzcv & 0x30000000u) | ((uint32_t)(r >> 32) & CPSR_N) | (r ? 0 : CPSR_Z);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static inline int32_t half(uint32_t v, int hi) { return hi ? (int16_t)(v >> 16) : (int16_t)v; }
|
||||
|
||||
static void exec_mulxy(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t n = c->r[i->rn], m = c->r[i->rm];
|
||||
int32_t a16 = half(n, i->flags & MF_NHI), b16 = half(m, i->flags & MF_MHI);
|
||||
int sat = 0;
|
||||
switch (i->sub) {
|
||||
case MX_SMUL:
|
||||
c->r[i->rd] = (uint32_t)(a16 * b16);
|
||||
break;
|
||||
case MX_SMLA: {
|
||||
int64_t r = (int64_t)(a16 * b16) + (int32_t)c->r[i->ra];
|
||||
c->r[i->rd] = (uint32_t)r;
|
||||
if (r != (int32_t)r) c->q = 1;
|
||||
break;
|
||||
}
|
||||
case MX_SMULW:
|
||||
c->r[i->rd] = (uint32_t)(((int64_t)(int32_t)n * b16) >> 16);
|
||||
break;
|
||||
case MX_SMLAW: {
|
||||
int64_t r = (((int64_t)(int32_t)n * b16) >> 16) + (int32_t)c->r[i->ra];
|
||||
c->r[i->rd] = (uint32_t)r;
|
||||
if (r != (int32_t)r) c->q = 1;
|
||||
break;
|
||||
}
|
||||
default: { /* SMLAL<x><y>: rd = RdHi, ra = RdLo */
|
||||
uint64_t acc = (uint64_t)c->r[i->rd] << 32 | c->r[i->ra];
|
||||
acc += (uint64_t)(int64_t)(a16 * b16);
|
||||
c->r[i->ra] = (uint32_t)acc;
|
||||
c->r[i->rd] = (uint32_t)(acc >> 32);
|
||||
break;
|
||||
}
|
||||
}
|
||||
(void)sat;
|
||||
}
|
||||
|
||||
static void exec_dualmul(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t n = c->r[i->rn], m = c->r[i->rm];
|
||||
if (i->flags & MF_SWAP) m = ror32(m, 16);
|
||||
int64_t p1 = (int64_t)(int16_t)n * (int16_t)m, p2 = (int64_t)(int16_t)(n >> 16) * (int16_t)(m >> 16);
|
||||
int sub = i->sub == DM_SMLSD || i->sub == DM_SMLSLD;
|
||||
int64_t r = sub ? p1 - p2 : p1 + p2;
|
||||
if (i->sub == DM_SMLAD || i->sub == DM_SMLSD) {
|
||||
if (i->ra != 15) r += (int32_t)c->r[i->ra];
|
||||
c->r[i->rd] = (uint32_t)r;
|
||||
if (r != (int32_t)r) c->q = 1;
|
||||
} else {
|
||||
uint64_t acc = ((uint64_t)c->r[i->rd] << 32 | c->r[i->ra]) + (uint64_t)r;
|
||||
c->r[i->ra] = (uint32_t)acc;
|
||||
c->r[i->rd] = (uint32_t)(acc >> 32);
|
||||
}
|
||||
}
|
||||
|
||||
static void exec_smmul(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
int64_t p = (int64_t)(int32_t)c->r[i->rn] * (int32_t)c->r[i->rm];
|
||||
int64_t r;
|
||||
uint64_t a = (uint64_t)c->r[i->ra] << 32;
|
||||
if (i->sub == 0) r = p;
|
||||
else if (i->sub == 1) r = (int64_t)(a + (uint64_t)p);
|
||||
else r = (int64_t)(a - (uint64_t)p);
|
||||
if (i->flags & MF_ROUND) r = (int64_t)((uint64_t)r + 0x80000000u);
|
||||
c->r[i->rd] = (uint32_t)((uint64_t)r >> 32);
|
||||
}
|
||||
|
||||
static uint32_t extend(const insn_t *i, uint32_t m, uint32_t n, int add)
|
||||
{
|
||||
uint32_t v = ror32(m, i->shimm);
|
||||
switch (i->sub) {
|
||||
case E_SXTB: return (add ? n : 0) + (uint32_t)(int8_t)v;
|
||||
case E_SXTH: return (add ? n : 0) + (uint32_t)(int16_t)v;
|
||||
case E_UXTB: return (add ? n : 0) + (v & 0xff);
|
||||
case E_UXTH: return (add ? n : 0) + (v & 0xffff);
|
||||
case E_SXTB16: {
|
||||
uint32_t lo = (uint32_t)(int8_t)v, hi = (uint32_t)(int8_t)(v >> 16);
|
||||
if (add) lo += n, hi += n >> 16;
|
||||
return (lo & 0xffff) | hi << 16;
|
||||
}
|
||||
default: {
|
||||
uint32_t lo = v & 0xff, hi = (v >> 16) & 0xff;
|
||||
if (add) lo += n, hi += n >> 16;
|
||||
return (lo & 0xffff) | hi << 16;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t parallel(a32_cpu *c, unsigned sub, uint32_t n, uint32_t m)
|
||||
{
|
||||
unsigned pre = sub >> 4, op = sub & 15;
|
||||
int bits = (op == PO_ADD8 || op == PO_SUB8) ? 8 : 16, lanes = 32 / bits;
|
||||
int sgn = pre == PP_S || pre == PP_Q || pre == PP_SH;
|
||||
uint32_t r = 0, ge = 0, mask = (1u << bits) - 1;
|
||||
for (int k = 0; k < lanes; k++) {
|
||||
int64_t a, b, v;
|
||||
/* ASX: lane 0 = n.lo - m.hi, lane 1 = n.hi + m.lo; SAX: lane 0 = n.lo + m.hi, lane 1 = n.hi - m.lo */
|
||||
int mk = k, add;
|
||||
switch (op) {
|
||||
case PO_ADD16: case PO_ADD8: add = 1; break;
|
||||
case PO_SUB16: case PO_SUB8: add = 0; break;
|
||||
case PO_ASX: mk = 1 - k; add = k == 1; break;
|
||||
default: mk = 1 - k; add = k == 0; break;
|
||||
}
|
||||
uint32_t ua = (n >> (k * bits)) & mask, ub = (m >> (mk * bits)) & mask;
|
||||
if (sgn) {
|
||||
a = bits == 8 ? (int8_t)ua : (int16_t)ua;
|
||||
b = bits == 8 ? (int8_t)ub : (int16_t)ub;
|
||||
} else {
|
||||
a = ua;
|
||||
b = ub;
|
||||
}
|
||||
v = add ? a + b : a - b;
|
||||
int satd = 0;
|
||||
int64_t out;
|
||||
switch (pre) {
|
||||
case PP_S: out = v; if (v >= 0) ge |= ((1u << (bits / 8)) - 1) << (k * bits / 8); break;
|
||||
case PP_U:
|
||||
out = v;
|
||||
if (add ? v >= (1ll << bits) : v >= 0) ge |= ((1u << (bits / 8)) - 1) << (k * bits / 8);
|
||||
break;
|
||||
case PP_Q: out = sat_s(v, bits, &satd); break;
|
||||
case PP_UQ: out = sat_u(v, bits, &satd); break;
|
||||
default: out = v >> 1; break; /* SH / UH: halving (arithmetic shift of the exact result) */
|
||||
}
|
||||
r |= ((uint32_t)out & mask) << (k * bits);
|
||||
}
|
||||
if (pre == PP_S || pre == PP_U) c->ge = ge;
|
||||
return r;
|
||||
}
|
||||
|
||||
static int ldst(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t base = rreg(c, i, i->rn), off;
|
||||
if (i->form == F_IMM) {
|
||||
off = i->imm;
|
||||
} else {
|
||||
unsigned cy;
|
||||
off = shift_c(rreg(c, i, i->rm), i->shtype, i->shimm, carry(c), &cy);
|
||||
}
|
||||
uint32_t oaddr = i->u ? base + off : base - off;
|
||||
uint32_t addr = i->p ? oaddr : base;
|
||||
if (i->flags & MF_LOAD) {
|
||||
uint32_t v, v2 = 0;
|
||||
switch (i->size) {
|
||||
case 1: v = i->sign ? (uint32_t)(int8_t)ld8(addr) : ld8(addr); break;
|
||||
case 2: v = i->sign ? (uint32_t)(int16_t)ld16(addr) : ld16(addr); break;
|
||||
case 4: v = ld32(addr); break;
|
||||
default: v = ld32(addr); v2 = ld32(addr + 4); break;
|
||||
}
|
||||
if (i->w) c->r[i->rn] = oaddr;
|
||||
if (i->size == 8) {
|
||||
c->r[i->rd] = v;
|
||||
c->r[i->ra] = v2;
|
||||
} else if (i->rd == 15) {
|
||||
bx_write(c, v);
|
||||
return 1;
|
||||
} else {
|
||||
c->r[i->rd] = v;
|
||||
}
|
||||
} else {
|
||||
uint32_t v = rreg(c, i, i->rd);
|
||||
switch (i->size) {
|
||||
case 1: st8(addr, (uint8_t)v); break;
|
||||
case 2: st16(addr, (uint16_t)v); break;
|
||||
case 4: st32(addr, v); break;
|
||||
default: st32(addr, v); st32(addr + 4, rreg(c, i, i->ra)); break;
|
||||
}
|
||||
if (i->w) c->r[i->rn] = oaddr;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ldm_stm(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t base = c->r[i->rn], n = __builtin_popcount(i->reglist);
|
||||
uint32_t start, wb;
|
||||
if (i->u) {
|
||||
start = i->p ? base + 4 : base;
|
||||
wb = base + 4 * n;
|
||||
} else {
|
||||
start = i->p ? base - 4 * n : base - 4 * n + 4;
|
||||
wb = base - 4 * n;
|
||||
}
|
||||
uint32_t a = start;
|
||||
if (i->op == OP_STM) {
|
||||
for (int r = 0; r < 16; r++) {
|
||||
if (!(i->reglist & (1u << r))) continue;
|
||||
st32(a, r == 15 ? i->pcval : c->r[r]);
|
||||
a += 4;
|
||||
}
|
||||
if (i->w) c->r[i->rn] = wb;
|
||||
return 0;
|
||||
}
|
||||
uint32_t vals[16];
|
||||
for (int r = 0; r < 16; r++) {
|
||||
if (!(i->reglist & (1u << r))) continue;
|
||||
vals[r] = ld32(a);
|
||||
a += 4;
|
||||
}
|
||||
if (i->w) c->r[i->rn] = wb;
|
||||
for (int r = 0; r < 15; r++)
|
||||
if (i->reglist & (1u << r)) c->r[r] = vals[r];
|
||||
if (i->reglist & 0x8000) {
|
||||
bx_write(c, vals[15]);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static uint32_t load_sized(uint32_t a, unsigned size, int order)
|
||||
{
|
||||
switch (size) {
|
||||
case 1: return __atomic_load_n((uint8_t *)g2h(a), order);
|
||||
case 2: return __atomic_load_n((uint16_t *)g2h(a), order);
|
||||
default: return __atomic_load_n((uint32_t *)g2h(a), order);
|
||||
}
|
||||
}
|
||||
|
||||
static void store_sized(uint32_t a, unsigned size, uint32_t v, int order)
|
||||
{
|
||||
switch (size) {
|
||||
case 1: __atomic_store_n((uint8_t *)g2h(a), (uint8_t)v, order); break;
|
||||
case 2: __atomic_store_n((uint16_t *)g2h(a), (uint16_t)v, order); break;
|
||||
default: __atomic_store_n((uint32_t *)g2h(a), v, order); break;
|
||||
}
|
||||
}
|
||||
|
||||
static void exec_ldrex(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t a = c->r[i->rn] + i->imm;
|
||||
int order = (i->flags & MF_ACQREL) ? __ATOMIC_ACQUIRE : __ATOMIC_RELAXED;
|
||||
if (i->size == 8) {
|
||||
uint64_t v = __atomic_load_n((uint64_t *)g2h(a), order);
|
||||
c->r[i->rd] = (uint32_t)v;
|
||||
c->r[i->ra] = (uint32_t)(v >> 32);
|
||||
c->excl_val = v;
|
||||
} else {
|
||||
uint32_t v = load_sized(a, i->size, order);
|
||||
c->r[i->rd] = v;
|
||||
c->excl_val = v;
|
||||
}
|
||||
c->excl_addr = a;
|
||||
c->excl_valid = i->size;
|
||||
}
|
||||
|
||||
static void exec_strex(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t a = c->r[i->rn] + i->imm;
|
||||
int ok = 0;
|
||||
int order = (i->flags & MF_ACQREL) ? __ATOMIC_SEQ_CST : __ATOMIC_SEQ_CST;
|
||||
if (c->excl_valid == i->size && c->excl_addr == a) {
|
||||
switch (i->size) {
|
||||
case 1: {
|
||||
uint8_t e = (uint8_t)c->excl_val;
|
||||
ok = __atomic_compare_exchange_n((uint8_t *)g2h(a), &e, (uint8_t)c->r[i->rm], 0, order, __ATOMIC_RELAXED);
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
uint16_t e = (uint16_t)c->excl_val;
|
||||
ok = __atomic_compare_exchange_n((uint16_t *)g2h(a), &e, (uint16_t)c->r[i->rm], 0, order, __ATOMIC_RELAXED);
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
uint32_t e = (uint32_t)c->excl_val;
|
||||
ok = __atomic_compare_exchange_n((uint32_t *)g2h(a), &e, c->r[i->rm], 0, order, __ATOMIC_RELAXED);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
uint64_t e = c->excl_val, v = (uint64_t)c->r[i->ra] << 32 | c->r[i->rm];
|
||||
ok = __atomic_compare_exchange_n((uint64_t *)g2h(a), &e, v, 0, order, __ATOMIC_RELAXED);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
c->excl_valid = 0;
|
||||
c->r[i->rd] = !ok;
|
||||
}
|
||||
|
||||
static uint32_t crc32_update(uint32_t crc, uint32_t v, unsigned bytes, int castagnoli)
|
||||
{
|
||||
uint32_t poly = castagnoli ? 0x82f63b78u : 0xedb88320u;
|
||||
for (unsigned b = 0; b < bytes; b++) {
|
||||
crc ^= (v >> (8 * b)) & 0xff;
|
||||
for (int k = 0; k < 8; k++) crc = (crc >> 1) ^ (poly & (0u - (crc & 1)));
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
static inline uint64_t read_cntvct(void)
|
||||
{
|
||||
uint64_t v;
|
||||
__asm__ volatile("mrs %0, cntvct_el0" : "=r"(v));
|
||||
return v;
|
||||
}
|
||||
|
||||
static inline uint64_t read_cntfrq(void)
|
||||
{
|
||||
uint64_t v;
|
||||
__asm__ volatile("mrs %0, cntfrq_el0" : "=r"(v));
|
||||
return v;
|
||||
}
|
||||
|
||||
static int exec_body(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t next = i->pc + i->len;
|
||||
switch (i->op) {
|
||||
case OP_NOP:
|
||||
case OP_IT:
|
||||
break;
|
||||
case OP_DP:
|
||||
if (exec_dp(c, i)) return EXIT_NONE;
|
||||
break;
|
||||
case OP_MOVW:
|
||||
c->r[i->rd] = i->imm;
|
||||
break;
|
||||
case OP_MOVT:
|
||||
c->r[i->rd] = (c->r[i->rd] & 0xffff) | i->imm << 16;
|
||||
break;
|
||||
case OP_MUL:
|
||||
exec_mul(c, i);
|
||||
break;
|
||||
case OP_MULXY:
|
||||
exec_mulxy(c, i);
|
||||
break;
|
||||
case OP_DUALMUL:
|
||||
exec_dualmul(c, i);
|
||||
break;
|
||||
case OP_SMMUL:
|
||||
exec_smmul(c, i);
|
||||
break;
|
||||
case OP_USAD8: {
|
||||
uint32_t n = c->r[i->rn], m = c->r[i->rm], s = 0;
|
||||
for (int k = 0; k < 32; k += 8) {
|
||||
int d = (int)((n >> k) & 0xff) - (int)((m >> k) & 0xff);
|
||||
s += d < 0 ? -d : d;
|
||||
}
|
||||
if (i->ra != 15) s += c->r[i->ra];
|
||||
c->r[i->rd] = s;
|
||||
break;
|
||||
}
|
||||
case OP_DIV: {
|
||||
uint32_t n = c->r[i->rn], m = c->r[i->rm], r;
|
||||
if (m == 0) r = 0;
|
||||
else if (i->sign) r = (n == 0x80000000u && m == 0xffffffffu) ? n : (uint32_t)((int32_t)n / (int32_t)m);
|
||||
else r = n / m;
|
||||
c->r[i->rd] = r;
|
||||
break;
|
||||
}
|
||||
case OP_CLZ: {
|
||||
uint32_t m = c->r[i->rm];
|
||||
c->r[i->rd] = m ? __builtin_clz(m) : 32;
|
||||
break;
|
||||
}
|
||||
case OP_REV:
|
||||
c->r[i->rd] = __builtin_bswap32(c->r[i->rm]);
|
||||
break;
|
||||
case OP_REV16: {
|
||||
uint32_t m = c->r[i->rm];
|
||||
c->r[i->rd] = ((m & 0x00ff00ffu) << 8) | ((m >> 8) & 0x00ff00ffu);
|
||||
break;
|
||||
}
|
||||
case OP_REVSH: {
|
||||
uint32_t m = c->r[i->rm];
|
||||
c->r[i->rd] = (uint32_t)(int16_t)(((m & 0xff) << 8) | ((m >> 8) & 0xff));
|
||||
break;
|
||||
}
|
||||
case OP_RBIT: {
|
||||
uint32_t m = c->r[i->rm], r = 0;
|
||||
for (int k = 0; k < 32; k++) r |= ((m >> k) & 1) << (31 - k);
|
||||
c->r[i->rd] = r;
|
||||
break;
|
||||
}
|
||||
case OP_EXTEND:
|
||||
c->r[i->rd] = extend(i, c->r[i->rm], i->rn == 15 ? 0 : c->r[i->rn], i->rn != 15);
|
||||
break;
|
||||
case OP_PKH: {
|
||||
uint32_t n = c->r[i->rn], m = c->r[i->rm];
|
||||
if (i->sub == 0) {
|
||||
c->r[i->rd] = (n & 0xffff) | ((m << i->shimm) & 0xffff0000u);
|
||||
} else {
|
||||
uint32_t s = (uint32_t)((int32_t)m >> (i->shimm >= 32 ? 31 : i->shimm));
|
||||
c->r[i->rd] = (n & 0xffff0000u) | (s & 0xffff);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case OP_BFX: {
|
||||
uint32_t n = c->r[i->rn];
|
||||
unsigned lsb = i->imm, width = i->shimm;
|
||||
if (lsb + width > 32) width = 32 - lsb;
|
||||
uint32_t v = n >> lsb;
|
||||
if (width < 32) {
|
||||
v &= (1u << width) - 1;
|
||||
if (i->sign && (v >> (width - 1)) & 1) v |= ~0u << width;
|
||||
}
|
||||
c->r[i->rd] = v;
|
||||
break;
|
||||
}
|
||||
case OP_BFI: {
|
||||
unsigned lsb = i->imm, msb = i->shimm;
|
||||
if (msb >= lsb) {
|
||||
uint32_t mask = (msb - lsb == 31) ? ~0u : (((1u << (msb - lsb + 1)) - 1) << lsb);
|
||||
uint32_t src = i->rn == 15 ? 0 : c->r[i->rn] << lsb;
|
||||
c->r[i->rd] = (c->r[i->rd] & ~mask) | (src & mask);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case OP_SAT: {
|
||||
unsigned cy;
|
||||
uint32_t v = shift_c(c->r[i->rn], i->shtype, i->shimm, 0, &cy);
|
||||
int sat = 0;
|
||||
if (i->sign) c->r[i->rd] = (uint32_t)sat_s((int32_t)v, i->imm, &sat);
|
||||
else c->r[i->rd] = sat_u((int32_t)v, i->imm, &sat);
|
||||
if (sat) c->q = 1;
|
||||
break;
|
||||
}
|
||||
case OP_SAT16: {
|
||||
uint32_t n = c->r[i->rn];
|
||||
int sat = 0;
|
||||
uint32_t lo, hi;
|
||||
if (i->sign) {
|
||||
lo = (uint32_t)sat_s((int16_t)n, i->imm, &sat);
|
||||
hi = (uint32_t)sat_s((int16_t)(n >> 16), i->imm, &sat);
|
||||
} else {
|
||||
lo = sat_u((int16_t)n, i->imm, &sat);
|
||||
hi = sat_u((int16_t)(n >> 16), i->imm, &sat);
|
||||
}
|
||||
c->r[i->rd] = (lo & 0xffff) | hi << 16;
|
||||
if (sat) c->q = 1;
|
||||
break;
|
||||
}
|
||||
case OP_QADDSUB: {
|
||||
int sat = 0;
|
||||
int64_t m = (int32_t)c->r[i->rm], n = (int32_t)c->r[i->rn];
|
||||
if (i->sub >= 2) n = sat_s(2 * n, 32, &sat);
|
||||
int64_t r = (i->sub & 1) ? m - n : m + n;
|
||||
c->r[i->rd] = (uint32_t)sat_s(r, 32, &sat);
|
||||
if (sat) c->q = 1;
|
||||
break;
|
||||
}
|
||||
case OP_PARALLEL:
|
||||
c->r[i->rd] = parallel(c, i->sub, c->r[i->rn], c->r[i->rm]);
|
||||
break;
|
||||
case OP_SEL: {
|
||||
uint32_t n = c->r[i->rn], m = c->r[i->rm], r = 0;
|
||||
for (int k = 0; k < 4; k++) r |= ((c->ge >> k) & 1 ? n : m) & (0xffu << (8 * k));
|
||||
c->r[i->rd] = r;
|
||||
break;
|
||||
}
|
||||
case OP_LDST:
|
||||
if (ldst(c, i)) return EXIT_NONE;
|
||||
break;
|
||||
case OP_LDM:
|
||||
case OP_STM:
|
||||
if (ldm_stm(c, i)) return EXIT_NONE;
|
||||
break;
|
||||
case OP_LDREX:
|
||||
exec_ldrex(c, i);
|
||||
break;
|
||||
case OP_STREX:
|
||||
exec_strex(c, i);
|
||||
break;
|
||||
case OP_LDA:
|
||||
c->r[i->rd] = load_sized(c->r[i->rn], i->size, __ATOMIC_ACQUIRE);
|
||||
break;
|
||||
case OP_STL:
|
||||
store_sized(c->r[i->rn], i->size, c->r[i->rm], __ATOMIC_RELEASE);
|
||||
break;
|
||||
case OP_SWP: {
|
||||
uint32_t a = c->r[i->rn], v = c->r[i->rm];
|
||||
if (i->size == 1) c->r[i->rd] = __atomic_exchange_n((uint8_t *)g2h(a), (uint8_t)v, __ATOMIC_SEQ_CST);
|
||||
else c->r[i->rd] = __atomic_exchange_n((uint32_t *)g2h(a), v, __ATOMIC_SEQ_CST);
|
||||
break;
|
||||
}
|
||||
case OP_B:
|
||||
c->r[15] = i->imm;
|
||||
return EXIT_NONE;
|
||||
case OP_BL:
|
||||
c->r[14] = c->thumb ? next | 1 : next;
|
||||
c->r[15] = i->imm;
|
||||
return EXIT_NONE;
|
||||
case OP_BLX_IMM:
|
||||
c->r[14] = c->thumb ? next | 1 : next;
|
||||
c->thumb ^= 1;
|
||||
c->r[15] = i->imm;
|
||||
return EXIT_NONE;
|
||||
case OP_BX:
|
||||
bx_write(c, rreg(c, i, i->rm));
|
||||
return EXIT_NONE;
|
||||
case OP_BLX_REG: {
|
||||
uint32_t t = rreg(c, i, i->rm);
|
||||
c->r[14] = c->thumb ? next | 1 : next;
|
||||
bx_write(c, t);
|
||||
return EXIT_NONE;
|
||||
}
|
||||
case OP_CBZ:
|
||||
if ((c->r[i->rn] != 0) == !!(i->flags & MF_NONZERO)) {
|
||||
c->r[15] = i->imm;
|
||||
return EXIT_NONE;
|
||||
}
|
||||
break;
|
||||
case OP_TB: {
|
||||
uint32_t base = rreg(c, i, i->rn), idx = c->r[i->rm];
|
||||
uint32_t off = i->size == 1 ? ld8(base + idx) : ld16(base + 2 * idx);
|
||||
c->r[15] = i->pcval + 2 * off;
|
||||
return EXIT_NONE;
|
||||
}
|
||||
case OP_SVC:
|
||||
c->svc_imm = i->imm;
|
||||
c->r[15] = next;
|
||||
return EXIT_SVC;
|
||||
case OP_BKPT:
|
||||
c->r[15] = i->pc;
|
||||
return EXIT_BKPT;
|
||||
case OP_MRS:
|
||||
c->r[i->rd] = cpu_apsr(c) | 0x10;
|
||||
break;
|
||||
case OP_MSR: {
|
||||
uint32_t v = i->form == F_IMM ? i->reglist : c->r[i->rn];
|
||||
if (i->imm & 8) {
|
||||
c->nzcv = v & 0xf0000000u;
|
||||
c->q = (v >> 27) & 1;
|
||||
}
|
||||
if (i->imm & 4) c->ge = (v >> 16) & 0xf;
|
||||
break;
|
||||
}
|
||||
case OP_MRC:
|
||||
switch (i->imm) {
|
||||
case CP15_TPIDRURO: c->r[i->rd] = c->tpidruro; break;
|
||||
case CP15_TPIDRURW: c->r[i->rd] = c->tpidrurw; break;
|
||||
default: c->r[i->rd] = (uint32_t)read_cntfrq(); break;
|
||||
}
|
||||
break;
|
||||
case OP_MCR:
|
||||
if (i->imm == CP15_TPIDRURW) c->tpidrurw = c->r[i->rd];
|
||||
break;
|
||||
case OP_MRRC: {
|
||||
uint64_t v = read_cntvct();
|
||||
c->r[i->rd] = (uint32_t)v;
|
||||
c->r[i->ra] = (uint32_t)(v >> 32);
|
||||
break;
|
||||
}
|
||||
case OP_BARRIER:
|
||||
__atomic_thread_fence(__ATOMIC_SEQ_CST);
|
||||
break;
|
||||
case OP_CLREX:
|
||||
c->excl_valid = 0;
|
||||
break;
|
||||
case OP_SETEND:
|
||||
if (i->imm) {
|
||||
c->r[15] = i->pc;
|
||||
return EXIT_UNDEF; /* big-endian data accesses are not supported */
|
||||
}
|
||||
break;
|
||||
case OP_CRC32: {
|
||||
uint32_t v = c->r[i->rm];
|
||||
c->r[i->rd] = crc32_update(c->r[i->rn], v, i->size, i->flags & MF_CRC32C);
|
||||
break;
|
||||
}
|
||||
case OP_VFP: {
|
||||
int r = a32_exec_vfp(c, i);
|
||||
if (r) {
|
||||
c->r[15] = i->pc;
|
||||
return r;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case OP_NEON: {
|
||||
int r = a32_exec_neon(c, i);
|
||||
if (r) {
|
||||
c->r[15] = i->pc;
|
||||
return r;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
c->r[15] = i->pc;
|
||||
return EXIT_UNDEF;
|
||||
}
|
||||
c->r[15] = next;
|
||||
return EXIT_NONE;
|
||||
}
|
||||
|
||||
int a32_exec(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint32_t it = c->itstate;
|
||||
int r;
|
||||
if (i->op == OP_UNDEF && (i->cond == C_AL || cond_pass(c->nzcv, i->cond))) {
|
||||
/* an UNDEFINED instruction in an IT block that fails its condition is skipped (IMPLEMENTATION DEFINED;
|
||||
* qemu does the same) */
|
||||
c->r[15] = i->pc;
|
||||
return EXIT_UNDEF;
|
||||
}
|
||||
if (i->cond != C_AL && !cond_pass(c->nzcv, i->cond)) {
|
||||
c->r[15] = i->pc + i->len;
|
||||
r = EXIT_NONE;
|
||||
} else {
|
||||
r = exec_body(c, i);
|
||||
}
|
||||
if (i->thumb) {
|
||||
if (i->op == OP_IT && (i->cond == C_AL || r == EXIT_NONE)) c->itstate = i->imm;
|
||||
else if (it) c->itstate = (r == EXIT_UNDEF || r == EXIT_BKPT) ? it : itstate_advance(it);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
int a32_decode_at(const a32_cpu *c, uint32_t pc, insn_t *i)
|
||||
{
|
||||
if (!c->thumb) return a32_decode(ld32(pc), pc, i);
|
||||
uint16_t hw[2];
|
||||
hw[0] = ld16(pc);
|
||||
if (t32_insn_len(hw[0]) == 4) hw[1] = ld16(pc + 2);
|
||||
int in_it = (c->itstate & 0xf) != 0;
|
||||
int itcond = (c->itstate >> 4) | ((c->itstate & 0xf) == 8 ? 0x100 : 0);
|
||||
return t32_decode(hw, pc, in_it, itcond, i);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/* Reference interpreter: executes one decoded instruction on the CPU state. It defines the semantics; the JIT
|
||||
* calls it for instructions it does not translate itself. */
|
||||
#ifndef A32_INTERP_H
|
||||
#define A32_INTERP_H
|
||||
|
||||
#include <string.h>
|
||||
#include "cpu.h"
|
||||
#include "insn.h"
|
||||
|
||||
/* Executes i (condition included), sets r[15] to the next instruction and advances ITSTATE.
|
||||
* Returns an enum exit_reason (EXIT_NONE to continue). */
|
||||
int a32_exec(a32_cpu *c, const insn_t *i);
|
||||
int a32_exec_vfp(a32_cpu *c, const insn_t *i);
|
||||
int a32_exec_neon(a32_cpu *c, const insn_t *i);
|
||||
|
||||
/* Decodes the instruction at r[15] in the current state (ARM/Thumb, ITSTATE). */
|
||||
int a32_decode_at(const a32_cpu *c, uint32_t pc, insn_t *i);
|
||||
|
||||
static inline int cond_pass(uint32_t nzcv, unsigned cond)
|
||||
{
|
||||
unsigned n = nzcv >> 31, z = (nzcv >> 30) & 1, cy = (nzcv >> 29) & 1, v = (nzcv >> 28) & 1;
|
||||
int r;
|
||||
switch (cond >> 1) {
|
||||
case 0: r = z; break;
|
||||
case 1: r = cy; break;
|
||||
case 2: r = n; break;
|
||||
case 3: r = v; break;
|
||||
case 4: r = cy && !z; break;
|
||||
case 5: r = n == v; break;
|
||||
case 6: r = !z && n == v; break;
|
||||
default: return 1;
|
||||
}
|
||||
return (cond & 1) ? !r : r;
|
||||
}
|
||||
|
||||
static inline uint32_t itstate_advance(uint32_t it)
|
||||
{
|
||||
return (it & 7) == 0 ? 0 : ((it & 0xe0) | ((it << 1) & 0x1f));
|
||||
}
|
||||
|
||||
/* Guest memory is identity mapped into the low 4 GiB of the host address space. */
|
||||
static inline void *g2h(uint32_t a) { return (void *)(uintptr_t)a; }
|
||||
static inline uint8_t ld8(uint32_t a) { return *(volatile uint8_t *)g2h(a); }
|
||||
static inline uint16_t ld16(uint32_t a) { uint16_t v; memcpy(&v, g2h(a), 2); return v; }
|
||||
static inline uint32_t ld32(uint32_t a) { uint32_t v; memcpy(&v, g2h(a), 4); return v; }
|
||||
static inline uint64_t ld64(uint32_t a) { uint64_t v; memcpy(&v, g2h(a), 8); return v; }
|
||||
static inline void st8(uint32_t a, uint8_t v) { *(volatile uint8_t *)g2h(a) = v; }
|
||||
static inline void st16(uint32_t a, uint16_t v) { memcpy(g2h(a), &v, 2); }
|
||||
static inline void st32(uint32_t a, uint32_t v) { memcpy(g2h(a), &v, 4); }
|
||||
static inline void st64(uint32_t a, uint64_t v) { memcpy(g2h(a), &v, 8); }
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,802 @@
|
||||
/* Advanced SIMD (NEON) semantics. Sources are copied out before the destination is written, so overlapping
|
||||
* registers behave like the ARM pseudocode. Floating-point lanes use the "standard FPSCR value" (DN, FZ, round to
|
||||
* nearest; AHP from FPSCR) like every Advanced SIMD floating-point instruction. */
|
||||
#include <string.h>
|
||||
#include "interp.h"
|
||||
#include "fp_host.h"
|
||||
|
||||
typedef __int128 i128;
|
||||
|
||||
/* ---------------------------------------------------------------- register buffers */
|
||||
|
||||
static void vload(const a32_cpu *c, unsigned reg, unsigned nd, uint8_t *buf)
|
||||
{
|
||||
for (unsigned k = 0; k < nd; k++) memcpy(buf + 8 * k, &c->d[(reg + k) & 31], 8);
|
||||
}
|
||||
|
||||
static void vstore(a32_cpu *c, unsigned reg, unsigned nd, const uint8_t *buf)
|
||||
{
|
||||
for (unsigned k = 0; k < nd; k++) memcpy(&c->d[(reg + k) & 31], buf + 8 * k, 8);
|
||||
}
|
||||
|
||||
static inline uint64_t getu(const uint8_t *b, unsigned idx, unsigned es)
|
||||
{
|
||||
switch (es) {
|
||||
case 0: return b[idx];
|
||||
case 1: { uint16_t v; memcpy(&v, b + 2 * idx, 2); return v; }
|
||||
case 2: { uint32_t v; memcpy(&v, b + 4 * idx, 4); return v; }
|
||||
default: { uint64_t v; memcpy(&v, b + 8 * idx, 8); return v; }
|
||||
}
|
||||
}
|
||||
|
||||
static inline int64_t gets(const uint8_t *b, unsigned idx, unsigned es)
|
||||
{
|
||||
switch (es) {
|
||||
case 0: return (int8_t)b[idx];
|
||||
case 1: return (int16_t)getu(b, idx, 1);
|
||||
case 2: return (int32_t)getu(b, idx, 2);
|
||||
default: return (int64_t)getu(b, idx, 3);
|
||||
}
|
||||
}
|
||||
|
||||
/* lane value, sign- or zero-extended (128 bits so unsigned 64-bit lanes stay positive) */
|
||||
static inline i128 get(const uint8_t *b, unsigned idx, unsigned es, int sgn)
|
||||
{
|
||||
return sgn ? (i128)gets(b, idx, es) : (i128)getu(b, idx, es);
|
||||
}
|
||||
|
||||
static inline void put(uint8_t *b, unsigned idx, unsigned es, uint64_t v)
|
||||
{
|
||||
switch (es) {
|
||||
case 0: b[idx] = (uint8_t)v; break;
|
||||
case 1: { uint16_t x = (uint16_t)v; memcpy(b + 2 * idx, &x, 2); break; }
|
||||
case 2: { uint32_t x = (uint32_t)v; memcpy(b + 4 * idx, &x, 4); break; }
|
||||
default: memcpy(b + 8 * idx, &v, 8); break;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- saturation helpers */
|
||||
|
||||
static __thread int qc; /* cumulative saturation (FPSCR.QC) of the current instruction */
|
||||
|
||||
static inline i128 smax_of(unsigned es) { return ((i128)1 << (8 * (1u << es) - 1)) - 1; }
|
||||
static inline i128 smin_of(unsigned es) { return -((i128)1 << (8 * (1u << es) - 1)); }
|
||||
static inline i128 umax_of(unsigned es) { return ((i128)1 << (8 * (1u << es))) - 1; }
|
||||
|
||||
static inline uint64_t sat(i128 v, unsigned es, int sgn)
|
||||
{
|
||||
i128 hi = sgn ? smax_of(es) : umax_of(es), lo = sgn ? smin_of(es) : 0;
|
||||
if (v > hi) { qc = 1; return (uint64_t)hi; }
|
||||
if (v < lo) { qc = 1; return (uint64_t)lo; }
|
||||
return (uint64_t)v;
|
||||
}
|
||||
|
||||
static inline uint64_t emask(unsigned es) { return es == 3 ? ~0ull : ((1ull << (8u << es)) - 1); }
|
||||
|
||||
/* Shift by a signed amount (VSHL/VQSHL/VRSHL/VQRSHL register forms and immediate forms). */
|
||||
static uint64_t shift_any(i128 val, int shift, unsigned es, int sgn, int round, int saturate)
|
||||
{
|
||||
unsigned bits = 8u << es;
|
||||
i128 v = val, r;
|
||||
(void)sgn;
|
||||
if (shift >= 0) {
|
||||
if (v == 0) return 0;
|
||||
if (shift >= (int)bits + 1) {
|
||||
if (!saturate) return 0;
|
||||
r = v < 0 ? -((i128)1 << 100) : ((i128)1 << 100);
|
||||
} else {
|
||||
r = v << shift;
|
||||
}
|
||||
if (saturate) return sat(r, es, sgn);
|
||||
return (uint64_t)r & emask(es);
|
||||
}
|
||||
int n = -shift;
|
||||
if (n > 120) n = 120;
|
||||
if (round) r = (v + ((i128)1 << (n - 1))) >> n;
|
||||
else r = v >> n;
|
||||
if (saturate) return sat(r, es, sgn);
|
||||
return (uint64_t)r & emask(es);
|
||||
}
|
||||
|
||||
static uint64_t polymul(uint64_t a, uint64_t b, unsigned bits)
|
||||
{
|
||||
uint64_t r = 0;
|
||||
for (unsigned k = 0; k < bits; k++)
|
||||
if ((b >> k) & 1) r ^= a << k;
|
||||
return r;
|
||||
}
|
||||
|
||||
static void polymul64(uint64_t a, uint64_t b, uint64_t *lo, uint64_t *hi)
|
||||
{
|
||||
uint64_t l = 0, h = 0;
|
||||
for (unsigned k = 0; k < 64; k++)
|
||||
if ((b >> k) & 1) {
|
||||
l ^= a << k;
|
||||
if (k) h ^= a >> (64 - k);
|
||||
}
|
||||
*lo = l;
|
||||
*hi = h;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- floating point lanes */
|
||||
|
||||
#define FCMPV(name, ins) \
|
||||
static inline uint32_t name(uint32_t a, uint32_t b) \
|
||||
{ \
|
||||
f32 r; \
|
||||
__asm__ volatile(ins " %s0, %s1, %s2" : "=w"(r) : "w"(u2f(a)), "w"(u2f(b))); \
|
||||
return f2u(r); \
|
||||
}
|
||||
FCMPV(fcmeq_v, "fcmeq") FCMPV(fcmge_v, "fcmge") FCMPV(fcmgt_v, "fcmgt") FCMPV(facge_v, "facge")
|
||||
FCMPV(facgt_v, "facgt")
|
||||
#define FCMP0V(name, ins) \
|
||||
static inline uint32_t name(uint32_t a) \
|
||||
{ \
|
||||
f32 r; \
|
||||
__asm__ volatile(ins " %s0, %s1, #0.0" : "=w"(r) : "w"(u2f(a))); \
|
||||
return f2u(r); \
|
||||
}
|
||||
FCMP0V(fcmgt0_v, "fcmgt") FCMP0V(fcmge0_v, "fcmge") FCMP0V(fcmeq0_v, "fcmeq") FCMP0V(fcmle0_v, "fcmle")
|
||||
FCMP0V(fcmlt0_v, "fcmlt")
|
||||
|
||||
static inline int is_inf(uint32_t a) { return (a & 0x7fffffffu) == 0x7f800000u; }
|
||||
static inline int is_zero_or_denorm(uint32_t a) { return (a & 0x7f800000u) == 0; }
|
||||
|
||||
static uint32_t recip_step(uint32_t a, uint32_t b, int rsqrt)
|
||||
{
|
||||
if ((is_inf(a) && is_zero_or_denorm(b)) || (is_inf(b) && is_zero_or_denorm(a))) {
|
||||
if ((a & 0x7fffffffu) && (b & 0x7fffffffu)) set_host_fpsr(host_fpsr() | 0x80); /* input denormal */
|
||||
return rsqrt ? 0x3fc00000u : 0x40000000u;
|
||||
}
|
||||
f32 p = fmul_s(u2f(a), u2f(b));
|
||||
if (rsqrt) return f2u(fdiv_s(fsub_s(u2f(0x40400000u), p), u2f(0x40000000u)));
|
||||
return f2u(fsub_s(u2f(0x40000000u), p));
|
||||
}
|
||||
|
||||
static uint32_t urecpe(uint32_t a)
|
||||
{
|
||||
uint32_t r;
|
||||
__asm__ volatile("fmov s16, %w1\n\turecpe v16.2s, v16.2s\n\tfmov %w0, s16" : "=r"(r) : "r"(a) : "v16");
|
||||
return r;
|
||||
}
|
||||
|
||||
static uint32_t ursqrte(uint32_t a)
|
||||
{
|
||||
uint32_t r;
|
||||
__asm__ volatile("fmov s16, %w1\n\tursqrte v16.2s, v16.2s\n\tfmov %w0, s16" : "=r"(r) : "r"(a) : "v16");
|
||||
return r;
|
||||
}
|
||||
|
||||
static uint32_t flt_rint(uint32_t a, unsigned mode)
|
||||
{
|
||||
f32 x = u2f(a);
|
||||
switch (mode) {
|
||||
case 0: return f2u(frintn_s(x));
|
||||
case 1: return f2u(frintp_s(x));
|
||||
case 2: return f2u(frintm_s(x));
|
||||
case 3: return f2u(frintz_s(x));
|
||||
case 5: return f2u(frintx_s(x));
|
||||
default: return f2u(frinta_s(x));
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t f3(unsigned op, uint32_t a, uint32_t b, uint32_t d)
|
||||
{
|
||||
f32 x = u2f(a), y = u2f(b), z = u2f(d);
|
||||
switch (op) {
|
||||
case N_FADD: case N_FPADD: return f2u(fadd_s(x, y));
|
||||
case N_FSUB: return f2u(fsub_s(x, y));
|
||||
case N_FABD: return f2u(fabd_s(x, y));
|
||||
case N_FMUL: case N_FMUL_S: return f2u(fmul_s(x, y));
|
||||
case N_FMLA: case N_FMLA_S: return f2u(fadd_s(z, fmul_s(x, y)));
|
||||
case N_FMLS: case N_FMLS_S: return f2u(fadd_s(z, fneg_s(fmul_s(x, y))));
|
||||
case N_FCEQ: return fcmeq_v(a, b);
|
||||
case N_FCGE: return fcmge_v(a, b);
|
||||
case N_FCGT: return fcmgt_v(a, b);
|
||||
case N_FACGE: return facge_v(a, b);
|
||||
case N_FACGT: return facgt_v(a, b);
|
||||
case N_FMAX: case N_FPMAX: return f2u(fmax_s(x, y));
|
||||
case N_FMIN: case N_FPMIN: return f2u(fmin_s(x, y));
|
||||
case N_FRECPS: return recip_step(a, b, 0);
|
||||
case N_FRSQRTS: return recip_step(a, b, 1);
|
||||
case N_FMA: return f2u(fmadd_s(x, y, z));
|
||||
case N_FMS: return f2u(fmsub_s(x, y, z));
|
||||
case N_FMAXNM: return f2u(fmaxnm_s(x, y));
|
||||
default: return f2u(fminnm_s(x, y));
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- crypto (host instructions) */
|
||||
|
||||
static void crypto(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
uint8_t d[16], n[16], m[16];
|
||||
vload(c, i->vd, 2, d);
|
||||
vload(c, i->vn, 2, n);
|
||||
vload(c, i->vm, 2, m);
|
||||
__asm__ volatile("ld1 {v16.16b}, [%0]\n\tld1 {v17.16b}, [%1]\n\tld1 {v18.16b}, [%2]" ::"r"(d), "r"(n), "r"(m)
|
||||
: "v16", "v17", "v18", "memory");
|
||||
switch (i->sub) {
|
||||
case N_AESE: __asm__ volatile(".arch_extension crypto\n\taese v16.16b, v18.16b" ::: "v16"); break;
|
||||
case N_AESD: __asm__ volatile(".arch_extension crypto\n\taesd v16.16b, v18.16b" ::: "v16"); break;
|
||||
case N_AESMC: __asm__ volatile(".arch_extension crypto\n\taesmc v16.16b, v18.16b" ::: "v16"); break;
|
||||
case N_AESIMC: __asm__ volatile(".arch_extension crypto\n\taesimc v16.16b, v18.16b" ::: "v16"); break;
|
||||
case N_SHA1H: __asm__ volatile(".arch_extension crypto\n\tsha1h s16, s18" ::: "v16"); break;
|
||||
case N_SHA1SU1: __asm__ volatile(".arch_extension crypto\n\tsha1su1 v16.4s, v18.4s" ::: "v16"); break;
|
||||
case N_SHA256SU0: __asm__ volatile(".arch_extension crypto\n\tsha256su0 v16.4s, v18.4s" ::: "v16"); break;
|
||||
case N_SHA1C: __asm__ volatile(".arch_extension crypto\n\tsha1c q16, s17, v18.4s" ::: "v16"); break;
|
||||
case N_SHA1P: __asm__ volatile(".arch_extension crypto\n\tsha1p q16, s17, v18.4s" ::: "v16"); break;
|
||||
case N_SHA1M: __asm__ volatile(".arch_extension crypto\n\tsha1m q16, s17, v18.4s" ::: "v16"); break;
|
||||
case N_SHA1SU0: __asm__ volatile(".arch_extension crypto\n\tsha1su0 v16.4s, v17.4s, v18.4s" ::: "v16"); break;
|
||||
case N_SHA256H: __asm__ volatile(".arch_extension crypto\n\tsha256h q16, q17, v18.4s" ::: "v16"); break;
|
||||
case N_SHA256H2: __asm__ volatile(".arch_extension crypto\n\tsha256h2 q16, q17, v18.4s" ::: "v16"); break;
|
||||
default: __asm__ volatile(".arch_extension crypto\n\tsha256su1 v16.4s, v17.4s, v18.4s" ::: "v16"); break;
|
||||
}
|
||||
__asm__ volatile("st1 {v16.16b}, [%0]" ::"r"(d) : "memory");
|
||||
vstore(c, i->vd, 2, d);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 3 registers, same length */
|
||||
|
||||
static void three_same(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned nd = i->q ? 2 : 1, es = i->esize, lanes = (nd * 8) >> es, op = i->sub;
|
||||
int sgn = (i->flags & VF_SIGNED) != 0;
|
||||
uint8_t n[16], m[16], d[16], r[16];
|
||||
vload(c, i->vn, nd, n);
|
||||
vload(c, i->vm, nd, m);
|
||||
vload(c, i->vd, nd, d);
|
||||
if (op >= N_VAND && op <= N_VBIF) {
|
||||
for (unsigned k = 0; k < nd * 8; k++) {
|
||||
uint8_t a = n[k], b = m[k], x = d[k];
|
||||
switch (op) {
|
||||
case N_VAND: r[k] = a & b; break;
|
||||
case N_VBIC: r[k] = a & ~b; break;
|
||||
case N_VORR: r[k] = a | b; break;
|
||||
case N_VORN: r[k] = a | ~b; break;
|
||||
case N_VEOR: r[k] = a ^ b; break;
|
||||
case N_VBSL: r[k] = (x & a) | (~x & b); break;
|
||||
case N_VBIT: r[k] = (x & ~b) | (a & b); break;
|
||||
default: r[k] = (x & b) | (a & ~b); break;
|
||||
}
|
||||
}
|
||||
vstore(c, i->vd, nd, r);
|
||||
return;
|
||||
}
|
||||
if (op == N_VPMAX || op == N_VPMIN || op == N_VPADD || op == N_FPADD || op == N_FPMAX || op == N_FPMIN) {
|
||||
unsigned half = lanes / 2;
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
const uint8_t *src = k < half ? n : m;
|
||||
unsigned j = 2 * (k % half);
|
||||
uint64_t v;
|
||||
if (op >= N_FADD) {
|
||||
v = f3(op, (uint32_t)getu(src, j, 2), (uint32_t)getu(src, j + 1, 2), 0);
|
||||
} else {
|
||||
i128 a = get(src, j, es, sgn), b = get(src, j + 1, es, sgn);
|
||||
v = op == N_VPADD ? (uint64_t)(a + b) : (uint64_t)((op == N_VPMAX) == (a > b) ? a : b);
|
||||
}
|
||||
put(r, k, es, v);
|
||||
}
|
||||
vstore(c, i->vd, nd, r);
|
||||
return;
|
||||
}
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
i128 a = get(n, k, es, sgn), b = get(m, k, es, sgn), x = get(d, k, es, sgn);
|
||||
uint64_t v;
|
||||
switch (op) {
|
||||
case N_VHADD: v = (uint64_t)((a + b) >> 1); break;
|
||||
case N_VRHADD: v = (uint64_t)((a + b + 1) >> 1); break;
|
||||
case N_VHSUB: v = (uint64_t)((a - b) >> 1); break;
|
||||
case N_VQADD: v = sat(a + b, es, sgn); break;
|
||||
case N_VQSUB: v = sat(a - b, es, sgn); break;
|
||||
case N_VCGT: v = a > b ? ~0ull : 0; break;
|
||||
case N_VCGE: v = a >= b ? ~0ull : 0; break;
|
||||
case N_VSHL: v = shift_any(b, (int8_t)a, es, sgn, 0, 0); break;
|
||||
case N_VQSHL: v = shift_any(b, (int8_t)a, es, sgn, 0, 1); break;
|
||||
case N_VRSHL: v = shift_any(b, (int8_t)a, es, sgn, 1, 0); break;
|
||||
case N_VQRSHL: v = shift_any(b, (int8_t)a, es, sgn, 1, 1); break;
|
||||
case N_VMAX: v = (uint64_t)(a > b ? a : b); break;
|
||||
case N_VMIN: v = (uint64_t)(a < b ? a : b); break;
|
||||
case N_VABD: { i128 t = a - b; v = (uint64_t)(t < 0 ? -t : t); break; }
|
||||
case N_VABA: { i128 t = a - b; v = (uint64_t)x + (uint64_t)(t < 0 ? -t : t); break; }
|
||||
case N_VADD: v = (uint64_t)a + (uint64_t)b; break;
|
||||
case N_VSUB: v = (uint64_t)a - (uint64_t)b; break;
|
||||
case N_VTST: v = ((uint64_t)a & (uint64_t)b & emask(es)) ? ~0ull : 0; break;
|
||||
case N_VCEQ: v = ((uint64_t)(a ^ b) & emask(es)) == 0 ? ~0ull : 0; break;
|
||||
case N_VMLA: v = (uint64_t)x + (uint64_t)a * (uint64_t)b; break;
|
||||
case N_VMLS: v = (uint64_t)x - (uint64_t)a * (uint64_t)b; break;
|
||||
case N_VMUL: v = (uint64_t)a * (uint64_t)b; break;
|
||||
case N_VMULP: v = polymul((uint64_t)a & 0xff, (uint64_t)b & 0xff, 8); break;
|
||||
case N_VQDMULH: v = sat((2 * a * b) >> (8u << es), es, 1); break;
|
||||
case N_VQRDMULH: v = sat((2 * a * b + ((i128)1 << ((8u << es) - 1))) >> (8u << es), es, 1); break;
|
||||
default: v = f3(op, (uint32_t)a, (uint32_t)b, (uint32_t)x); break;
|
||||
}
|
||||
put(r, k, es, v);
|
||||
}
|
||||
vstore(c, i->vd, nd, r);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 3 registers, different lengths */
|
||||
|
||||
static void three_diff(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned es = i->esize, op = i->sub, lanes = 8 >> es;
|
||||
int sgn = (i->flags & VF_SIGNED) != 0;
|
||||
uint8_t n[16], m[16], d[16], r[16];
|
||||
int wide_n = op == N_VADDW || op == N_VSUBW || op == N_VADDHN || op == N_VRADDHN || op == N_VSUBHN ||
|
||||
op == N_VRSUBHN;
|
||||
int narrow = op == N_VADDHN || op == N_VRADDHN || op == N_VSUBHN || op == N_VRSUBHN;
|
||||
vload(c, i->vn, wide_n ? 2 : 1, n);
|
||||
vload(c, i->vm, narrow ? 2 : 1, m);
|
||||
vload(c, i->vd, 2, d);
|
||||
if (op == N_VMULLP && es == 2) { /* VMULL.P64 */
|
||||
uint64_t lo, hi;
|
||||
polymul64(getu(n, 0, 3), getu(m, 0, 3), &lo, &hi);
|
||||
put(r, 0, 3, lo);
|
||||
put(r, 1, 3, hi);
|
||||
vstore(c, i->vd, 2, r);
|
||||
return;
|
||||
}
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
i128 a = wide_n ? get(n, k, es + 1, sgn) : get(n, k, es, sgn);
|
||||
i128 b = narrow ? get(m, k, es + 1, sgn) : get(m, k, es, sgn);
|
||||
i128 x = get(d, k, es + 1, sgn);
|
||||
uint64_t v;
|
||||
unsigned hb = 8u << es;
|
||||
switch (op) {
|
||||
case N_VADDL: case N_VADDW: v = (uint64_t)a + (uint64_t)b; break;
|
||||
case N_VSUBL: case N_VSUBW: v = (uint64_t)a - (uint64_t)b; break;
|
||||
case N_VADDHN: v = ((uint64_t)a + (uint64_t)b) >> hb; break;
|
||||
case N_VRADDHN: v = ((uint64_t)a + (uint64_t)b + (1ull << (hb - 1))) >> hb; break;
|
||||
case N_VSUBHN: v = ((uint64_t)a - (uint64_t)b) >> hb; break;
|
||||
case N_VRSUBHN: v = ((uint64_t)a - (uint64_t)b + (1ull << (hb - 1))) >> hb; break;
|
||||
case N_VABAL: { i128 t = a - b; v = (uint64_t)x + (uint64_t)(t < 0 ? -t : t); break; }
|
||||
case N_VABDL: { i128 t = a - b; v = (uint64_t)(t < 0 ? -t : t); break; }
|
||||
case N_VMLAL: v = (uint64_t)x + (uint64_t)a * (uint64_t)b; break;
|
||||
case N_VMLSL: v = (uint64_t)x - (uint64_t)a * (uint64_t)b; break;
|
||||
case N_VMULL: v = (uint64_t)a * (uint64_t)b; break;
|
||||
case N_VMULLP: v = polymul((uint64_t)a & 0xff, (uint64_t)b & 0xff, 8); break;
|
||||
case N_VQDMULL: v = sat(2 * a * b, es + 1, 1); break;
|
||||
case N_VQDMLAL: { i128 p = (int64_t)sat(2 * a * b, es + 1, 1); v = sat(x + p, es + 1, 1); break; }
|
||||
default: { i128 p = (int64_t)sat(2 * a * b, es + 1, 1); v = sat(x - p, es + 1, 1); break; }
|
||||
}
|
||||
if (narrow) put(r, k, es, v);
|
||||
else put(r, k, es + 1, v);
|
||||
}
|
||||
vstore(c, i->vd, narrow ? 1 : 2, r);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 2 registers and a scalar */
|
||||
|
||||
static void by_scalar(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned es = i->esize, op = i->sub;
|
||||
int sgn = (i->flags & VF_SIGNED) != 0;
|
||||
int lng = op == N_VMLAL_S || op == N_VMLSL_S || op == N_VQDMLAL_S || op == N_VQDMLSL_S || op == N_VMULL_S ||
|
||||
op == N_VQDMULL_S;
|
||||
unsigned nd = lng ? 1 : (i->q ? 2 : 1), lanes = (nd * 8) >> es;
|
||||
uint8_t n[16], sm[8], d[16], r[16];
|
||||
vload(c, i->vn, nd, n);
|
||||
vload(c, i->vm, 1, sm);
|
||||
vload(c, i->vd, lng ? 2 : nd, d);
|
||||
int qd = op == N_VQDMULH_S || op == N_VQRDMULH_S || op == N_VQDMLAL_S || op == N_VQDMLSL_S || op == N_VQDMULL_S;
|
||||
i128 s = get(sm, i->imm, es, sgn || qd);
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
i128 a = get(n, k, es, sgn || qd);
|
||||
uint64_t v;
|
||||
if (op == N_FMLA_S || op == N_FMLS_S || op == N_FMUL_S) {
|
||||
v = f3(op, (uint32_t)a, (uint32_t)s, (uint32_t)getu(d, k, 2));
|
||||
put(r, k, es, v);
|
||||
continue;
|
||||
}
|
||||
if (lng) {
|
||||
i128 x = get(d, k, es + 1, sgn || qd);
|
||||
switch (op) {
|
||||
case N_VMLAL_S: v = (uint64_t)x + (uint64_t)a * (uint64_t)s; break;
|
||||
case N_VMLSL_S: v = (uint64_t)x - (uint64_t)a * (uint64_t)s; break;
|
||||
case N_VMULL_S: v = (uint64_t)a * (uint64_t)s; break;
|
||||
case N_VQDMULL_S: v = sat(2 * a * s, es + 1, 1); break;
|
||||
case N_VQDMLAL_S: { i128 p = (int64_t)sat(2 * a * s, es + 1, 1); v = sat(x + p, es + 1, 1); break; }
|
||||
default: { i128 p = (int64_t)sat(2 * a * s, es + 1, 1); v = sat(x - p, es + 1, 1); break; }
|
||||
}
|
||||
put(r, k, es + 1, v);
|
||||
continue;
|
||||
}
|
||||
uint64_t x = getu(d, k, es);
|
||||
switch (op) {
|
||||
case N_VMLA_S: v = x + (uint64_t)a * (uint64_t)s; break;
|
||||
case N_VMLS_S: v = x - (uint64_t)a * (uint64_t)s; break;
|
||||
case N_VMUL_S: v = (uint64_t)a * (uint64_t)s; break;
|
||||
case N_VQDMULH_S: v = sat((2 * a * s) >> (8u << es), es, 1); break;
|
||||
default: v = sat((2 * a * s + ((i128)1 << ((8u << es) - 1))) >> (8u << es), es, 1); break;
|
||||
}
|
||||
put(r, k, es, v);
|
||||
}
|
||||
vstore(c, i->vd, lng ? 2 : nd, r);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- shifts by immediate */
|
||||
|
||||
static void shift_imm(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned es = i->esize, op = i->sub, sh = i->imm;
|
||||
int sgn = (i->flags & VF_SIGNED) != 0;
|
||||
uint8_t m[16], d[16], r[16];
|
||||
if (op == N_VSHRN || op == N_VRSHRN || op == N_VQSHRUN || op == N_VQRSHRUN || op == N_VQSHRN || op == N_VQRSHRN) {
|
||||
unsigned lanes = 8 >> es;
|
||||
vload(c, i->vm, 2, m);
|
||||
int round = op == N_VRSHRN || op == N_VQRSHRUN || op == N_VQRSHRN;
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
i128 a = get(m, k, es + 1, sgn);
|
||||
i128 v = round ? ((a + ((i128)1 << (sh - 1))) >> sh) : (a >> sh);
|
||||
uint64_t x;
|
||||
if (op == N_VSHRN || op == N_VRSHRN) x = (uint64_t)v;
|
||||
else if (op == N_VQSHRUN || op == N_VQRSHRUN) x = sat(v, es, 0);
|
||||
else x = sat(v, es, sgn);
|
||||
put(r, k, es, x);
|
||||
}
|
||||
vstore(c, i->vd, 1, r);
|
||||
return;
|
||||
}
|
||||
if (op == N_VSHLL || op == N_VMOVL) {
|
||||
unsigned lanes = 8 >> es;
|
||||
vload(c, i->vm, 1, m);
|
||||
for (unsigned k = 0; k < lanes; k++) put(r, k, es + 1, (uint64_t)get(m, k, es, sgn) << sh);
|
||||
vstore(c, i->vd, 2, r);
|
||||
return;
|
||||
}
|
||||
unsigned nd = i->q ? 2 : 1, lanes = (nd * 8) >> es, bits = 8u << es;
|
||||
vload(c, i->vm, nd, m);
|
||||
vload(c, i->vd, nd, d);
|
||||
if (op == N_VCVT_FIXF) {
|
||||
fp_saved s = fp_begin(FPCR_STANDARD | (c->fpcr & FPCR_AHP));
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
uint32_t a = (uint32_t)getu(m, k, 2), v;
|
||||
if (i->flags & VF_TOFIX) v = cvt_s2fix(u2f(a), sh, sgn);
|
||||
else v = f2u(cvt_fix2s(a, sh, sgn));
|
||||
put(r, k, 2, v);
|
||||
}
|
||||
c->fpsr |= fp_end(s);
|
||||
vstore(c, i->vd, nd, r);
|
||||
return;
|
||||
}
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
i128 a = get(m, k, es, sgn);
|
||||
uint64_t x = getu(d, k, es), v, mask;
|
||||
switch (op) {
|
||||
case N_VSHR: v = shift_any(a, -(int)sh, es, sgn, 0, 0); break;
|
||||
case N_VSRA: v = x + shift_any(a, -(int)sh, es, sgn, 0, 0); break;
|
||||
case N_VRSHR: v = shift_any(a, -(int)sh, es, sgn, 1, 0); break;
|
||||
case N_VRSRA: v = x + shift_any(a, -(int)sh, es, sgn, 1, 0); break;
|
||||
case N_VSRI:
|
||||
mask = sh >= bits ? 0 : emask(es) >> sh;
|
||||
v = (x & ~mask) | ((sh >= bits ? 0 : (uint64_t)a >> sh) & mask);
|
||||
break;
|
||||
case N_VSHL_I: v = (uint64_t)a << sh; break;
|
||||
case N_VSLI:
|
||||
mask = (emask(es) << sh) & emask(es);
|
||||
v = (x & ~mask) | (((uint64_t)a << sh) & mask);
|
||||
break;
|
||||
case N_VQSHLU_I: v = sat(a << sh, es, 0); break;
|
||||
default: v = sat(a << sh, es, sgn); break; /* VQSHL imm */
|
||||
}
|
||||
put(r, k, es, v);
|
||||
}
|
||||
vstore(c, i->vd, nd, r);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 2 registers, miscellaneous */
|
||||
|
||||
static void misc(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned nd = i->q ? 2 : 1, es = i->esize, lanes = (nd * 8) >> es, op = i->sub;
|
||||
int sgn = (i->flags & VF_SIGNED) != 0;
|
||||
uint8_t m[16], d[16], r[16];
|
||||
vload(c, i->vm, nd, m);
|
||||
vload(c, i->vd, nd, d);
|
||||
switch (op) {
|
||||
case N_VREV64: case N_VREV32: case N_VREV16: {
|
||||
unsigned cont = op == N_VREV64 ? 8 : op == N_VREV32 ? 4 : 2, per = cont >> es;
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
unsigned base = k - k % per, j = base + (per - 1 - k % per);
|
||||
put(r, k, es, getu(m, j, es));
|
||||
}
|
||||
vstore(c, i->vd, nd, r);
|
||||
return;
|
||||
}
|
||||
case N_VPADDL: case N_VPADAL: {
|
||||
for (unsigned k = 0; k < lanes / 2; k++) {
|
||||
uint64_t v = (uint64_t)get(m, 2 * k, es, sgn) + (uint64_t)get(m, 2 * k + 1, es, sgn);
|
||||
if (op == N_VPADAL) v += getu(d, k, es + 1);
|
||||
put(r, k, es + 1, v);
|
||||
}
|
||||
vstore(c, i->vd, nd, r);
|
||||
return;
|
||||
}
|
||||
case N_VSWP: {
|
||||
vstore(c, i->vd, nd, m);
|
||||
vstore(c, i->vm, nd, d);
|
||||
return;
|
||||
}
|
||||
case N_VTRN: {
|
||||
uint8_t rd[16], rm[16];
|
||||
memcpy(rd, d, sizeof rd);
|
||||
memcpy(rm, m, sizeof rm);
|
||||
for (unsigned k = 0; k + 1 < lanes; k += 2) {
|
||||
put(rd, k + 1, es, getu(m, k, es));
|
||||
put(rm, k, es, getu(d, k + 1, es));
|
||||
}
|
||||
vstore(c, i->vd, nd, rd);
|
||||
vstore(c, i->vm, nd, rm);
|
||||
return;
|
||||
}
|
||||
case N_VUZP: case N_VZIP: {
|
||||
uint8_t cat[32], out[32];
|
||||
memcpy(cat, d, nd * 8);
|
||||
memcpy(cat + nd * 8, m, nd * 8);
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
if (op == N_VUZP) {
|
||||
put(out, k, es, getu(cat, 2 * k, es));
|
||||
put(out, lanes + k, es, getu(cat, 2 * k + 1, es));
|
||||
} else {
|
||||
put(out, 2 * k, es, getu(d, k, es));
|
||||
put(out, 2 * k + 1, es, getu(m, k, es));
|
||||
}
|
||||
}
|
||||
vstore(c, i->vd, nd, out);
|
||||
vstore(c, i->vm, nd, out + nd * 8);
|
||||
return;
|
||||
}
|
||||
case N_VMOVN: case N_VQMOVUN: case N_VQMOVN: {
|
||||
uint8_t w[16];
|
||||
vload(c, i->vm, 2, w);
|
||||
for (unsigned k = 0; k < (8u >> es); k++) {
|
||||
i128 a = get(w, k, es + 1, sgn);
|
||||
uint64_t v = op == N_VMOVN ? (uint64_t)a : op == N_VQMOVUN ? sat(a, es, 0) : sat(a, es, sgn);
|
||||
put(r, k, es, v);
|
||||
}
|
||||
vstore(c, i->vd, 1, r);
|
||||
return;
|
||||
}
|
||||
case N_VSHLL_MAX: {
|
||||
uint8_t s[8];
|
||||
vload(c, i->vm, 1, s);
|
||||
for (unsigned k = 0; k < (8u >> es); k++) put(r, k, es + 1, getu(s, k, es) << i->imm);
|
||||
vstore(c, i->vd, 2, r);
|
||||
return;
|
||||
}
|
||||
case N_VCVT_HS: {
|
||||
fp_saved sv = fp_begin(FPCR_STANDARD | (c->fpcr & FPCR_AHP));
|
||||
uint8_t w[16];
|
||||
if (i->flags & VF_TOHALF) {
|
||||
vload(c, i->vm, 2, w);
|
||||
for (unsigned k = 0; k < 4; k++) put(r, k, 1, cvt_s2h(u2f((uint32_t)getu(w, k, 2))));
|
||||
c->fpsr |= fp_end(sv);
|
||||
vstore(c, i->vd, 1, r);
|
||||
} else {
|
||||
vload(c, i->vm, 1, w);
|
||||
for (unsigned k = 0; k < 4; k++) put(r, k, 2, f2u(cvt_h2s((uint16_t)getu(w, k, 1))));
|
||||
c->fpsr |= fp_end(sv);
|
||||
vstore(c, i->vd, 2, r);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case N_AESE: case N_AESD: case N_AESMC: case N_AESIMC: case N_SHA1H: case N_SHA1SU1: case N_SHA256SU0:
|
||||
crypto(c, i);
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
int fl = (op >= N_FCGT0 && op <= N_FCLT0) || op == N_FRECPE || op == N_FRSQRTE || op == N_VCVT_FI ||
|
||||
op == N_FRINT || op == N_VCVT_RND;
|
||||
fp_saved sv = {0, 0};
|
||||
if (fl) sv = fp_begin(FPCR_STANDARD | (c->fpcr & FPCR_AHP));
|
||||
for (unsigned k = 0; k < lanes; k++) {
|
||||
i128 a = get(m, k, es, op == N_VQABS || op == N_VQNEG || op == N_VABS || op == N_VNEG || op == N_VCLS ||
|
||||
(op >= N_VCGT0 && op <= N_VCLT0));
|
||||
uint64_t ua = getu(m, k, es), v;
|
||||
unsigned bits = 8u << es;
|
||||
switch (op) {
|
||||
case N_VCLS: {
|
||||
uint64_t x = (uint64_t)(a < 0 ? ~a : a) & emask(es);
|
||||
unsigned n = 0;
|
||||
for (int b = bits - 2; b >= 0 && !((x >> b) & 1); b--) n++;
|
||||
v = n;
|
||||
break;
|
||||
}
|
||||
case N_VCLZ: {
|
||||
unsigned n = 0;
|
||||
for (int b = bits - 1; b >= 0 && !((ua >> b) & 1); b--) n++;
|
||||
v = n;
|
||||
break;
|
||||
}
|
||||
case N_VCNT: v = __builtin_popcountll(ua); break;
|
||||
case N_VMVN: v = ~ua; break;
|
||||
case N_VQABS: v = sat(a < 0 ? -a : a, es, 1); break;
|
||||
case N_VQNEG: v = sat(-a, es, 1); break;
|
||||
case N_VCGT0: v = a > 0 ? ~0ull : 0; break;
|
||||
case N_VCGE0: v = a >= 0 ? ~0ull : 0; break;
|
||||
case N_VCEQ0: v = a == 0 ? ~0ull : 0; break;
|
||||
case N_VCLE0: v = a <= 0 ? ~0ull : 0; break;
|
||||
case N_VCLT0: v = a < 0 ? ~0ull : 0; break;
|
||||
case N_VABS: v = (uint64_t)(a < 0 ? -a : a); break;
|
||||
case N_VNEG: v = (uint64_t)-a; break;
|
||||
case N_FCGT0: v = fcmgt0_v((uint32_t)ua); break;
|
||||
case N_FCGE0: v = fcmge0_v((uint32_t)ua); break;
|
||||
case N_FCEQ0: v = fcmeq0_v((uint32_t)ua); break;
|
||||
case N_FCLE0: v = fcmle0_v((uint32_t)ua); break;
|
||||
case N_FCLT0: v = fcmlt0_v((uint32_t)ua); break;
|
||||
case N_FABS: v = ua & 0x7fffffffu; break;
|
||||
case N_FNEG: v = ua ^ 0x80000000u; break;
|
||||
case N_VRECPE: v = urecpe((uint32_t)ua); break;
|
||||
case N_VRSQRTE: v = ursqrte((uint32_t)ua); break;
|
||||
case N_FRECPE: v = f2u(frecpe_s(u2f((uint32_t)ua))); break;
|
||||
case N_FRSQRTE: v = f2u(frsqrte_s(u2f((uint32_t)ua))); break;
|
||||
case N_VCVT_FI:
|
||||
if (i->flags & VF_TOFIX) v = cvt_s2i(u2f((uint32_t)ua), 3, sgn);
|
||||
else v = f2u(cvt_i2s((uint32_t)ua, sgn));
|
||||
break;
|
||||
case N_FRINT: v = flt_rint((uint32_t)ua, i->imm); break;
|
||||
case N_VCVT_RND: v = cvt_s2i(u2f((uint32_t)ua), i->imm, sgn); break;
|
||||
default: v = ua; break;
|
||||
}
|
||||
put(r, k, es, v);
|
||||
}
|
||||
if (fl) c->fpsr |= fp_end(sv);
|
||||
vstore(c, i->vd, nd, r);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- element and structure loads/stores */
|
||||
|
||||
static void ld_el(uint8_t *reg, unsigned idx, unsigned es, uint32_t a)
|
||||
{
|
||||
switch (es) {
|
||||
case 0: put(reg, idx, 0, ld8(a)); break;
|
||||
case 1: put(reg, idx, 1, ld16(a)); break;
|
||||
case 2: put(reg, idx, 2, ld32(a)); break;
|
||||
default: put(reg, idx, 3, ld64(a)); break;
|
||||
}
|
||||
}
|
||||
|
||||
static void st_el(const uint8_t *reg, unsigned idx, unsigned es, uint32_t a)
|
||||
{
|
||||
switch (es) {
|
||||
case 0: st8(a, (uint8_t)getu(reg, idx, 0)); break;
|
||||
case 1: st16(a, (uint16_t)getu(reg, idx, 1)); break;
|
||||
case 2: st32(a, (uint32_t)getu(reg, idx, 2)); break;
|
||||
default: st64(a, getu(reg, idx, 3)); break;
|
||||
}
|
||||
}
|
||||
|
||||
static void ldst_struct(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned es = i->esize, eb = 1u << es, n = i->imm, load = (i->flags & VF_LOAD) != 0;
|
||||
uint32_t a = c->r[i->rn], start = a, total;
|
||||
uint8_t regs[32 * 8];
|
||||
memcpy(regs, c->d, sizeof regs);
|
||||
#define DREG(r) (regs + 8 * ((r) & 31))
|
||||
if (i->sub == N_VLDST_MULTI) {
|
||||
unsigned elements = 8 / eb;
|
||||
if (n == 1) {
|
||||
for (unsigned r = 0; r < i->nregs; r++)
|
||||
for (unsigned e = 0; e < elements; e++, a += eb) {
|
||||
if (load) ld_el(DREG(i->vd + r), e, es, a);
|
||||
else st_el(DREG(i->vd + r), e, es, a);
|
||||
}
|
||||
total = 8 * i->nregs;
|
||||
} else {
|
||||
unsigned regs_per = i->nregs; /* VLD2 with 4 registers: 2 */
|
||||
for (unsigned r = 0; r < regs_per; r++)
|
||||
for (unsigned e = 0; e < elements; e++)
|
||||
for (unsigned s = 0; s < n; s++, a += eb) {
|
||||
unsigned reg = i->vd + r + s * i->inc;
|
||||
if (load) ld_el(DREG(reg), e, es, a);
|
||||
else st_el(DREG(reg), e, es, a);
|
||||
}
|
||||
total = 8 * n * regs_per;
|
||||
}
|
||||
} else if (i->sub == N_VLDST_LANE) {
|
||||
for (unsigned s = 0; s < n; s++, a += eb) {
|
||||
unsigned reg = i->vd + s * i->inc;
|
||||
if (load) ld_el(DREG(reg), i->imm2, es, a);
|
||||
else st_el(DREG(reg), i->imm2, es, a);
|
||||
}
|
||||
total = n * eb;
|
||||
} else { /* to all lanes */
|
||||
unsigned elements = 8 / eb;
|
||||
if (n == 1) {
|
||||
uint8_t tmp[8];
|
||||
ld_el(tmp, 0, es, a);
|
||||
uint64_t v = getu(tmp, 0, es);
|
||||
for (unsigned r = 0; r < i->nregs; r++)
|
||||
for (unsigned e = 0; e < elements; e++) put(DREG(i->vd + r), e, es, v);
|
||||
total = eb;
|
||||
} else {
|
||||
for (unsigned s = 0; s < n; s++, a += eb) {
|
||||
uint8_t tmp[8];
|
||||
ld_el(tmp, 0, es, a);
|
||||
uint64_t v = getu(tmp, 0, es);
|
||||
for (unsigned e = 0; e < elements; e++) put(DREG(i->vd + s * i->inc), e, es, v);
|
||||
}
|
||||
total = n * eb;
|
||||
}
|
||||
}
|
||||
#undef DREG
|
||||
if (load) memcpy(c->d, regs, sizeof regs);
|
||||
if (i->rm != 15) c->r[i->rn] = start + (i->rm == 13 ? total : c->r[i->rm]);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- dispatch */
|
||||
|
||||
int a32_exec_neon(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned op = i->sub;
|
||||
qc = 0;
|
||||
if (op == N_VLDST_MULTI || op == N_VLDST_LANE || op == N_VLD_ALL) {
|
||||
ldst_struct(c, i);
|
||||
return EXIT_NONE;
|
||||
}
|
||||
if (op <= N_FMINNM) {
|
||||
if (op >= N_FADD) {
|
||||
fp_saved s = fp_begin(FPCR_STANDARD | (c->fpcr & FPCR_AHP));
|
||||
three_same(c, i);
|
||||
c->fpsr |= fp_end(s);
|
||||
} else {
|
||||
three_same(c, i);
|
||||
}
|
||||
} else if (op <= N_VMULLP) {
|
||||
three_diff(c, i);
|
||||
} else if (op <= N_FMUL_S) {
|
||||
if (op >= N_FMLA_S) {
|
||||
fp_saved s = fp_begin(FPCR_STANDARD | (c->fpcr & FPCR_AHP));
|
||||
by_scalar(c, i);
|
||||
c->fpsr |= fp_end(s);
|
||||
} else {
|
||||
by_scalar(c, i);
|
||||
}
|
||||
} else if (op <= N_VCVT_FIXF) {
|
||||
shift_imm(c, i);
|
||||
} else if (op <= N_VBIC_I) {
|
||||
unsigned nd = i->q ? 2 : 1;
|
||||
for (unsigned k = 0; k < nd; k++) {
|
||||
uint64_t *d = &c->d[(i->vd + k) & 31];
|
||||
switch (op) {
|
||||
case N_VMOV_I: case N_VMVN_I: *d = i->imm64; break;
|
||||
case N_VORR_I: *d |= i->imm64; break;
|
||||
default: *d &= i->imm64; break;
|
||||
}
|
||||
}
|
||||
} else if (op <= N_SHA256SU0) {
|
||||
misc(c, i);
|
||||
} else if (op == N_VEXT) {
|
||||
unsigned nb = i->q ? 16 : 8;
|
||||
uint8_t n[16], m[16], r[16];
|
||||
vload(c, i->vn, nb / 8, n);
|
||||
vload(c, i->vm, nb / 8, m);
|
||||
for (unsigned k = 0; k < nb; k++) {
|
||||
unsigned j = k + i->imm;
|
||||
r[k] = j < nb ? n[j] : m[j - nb];
|
||||
}
|
||||
vstore(c, i->vd, nb / 8, r);
|
||||
} else if (op == N_VTBL) {
|
||||
uint8_t t[32], m[8], d[8], r[8];
|
||||
vload(c, i->vn, i->nregs, t);
|
||||
vload(c, i->vm, 1, m);
|
||||
vload(c, i->vd, 1, d);
|
||||
for (unsigned k = 0; k < 8; k++) r[k] = m[k] < 8 * i->nregs ? t[m[k]] : ((i->flags & VF_E) ? d[k] : 0);
|
||||
vstore(c, i->vd, 1, r);
|
||||
} else if (op == N_VDUP_S) {
|
||||
uint8_t m[8], r[16];
|
||||
unsigned nd = i->q ? 2 : 1;
|
||||
vload(c, i->vm, 1, m);
|
||||
uint64_t v = getu(m, i->imm, i->esize);
|
||||
for (unsigned k = 0; k < (nd * 8 >> i->esize); k++) put(r, k, i->esize, v);
|
||||
vstore(c, i->vd, nd, r);
|
||||
} else if (op <= N_SHA256SU1) {
|
||||
crypto(c, i);
|
||||
} else {
|
||||
return EXIT_UNDEF;
|
||||
}
|
||||
if (qc) c->fpsr |= FPSR_QC;
|
||||
return EXIT_NONE;
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
/* VFP (scalar floating-point) semantics and VFP register transfers. */
|
||||
#include "interp.h"
|
||||
#include "fp_host.h"
|
||||
|
||||
#define S(n) (cpu_s(c)[n])
|
||||
#define D(n) (c->d[n])
|
||||
|
||||
static inline int rmode_of(const a32_cpu *c) { return (c->fpcr >> FPCR_RMODE_SHIFT) & 3; }
|
||||
|
||||
static void arith(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned d = i->vd, n = i->vn, m = i->vm;
|
||||
if (!i->dp) {
|
||||
f32 a = u2f(S(n)), b = u2f(S(m)), x = u2f(S(d)), r;
|
||||
switch (i->sub) {
|
||||
case V_MLA: r = fadd_s(x, fmul_s(a, b)); break;
|
||||
case V_MLS: r = fadd_s(x, fneg_s(fmul_s(a, b))); break;
|
||||
case V_NMLA: r = fadd_s(fneg_s(x), fneg_s(fmul_s(a, b))); break;
|
||||
case V_NMLS: r = fadd_s(fneg_s(x), fmul_s(a, b)); break;
|
||||
case V_MUL: r = fmul_s(a, b); break;
|
||||
case V_NMUL: r = fneg_s(fmul_s(a, b)); break;
|
||||
case V_ADD: r = fadd_s(a, b); break;
|
||||
case V_SUB: r = fsub_s(a, b); break;
|
||||
case V_DIV: r = fdiv_s(a, b); break;
|
||||
case V_FMA: r = fmadd_s(a, b, x); break;
|
||||
case V_FMS: r = fmsub_s(a, b, x); break;
|
||||
case V_FNMA: r = fnmadd_s(a, b, x); break;
|
||||
case V_FNMS: r = fnmsub_s(a, b, x); break;
|
||||
case V_MAXNM: r = fmaxnm_s(a, b); break;
|
||||
default: r = fminnm_s(a, b); break;
|
||||
}
|
||||
S(d) = f2u(r);
|
||||
} else {
|
||||
f64 a = u2d(D(n)), b = u2d(D(m)), x = u2d(D(d)), r;
|
||||
switch (i->sub) {
|
||||
case V_MLA: r = fadd_d(x, fmul_d(a, b)); break;
|
||||
case V_MLS: r = fadd_d(x, fneg_d(fmul_d(a, b))); break;
|
||||
case V_NMLA: r = fadd_d(fneg_d(x), fneg_d(fmul_d(a, b))); break;
|
||||
case V_NMLS: r = fadd_d(fneg_d(x), fmul_d(a, b)); break;
|
||||
case V_MUL: r = fmul_d(a, b); break;
|
||||
case V_NMUL: r = fneg_d(fmul_d(a, b)); break;
|
||||
case V_ADD: r = fadd_d(a, b); break;
|
||||
case V_SUB: r = fsub_d(a, b); break;
|
||||
case V_DIV: r = fdiv_d(a, b); break;
|
||||
case V_FMA: r = fmadd_d(a, b, x); break;
|
||||
case V_FMS: r = fmsub_d(a, b, x); break;
|
||||
case V_FNMA: r = fnmadd_d(a, b, x); break;
|
||||
case V_FNMS: r = fnmsub_d(a, b, x); break;
|
||||
case V_MAXNM: r = fmaxnm_d(a, b); break;
|
||||
default: r = fminnm_d(a, b); break;
|
||||
}
|
||||
D(d) = d2u(r);
|
||||
}
|
||||
}
|
||||
|
||||
static f32 rint_s(f32 a, unsigned mode)
|
||||
{
|
||||
switch (mode) {
|
||||
case 0: return frintn_s(a);
|
||||
case 1: return frintp_s(a);
|
||||
case 2: return frintm_s(a);
|
||||
case 3: return frintz_s(a);
|
||||
case 4: return frinti_s(a);
|
||||
case 5: return frintx_s(a);
|
||||
default: return frinta_s(a);
|
||||
}
|
||||
}
|
||||
|
||||
static f64 rint_d(f64 a, unsigned mode)
|
||||
{
|
||||
switch (mode) {
|
||||
case 0: return frintn_d(a);
|
||||
case 1: return frintp_d(a);
|
||||
case 2: return frintm_d(a);
|
||||
case 3: return frintz_d(a);
|
||||
case 4: return frinti_d(a);
|
||||
case 5: return frintx_d(a);
|
||||
default: return frinta_d(a);
|
||||
}
|
||||
}
|
||||
|
||||
/* Saturates a 32-bit fixed-point conversion result to 16 bits; reports whether it saturated. */
|
||||
static uint32_t sat16(uint32_t v, int sgn, int *sat)
|
||||
{
|
||||
if (sgn) {
|
||||
int32_t x = (int32_t)v;
|
||||
if (x > 32767) { *sat = 1; return 32767; }
|
||||
if (x < -32768) { *sat = 1; return (uint32_t)-32768; }
|
||||
return v;
|
||||
}
|
||||
if (v > 65535) { *sat = 1; return 65535; }
|
||||
return v;
|
||||
}
|
||||
|
||||
static int fp_ops(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
unsigned d = i->vd, m = i->vm;
|
||||
switch (i->sub) {
|
||||
case V_MOVI:
|
||||
if (i->dp) D(d) = i->imm64;
|
||||
else S(d) = (uint32_t)i->imm64;
|
||||
break;
|
||||
case V_MOV:
|
||||
if (i->dp) D(d) = D(m);
|
||||
else S(d) = S(m);
|
||||
break;
|
||||
case V_ABS:
|
||||
if (i->dp) D(d) = D(m) & ~(1ull << 63);
|
||||
else S(d) = S(m) & ~(1u << 31);
|
||||
break;
|
||||
case V_NEG:
|
||||
if (i->dp) D(d) = D(m) ^ (1ull << 63);
|
||||
else S(d) = S(m) ^ (1u << 31);
|
||||
break;
|
||||
case V_SQRT:
|
||||
if (i->dp) D(d) = d2u(fsqrt_d(u2d(D(m))));
|
||||
else S(d) = f2u(fsqrt_s(u2f(S(m))));
|
||||
break;
|
||||
case V_CVT_HALF: {
|
||||
int top = (i->flags & VF_TOP) != 0;
|
||||
if (i->flags & VF_TOHALF) {
|
||||
uint16_t h = i->dp ? cvt_d2h(u2d(D(m))) : cvt_s2h(u2f(S(m)));
|
||||
S(d) = top ? (S(d) & 0xffff) | (uint32_t)h << 16 : (S(d) & 0xffff0000u) | h;
|
||||
} else {
|
||||
uint16_t h = top ? S(m) >> 16 : S(m) & 0xffff;
|
||||
if (i->dp) D(d) = d2u(cvt_h2d(h));
|
||||
else S(d) = f2u(cvt_h2s(h));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case V_CMP: {
|
||||
int e = (i->flags & VF_E) != 0;
|
||||
uint32_t f;
|
||||
if (i->flags & VF_ZERO) f = i->dp ? fcmp0_d(u2d(D(d)), e) : fcmp0_s(u2f(S(d)), e);
|
||||
else f = i->dp ? fcmp_d(u2d(D(d)), u2d(D(m)), e) : fcmp_s(u2f(S(d)), u2f(S(m)), e);
|
||||
c->fpscr_nzcv = f & 0xf0000000u;
|
||||
break;
|
||||
}
|
||||
case V_RINT:
|
||||
if (i->dp) D(d) = d2u(rint_d(u2d(D(m)), i->imm));
|
||||
else S(d) = f2u(rint_s(u2f(S(m)), i->imm));
|
||||
break;
|
||||
case V_CVT_DS:
|
||||
if (i->dp) S(d) = f2u(cvt_d2s(u2d(D(m))));
|
||||
else D(d) = d2u(cvt_s2d(u2f(S(m))));
|
||||
break;
|
||||
case V_CVT_I2F: {
|
||||
int sgn = (i->flags & VF_SIGNED) != 0;
|
||||
if (i->dp) D(d) = d2u(cvt_i2d(S(m), sgn));
|
||||
else S(d) = f2u(cvt_i2s(S(m), sgn));
|
||||
break;
|
||||
}
|
||||
case V_CVT_F2I: {
|
||||
int sgn = (i->flags & VF_SIGNED) != 0, mode = i->imm == 4 ? rmode_of(c) : i->imm;
|
||||
S(d) = i->dp ? cvt_d2i(u2d(D(m)), mode, sgn) : cvt_s2i(u2f(S(m)), mode, sgn);
|
||||
break;
|
||||
}
|
||||
case V_CVT_FIX: {
|
||||
int sgn = (i->flags & VF_SIGNED) != 0, fb = i->imm;
|
||||
if (i->flags & VF_TOFIX) {
|
||||
uint32_t r = i->dp ? cvt_d2fix(u2d(D(d)), fb, sgn) : cvt_s2fix(u2f(S(d)), fb, sgn);
|
||||
if (i->size == 16) {
|
||||
int sat = 0;
|
||||
r = sat16(r, sgn, &sat);
|
||||
if (sat) set_host_fpsr((host_fpsr() & ~0x10ull) | 1); /* InvalidOp instead of Inexact */
|
||||
r = sgn ? (uint32_t)(int16_t)r : (r & 0xffff);
|
||||
}
|
||||
if (i->dp) D(d) = sgn ? (uint64_t)(int64_t)(int32_t)r : r;
|
||||
else S(d) = r;
|
||||
} else {
|
||||
uint32_t v = i->dp ? (uint32_t)D(d) : S(d);
|
||||
if (i->size == 16) v = sgn ? (uint32_t)(int16_t)v : (v & 0xffff);
|
||||
if (i->dp) D(d) = d2u(cvt_fix2d(v, fb, sgn));
|
||||
else S(d) = f2u(cvt_fix2s(v, fb, sgn));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case V_SEL:
|
||||
if (i->dp) D(d) = cond_pass(c->nzcv, i->imm) ? D(i->vn) : D(m);
|
||||
else S(d) = cond_pass(c->nzcv, i->imm) ? S(i->vn) : S(m);
|
||||
break;
|
||||
default:
|
||||
arith(c, i);
|
||||
break;
|
||||
}
|
||||
return EXIT_NONE;
|
||||
}
|
||||
|
||||
static int transfers(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
switch (i->sub) {
|
||||
case V_MOV_CS:
|
||||
if (i->flags & VF_TOCORE) c->r[i->rd] = S(i->vn);
|
||||
else S(i->vn) = c->r[i->rd];
|
||||
return EXIT_NONE;
|
||||
case V_MOV_CSS:
|
||||
if (i->flags & VF_TOCORE) {
|
||||
c->r[i->rd] = S(i->vm);
|
||||
c->r[i->ra] = S((i->vm + 1) & 31);
|
||||
} else {
|
||||
S(i->vm) = c->r[i->rd];
|
||||
S((i->vm + 1) & 31) = c->r[i->ra];
|
||||
}
|
||||
return EXIT_NONE;
|
||||
case V_MOV_CD:
|
||||
if (i->flags & VF_TOCORE) {
|
||||
c->r[i->rd] = (uint32_t)D(i->vm);
|
||||
c->r[i->ra] = (uint32_t)(D(i->vm) >> 32);
|
||||
} else {
|
||||
D(i->vm) = (uint64_t)c->r[i->ra] << 32 | c->r[i->rd];
|
||||
}
|
||||
return EXIT_NONE;
|
||||
case V_MOV_SCALAR: {
|
||||
unsigned bits = i->size * 8, sh = i->imm * bits;
|
||||
uint64_t mask = (bits == 32 ? 0xffffffffull : ((1ull << bits) - 1)) << sh;
|
||||
if (i->flags & VF_TOCORE) {
|
||||
uint32_t v = (uint32_t)((D(i->vd) & mask) >> sh);
|
||||
if (i->flags & VF_SIGNED) v = bits == 8 ? (uint32_t)(int8_t)v : bits == 16 ? (uint32_t)(int16_t)v : v;
|
||||
c->r[i->rd] = v;
|
||||
} else {
|
||||
D(i->vd) = (D(i->vd) & ~mask) | (((uint64_t)c->r[i->rd] << sh) & mask);
|
||||
}
|
||||
return EXIT_NONE;
|
||||
}
|
||||
case V_DUP: {
|
||||
uint32_t v = c->r[i->rd];
|
||||
uint64_t r = i->size == 1 ? (v & 0xff) * 0x0101010101010101ull
|
||||
: i->size == 2 ? (v & 0xffff) * 0x0001000100010001ull
|
||||
: (uint64_t)v << 32 | v;
|
||||
D(i->vd) = r;
|
||||
if (i->q) D(i->vd + 1) = r;
|
||||
return EXIT_NONE;
|
||||
}
|
||||
case V_MSR:
|
||||
cpu_set_fpscr(c, c->r[i->rd]);
|
||||
return EXIT_NONE;
|
||||
case V_MRS:
|
||||
if (i->rd == 15) c->nzcv = c->fpscr_nzcv;
|
||||
else c->r[i->rd] = cpu_fpscr(c);
|
||||
return EXIT_NONE;
|
||||
case V_LDST: {
|
||||
uint32_t base = i->rn == 15 ? (i->pcval & ~3u) : c->r[i->rn];
|
||||
uint32_t a = i->u ? base + i->imm : base - i->imm;
|
||||
if (i->flags & VF_LOAD) {
|
||||
if (i->dp) D(i->vd) = (uint64_t)ld32(a + 4) << 32 | ld32(a);
|
||||
else S(i->vd) = ld32(a);
|
||||
} else {
|
||||
if (i->dp) {
|
||||
st32(a, (uint32_t)D(i->vd));
|
||||
st32(a + 4, (uint32_t)(D(i->vd) >> 32));
|
||||
} else {
|
||||
st32(a, S(i->vd));
|
||||
}
|
||||
}
|
||||
return EXIT_NONE;
|
||||
}
|
||||
case V_LDSTM: {
|
||||
uint32_t base = i->rn == 15 ? (i->pcval & ~3u) : c->r[i->rn], words = i->imm;
|
||||
uint32_t a = i->u ? base : base - 4 * words;
|
||||
if (i->w) c->r[i->rn] = i->u ? base + 4 * words : base - 4 * words;
|
||||
for (unsigned k = 0; k < i->nregs; k++) {
|
||||
unsigned r = i->vd + k;
|
||||
if (i->dp) {
|
||||
if (r >= 32) break;
|
||||
if (i->flags & VF_LOAD) D(r) = (uint64_t)ld32(a + 4) << 32 | ld32(a);
|
||||
else st32(a, (uint32_t)D(r)), st32(a + 4, (uint32_t)(D(r) >> 32));
|
||||
a += 8;
|
||||
} else {
|
||||
if (r >= 32) break;
|
||||
if (i->flags & VF_LOAD) S(r) = ld32(a);
|
||||
else st32(a, S(r));
|
||||
a += 4;
|
||||
}
|
||||
}
|
||||
return EXIT_NONE;
|
||||
}
|
||||
}
|
||||
return EXIT_UNDEF;
|
||||
}
|
||||
|
||||
int a32_exec_vfp(a32_cpu *c, const insn_t *i)
|
||||
{
|
||||
if (i->sub >= V_MOV_CS) return transfers(c, i);
|
||||
fp_saved s = fp_begin(c->fpcr);
|
||||
int r = fp_ops(c, i);
|
||||
c->fpsr |= fp_end(s);
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/* JIT internals shared by jit.c (blocks, cache, integer instructions) and jit_vfp.c (VFP/NEON). */
|
||||
#ifndef A32_JIT_H
|
||||
#define A32_JIT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include "a64.h"
|
||||
#include "cpu.h"
|
||||
#include "insn.h"
|
||||
|
||||
/* host registers */
|
||||
#define R_CPU 19
|
||||
#define T0 16
|
||||
#define T1 17
|
||||
#define T2 15
|
||||
#define T3 20 /* T3..T6 survive helper calls */
|
||||
#define T4 21
|
||||
#define T5 22
|
||||
#define T6 23
|
||||
|
||||
#define OFF_PC OFF_R(15)
|
||||
#define OFF_THUMB offsetof(a32_cpu, thumb)
|
||||
#define OFF_ITSTATE offsetof(a32_cpu, itstate)
|
||||
#define OFF_EXIT offsetof(a32_cpu, exit_reason)
|
||||
#define OFF_SVC offsetof(a32_cpu, svc_imm)
|
||||
#define OFF_EXIT_STUB offsetof(a32_cpu, exit_stub)
|
||||
#define OFF_HELPERS offsetof(a32_cpu, helper_tab)
|
||||
#define OFF_LOOKUP offsetof(a32_cpu, lookup_tab)
|
||||
#define OFF_INTERRUPT offsetof(a32_cpu, interrupt)
|
||||
#define OFF_LAST_EXIT offsetof(a32_cpu, last_exit)
|
||||
#define OFF_Q offsetof(a32_cpu, q)
|
||||
#define OFF_GE offsetof(a32_cpu, ge)
|
||||
#define OFF_FPSCR_NZCV offsetof(a32_cpu, fpscr_nzcv)
|
||||
#define OFF_FPCR offsetof(a32_cpu, fpcr)
|
||||
#define OFF_FPSR offsetof(a32_cpu, fpsr)
|
||||
#define OFF_TPIDRURO offsetof(a32_cpu, tpidruro)
|
||||
#define OFF_TPIDRURW offsetof(a32_cpu, tpidrurw)
|
||||
#define OFF_EXCL_VALID offsetof(a32_cpu, excl_valid)
|
||||
|
||||
/* helper table indices (cpu->helper_tab) */
|
||||
enum { HELP_EXEC, HELP_COUNT };
|
||||
|
||||
struct jit_block;
|
||||
|
||||
/* A chainable exit: the "b" at insn starts at the stub; once the target is translated it is patched to jump there. */
|
||||
typedef struct jit_site {
|
||||
uint32_t *insn;
|
||||
uint32_t *stub;
|
||||
struct jit_block *owner;
|
||||
struct jit_block *target; /* chained target, or NULL */
|
||||
struct jit_site *next_in; /* list of sites chained into the same target */
|
||||
} jit_site;
|
||||
|
||||
typedef struct jit_block {
|
||||
uint64_t key; /* must stay first: inline lookup reads key and code with one ldp */
|
||||
uint32_t *code;
|
||||
uint32_t *end;
|
||||
uint32_t guest_lo, guest_hi; /* guest bytes covered */
|
||||
struct jit_block *hnext;
|
||||
jit_site *in; /* sites chained into this block */
|
||||
jit_site *sites; /* this block's own chainable exits */
|
||||
int nsites;
|
||||
uint32_t *map_host; /* per guest instruction: first host instruction */
|
||||
uint32_t *map_pc; /* guest pc */
|
||||
uint8_t *map_it; /* ITSTATE before the instruction */
|
||||
uint64_t *map_vc; /* scalar VFP cache state before the instruction (jit_vfp_state) */
|
||||
int nmap;
|
||||
uint8_t thumb, valid;
|
||||
struct jit_block *pnext[2]; /* lists of the blocks on the guest page(s) of guest_lo and guest_hi - 1 */
|
||||
} jit_block;
|
||||
|
||||
#define MAX_STUBS 64
|
||||
typedef struct {
|
||||
int kind; /* STUB_DIRECT, STUB_INDIRECT, STUB_REASON, STUB_ASIS, STUB_HELPER_EXIT */
|
||||
uint32_t *site; /* instruction(s) that branch to the stub (patched once the stub exists) */
|
||||
uint32_t pc;
|
||||
uint8_t thumb, it;
|
||||
uint32_t reason, svc;
|
||||
} jit_stub;
|
||||
enum { STUB_DIRECT, STUB_INDIRECT, STUB_REASON, STUB_ASIS };
|
||||
enum { FPCR_GUEST, FPCR_STD, FPCR_UNKNOWN };
|
||||
|
||||
typedef struct {
|
||||
cbuf cb;
|
||||
jit_block *b;
|
||||
uint32_t b_pc, b_it; /* the block's start (pc, ITSTATE) */
|
||||
uint32_t pc; /* current guest instruction */
|
||||
int thumb;
|
||||
uint32_t it; /* ITSTATE before the current instruction */
|
||||
const insn_t *i;
|
||||
const insn_t *next; /* the following instruction if it is in this block (peepholes), else NULL */
|
||||
int skip_vmrs; /* the previous VCMP already put its flags into NZCV */
|
||||
jit_stub stubs[MAX_STUBS];
|
||||
int nstubs;
|
||||
int ended; /* the block ended (unconditional exit emitted) */
|
||||
int side_exit; /* the instruction emitted a conditional exit and falls through (CBZ) */
|
||||
int fpcr_std; /* host FPCR: FPCR_GUEST, FPCR_STD (Advanced SIMD standard value) or FPCR_UNKNOWN */
|
||||
/* scalar VFP cache in v8-v15 (jit_vfp.c): view 0 = empty, 1 = S register, 2 = D register */
|
||||
struct { uint8_t view, reg, dirty; uint32_t used; } vc[8];
|
||||
uint32_t vc_tick;
|
||||
} jit_ctx;
|
||||
|
||||
/* merges dirty cached VFP values into the pinned Q registers and empties the cache (before exits, helpers and
|
||||
* control-flow splits) */
|
||||
void jit_vfp_flush(jit_ctx *x);
|
||||
void jit_vfp_emit_merges(jit_ctx *x); /* same code, translation-time state unchanged (side exits) */
|
||||
/* encodes the cache state for the fault map (slot k: byte k = dirty << 7 | view << 5 | reg) */
|
||||
uint64_t jit_vfp_state(const jit_ctx *x);
|
||||
|
||||
/* emit helpers (jit.c) */
|
||||
void jx_mov32(cbuf *b, int rd, uint32_t v);
|
||||
void jx_mov64(cbuf *b, int rd, uint64_t v);
|
||||
int jx_src(jit_ctx *x, unsigned guest_reg, int tmp); /* host register holding guest_reg (pc materialized in tmp) */
|
||||
void jx_spill(cbuf *b); /* guest r0-r14 + NZCV -> cpu */
|
||||
void jx_reload(cbuf *b);
|
||||
void jx_call_helper(jit_ctx *x, const insn_t *i); /* full interpreter fallback for one instruction */
|
||||
uint32_t *jx_placeholder(cbuf *b);
|
||||
void jx_patch_bcond(uint32_t *site, int cond, uint32_t *target);
|
||||
void jx_patch_b(uint32_t *site, uint32_t *target);
|
||||
void jx_patch_cbz(uint32_t *site, uint32_t *target);
|
||||
/* exits */
|
||||
void jx_exit_direct(jit_ctx *x, uint32_t pc, int thumb, uint32_t it);
|
||||
void jx_exit_indirect_t0(jit_ctx *x); /* target (bit 0 = Thumb) in w16 */
|
||||
void jx_exit_reason(jit_ctx *x, uint32_t pc, int thumb, uint32_t it, uint32_t reason, uint32_t svc);
|
||||
/* host FPCR = guest VFP control bits / Advanced SIMD standard value (emits nothing if already so) */
|
||||
void jx_fpcr_guest(jit_ctx *x);
|
||||
void jx_fpcr_std(jit_ctx *x);
|
||||
extern int jit_exact_addr;
|
||||
|
||||
/* jit_vfp.c: returns 1 if it emitted native code for the VFP/NEON instruction */
|
||||
int jit_vfp(jit_ctx *x, const insn_t *i);
|
||||
|
||||
extern int jit_stats;
|
||||
#endif
|
||||