Files
DroidDeck/tools/tests/test_lse_emu.py
T
LunaDLandKurt Himebauch 88d44b0dc6 Feat: Improve ARMv8.0 Steam compatibility with LSE emulation (#3720)
* feat: emulate LSE atomics so the Steam client starts on ARMv8.0 CPUs

* fix: keep NZCV across patched LSE min/max stubs and catch st* aliases

* fix: fail the LSE check when objdump fails

* fix: validate the CASP pair on a mismatch in the LSE emulator

* fix: sandboxes switch on the LSE emulator when it is preloaded

* fix: keep the MaliBridge pointer from main

* Handle LSE atomics before preload constructors

* Support early LSE handling in root guest processes

* Fix LSE-Emu signal and patching review findings

* Assert CASP and min/max sites use patched stubs

* Correct patch test statistics regexes

* Validate SIGILL syscall ABI and retain active state on restore failure

* Preserve the previous SIGILL disposition during early install

* Synchronize instruction fetch on generated LSE stubs

* Address LSE-Emu follow-up review findings

* Fix missing LSE signal handler state declarations

* Honor application signal mask when forwarding SIGILL

* Preserve SA_RESETHAND mask during handler forwarding

* Fix LSE opt-out after early handler install

* Avoid recursive SIGILL forwarding during LSE emulation

* Fix LSE SIGILL handler re-entry tracking

* Honor SA_NODEFER in forwarded SIGILL mask

* Preserve nested SIGILL delivery semantics

* Preserve explicit SIGILL mask with SA_NODEFER

* Reduce LSE patch contention across threads

* Guard nested faults before acquiring patch lock

* Fix early SIGILL restore and wake patch waiters

* Preserve libc restorer when restoring application SIGILL

* Wait for concurrent LSE patch instead of skipping

* Fix LSE patch lock release and fork recovery

* Avoid reinstalling the early SIGILL handler

* chore: retrigger CI

* Avoid proc maps reads in concurrent SIGILL patching

* Prevent late IFUNC handler install when emulation is disabled

* Clarify cached mapping lookup

* Move cached map declarations before find_gap

* Default LSE instruction patching to off

* Document conservative LSE emulation default

* Keep LSE instruction patching opt-in in sandbox preload

* Document default and opt-in LSE emulation checks

* Assert LSE patching remains opt-in in sandbox tests

* Align LSE device checks with SDK 34 patching behavior

* Check expected mprotect failures in opt-in device run

* Clarify LSE emulator device validation criteria

* Specify controlled SDK mprotect validation

* fix(lse-emu): publish SIGILL actions atomically

* fix(runtime): honor LSE_EMU=0 before preload

* test(runtime): keep LSE preload disabled when opted out

* fix(runtime): fully honor LSE_EMU=0 opt-out

* test(runtime): verify LSE opt-out removes inherited preload

* fix(runtime): filter inherited LSE preload without preload file

* fix(lse-emu): use bounded signal-safe action snapshots

* fix(runtime): split inherited preloads on spaces and colons

* test(runtime): cover both LSE preload entry orders

* fix(lse-emu): recycle displaced SIGILL snapshots

* fix(preload): preserve colliding path cache entries

* test(lse-emu): report patch failure details

* fix(lse-emu): serialize action snapshot publishers

* fix(lse-emu): fall back to reachable arena mapping

* fix(lse-emu): make signal action publication nonblocking

* refactor(lse-emu): remove obsolete publisher lock

* Fix SIGILL snapshot retirement and honor session LSE opt-out

* Preserve the Java staging API and isolate the SIGILL stress test

* fix(nativeguest): filter LSE preload when disabled

* fix(lse-emu): tighten seccomp and signal setup

* fix(session): preserve active LSE override while staging

* fix(lse-emu): return atomically displaced signal actions

* fix(lse-emu): stage raw signal masks safely

* fix(lse-emu): distinguish seccomp listener success

* fix(lse-emu): publish seccomp veto atomically

* fix(lse-emu): fail closed on RX restore errors

* fix(lse-emu): keep stack-using atomic stubs on trap path

* fix(lse-emu): allow patching with inherited seccomp

* test(lse-emu): cover LDAPR patch path

* test(lse-emu): assert LDAPR-only patching

* fix(nativeguest): filter disabled LSE from preload chains

* docs(lse-emu): define inherited seccomp patch policy

* fix(lse-emu): emulate LDAPR trap fallback

* refactor(lse-emu): remove unused seccomp query

* fix(nativeguest): release filtered preload chain in scope

* test(lse-emu): allow forwarded udf diagnostic

* fix(nativeguest): avoid unsafe preload fallback when disabled

* test(lse-emu): match full zero instruction field

* test(lse-emu): match complete instruction diagnostics

* Keep nested native preloads from duplicating host libraries

* fix(nativeguest): fail exec when disabled preload cannot map

* fix(nativeguest): stop exec when preload mapping fails

* fix(nativeguest): propagate preload filter allocation failures

* Consume only the selected one-shot SIGILL action

* Reclaim abandoned SIGILL action slots after fork

* Revalidate the live file mapping before optional LSE patching

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-12-05 19:09:28 -05:00

142 lines
6.8 KiB
Python

import os
import re
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
SYSROOT = Path("/usr/aarch64-linux-gnu")
def toolchain():
if not (shutil.which("aarch64-linux-gnu-gcc") and shutil.which("qemu-aarch64") and SYSROOT.is_dir()):
if os.environ.get("CI"):
raise AssertionError("CI must install gcc-aarch64-linux-gnu, libc6-dev-arm64-cross and qemu-user")
raise unittest.SkipTest("needs aarch64-linux-gnu-gcc, libc6-dev-arm64-cross and qemu-user")
class LseEmuTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
toolchain()
cls.tmp = tempfile.TemporaryDirectory(prefix="droiddeck-lse-")
out = Path(cls.tmp.name)
subprocess.run(["bash", str(TOOLS / "linuxfs/lse-emu/build.sh"), str(out)], check=True)
cls.library = out / "usr/local/lib/droiddeck-lse/liblse_emu.so"
cls.program = out / "lse-test"
subprocess.run(["aarch64-linux-gnu-gcc", "-O1", "-march=armv8.1-a", "-Wall", "-Wextra", "-Werror", "-pthread",
str(Path(__file__).with_name("lse_emu_test.c")), "-o", str(cls.program)], check=True)
cls.early_library = out / "liblse_emu_early.so"
subprocess.run(["aarch64-linux-gnu-gcc", "-shared", "-fPIC", "-O1", "-march=armv8.1-a", "-Wall", "-Wextra", "-Werror",
str(Path(__file__).with_name("lse_emu_early_dependency.c")), "-o", str(cls.early_library)], check=True)
cls.early_program = out / "lse-early-test"
subprocess.run(["aarch64-linux-gnu-gcc", "-O1", "-Wall", "-Wextra", "-Werror",
str(Path(__file__).with_name("lse_emu_early_main.c")), "-L", str(out),
"-Wl,--no-as-needed", "-llse_emu_early", "-Wl,-rpath,$ORIGIN", "-o", str(cls.early_program)], check=True)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_on(self, cpu, *env, threads=4, program=None, program_args=None):
command = ["qemu-aarch64",
"-U", "LSE_EMU", "-U", "LSE_EMU_PATCH",
"-U", "LSE_EMU_STATS", "-U", "LSE_EMU_LOG", "-U", "LSE_EMU_SKIP",
"-cpu", cpu, "-L", str(SYSROOT)]
for item in env:
command += ["-E", item]
args = [str(program or self.program)]
if program_args is not None:
args.extend(program_args)
elif program is None:
args.append(str(threads))
return subprocess.run(command + args, capture_output=True, text=True, timeout=120)
def test_an_armv8_0_cpu_faults_without_the_emulator(self):
result = self.run_on("cortex-a57")
self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
def test_dependency_constructor_can_execute_lse_before_preload_init(self):
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", program=self.early_program)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("early lse ok", result.stdout)
def test_trapping_alone_runs_every_form_on_an_armv8_0_cpu(self):
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("lse ok", result.stdout)
self.assertRegex(result.stderr, r"traps=[1-9]\d* patched=0 ")
def test_concurrent_sigill_registrations_keep_recycled_snapshots_coherent(self):
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
program_args=["sigill-actions"])
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("sigill actions ok", result.stdout)
def test_child_inherits_the_sigill_handler_but_not_other_threads_action_slots(self):
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
program_args=["sigill-fork"])
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("sigill fork ok", result.stdout)
def test_oneshot_sigill_is_consumed_before_dispatch_and_replacement_survives(self):
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
program_args=["sigill-oneshot"])
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("sigill one-shot ok", result.stdout)
def patched(self, threads):
log = Path(self.tmp.name) / f"patched-{threads}.log"
log.unlink(missing_ok=True)
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_PATCH=1",
"LSE_EMU_STATS=1", f"LSE_EMU_LOG={log}", threads=threads)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("lse ok", result.stdout)
self.assertRegex(result.stderr, r"patched=[1-9]\d* failed=0",
f"{result.stderr}\nLSE log:\n{log.read_text() if log.is_file() else '<missing>'}")
self.assertTrue(log.is_file(), "patch log was not created")
instructions = [
int(match, 16)
for match in re.findall(r"patched pc=0x[0-9a-f]+ insn=0x([0-9a-f]+)", log.read_text())
]
self.assertTrue(
any((insn & 0x3FFFFC00) == 0x38BFC000 for insn in instructions),
"LDAPR did not use a generated stub",
)
self.assertFalse(
any((insn & 0xBFA07C00) == 0x08207C00 for insn in instructions),
"CASP must remain on the stack-safe trap path",
)
self.assertFalse(
any(
(insn & 0x3F200C00) == 0x38200000
and ((insn >> 15) & 1) == 0
and ((insn >> 12) & 7) >= 4
for insn in instructions
),
"min/max must remain on the stack-safe trap path",
)
self.assertNotRegex(result.stderr, r"unhandled pc=.*insn=0x(?!0000000000000000(?:\n|$))[0-9a-f]{16}")
def test_patching_runs_every_form_on_an_armv8_0_cpu(self):
self.patched(threads=1)
def test_patching_stays_atomic_across_threads(self):
self.patched(threads=4)
def test_it_stays_off_without_the_switch(self):
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=0", "LSE_EMU_PATCH=0")
self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
def test_it_stays_off_on_a_cpu_with_lse(self):
result = self.run_on("neoverse-n1", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertNotIn("traps=", result.stderr)
if __name__ == "__main__":
unittest.main()