From 88d44b0dc6a50fed4819206241ad0a5b9809b7bf Mon Sep 17 00:00:00 2001 From: LunaDL <91587464+EnzoDLofi@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:09:28 -0400 Subject: [PATCH] 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> --- .github/workflows/build.yml | 3 + .../droiddeck/launcher/core/CpuFeatures.kt | 17 + .../launcher/runtime/BwrapSpawner.kt | 22 +- .../droiddeck/launcher/runtime/NativeGuest.kt | 8 +- .../launcher/session/BottomDesktop.kt | 3 +- .../launcher/session/SessionFiles.kt | 26 +- .../launcher/session/SessionService.kt | 5 +- .../launcher/core/CpuFeaturesTest.kt | 48 + .../launcher/runtime/BwrapSpawnerTest.kt | 46 + .../launcher/runtime/NativeGuestTest.kt | 21 + docs/arm-v8.0-steam-client.md | 147 ++ tools/build_local.sh | 1 + tools/components/reuse.py | 4 +- tools/linuxfs/check-preloads.sh | 4 + tools/linuxfs/lse-emu/README.md | 23 + tools/linuxfs/lse-emu/build.sh | 15 + tools/linuxfs/lse-emu/lse_emu.c | 1184 +++++++++++++++++ .../overlay/usr/local/bin/droiddeck-session | 7 + tools/linuxfs/preload/pathcache.c | 31 +- tools/nativeguest/hook/env.c | 152 ++- tools/nativeguest/hook/exec.c | 15 + tools/release/runtime_inputs.py | 1 + tools/tests/lse_emu_early_dependency.c | 17 + tools/tests/lse_emu_early_main.c | 9 + tools/tests/lse_emu_test.c | 300 +++++ tools/tests/test_lse_emu.py | 141 ++ tools/tests/test_native_hook_preload_list.py | 53 + 27 files changed, 2263 insertions(+), 40 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/core/CpuFeatures.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/core/CpuFeaturesTest.kt create mode 100644 docs/arm-v8.0-steam-client.md create mode 100644 tools/linuxfs/lse-emu/README.md create mode 100644 tools/linuxfs/lse-emu/build.sh create mode 100644 tools/linuxfs/lse-emu/lse_emu.c mode change 100755 => 100644 tools/linuxfs/overlay/usr/local/bin/droiddeck-session create mode 100644 tools/tests/lse_emu_early_dependency.c create mode 100644 tools/tests/lse_emu_early_main.c create mode 100644 tools/tests/lse_emu_test.c create mode 100644 tools/tests/test_lse_emu.py create mode 100644 tools/tests/test_native_hook_preload_list.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e4229729de..40ae60df71 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -307,6 +307,9 @@ jobs: aarch64-linux-gnu-gcc -O2 -Wall -o "$D/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-glprobe" + - name: Build the LSE atomics emulator for ARMv8.0 CPUs + run: bash tools/linuxfs/lse-emu/build.sh app/src/main/assets/linuxfs + - name: Check the preloads run: | set -euo pipefail diff --git a/app/src/main/java/com/droiddeck/launcher/core/CpuFeatures.kt b/app/src/main/java/com/droiddeck/launcher/core/CpuFeatures.kt new file mode 100644 index 0000000000..e8cd318bc2 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/CpuFeatures.kt @@ -0,0 +1,17 @@ +package com.droiddeck.launcher.core + +import java.io.File + +object CpuFeatures { + internal fun lacksAtomics(cpuInfo: String): Boolean { + val cores = cpuInfo.lineSequence() + .filter { it.substringBefore(':').trim() == "Features" } + .map { it.substringAfter(':').trim().split(Regex("\\s+")) } + .toList() + return cores.isNotEmpty() && cores.any { "atomics" !in it } + } + + val lacksAtomics: Boolean by lazy { + runCatching { lacksAtomics(File("/proc/cpuinfo").readText()) }.getOrDefault(false) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt index 0e42e770e3..0577c2fece 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt @@ -288,12 +288,26 @@ object BwrapSpawner { } private fun preload(session: List, rootfs: String, env: MutableMap): List { - val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines() - ?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: return emptyList() - if (libs.isEmpty()) return emptyList() + val configured = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines() + ?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: emptyList() + val lseDisabled = env["LSE_EMU"] == "0" + val libs = configured.filterNot { lseDisabled && it.endsWith("/liblse_emu.so") } + val inherited = env["LD_PRELOAD"]?.split(Regex("[\\s:]+")) + ?.filter { it.isNotEmpty() && !(lseDisabled && it.substringAfterLast('/') == "liblse_emu.so") } + ?: emptyList() + if (libs.isEmpty()) { + if (lseDisabled) { + if (inherited.isEmpty()) env.remove("LD_PRELOAD") + else env["LD_PRELOAD"] = inherited.joinToString(":") + } + return emptyList() + } val binds = ArrayList() val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } } - env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":") + env["LD_PRELOAD"] = (paths + inherited).joinToString(":") + if (libs.any { it.endsWith("/liblse_emu.so") }) { + env.putIfAbsent("LSE_EMU", "1") + } File(rootfs, NET_LINK).takeIf { it.isFile }?.let { binds.add(Bind(it.path, "/$NET_LINK")) } env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev -> binds.addAll(bindsFor(session, rootfs, dev, dev)) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt index 95a660eaf4..6ad6a321c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt @@ -104,8 +104,11 @@ object NativeGuest { private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/")) /** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */ - fun sessionEnvironment(root: File, binds: List, program: String, hostname: String? = null): Map { - val preload = preloadList(root) + fun sessionEnvironment( + root: File, binds: List, program: String, hostname: String? = null, lseEmu: String? = null, + ): Map { + val preload = preloadList(root).filterNot { lseEmu == "0" && it.substringAfterLast('/') == "liblse_emu.so" } + val lse = lseEmu ?: "1".takeIf { preload.any { it.substringAfterLast('/') == "liblse_emu.so" } } return linkedMapOf( "DDNATV_ROOT" to root.path, "DDNATV_EXEC" to execLoader.orEmpty(), @@ -113,6 +116,7 @@ object NativeGuest { "DDNATV_HOSTNAME" to hostname.orEmpty(), "DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" }, "DDNATV_PRELOAD" to preload.joinToString(":"), + "LSE_EMU" to lse.orEmpty(), "LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"), ).filterValues { it.isNotEmpty() } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt index ffccd3e237..b815d29fdd 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt @@ -343,7 +343,8 @@ object BottomDesktop { LinuxRuntime.commandWithBinds(context, current.root, binds, guest) } val environment = if (current.nativeUserland) { - com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context)) + val lseEmu = current.guest.lastOrNull { it.startsWith("LSE_EMU=") }?.substringAfter('=') + com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context), lseEmu) .map { (k, v) -> "$k=$v" }.toTypedArray() } else current.hostEnvironment val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index d28ae192db..525844d880 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -5,6 +5,7 @@ import android.content.Context import android.os.Environment import android.util.Log import com.droiddeck.launcher.R +import com.droiddeck.launcher.core.CpuFeatures import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.runtime.BwrapSpawner import com.droiddeck.launcher.runtime.DesktopCatalog @@ -22,6 +23,10 @@ object SessionFiles { private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad" const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio" private const val STAGED_LEDGER = "usr/local/.droiddeck-staged" + internal const val LSE_EMU = "usr/local/lib/droiddeck-lse/liblse_emu.so" + + internal fun lsePreload(lacksAtomics: Boolean, staged: Boolean, lseEmu: String? = null): String = + if (lacksAtomics && staged && lseEmu != "0") "/$LSE_EMU\n" else "" private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json" private const val IME_DEFAULT_MODE = 420 val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread") @@ -102,10 +107,23 @@ object SessionFiles { } private val STAGE_LOCK = Any() + @Volatile private var activeSessionLseEmu: String? = null - fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) } + fun stage(context: Context, root: File, startsSession: Boolean = false) = + stage(context, root, startsSession, lseEmu = null) - private fun stageNow(context: Context, root: File, startsSession: Boolean) { + fun stage(context: Context, root: File, startsSession: Boolean, lseEmu: String?) = + synchronized(STAGE_LOCK) { + val selection = if (startsSession) { + activeSessionLseEmu = lseEmu + lseEmu + } else { + lseEmu ?: activeSessionLseEmu + } + stageNow(context, root, startsSession, selection) + } + + private fun stageNow(context: Context, root: File, startsSession: Boolean, lseEmu: String?) { if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) } catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) } GameEnvironmentStore.publish(context) @@ -281,6 +299,7 @@ object SessionFiles { "usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst", "usr/local/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE", "usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE", + LSE_EMU to LSE_EMU, ) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) -> val dir = asset.substringBeforeLast('/') runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false) @@ -343,7 +362,8 @@ object SessionFiles { stageImeFiles(context, root, ledger) ledger.save() for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively() - val preload = StringBuilder("/usr/local/lib/libddsession.so\n") + val preload = StringBuilder(lsePreload(CpuFeatures.lacksAtomics, File(root, LSE_EMU).isFile, lseEmu)) + preload.append("/usr/local/lib/libddsession.so\n") if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) { preload.append("/usr/local/lib/libfakeinput.so\n") } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 5ad8fe253e..3e53e37d75 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -566,6 +566,7 @@ class SessionService : Service() { .onFailure { Log.w(TAG, "agent environment skipped", it) } val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList()) val customEnvironment = extraEnv() + val lseEmu = (customEnvironment + agentEnvironment).lastOrNull { it.startsWith("LSE_EMU=") }?.substringAfter('=') try { if (systemVulkan) { SystemVulkanDriver.prepare(this) @@ -575,7 +576,7 @@ class SessionService : Service() { } pruneSystemVulkanRuntime() } - SessionFiles.stage(this, root, startsSession = true) + SessionFiles.stage(this, root, startsSession = true, lseEmu = lseEmu) } catch (error: Exception) { Log.e(TAG, "Could not prepare the session graphics runtime", error) failSession(gen, "GRAPHICS_RUNTIME_FAILED", getString(R.string.session_graphics_runtime_failed), -1) @@ -830,7 +831,7 @@ class SessionService : Service() { if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back") val hostEnv = if (nativeUserland) HostEnvironment().also { env -> Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)") - com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this)) + com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this), lseEmu) .forEach { (k, v) -> env[k] = v } } else prootEnv diff --git a/app/src/test/java/com/droiddeck/launcher/core/CpuFeaturesTest.kt b/app/src/test/java/com/droiddeck/launcher/core/CpuFeaturesTest.kt new file mode 100644 index 0000000000..cbb7c374a0 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/CpuFeaturesTest.kt @@ -0,0 +1,48 @@ +package com.droiddeck.launcher.core + +import com.droiddeck.launcher.session.SessionFiles +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class CpuFeaturesTest { + @Test fun anArmv80CpuLacksAtomics() { + val cpuInfo = """ + processor : 0 + Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid + processor : 1 + Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid + """.trimIndent() + assertTrue(CpuFeatures.lacksAtomics(cpuInfo)) + } + + @Test fun oneCoreWithoutAtomicsIsEnough() { + val cpuInfo = """ + processor : 0 + Features : fp asimd atomics + processor : 4 + Features : fp asimd + """.trimIndent() + assertTrue(CpuFeatures.lacksAtomics(cpuInfo)) + } + + @Test fun anArmv82CpuHasAtomics() { + val cpuInfo = """ + processor : 0 + Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp + """.trimIndent() + assertFalse(CpuFeatures.lacksAtomics(cpuInfo)) + } + + @Test fun noFeatureLinesMeansNoEmulation() { + assertFalse(CpuFeatures.lacksAtomics("processor : 0\n")) + assertFalse(CpuFeatures.lacksAtomics("")) + } + + @Test fun theEmulatorIsPreloadedFirstOnlyWhenNeededAndStaged() { + assertEquals("/usr/local/lib/droiddeck-lse/liblse_emu.so\n", SessionFiles.lsePreload(lacksAtomics = true, staged = true)) + assertEquals("", SessionFiles.lsePreload(lacksAtomics = true, staged = false)) + assertEquals("", SessionFiles.lsePreload(lacksAtomics = false, staged = true)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt index 5b5cef26b4..cfb40f5404 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt @@ -251,6 +251,52 @@ class BwrapSpawnerPlanTest { } } + @Test fun sandboxesSwitchOnTheLseEmulatorWhenItIsPreloaded() { + val context = RuntimeEnvironment.getApplication() + val rootfs = LinuxRuntime.rootDir(context) + val emu = File(rootfs, "usr/local/lib/droiddeck-lse/liblse_emu.so").apply { parentFile?.mkdirs(); writeText("") } + val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/droiddeck-lse/liblse_emu.so\n") } + try { + val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir) + assertEquals("/run/droiddeck-preload/liblse_emu.so", plan.env["LD_PRELOAD"]) + assertEquals("1", plan.env["LSE_EMU"]) + assertFalse(plan.env.containsKey("LSE_EMU_PATCH")) + val chosen = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")) + .apply { getJSONObject("env").put("LSE_EMU_PATCH", "0") }, dir) + assertEquals("0", chosen.env["LSE_EMU_PATCH"]) + assertEquals("1", chosen.env["LSE_EMU"]) + for (inherited in listOf( + "/run/droiddeck-preload/liblse_emu.so /custom.so", + "/custom.so:/run/droiddeck-preload/liblse_emu.so", + )) { + val disabled = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")) + .apply { + getJSONObject("env").put("LSE_EMU", "0") + getJSONObject("env").put("LD_PRELOAD", inherited) + }, dir) + assertEquals("0", disabled.env["LSE_EMU"]) + assertEquals("/custom.so", disabled.env["LD_PRELOAD"]) + assertFalse(disabled.binds.any { it.guest == "/run/droiddeck-preload/liblse_emu.so" }) + } + } finally { + listOf(emu, preload).forEach { it.delete() } + } + } + + @Test fun sandboxesLeaveTheLseSwitchesAloneWithoutTheEmulator() { + val context = RuntimeEnvironment.getApplication() + val rootfs = LinuxRuntime.rootDir(context) + val lib = File(rootfs, "usr/local/lib/libddsession.so").apply { parentFile?.mkdirs(); writeText("") } + val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libddsession.so\n") } + try { + val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir) + assertFalse(plan.env.containsKey("LSE_EMU")) + assertFalse(plan.env.containsKey("LSE_EMU_PATCH")) + } finally { + listOf(lib, preload).forEach { it.delete() } + } + } + @Test fun zypakLaunchesTheBrowserWithoutItsSandbox() { val context = RuntimeEnvironment.getApplication() val app = File(runtime, "app").apply { File(this, "bin").mkdirs() } diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt index 563b09dd36..2375b8497d 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt @@ -94,6 +94,27 @@ class NativeGuestTest { assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so")) } + @Test + fun disablingLseKeepsItOutOfTheLoaderAndItsDescendants() { + val root = rootWithLoader() + val emulator = "/usr/lib/liblse_emu.so" + val session = "/usr/lib/libddsession.so" + listOf(emulator, session).forEach { File(root, it.removePrefix("/")).writeText("") } + File(root, "etc/droiddeck").mkdirs() + File(root, "etc/droiddeck/native-preload").writeText("$emulator\n$session\n") + + val enabled = NativeGuest.sessionEnvironment(root, emptyList(), "/usr/bin/env") + assertEquals("1", enabled["LSE_EMU"]) + assertEquals("$emulator:$session", enabled["DDNATV_PRELOAD"]) + assertTrue(enabled.getValue("LD_PRELOAD").startsWith(File(root, emulator.removePrefix("/")).path + ":")) + + val disabled = NativeGuest.sessionEnvironment(root, emptyList(), "/usr/bin/env", lseEmu = "0") + assertEquals("0", disabled["LSE_EMU"]) + assertEquals(session, disabled["DDNATV_PRELOAD"]) + assertEquals(listOf(File(root, session.removePrefix("/")).path, NativeGuest.hook(root).path), + disabled.getValue("LD_PRELOAD").split(':')) + } + @Test fun theProgramTheLoaderRunsIsNamedInItsEnvironment() { val root = rootWithLoader() diff --git a/docs/arm-v8.0-steam-client.md b/docs/arm-v8.0-steam-client.md new file mode 100644 index 0000000000..5b6de79d32 --- /dev/null +++ b/docs/arm-v8.0-steam-client.md @@ -0,0 +1,147 @@ +# Steam client on ARMv8.0 CPUs + +## The crash + +Valve's native arm64 Steam client stopped starting on ARMv8.0 CPUs after the April 15 2026 +build (client version 1776387948). The process dies with SIGILL right away, the session log +shows `"$steam_root/steamrtarm64/steam" ... Illegal instruction` and `steam exited rc=132`, +and the screen stays black. + +The faulting instruction is an ARMv8.1 LSE atomic. The GDB trace in +[ValveSoftware/steam-for-linux#13288](https://github.com/ValveSoftware/steam-for-linux/issues/13288) +stops on `ldaddal x1, x0, [x0]`, with `swpa` and `casal` next to it. Earlier builds were most +likely compiled with `-moutline-atomics`, which picks LL/SC or LSE at run time. Newer builds +inline LSE. Valve has not replied on that issue, so the cause comes from the reporter's +disassembly, not from Valve. + +Affected cores are the ARMv8.0 ones without LSE: Cortex-A35, A53, A57, A72 and A73. A55, A75 +and later have it. On Android that covers the Snapdragon 4xx/6xx parts built on A53/A73 (for example the +Snapdragon 685 with Adreno 610 in +[Droid-Deck/DroidDeck#380](https://github.com/Droid-Deck/DroidDeck/issues/380)), plus the +Nintendo Switch, Raspberry Pi 4 and older, and the Jetson Nano outside Android. +`/proc/cpuinfo` shows it: the `Features` line has no `atomics`. + +LSE is an ARMv8.1 feature. LSE-Emu users report the current client running on a Cortex-A57, +so nothing later than LSE seems to be required yet. + +## What other projects do + +- [SildurFX/Switchdeck](https://github.com/SildurFX/Switchdeck) (Switch, L4T Linux) lets the + client update once, then overlays `linuxarm64`, `steamrtarm64`, `steamui` and a `steam.cfg` + from the April build. It works there because the install script controls the whole system. + For us a pinned client is replaced by the self updater on its next start, which is why #380 + was closed. +- [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) is a preload library by the same + author, written to run the current arm64 client on the Switch. A SIGILL handler performs + each LSE instruction with an LL/SC loop. With `LSE_EMU_PATCH=1` the first trap at a site + writes an LL/SC stub within branch range and replaces the instruction with a `b` to it, so + the site runs natively after that. It covers the full LSE set plus `LDAPR`. The author + reports Steam, FEX, Proton games and ARMSX2 running on a Cortex-A57, with ARMSX2 close to + native ARMv8.0 speed once patched. GPL-3.0, same as this repo. +- [Azkali/proton-arm64-a57](https://github.com/Azkali/proton-arm64-a57) rebuilds Proton 11 + arm64 (Wine, DXVK, vkd3d-proton, FEX's WoW64 and ARM64EC DLLs) with + `-march=armv8-a -mtune=cortex-a57`. Stock Proton 11 arm64 also SIGILLs on ARMv8.0 + (`wineboot` rc=132), so the client is not the only problem for games. +- Some installers fall back to Valve's x86-64 client under FEX on CPUs without LSE. We already + have that path (`DD_STEAM_CLIENT_ARCH=x86_64`, `droiddeck-steam-x64`), but it is slower and + FEX itself has to be built without LSE. +- [FrankNat996/armor](https://github.com/FrankNat996/armor) notes a separate problem: the arm64 + client's ELF segments are 4K aligned, so it SIGSEGVs at once on 16K page kernels. + +## This change + +The session vendors LSE-Emu (`tools/linuxfs/lse-emu`, upstream commit `8bc9548`). CI and +`tools/build_local.sh` build it as `usr/local/lib/droiddeck-lse/liblse_emu.so` with +`-march=armv8-a -mno-outline-atomics`. The build fails if the library contains LSE +instructions itself. + +When `/proc/cpuinfo` reports any core without `atomics`, `SessionFiles` puts the library first +in the rootfs `/etc/ld.so.preload`. `BwrapSpawner` already turns that file into `LD_PRELOAD` +for sandboxed processes. On CPUs with LSE nothing changes: the file is staged but not +preloaded, and the library would also stay idle on its own because it checks `HWCAP_ATOMICS`. + +`droiddeck-session` sees the library in `ld.so.preload` and exports `LSE_EMU=1`. Runtime +instruction rewriting is disabled by default (`LSE_EMU_PATCH=0`): the emulator uses the slower +SIGILL path rather than rewriting executable code while other threads may be running it. To +opt in to patching for testing, set `LSE_EMU_PATCH=1` explicitly. With a session debug folder, +the script also sets `LSE_EMU_LOG=$DD_DEBUG_DIR/lse_emu.log`, and `session.log` gets a line +starting with `== cpu: no LSE atomics`. + +The test APK targets SDK 34. To verify the expected `mprotect` restriction, run a controlled +test executable containing a known-patchable, file-backed LSE instruction with +`LSE_EMU_PATCH=1` under this APK configuration, and confirm `mprotect-failed` for that site. +A normal Steam run alone cannot establish the restriction. + +## Tests + +`tools/tests/test_lse_emu.py` builds the library and a program that uses every LSE family +(`ldadd` in all four sizes, `ldclr`, `ldeor`, `ldset`, `swp`, `ldsmax`, `ldumin`, `casal`, +`caspal`) from four threads, and runs it under `qemu-aarch64 -cpu cortex-a57`: + +- without the library the program dies with SIGILL +- trapping alone runs every form and keeps the threaded counters exact +- patching runs every form twice, so the second run goes through the generated stubs, both + single threaded and with four threads +- condition flags survive a patched `ldumax`/`ldsmaxb`, and `caspal` returns the current pair + on a mismatch +- without `LSE_EMU=1`, and on `-cpu neoverse-n1`, the library stays out of the way +- a SIGILL handler the program installs itself still runs for an unrelated `udf` + +The patch tests cannot run on an Apple Silicon Mac in an amd64 Docker container: qemu-aarch64 +there segfaults whenever code is written to an executable page after code on it has run, even +in a ten line program without the library. CI runs them on x86 hardware. + +## Fixes over upstream + +The vendored copy carries two fixes found in review, both in the patched stubs and the +emulation path: + +- `LDSMAX`/`LDSMIN`/`LDUMAX`/`LDUMIN` stubs used `cmp`/`csel` and overwrote NZCV. They now + save and restore it. +- `CASP` with a 64-bit pair returned the `ldxp` result on a mismatch without a store. A 128-bit + `ldxp` is only single-copy atomic once a `stxp` succeeds, so a concurrent update could give + one old and one new half. Both the trap path and the stub now store the loaded pair back on a + mismatch and retry if that store fails, as libatomic does. + +Patching replaces an LSE instruction with a `b` while other threads may be running it. +The architecture does not guarantee safe concurrent replacement for every instruction (including +`LDADD`), so patching is opt-in and defaults to `LSE_EMU_PATCH=0`. This avoids that specific +self-modifying-code race by keeping sites on the SIGILL emulation path, at the cost of speed. +It does not eliminate all signal-handler compatibility risks: direct raw `rt_sigaction` syscalls, +complex signal masks/flags, and applications that depend on exact kernel signal semantics still +need dedicated tests. The handler forwarding is not a complete substitute for kernel delivery. + +## Testing on a device + +On an ARMv8.0 phone or handheld (no `atomics` in `/proc/cpuinfo`): + +1. Install the test APK and start a Steam session. +2. `session.log` should have `== cpu: no LSE atomics` and no `steam exited rc=132`. +3. In the default-mode run, check that `lse_emu.log` contains a `start` record for the + affected PID and that the process remains on the trap path. While Steam is running, its + `exit` record may not exist yet: either confirm a `no-patch` record for that PID, or exit + Steam normally before checking that its `exit` record has a nonzero `traps=` value. Confirm + there are no `patched` records. Summarise events with + `cut -d' ' -f2 lse_emu.log | sort | uniq -c`. + Then repeat with `LSE_EMU_PATCH=1` explicitly set in the session environment. Do not require + `mprotect-failed` for a valid trap-path run: `no-arena` means arena allocation failed before + `mprotect` was attempted, so it is inconclusive about the SDK restriction. Check that + restriction separately using the controlled patchable site described above. `unhandled` + means an instruction the library does not cover. +4. Compare UI responsiveness against an ARMv8.2 device, and note any `lse_emu: unhandled` + lines in `session.log`. + +## Still open + +- Games. Proton 11 arm64 and Valve's FEX build need the same treatment. The preload reaches + them when they inherit `LD_PRELOAD`, but pressure-vessel and static binaries can drop it, + and FEX installs its own signal handlers with raw syscalls. An ARMv8.0 Proton build like + Azkali's is the cleaner fix. +- In #380 the session first died with SIGILL in the app's own `wl-compositor` thread, inside + `turnip-sdk36/vulkan.ad08XX.so`, which is the A8xx driver build loaded on an Adreno 610. + Picking the 6xx/7xx Turnip fixed it, and Auto picks that build once the driver release list + is loaded. Nobody has checked yet whether our bundled driver builds avoid LSE. The preload + cannot help there because the compositor is a bionic thread in the app process. +- JIT code (anonymous memory) is never patched and always traps. +- If Valve starts requiring something past LSE, the library prints + `lse_emu: unhandled pc=... insn=...` and the client crashes as before. diff --git a/tools/build_local.sh b/tools/build_local.sh index 3c4feff55f..4d05bc6b02 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -225,6 +225,7 @@ else external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe" + bash tools/linuxfs/lse-emu/build.sh "$d" aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard" for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do diff --git a/tools/components/reuse.py b/tools/components/reuse.py index 1eb02dca9d..2000396d6c 100644 --- a/tools/components/reuse.py +++ b/tools/components/reuse.py @@ -23,8 +23,8 @@ import prepare # noqa: E402 # CI records identities under its runner labels and pinned NDK, not this host's. RUNNER_ARCHITECTURES = ('X64', 'ARM64') # The components job builds these outside the recipe registry. -UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c', - 'tools/quest'] +UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/linuxfs/lse-emu', + 'tools/venus/glprobe.c', 'tools/quest'] def ci_environment(architecture, root): diff --git a/tools/linuxfs/check-preloads.sh b/tools/linuxfs/check-preloads.sh index 0f801f87a0..f329f3537c 100644 --- a/tools/linuxfs/check-preloads.sh +++ b/tools/linuxfs/check-preloads.sh @@ -31,5 +31,9 @@ for sym in vkNegotiateLoaderLayerInterfaceVersion vkGetInstanceProcAddr vkGetDev grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; } done test -f "$D/usr/local/lib/droiddeck-xclipse/VkLayer_droiddeck_xclipse.json" +LSE=$(syms "$D/usr/local/lib/droiddeck-lse/liblse_emu.so") +for sym in sigaction signal sigprocmask pthread_sigmask prctl syscall; do + grep -qx "$sym" <<<"$LSE" || { echo "::error::liblse_emu.so does not export $sym"; exit 1; } +done test -f "$D/usr/local/bin/droiddeck-session" test -f "$D/usr/local/bin/droiddeck-proton-extra" diff --git a/tools/linuxfs/lse-emu/README.md b/tools/linuxfs/lse-emu/README.md new file mode 100644 index 0000000000..df6dd93cfd --- /dev/null +++ b/tools/linuxfs/lse-emu/README.md @@ -0,0 +1,23 @@ +# LSE-Emu + +`lse_emu.c` is a copy of [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) at commit +`8bc9548ac6fd24a8d506b266b17ba8d0e71a9b01` (GPL-3.0-or-later) with two fixes, listed in +`docs/arm-v8.0-steam-client.md` under "Fixes over upstream": NZCV kept across the min/max +stubs, and a store-back on `CASP` mismatches so the returned pair is atomic. Carry them forward +until upstream has them. + +It is an `LD_PRELOAD` library that emulates the ARMv8.1 LSE atomic instructions (and `LDAPR`) +on ARMv8.0 CPUs. A SIGILL handler performs each trapped instruction with an LL/SC loop. A GNU +IFUNC resolver installs a minimal early handler on CPUs without LSE before dependency +constructors, covering LSE instructions executed before the preload constructor. The early handler +is removed after initialization unless `LSE_EMU=1` is set. With `LSE_EMU_PATCH=1` the first trap at a site +writes an LL/SC stub nearby and replaces the instruction with a branch to it, so later runs do not trap. +Patching is off by default. It is restricted to private file-backed executable mappings whose +live file and offset still match the original mapping. Leave patching off for programs that +can remap executable pages concurrently: checking the mapping cannot lock it against a remap. + +The session stages it as `/usr/local/lib/droiddeck-lse/liblse_emu.so` and only lists it in +`/etc/ld.so.preload` when `/proc/cpuinfo` has no `atomics` flag. See +`docs/arm-v8.0-steam-client.md` for why. + +To update, copy `lse_emu.c` from a newer upstream commit and change the commit above. diff --git a/tools/linuxfs/lse-emu/build.sh b/tools/linuxfs/lse-emu/build.sh new file mode 100644 index 0000000000..76eaa50375 --- /dev/null +++ b/tools/linuxfs/lse-emu/build.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +set -euo pipefail +D=${1:?asset directory} +CC=${CC:-aarch64-linux-gnu-gcc} +STRIP=${STRIP:-aarch64-linux-gnu-strip} +here=$(cd "$(dirname "$0")" && pwd) +out="$D/usr/local/lib/droiddeck-lse/liblse_emu.so" +mkdir -p "$(dirname "$out")" +"$CC" -shared -fPIC -O2 -march=armv8-a -mno-outline-atomics -Wall -Wextra -Wno-unused-parameter \ + -Wl,-z,now,-z,max-page-size=65536 -o "$out" "$here/lse_emu.c" -ldl +"$STRIP" --strip-unneeded "$out" +disassembly=$("${OBJDUMP:-aarch64-linux-gnu-objdump}" -d "$out") +if grep -qE $'\t((ld|st)(add|clr|eor|set|smax|smin|umax|umin)|swp|cas)[a-z]*\t' <<<"$disassembly"; then + echo "::error::liblse_emu.so itself contains LSE instructions"; exit 1 +fi diff --git a/tools/linuxfs/lse-emu/lse_emu.c b/tools/linuxfs/lse-emu/lse_emu.c new file mode 100644 index 0000000000..1c07d32ada --- /dev/null +++ b/tools/linuxfs/lse-emu/lse_emu.c @@ -0,0 +1,1184 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// https://github.com/SildurFX/LSE-Emu +// Copyright (C) 2026 SildurFX + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef HWCAP_ATOMICS +#define HWCAP_ATOMICS (1UL << 8) +#endif +#ifndef SA_RESTORER +#define SA_RESTORER 0x04000000 +#endif +#ifndef MAP_FIXED_NOREPLACE +#define MAP_FIXED_NOREPLACE 0x100000 +#endif + +/* ======================= raw syscalls (no PLT in handler) ================= */ + +static long sc(long n, long a, long b, long c, long d, long e, long f) { + register long x8 asm("x8") = n, x0 asm("x0") = a, x1 asm("x1") = b; + register long x2 asm("x2") = c, x3 asm("x3") = d, x4 asm("x4") = e, x5 asm("x5") = f; + asm volatile("svc 0" : "+r"(x0) + : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) + : "memory", "cc"); + return x0; +} + +/* ======================= slow path: emulation ============================= */ + +#define DEFINE_RMW(NAME, UT, ST) \ +static UT NAME(void *p, unsigned op, UT v) { \ + UT *q = (UT *)p; \ + switch (op) { \ + case 0: return __atomic_fetch_add(q, v, __ATOMIC_SEQ_CST); \ + case 1: return __atomic_fetch_and(q, (UT)~v, __ATOMIC_SEQ_CST); \ + case 2: return __atomic_fetch_xor(q, v, __ATOMIC_SEQ_CST); \ + case 3: return __atomic_fetch_or (q, v, __ATOMIC_SEQ_CST); \ + case 8: return __atomic_exchange_n(q, v, __ATOMIC_SEQ_CST); \ + } \ + UT old = __atomic_load_n(q, __ATOMIC_RELAXED), nw; \ + do { \ + switch (op) { \ + case 4: nw = ((ST)old > (ST)v) ? old : v; break; \ + case 5: nw = ((ST)old < (ST)v) ? old : v; break; \ + case 6: nw = (old > v) ? old : v; break; \ + default: nw = (old < v) ? old : v; break; \ + } \ + } while (!__atomic_compare_exchange_n(q, &old, nw, 1, \ + __ATOMIC_SEQ_CST, __ATOMIC_RELAXED));\ + return old; \ +} +DEFINE_RMW(rmw8, uint8_t, int8_t) +DEFINE_RMW(rmw16, uint16_t, int16_t) +DEFINE_RMW(rmw32, uint32_t, int32_t) +DEFINE_RMW(rmw64, uint64_t, int64_t) + +#define DEFINE_CAS(NAME, UT) \ +static UT NAME(void *p, UT exp, UT des) { \ + UT e = exp; \ + __atomic_compare_exchange_n((UT *)p, &e, des, 0, \ + __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); \ + return e; \ +} +DEFINE_CAS(cas8, uint8_t) +DEFINE_CAS(cas16, uint16_t) +DEFINE_CAS(cas32, uint32_t) +DEFINE_CAS(cas64, uint64_t) + +static void casp128(void *p, uint64_t *o0, uint64_t *o1, + uint64_t e0, uint64_t e1, uint64_t d0, uint64_t d1) { + uint64_t a, b, t, s; + asm volatile( + "1: ldaxp %0, %1, [%6]\n" + " eor %2, %0, %7\n" + " eor %3, %1, %8\n" + " orr %2, %2, %3\n" + " cbnz %2, 2f\n" + " stlxp %w2, %9, %10, [%6]\n" + " cbnz %w2, 1b\n" + " b 3f\n" + "2: stlxp %w2, %0, %1, [%6]\n" // a 128-bit ldxp is only single-copy atomic once a stxp succeeds + " cbnz %w2, 1b\n" + "3:\n" + : "=&r"(a), "=&r"(b), "=&r"(t), "=&r"(s) + : "0"(0), "1"(0), "r"(p), "r"(e0), "r"(e1), "r"(d0), "r"(d1) + : "memory", "cc"); + *o0 = a; *o1 = b; +} + +static int emulate(ucontext_t *uc, uint32_t i) { + uint64_t *x = (uint64_t *)uc->uc_mcontext.regs; + unsigned rt = i & 31, rn = (i >> 5) & 31, rs = (i >> 16) & 31; + unsigned size = i >> 30; + void *p = (void *)(rn == 31 ? uc->uc_mcontext.sp : x[rn]); +#define RD(r) ((r) >= 31 ? 0 : x[r]) +#define WR(r, v) do { if ((r) < 31) x[r] = (v); } while (0) + + /* LDAPR is not covered by the LD/SWP encoding mask below. Emulate it + as an acquire load so patch mode can safely fall back if stub allocation + or code modification is unavailable. */ + if ((i & 0x3FFFFC00u) == 0x38BFC000u) { + uint64_t v; + switch (size) { + case 0: v = __atomic_load_n((uint8_t *)p, __ATOMIC_ACQUIRE); break; + case 1: v = __atomic_load_n((uint16_t *)p, __ATOMIC_ACQUIRE); break; + case 2: v = __atomic_load_n((uint32_t *)p, __ATOMIC_ACQUIRE); break; + default: v = __atomic_load_n((uint64_t *)p, __ATOMIC_ACQUIRE); break; + } + WR(rt, v); + return 1; + } + + if ((i & 0x3f200c00) == 0x38200000) { // LD, SWP + unsigned o3 = (i >> 15) & 1, opc = (i >> 12) & 7, op; + uint64_t v, old; + if (!o3) op = opc; + else if (opc == 0) op = 8; + else if (opc == 4 && rs == 31 && + (i & (1u << 23)) && !(i & (1u << 22))) { + switch (size) { + case 0: v = __atomic_load_n((uint8_t *)p, __ATOMIC_ACQUIRE); break; + case 1: v = __atomic_load_n((uint16_t *)p, __ATOMIC_ACQUIRE); break; + case 2: v = __atomic_load_n((uint32_t *)p, __ATOMIC_ACQUIRE); break; + default: v = __atomic_load_n((uint64_t *)p, __ATOMIC_ACQUIRE); break; + } + WR(rt, v); + return 1; + } else return 0; + v = RD(rs); + switch (size) { + case 0: old = rmw8 (p, op, (uint8_t)v); break; + case 1: old = rmw16(p, op, (uint16_t)v); break; + case 2: old = rmw32(p, op, (uint32_t)v); break; + default: old = rmw64(p, op, v); break; + } + WR(rt, old); + return 1; + } + if ((i & 0x3fa07c00) == 0x08a07c00) { // CAS + uint64_t e = RD(rs), d = RD(rt), old; + switch (size) { + case 0: old = cas8 (p, (uint8_t)e, (uint8_t)d); break; + case 1: old = cas16(p, (uint16_t)e, (uint16_t)d); break; + case 2: old = cas32(p, (uint32_t)e, (uint32_t)d); break; + default: old = cas64(p, e, d); break; + } + WR(rs, old); + return 1; + } + if ((i & 0xbfa07c00) == 0x08207c00) { // CASP + if ((rs & 1) || (rt & 1)) return 0; + uint64_t e0 = RD(rs), e1 = RD(rs + 1), d0 = RD(rt), d1 = RD(rt + 1); + if (size == 0) { + uint64_t e = (uint32_t)e0 | ((uint64_t)(uint32_t)e1 << 32); + uint64_t d = (uint32_t)d0 | ((uint64_t)(uint32_t)d1 << 32); + uint64_t o = cas64(p, e, d); + WR(rs, (uint32_t)o); WR(rs + 1, o >> 32); + } else { + uint64_t o0, o1; + casp128(p, &o0, &o1, e0, e1, d0, d1); + WR(rs, o0); WR(rs + 1, o1); + } + return 1; + } + return 0; +} + +/* ======================= fast path: stub generator ======================== */ + +#define STP2(a,b) (0xA9BE0000u | ((b) << 10) | (31u << 5) | (a)) // stp a,b,[sp,#-32]! +#define LDP2(a,b) (0xA8C20000u | ((b) << 10) | (31u << 5) | (a)) // ldp a,b,[sp],#32 +#define STR16(c) (0xF9000800u | (31u << 5) | (c)) // str c,[sp,#16] +#define LDR16(c) (0xF9400800u | (31u << 5) | (c)) // ldr c,[sp,#16] +#define MOVX(d,m) (0xAA0003E0u | ((m) << 16) | (d)) // mov xd,xm +#define W(x) do { uint32_t _v = (x); w[n++] = _v; } while (0) + +static uint32_t ldx(unsigned sz, unsigned acq, unsigned rt, unsigned rn) { + return (sz << 30) | 0x085F7C00u | (acq << 15) | (rn << 5) | rt; +} +static uint32_t stx(unsigned sz, unsigned rel, unsigned rs, unsigned rt, unsigned rn) { + return (sz << 30) | 0x08007C00u | (rs << 16) | (rel << 15) | (rn << 5) | rt; +} +static uint32_t alu(unsigned op, unsigned d, unsigned n, unsigned m) { + static const uint32_t base[4] = { 0x8B000000u, 0x8A200000u, 0xCA000000u, 0xAA000000u }; + return base[op] | (m << 16) | (n << 5) | d; // add, bic, eor, orr +} + +// CASP{A}{L} Xs,Xs+1,Xt,Xt+1,[Xn] (64-bit pair): ldxp/ldaxp + compare + stxp/stlxp. Four scratch registers, no flag changes, 17 words. +static int gen_casp(uint32_t *w, uintptr_t stub, uintptr_t ret, unsigned sz, + unsigned rs, unsigned rt, unsigned rn, unsigned acq, unsigned rel) { + // sz 1: 64-bit pair (LDXP x), sz 0: 32-bit pair (LDXP w, 8-byte aligned) + const uint32_t LDXP = sz ? 0xC87F0000u : 0x887F0000u, STXP = sz ? 0xC8200000u : 0x88200000u; + const uint32_t EOR = sz ? 0xCA000000u : 0x4A000000u, ORR = sz ? 0xAA000000u : 0x2A000000u; + unsigned t[4], k = 0; int n = 0; + for (unsigned r = 9; r <= 17 && k < 4; r++) + if (r != rs && r != rs + 1 && r != rt && r != rt + 1 && r != rn) t[k++] = r; + if (k < 4) return 0; + unsigned t0 = t[0], t1 = t[1], t2 = t[2], t3 = t[3]; + W(0xD5033FDFu); // isb: synchronize instruction fetch on every entry + W(STP2(t0, t1)); + W(0xA9010000u | (t3 << 10) | (31u << 5) | t2); // stp t2,t3,[sp,#16] + int loop = n; + W(LDXP | (acq << 15) | (t1 << 10) | (rn << 5) | t0); // ldxp/ldaxp t0,t1,[rn] + W(EOR | (rs << 16) | (t0 << 5) | t2); // eor t2,t0,rs + W(EOR | ((rs + 1) << 16) | (t1 << 5) | t3); // eor t3,t1,rs+1 + W(ORR | (t3 << 16) | (t2 << 5) | t2); // orr t2,t2,t3 + W(0xB4000000u | (3u << 5) | t2); // cbz t2, match (+3) + W(STXP | (t2 << 16) | (rel << 15) | (t1 << 10) | (rn << 5) | t0); // mismatch: store the loaded pair back, which validates it + W(0x14000002u); // b check (+2) + W(STXP | (t2 << 16) | (rel << 15) | ((rt + 1) << 10) | (rn << 5) | rt); // match: stxp/stlxp w(t2),rt,rt+1,[rn] + W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2); // check: cbnz w(t2), loop + W(MOVX(rs, t0)); + W(MOVX(rs + 1, t1)); + W(0xA9410000u | (t3 << 10) | (31u << 5) | t2); // ldp t2,t3,[sp,#16] + W(LDP2(t0, t1)); + { int64_t off = (int64_t)ret - (int64_t)(stub + 4 * (uintptr_t)n); + W(0x14000000u | (((uint32_t)(off >> 2)) & 0x03FFFFFFu)); } + return n; +} + +// Builds the stub for one instruction. Returns word count, 0 if unsupported. +static int gen(uint32_t *w, uintptr_t stub, uintptr_t ret, uint32_t i) { + unsigned size = i >> 30, rt = i & 31, rn = (i >> 5) & 31, rs = (i >> 16) & 31; + unsigned kind, op = 0, acq, rel; // kind: 0 ldop, 1 swp, 2 cas, 3 casp, 4 min/max + int n = 0; + + if ((i & 0x3FFFFC00u) == 0x38BFC000u) { // LDAPR[B|H]: stub = LDAR[B|H] (same operands, stronger ordering) ; b ret + W(0xD5033FDFu); // isb before executing the generated sequence + W((i & 0xC0000000u) | 0x08DFFC00u | (i & 0x3FFu)); + { int64_t off = (int64_t)ret - (int64_t)(stub + 4 * (uintptr_t)n); + W(0x14000000u | (((uint32_t)(off >> 2)) & 0x03FFFFFFu)); } + return n; + } + if ((i & 0x3f200c00) == 0x38200000) { + unsigned o3 = (i >> 15) & 1, opc = (i >> 12) & 7; + if (!o3 && opc <= 3) { kind = 0; op = opc; } + else if (!o3) { kind = 4; op = opc; } // LDSMAX LDSMIN LDUMAX LDUMIN (opc 4..7) + else if (o3 && opc == 0) kind = 1; + else return 0; + acq = (i >> 23) & 1; rel = (i >> 22) & 1; + } else if ((i & 0x3fa07c00) == 0x08a07c00) { + kind = 2; acq = (i >> 22) & 1; rel = (i >> 15) & 1; + } else if ((i & 0xbfa07c00) == 0x08207c00) { // CASP, 32-bit (size 0) and 64-bit (size 1) pairs + if (size > 1 || (rs & 1) || (rt & 1) || rs >= 30 || rt >= 30) return 0; + kind = 3; acq = (i >> 22) & 1; rel = (i >> 15) & 1; + } else return 0; + if (rn == 31) return 0; // sp-based: leave to trap path + if (kind == 3) return gen_casp(w, stub, ret, size, rs, rt, rn, acq, rel); + + W(0xD5033FDFu); // isb after the atomic branch redirects execution here + unsigned t[3], k = 0; // three scratch regs from x9..x17 + for (unsigned r = 9; r <= 17 && k < 3; r++) + if (r != rs && r != rt && r != rn) t[k++] = r; + unsigned t0 = t[0], t1 = t[1], t2 = t[2]; + + W(STP2(t0, t1)); + W(STR16(t2)); + if (kind == 4) { // cmp/csel below clobber NZCV, the real instruction does not + W(0xD53B4200u | t2); // mrs t2, nzcv + W(0xF9000C00u | (31u << 5) | t2); // str t2,[sp,#24] + } + int loop = n; + W(ldx(size, acq, t0, rn)); // t0 = old + if (kind == 1) { + W(stx(size, rel, t2, rs, rn)); + W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2); + } else if (kind == 4) { // LDSMAX/LDSMIN/LDUMAX/LDUMIN + static const unsigned cc[4] = { 0xC /*gt*/, 0xB /*lt*/, 0x8 /*hi*/, 0x3 /*lo*/ }; + unsigned sgn = !(op & 2), sf = (size == 3), cmpn = t0; + if (size < 2 && sgn) { // sign-extend the loaded value: sxtb/sxth wt1,wt0 + W((size == 1 ? 0x13003C00u : 0x13001C00u) | (t0 << 5) | t1); + cmpn = t1; + } + if (size < 2) // cmp wcmpn, wrs, {u,s}xt{b,h} + W(0x6B20001Fu | (rs << 16) | ((sgn ? (size == 1 ? 5u : 4u) : (size == 1 ? 1u : 0u)) << 13) | (cmpn << 5)); + else // cmp t0, rs + W((sf ? 0xEB00001Fu : 0x6B00001Fu) | (rs << 16) | (t0 << 5)); + W((sf ? 0x9A800000u : 0x1A800000u) | (rs << 16) | (cc[op - 4] << 12) | (t0 << 5) | t1); // csel t1,t0,rs,cond + W(stx(size, rel, t2, t1, rn)); + W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2); + } else if (kind == 0) { + W(alu(op, t1, t0, rs)); // t1 = new + W(stx(size, rel, t2, t1, rn)); + W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2); + } else { + if (size == 3) W(0xCA000000u | (rs << 16) | (t0 << 5) | t1); + else if (size == 2) W(0x4A000000u | (rs << 16) | (t0 << 5) | t1); // 32-bit eor + else { + W((size == 1 ? 0x53003C00u : 0x53001C00u) | (rs << 5) | t1); // uxth/uxtb + W(0xCA000000u | (t1 << 16) | (t0 << 5) | t1); + } + W(0xB5000000u | (3u << 5) | t1); // cbnz t1, fail (+3) + W(stx(size, rel, t2, rt, rn)); + W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2); + W(0xD5033F5Fu); // fail: clrex + } + if (kind == 2) { if (rs != 31) W(MOVX(rs, t0)); } + else if (rt != 31) W(MOVX(rt, t0)); + if (kind == 4) { + W(0xF9400C00u | (31u << 5) | t2); // ldr t2,[sp,#24] + W(0xD51B4200u | t2); // msr nzcv, t2 + } + W(LDR16(t2)); + W(LDP2(t0, t1)); + { int64_t off = (int64_t)ret - (int64_t)(stub + 4 * (uintptr_t)n); + W(0x14000000u | (((uint32_t)(off >> 2)) & 0x03FFFFFFu)); } + return n; +} + +/* ---- stub arenas (must sit within +-128 MiB of the patched code) ---- */ + +#define ARENA_SZ 0x10000 +#define SLOT 68 +#define MAX_ARENAS 256 +#define REACH 0x7000000 // 112 MiB, safely inside the 128 MiB branch range +#define MAX_MAPS 4096 +static struct { uintptr_t lo, hi; } maprng[MAX_MAPS]; +static volatile int nmap; +static struct { uintptr_t base, used; } arena[MAX_ARENAS]; +static volatile int narena; + +static int near_(uintptr_t b, uintptr_t pc) { + intptr_t d = (intptr_t)b - (intptr_t)pc; + return d > -(intptr_t)REACH && d < (intptr_t)REACH; +} +static int in_arena(uintptr_t a) { + int n = __atomic_load_n(&narena, __ATOMIC_ACQUIRE); // pairs with the release store in alloc_slot + for (int k = 0; k < n; k++) + if (a >= arena[k].base && a < arena[k].base + ARENA_SZ) return 1; + return 0; +} +static unsigned long hexv(const char **p); + +// Find a free 64 KiB-aligned hole within REACH using the cached map snapshot. +// Use the constructor-time mapping snapshot in the SIGILL path. mmap with +// MAP_FIXED_NOREPLACE remains the authority if another thread changes mappings. +static uintptr_t find_gap(uintptr_t pc, const uintptr_t *tr, int ntr) { + uintptr_t lo = pc > (uintptr_t)REACH + 0x100000 ? pc - REACH : 0x100000; + uintptr_t hi = pc + REACH; + uintptr_t prev = 0, best = 0, bestd = ~(uintptr_t)0; + int count = __atomic_load_n(&nmap, __ATOMIC_ACQUIRE); + for (int i = 0; i <= count; i++) { + uintptr_t s0 = i < count ? maprng[i].lo : hi; + uintptr_t e0 = i < count ? maprng[i].hi : hi; + uintptr_t g0 = prev > lo ? prev : lo; + g0 = (g0 + 0xFFFF) & ~(uintptr_t)0xFFFF; + uintptr_t g1 = (s0 < hi ? s0 : hi) & ~(uintptr_t)0xFFFF; + if (g1 > g0 && g1 - g0 >= ARENA_SZ) { + uintptr_t rlo = g0, rhi = g1 - ARENA_SZ; + uintptr_t cand = pc & ~(uintptr_t)0xFFFF; + if (cand < rlo) cand = rlo; + if (cand > rhi) cand = rhi; + for (int st = 0; st < 16; st++) { + uintptr_t pick = 0; int found = 0; + for (int w = 0; w < 2 && !found; w++) { + if (w == 1 && st == 0) continue; + uintptr_t c; + if (w == 0) { + if (cand + (uintptr_t)st * ARENA_SZ > rhi) continue; + c = cand + (uintptr_t)st * ARENA_SZ; + } else { + if (cand < rlo + (uintptr_t)st * ARENA_SZ) continue; + c = cand - (uintptr_t)st * ARENA_SZ; + } + int is_bad = 0; + for (int t = 0; t < ntr; t++) if (tr[t] == c) is_bad = 1; + if (!is_bad) { pick = c; found = 1; } + } + if (found) { + uintptr_t d = pick > pc ? pick - pc : pc - pick; + if (d < bestd) { bestd = d; best = pick; } + break; + } + } + } + if (e0 > prev) prev = e0; + if (i == count || prev >= hi) break; + } + return best; +} + +static uintptr_t alloc_slot(uintptr_t pc) { + for (int k = 0; k < narena; k++) + if (arena[k].used + SLOT <= ARENA_SZ && near_(arena[k].base, pc)) { + uintptr_t s = arena[k].base + arena[k].used; + arena[k].used += SLOT; + return s; + } + if (narena >= MAX_ARENAS) return 0; + // free hole nearest to the site, found by walking /proc/self/maps + uintptr_t tried[16]; int ntried = 0; // blocks mmap refused, don't offer them again + for (int attempt = 0; attempt < 12; attempt++) { + uintptr_t hint = find_gap(pc, tried, ntried); + if (!hint) break; + long r = sc(SYS_mmap, hint, ARENA_SZ, PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); + if ((unsigned long)r > (unsigned long)-4096) { tried[ntried++] = hint; continue; } + if ((uintptr_t)r != hint) { //kernel without MAP_FIXED_NOREPLACE moved it + sc(SYS_munmap, r, ARENA_SZ, 0, 0, 0, 0); + tried[ntried++] = hint; continue; + } + arena[narena].base = (uintptr_t)r; + arena[narena].used = SLOT; + int idx = narena; + __atomic_store_n(&narena, idx + 1, __ATOMIC_RELEASE); // publish the slot only after base/used are written + return arena[idx].base; + } + + /* The cached map snapshot may not expose a usable gap (e.g. under QEMU). + An advisory mapping is safe: the kernel chooses a free address, and we + keep it only if the generated branch can reach it. */ + uintptr_t hint = pc & ~(uintptr_t)0xFFFF; + long r = sc(SYS_mmap, hint, ARENA_SZ, PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if ((unsigned long)r > (unsigned long)-4096) return 0; + if (!near_((uintptr_t)r, pc)) { + sc(SYS_munmap, r, ARENA_SZ, 0, 0, 0, 0); + return 0; + } + arena[narena].base = (uintptr_t)r; + arena[narena].used = SLOT; + int idx = narena; + __atomic_store_n(&narena, idx + 1, __ATOMIC_RELEASE); + return arena[idx].base; +} + +/* ---- known executable file-backed ranges (parsed from /proc/self/maps) ---- */ + +#define MAX_RANGES 512 +struct file_range { + uintptr_t lo, hi; + unsigned long offset, major, minor, inode; +}; +static struct file_range rng[MAX_RANGES]; +static int nrng; + +static const struct file_range *recorded_range(uintptr_t pc) { + for (int k = 0; k < nrng; k++) + if (pc >= rng[k].lo && pc < rng[k].hi) return &rng[k]; + return NULL; +} +static unsigned long hexv(const char **p) { + unsigned long v = 0; + for (;; (*p)++) { + char c = **p; int d; + if (c >= '0' && c <= '9') d = c - '0'; + else if (c >= 'a' && c <= 'f') d = c - 'a' + 10; + else break; + v = (v << 4) | d; + } + return v; +} +static const char *skip_spaces(const char *p) { + while (*p == ' ') p++; + return p; +} + +static int file_range_at(const char *p, struct file_range *out, int remember_gap) { + struct file_range map = {0}; + map.lo = hexv(&p); + if (*p != '-') return 0; + p++; + map.hi = hexv(&p); + if (*p != ' ' || map.hi <= map.lo) return 0; + if (remember_gap && nmap < MAX_MAPS) { + maprng[nmap].lo = map.lo; maprng[nmap].hi = map.hi; + nmap = nmap + 1; + } + p = skip_spaces(p); + if (p[0] != 'r' || p[1] != '-' || p[2] != 'x' || p[3] != 'p' || p[4] != ' ') return 0; + p = skip_spaces(p + 4); + map.offset = hexv(&p); + if (*p != ' ') return 0; + p = skip_spaces(p); + map.major = hexv(&p); + if (*p != ':') return 0; + p++; + map.minor = hexv(&p); + if (*p != ' ') return 0; + p = skip_spaces(p); + while (*p >= '0' && *p <= '9') map.inode = map.inode * 10 + (unsigned)(*p++ - '0'); + if (map.inode == 0 || *p != ' ' || *skip_spaces(p) != '/') return 0; + *out = map; + return 1; +} + +static int same_file_at(const struct file_range *first, const struct file_range *now, uintptr_t pc) { + return pc >= now->lo && pc < now->hi && first->major == now->major && + first->minor == now->minor && first->inode == now->inode && + first->offset + (pc - first->lo) == now->offset + (pc - now->lo); +} + +/* The constructor records candidates. The patch lock serializes live reads + in the signal handler. Never treat a failed live read as a match. */ +static int read_ranges(const struct file_range *wanted, uintptr_t pc) { + static char buf[4096], line[512]; + long fd = sc(SYS_openat, -100, (long)"/proc/self/maps", O_RDONLY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + int ll = 0, found = 0; long n; + while (!found && (n = sc(SYS_read, fd, (long)buf, sizeof buf, 0, 0, 0)) > 0) + for (long k = 0; k < n; k++) { + char c = buf[k]; + if (c == '\n') { + struct file_range map; + line[ll] = 0; + ll = 0; + if (!file_range_at(line, &map, wanted == NULL)) continue; + if (wanted) { + if (same_file_at(wanted, &map, pc)) { found = 1; break; } + } else if (nrng < MAX_RANGES) { + rng[nrng++] = map; + } + } else if (ll < (int)sizeof line - 1) line[ll++] = c; + } + sc(SYS_close, fd, 0, 0, 0, 0, 0); + return found; +} + +static void refresh_ranges(void) { + nrng = 0; nmap = 0; + (void)read_ranges(NULL, 0); +} + +/* ---- debug log (LSE_EMU_LOG=1) ---- */ + +static int add_str(char *b, int n, const char *s); +static int add_dec(char *b, int n, unsigned long v); + +static volatile int logon; +static char logpath[200] = "/tmp/lse_emu.log"; +static unsigned long st_traps, st_patched, st_failed; + +static void logwrite(const char *b, int n) { // raw syscalls, O_APPEND: safe from the handler + long fd = sc(SYS_openat, -100, (long)logpath, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0666, 0, 0); + if (fd < 0) return; + sc(SYS_write, fd, (long)b, n, 0, 0, 0); + sc(SYS_close, fd, 0, 0, 0, 0, 0); +} +static int add_hex(char *b, int n, uint64_t v, int digits) { + for (int k = (digits - 1) * 4; k >= 0; k -= 4) b[n++] = "0123456789abcdef"[(v >> k) & 15]; + return n; +} +// One line per site, patched is logged as it happens, failures are de-duplicated. +static void logsite(const char *why, uintptr_t pc, uint32_t insn) { + if (!logon) return; + static uintptr_t seen[256]; + if (why[0] != 'p') { + for (int k = 0; k < 256; k++) + if (__atomic_load_n(&seen[k], __ATOMIC_ACQUIRE) == pc) return; + int claimed = 0; + for (int k = 0; k < 256; k++) { + uintptr_t empty = 0; + if (__atomic_compare_exchange_n(&seen[k], &empty, pc, 0, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { + claimed = 1; break; + } + } + if (!claimed) return; + } + char b[160]; int n = 0; + n = add_str(b, n, "pid="); n = add_dec(b, n, (unsigned long)sc(SYS_getpid, 0, 0, 0, 0, 0, 0)); + n = add_str(b, n, " "); n = add_str(b, n, why); + n = add_str(b, n, " pc=0x"); n = add_hex(b, n, pc, 16); + n = add_str(b, n, " insn=0x"); n = add_hex(b, n, insn, 8); + b[n++] = '\n'; + logwrite(b, n); +} +static void logstats(const char *tag) { + if (!logon) return; + char b[160]; int n = 0; + n = add_str(b, n, "pid="); n = add_dec(b, n, (unsigned long)sc(SYS_getpid, 0, 0, 0, 0, 0, 0)); + n = add_str(b, n, " "); n = add_str(b, n, tag); + n = add_str(b, n, " traps="); n = add_dec(b, n, st_traps); + n = add_str(b, n, " patched="); n = add_dec(b, n, st_patched); + n = add_str(b, n, " failed="); n = add_dec(b, n, st_failed); + n = add_str(b, n, " arenas="); n = add_dec(b, n, (unsigned long)narena); + b[n++] = '\n'; + logwrite(b, n); +} + +/* ---- patching ---- */ + +static volatile int plock, patch_enabled, stats; +static volatile int seccomp_filter_installed; +/* A per-thread guard prevents recursive acquisition from a nested SIGILL. */ +static __thread volatile sig_atomic_t patching; + +#define FUTEX_WAIT_PRIVATE 128 +#define FUTEX_WAKE_PRIVATE 129 +static size_t kernel_page_size = 4096; +static uintptr_t bad[256]; + +// Try-lock, a handler that interrupts try_patch on the same thread and traps again must never spin on a lock it already owns. A skipped site is simply retried on its next trap. +static int trylock(void) { return !__atomic_exchange_n(&plock, 1, __ATOMIC_ACQUIRE); } +static void unlock(void) { __atomic_store_n(&plock, 0, __ATOMIC_RELEASE); } + +// Overwrite one instruction word with a branch (single aligned release store), then flush the icache. +static int patch_word(uintptr_t pc, uint32_t v) { + size_t page_size = kernel_page_size ? kernel_page_size : 4096; + uintptr_t page = pc & ~((uintptr_t)page_size - 1); + if (sc(SYS_mprotect, page, page_size, PROT_READ | PROT_WRITE | PROT_EXEC, 0, 0, 0)) return -1; + __atomic_store_n((uint32_t *)pc, v, __ATOMIC_RELEASE); + __builtin___clear_cache((char *)pc, (char *)pc + 4); + if (sc(SYS_mprotect, page, page_size, PROT_READ | PROT_EXEC, 0, 0, 0)) { + if (!sc(SYS_mprotect, page, page_size, PROT_READ | PROT_EXEC, 0, 0, 0)) + return 0; + if (sc(SYS_mprotect, page, page_size, PROT_READ, 0, 0, 0)) + (void)sc(SYS_mprotect, page, page_size, PROT_NONE, 0, 0, 0); + return -2; // instruction was written, but execution permission could not be restored + } + return 0; +} + +static void try_patch(uintptr_t pc, uint32_t insn) { + uint32_t w[17]; + if (__atomic_load_n(&seccomp_filter_installed, __ATOMIC_ACQUIRE) || + !__atomic_load_n(&patch_enabled, __ATOMIC_ACQUIRE)) return; + if (bad[(pc >> 2) & 255] == pc) return; + if (!gen(w, 0, 0, insn)) { logsite("unsupported-form", pc, insn); return; } // not a patchable form + // The remaining generated atomic stubs save scratch registers on the guest + // stack. Keep them on the trap path: a later caller may have no stack headroom. + if ((insn & 0x3FFFFC00u) != 0x38BFC000u) return; + + if (patching) return; + /* Mark this thread before touching the lock: the lock operation itself + can fault and re-enter this handler on CPUs without native LSE. */ + patching = 1; + if (!trylock()) { + /* Nested faults return at the function entry while this thread + owns or waits for the patch operation. */ + for (;;) { + (void)sc(SYS_futex, (long)&plock, FUTEX_WAIT_PRIVATE, 1, 0, 0, 0); + if (trylock()) break; + } + } + const struct file_range *recorded = recorded_range(pc); + if (!recorded || !read_ranges(recorded, pc)) { + logsite("not-current-file-mapping", pc, insn); + bad[(pc >> 2) & 255] = pc; + goto out; + } + if (*(volatile uint32_t *)pc != insn) goto out; + uintptr_t slot = alloc_slot(pc); + if (!slot) { logsite("no-arena", pc, insn); bad[(pc >> 2) & 255] = pc; st_failed++; goto out; } + int n = gen(w, slot, pc + 4, insn); + + for (int k = 0; k < n; k++) ((volatile uint32_t *)slot)[k] = w[k]; + __builtin___clear_cache((char *)slot, (char *)slot + 4 * n); + + long off = (long)slot - (long)pc; + uint32_t b = 0x14000000u | (((uint32_t)(off >> 2)) & 0x03FFFFFFu); + if (!read_ranges(recorded, pc) || *(volatile uint32_t *)pc != insn) { + bad[(pc >> 2) & 255] = pc; + goto out; + } + int patch_result = patch_word(pc, b); + if (patch_result) { + logsite(patch_result == -2 ? "rx-restore-failed" : "mprotect-failed", pc, insn); + bad[(pc >> 2) & 255] = pc; st_failed++; + if (patch_result == -2) + (void)sc(SYS_exit_group, 128 + SIGSEGV, 0, 0, 0, 0, 0); + goto out; + } + st_patched++; + logsite("patched", pc, insn); +out: + unlock(); + (void)sc(SYS_futex, (long)&plock, FUTEX_WAKE_PRIVATE, INT32_MAX, 0, 0, 0); + patching = 0; +} + +/* ======================= libc hooks (unchanged logic) ===================== */ + +static int (*real_sigaction)(int, const struct sigaction *, struct sigaction *); +static int (*real_sigprocmask)(int, const sigset_t *, sigset_t *); +static int (*real_pthread_sigmask)(int, const sigset_t *, sigset_t *); +static long (*real_syscall)(long, ...); + +static void resolve(void) { + if (!real_sigaction) real_sigaction = dlsym(RTLD_NEXT, "sigaction"); + if (!real_sigprocmask) real_sigprocmask = dlsym(RTLD_NEXT, "sigprocmask"); + if (!real_pthread_sigmask) real_pthread_sigmask = dlsym(RTLD_NEXT, "pthread_sigmask"); + if (!real_syscall) real_syscall = dlsym(RTLD_NEXT, "syscall"); +} + +static volatile int active, app_replaced; +struct app_action { void *h; unsigned long f; sigset_t mask; int valid; }; +/* Retire a slot only after taking it out of current_app_action. A reader + that still holds it must have entered before that exchange. After claiming + the retired slot, a zero reader count therefore permits reuse. */ +#define APP_ACTION_SLOTS 256 +enum { ACTION_FREE, ACTION_IN_USE, ACTION_RETIRED }; +static struct app_action default_app_action; +static struct app_action early_app_action; +static struct app_action app_action_slots[APP_ACTION_SLOTS]; +static unsigned char app_action_state[APP_ACTION_SLOTS]; +static unsigned int app_action_readers; +static struct app_action *current_app_action = &default_app_action; +struct ksa { void *h; unsigned long f; void *restorer; uint64_t mask; }; +static struct ksa early_previous; +static volatile int early_saved_valid, early_disabled; + +/* fork() can be called from an unrelated signal handler. Prevent that handler + from interrupting this thread inside a snapshot or slot publication. This + does not run on the ordinary LSE emulation path. */ +static long block_action_signals(uint64_t *previous) { + uint64_t all = UINT64_MAX; + return sc(SYS_rt_sigprocmask, SIG_BLOCK, (long)&all, (long)previous, 8, 0, 0); +} +static void restore_action_signals(long blocked, const uint64_t *previous) { + if (blocked == 0) + (void)sc(SYS_rt_sigprocmask, SIG_SETMASK, (long)previous, 0, 8, 0, 0); +} + +/* Only the forking thread survives. Its live action is the last published + complete slot, not an unpublished write or the old process's reader count. */ +static void reset_after_fork(void) { + uint64_t previous = 0; + long blocked = block_action_signals(&previous); + struct app_action *current = __atomic_load_n(¤t_app_action, __ATOMIC_SEQ_CST); + __atomic_store_n(&app_action_readers, 0, __ATOMIC_SEQ_CST); + for (int i = 0; i < APP_ACTION_SLOTS; i++) + __atomic_store_n(&app_action_state[i], current == &app_action_slots[i] ? ACTION_IN_USE : ACTION_FREE, + __ATOMIC_RELEASE); + __atomic_store_n(&plock, 0, __ATOMIC_RELEASE); + patching = 0; + restore_action_signals(blocked, &previous); +} + +static void load_app_action(struct app_action *out) { + uint64_t previous = 0; + long blocked = block_action_signals(&previous); + __atomic_add_fetch(&app_action_readers, 1, __ATOMIC_SEQ_CST); + struct app_action *snapshot = __atomic_load_n(¤t_app_action, __ATOMIC_SEQ_CST); + *out = *snapshot; + __atomic_sub_fetch(&app_action_readers, 1, __ATOMIC_SEQ_CST); + restore_action_signals(blocked, &previous); +} +static void retire_app_action(struct app_action *old) { + if (old != &default_app_action && old != &early_app_action) { + __atomic_store_n(&app_action_state[old - app_action_slots], ACTION_RETIRED, __ATOMIC_RELEASE); + } +} + +static void replace_app_action(struct app_action *next, struct app_action *old_out) { + struct app_action *old = __atomic_exchange_n(¤t_app_action, next, __ATOMIC_SEQ_CST); + if (old_out) *old_out = *old; + retire_app_action(old); +} +static int publish_app_action(void *h, unsigned long flags, const sigset_t *mask, int valid, + struct app_action *old_out) { + uint64_t previous = 0; + long blocked = block_action_signals(&previous); + /* Never wait for a suspended publisher or reader in a nested handler. */ + for (int reclaim = 0; reclaim <= 1; reclaim++) { + unsigned char state = reclaim ? ACTION_RETIRED : ACTION_FREE; + for (int i = 0; i < APP_ACTION_SLOTS; i++) { + unsigned char expected = state; + if (__atomic_load_n(&app_action_state[i], __ATOMIC_RELAXED) != state || + !__atomic_compare_exchange_n(&app_action_state[i], &expected, ACTION_IN_USE, 0, + __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) continue; + if (state == ACTION_RETIRED && __atomic_load_n(&app_action_readers, __ATOMIC_SEQ_CST) != 0) { + __atomic_store_n(&app_action_state[i], ACTION_RETIRED, __ATOMIC_RELEASE); + continue; + } + struct app_action *next = &app_action_slots[i]; + next->h = h; next->f = flags; next->mask = *mask; next->valid = valid; + replace_app_action(next, old_out); + restore_action_signals(blocked, &previous); + return 0; + } + } + restore_action_signals(blocked, &previous); + errno = ENOMEM; + return -1; +} +/* Keep the publication pinned across snapshot and conditional consumption. + Slot reclamation cannot reuse that address while our reader is live. */ +static void select_app_action(struct app_action *out) { + uint64_t previous = 0; + long blocked = block_action_signals(&previous); + __atomic_add_fetch(&app_action_readers, 1, __ATOMIC_SEQ_CST); + for (;;) { + struct app_action *selected = __atomic_load_n(¤t_app_action, __ATOMIC_SEQ_CST); + *out = *selected; + if (!out->valid || out->h == (void *)SIG_IGN || out->h == (void *)SIG_DFL || + !(out->f & SA_RESETHAND)) break; + if (__atomic_compare_exchange_n(¤t_app_action, &selected, &default_app_action, 0, + __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { + retire_app_action(selected); + break; + } + } + __atomic_sub_fetch(&app_action_readers, 1, __ATOMIC_SEQ_CST); + restore_action_signals(blocked, &previous); +} + +int sigaction(int sig, const struct sigaction *act, struct sigaction *old) { + resolve(); + if (!active || sig != SIGILL) return real_sigaction(sig, act, old); + struct sigaction requested; + if (act) requested = *act; + struct app_action snapshot; + if (act) { + if (publish_app_action((void *)requested.sa_sigaction, (unsigned long)requested.sa_flags, + &requested.sa_mask, 1, &snapshot) < 0) return -1; + app_replaced = 1; + } else { + load_app_action(&snapshot); + } + if (old) { + memset(old, 0, sizeof *old); + if (snapshot.valid) { + old->sa_sigaction = snapshot.h; + old->sa_flags = (int)(snapshot.f & ~(unsigned long)SA_RESTORER); + old->sa_mask = snapshot.mask; + } else old->sa_handler = SIG_DFL; + } + return 0; +} + +sighandler_t signal(int sig, sighandler_t h) { + struct sigaction sa, o; + memset(&sa, 0, sizeof sa); + sa.sa_handler = h; sa.sa_flags = SA_RESTART; + sigemptyset(&sa.sa_mask); + if (sigaction(sig, &sa, &o) < 0) return SIG_ERR; + return o.sa_handler; +} + +int sigprocmask(int how, const sigset_t *set, sigset_t *old) { + resolve(); + if (active && set && how != SIG_UNBLOCK) { + sigset_t t = *set; sigdelset(&t, SIGILL); + return real_sigprocmask(how, &t, old); + } + return real_sigprocmask(how, set, old); +} +int pthread_sigmask(int how, const sigset_t *set, sigset_t *old) { + resolve(); + if (active && set && how != SIG_UNBLOCK) { + sigset_t t = *set; sigdelset(&t, SIGILL); + return real_pthread_sigmask(how, &t, old); + } + return real_pthread_sigmask(how, set, old); +} + +// a process that turns on seccomp must not be patched afterwards +int prctl(int opt, ...) { + va_list ap; va_start(ap, opt); + unsigned long a1 = va_arg(ap, unsigned long), a2 = va_arg(ap, unsigned long); + unsigned long a3 = va_arg(ap, unsigned long), a4 = va_arg(ap, unsigned long); + va_end(ap); + resolve(); + int result = (int)real_syscall(SYS_prctl, (long)opt, a1, a2, a3, a4); + if (opt == PR_SET_SECCOMP && result == 0) { + __atomic_store_n(&seccomp_filter_installed, 1, __ATOMIC_RELEASE); + __atomic_store_n(&patch_enabled, 0, __ATOMIC_RELEASE); + } + return result; +} + +long syscall(long n, ...) { + unsigned long a[6]; + va_list ap; va_start(ap, n); + for (int k = 0; k < 6; k++) a[k] = va_arg(ap, unsigned long); + va_end(ap); + resolve(); + if (active) { +#ifdef SYS_seccomp +#endif + if (n == SYS_rt_sigaction && a[0] == SIGILL) { + if (a[3] != 8) { errno = EINVAL; return -1; } + struct ksa *act = (struct ksa *)a[1], *old = (struct ksa *)a[2]; + struct ksa requested; + if (act) requested = *act; + sigset_t requested_mask; + memset(&requested_mask, 0, sizeof requested_mask); + if (act) memcpy(&requested_mask, &requested.mask, sizeof requested.mask); + struct app_action snapshot; + if (act) { + if (publish_app_action(requested.h, requested.f, &requested_mask, 1, &snapshot) < 0) return -1; + app_replaced = 1; + } else { + load_app_action(&snapshot); + } + if (old) { + memset(old, 0, sizeof *old); + if (snapshot.valid) { + old->h = snapshot.h; old->f = snapshot.f; + memcpy(&old->mask, &snapshot.mask, sizeof old->mask); + } + } + /* act was staged before old was written, so aliased buffers are safe. */ + return 0; + } + if (n == SYS_rt_sigprocmask && a[1] && a[3] == 8 && a[0] != SIG_UNBLOCK) { + uint64_t m = *(uint64_t *)a[1]; + m &= ~(1ULL << (SIGILL - 1)); + return real_syscall(n, a[0], &m, a[2], a[3], a[4], a[5]); + } + } + long result = real_syscall(n, a[0], a[1], a[2], a[3], a[4], a[5]); +#ifdef SYS_seccomp + if (active && n == SYS_seccomp && + (result == 0 || (result >= 0 && (a[1] & 8UL) != 0))) { + __atomic_store_n(&seccomp_filter_installed, 1, __ATOMIC_RELEASE); + __atomic_store_n(&patch_enabled, 0, __ATOMIC_RELEASE); + } +#endif + if (active && n == SYS_prctl && a[0] == PR_SET_SECCOMP && result == 0) { + __atomic_store_n(&seccomp_filter_installed, 1, __ATOMIC_RELEASE); + __atomic_store_n(&patch_enabled, 0, __ATOMIC_RELEASE); + } + return result; +} + +/* TLS keeps re-entry state isolated between threads and signal-safe. */ +static __thread volatile sig_atomic_t forwarding_app_handler; +static __thread uintptr_t forwarding_app_stack; + +static void forward_app_sigill(void *h, unsigned long flags, const sigset_t *mask_set, + int sig, siginfo_t *si, void *ctx) { + uint64_t mask = 0, oldmask = 0; + memcpy(&mask, mask_set, sizeof mask); + if (!(flags & SA_NODEFER)) mask |= 1ULL << (SIGILL - 1); + long blocked = sc(SYS_rt_sigprocmask, SIG_BLOCK, (long)&mask, + (long)&oldmask, 8, 0, 0); + uintptr_t marker = (uintptr_t)&mask; + sig_atomic_t was_forwarding = forwarding_app_handler; + uintptr_t was_stack = forwarding_app_stack; + forwarding_app_handler = 1; + forwarding_app_stack = marker; + if (flags & SA_SIGINFO) + ((void (*)(int, siginfo_t *, void *))h)(sig, si, ctx); + else + ((void (*)(int))h)(sig); + forwarding_app_handler = was_forwarding; + forwarding_app_stack = was_stack; + if (blocked == 0) + (void)sc(SYS_rt_sigprocmask, SIG_SETMASK, (long)&oldmask, 0, 8, 0, 0); +} + +/* ======================= handler ========================================== */ + +static void put_hex(uint64_t v) { + char b[18]; b[0] = '0'; b[1] = 'x'; + for (int k = 0; k < 16; k++) b[2 + k] = "0123456789abcdef"[(v >> (60 - 4 * k)) & 15]; + (void)!write(2, b, 18); +} + +static void on_sigill(int sig, siginfo_t *si, void *ctx) { + if (!si || si->si_code <= 0) { + uintptr_t marker = (uintptr_t)▮ + /* A siglongjmp can abandon the forwarding frame; detect the stale TLS + state when execution later resumes at a shallower stack address. */ + if (forwarding_app_handler && marker >= forwarding_app_stack) { + forwarding_app_handler = 0; + forwarding_app_stack = 0; + } + /* With SA_NODEFER, a nested application-generated SIGILL may be + delivered recursively; otherwise the forwarded mask keeps it pending. */ + struct app_action snapshot; select_app_action(&snapshot); + void *h = snapshot.h; unsigned long flags = snapshot.f; + if (snapshot.valid && h == (void *)SIG_IGN) return; + if (snapshot.valid && h != (void *)SIG_DFL && h != (void *)SIG_IGN) { + forward_app_sigill(h, flags, &snapshot.mask, sig, si, ctx); + return; + } + struct ksa dfl = { (void *)SIG_DFL, 0, 0, 0 }; + (void)sc(SYS_rt_sigaction, SIGILL, (long)&dfl, 0, 8, 0, 0); + (void)sc(SYS_tgkill, sc(SYS_getpid, 0, 0, 0, 0, 0, 0), + sc(SYS_gettid, 0, 0, 0, 0, 0, 0), SIGILL, 0, 0, 0); + return; + } + ucontext_t *uc = (ucontext_t *)ctx; + uintptr_t pc = uc->uc_mcontext.pc; + uint32_t insn = __atomic_load_n((uint32_t *)pc, __ATOMIC_ACQUIRE); // pairs with the release store in patch_word + + if ((insn & 0xFC000000u) == 0x14000000u) { // another thread patched it first + intptr_t off = ((int32_t)(insn << 6)) >> 4; + if (in_arena(pc + off)) return; // just re-execute the new branch + } + + if (emulate(uc, insn)) { + uc->uc_mcontext.pc = pc + 4; + st_traps++; + if (__atomic_load_n(&patch_enabled, __ATOMIC_ACQUIRE)) try_patch(pc, insn); + else if (logon) logsite("no-patch", pc, insn); + if (logon && !(st_traps & 0x3FFF)) logstats("stats"); // every 16384 traps + return; + } + + logsite("unhandled", pc, insn); + (void)!write(2, "lse_emu: unhandled pc=", 22); + put_hex(pc); + (void)!write(2, " insn=", 6); + put_hex(insn); + (void)!write(2, "\n", 1); + + /* A nested synchronous fault gets one emulation attempt, never re-forwarding. */ + if (forwarding_app_handler) { + (void)sc(SYS_exit_group, 128 + SIGILL, 0, 0, 0, 0, 0); + return; + } + + struct app_action snapshot; select_app_action(&snapshot); + void *h = snapshot.h; unsigned long flags = snapshot.f; + if (snapshot.valid && h != (void *)SIG_DFL && h != (void *)SIG_IGN) { + forward_app_sigill(h, flags, &snapshot.mask, sig, si, ctx); + return; + } + struct ksa dfl = { (void *)SIG_DFL, 0, 0, 0 }; + sc(SYS_rt_sigaction, SIGILL, (long)&dfl, 0, 8, 0, 0); +} + +/* ======================= early install ==================================== */ + +// A dependency may execute LSE in its constructor before this preload's constructor. +static void early_target(void) {} +static void (*early_install(uint64_t hwcap))(void) { + /* IFUNC resolution may happen more than once; never save our own handler + as the original action or re-enable emulation after init disables it. */ + if (!(hwcap & HWCAP_ATOMICS) && !early_saved_valid && !early_disabled) { + unsigned long restart = early_saved_valid ? (early_previous.f & SA_RESTART) : 0; + struct ksa k = { (void *)on_sigill, SA_SIGINFO | SA_ONSTACK | SA_NODEFER | restart, 0, 0 }; + if (sc(SYS_rt_sigaction, SIGILL, (long)&k, (long)&early_previous, 8, 0, 0) == 0) { + early_saved_valid = 1; + early_app_action.h = early_previous.h; early_app_action.f = early_previous.f; + memset(&early_app_action.mask, 0, sizeof early_app_action.mask); + memcpy(&early_app_action.mask, &early_previous.mask, sizeof early_previous.mask); + early_app_action.valid = early_previous.h != (void *)SIG_DFL; + __atomic_store_n(¤t_app_action, &early_app_action, __ATOMIC_RELEASE); + active = 1; + } + } + return early_target; +} +__attribute__((visibility("hidden"))) void lse_emu_early(void) __attribute__((ifunc("early_install"))); +void (*volatile lse_emu_early_ref)(void) = lse_emu_early; + +/* ======================= init / fini ====================================== */ + +static int add_str(char *b, int n, const char *s) { while (*s) b[n++] = *s++; return n; } +static int add_dec(char *b, int n, unsigned long v) { + char t[21]; int k = 0; + if (!v) t[k++] = '0'; + while (v) { t[k++] = '0' + v % 10; v /= 10; } + while (k) b[n++] = t[--k]; + return n; +} + +static int skipped(void) { // LSE_EMU_SKIP=name:name + const char *s = getenv("LSE_EMU_SKIP"); + if (!s || !*s) return 0; + char exe[512]; ssize_t r = readlink("/proc/self/exe", exe, sizeof exe - 1); + if (r <= 0) return 0; + exe[r] = 0; + char tok[128]; + while (*s) { + int k = 0; + while (*s && *s != ':' && k < 127) tok[k++] = *s++; + tok[k] = 0; + if (*s == ':') s++; + if (k && strstr(exe, tok)) return 1; + } + return 0; +} + +static void disable_early(void) { + if (!active) return; + struct sigaction sa; + memset(&sa, 0, sizeof sa); + struct app_action snapshot; load_app_action(&snapshot); + if (app_replaced) { + if (snapshot.valid) { + if (snapshot.f & SA_SIGINFO) sa.sa_sigaction = snapshot.h; + else sa.sa_handler = snapshot.h; + sa.sa_flags = (int)(snapshot.f & ~(unsigned long)SA_RESTORER); + sa.sa_mask = snapshot.mask; + } else sa.sa_handler = SIG_DFL; + } else if (early_saved_valid) { + if (early_previous.f & SA_SIGINFO) sa.sa_sigaction = early_previous.h; + else sa.sa_handler = early_previous.h; + sa.sa_flags = (int)(early_previous.f & ~(unsigned long)SA_RESTORER); + memcpy(&sa.sa_mask, &early_previous.mask, sizeof early_previous.mask); + } else sa.sa_handler = SIG_DFL; + int restored = -1; + if (app_replaced) { + restored = real_sigaction(SIGILL, &sa, NULL); + } else { + struct ksa kernel_sa = { (void *)SIG_DFL, 0, 0, 0 }; + if (early_saved_valid) kernel_sa = early_previous; + restored = (int)sc(SYS_rt_sigaction, SIGILL, (long)&kernel_sa, 0, 8, 0, 0); + } + if (restored == 0) active = 0; +} + +__attribute__((constructor)) static void init(void) { + (void)pthread_atfork(NULL, NULL, reset_after_fork); + resolve(); + long page_size = sysconf(_SC_PAGESIZE); + if (page_size > 0 && (((unsigned long)page_size & ((unsigned long)page_size - 1)) == 0)) + kernel_page_size = (size_t)page_size; + // The early IFUNC resolver can install the handler before this constructor. + // Always remove it when emulation is disabled, even if HWCAP disagrees with + // the resolver's view of the CPU features. + const char *emu_env = getenv("LSE_EMU"); + if (!emu_env || emu_env[0] != '1') { + early_disabled = 1; + disable_early(); + return; + } + + if (getauxval(AT_HWCAP) & HWCAP_ATOMICS) { + early_disabled = 1; + disable_early(); + return; // CPU has real LSE + } + + struct sigaction sa; memset(&sa, 0, sizeof sa); + sa.sa_sigaction = on_sigill; + sa.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_NODEFER | + (early_saved_valid ? (int)(early_previous.f & SA_RESTART) : 0); + sigemptyset(&sa.sa_mask); + if (real_sigaction(SIGILL, &sa, NULL) == 0) active = 1; + else if (!active) return; + + const char *p = getenv("LSE_EMU_PATCH"); + stats = getenv("LSE_EMU_STATS") != NULL; + /* LSE_EMU_PATCH=1 is an explicit opt-in to code modification. If a + restrictive seccomp filter was inherited, patching may fail or the + process may be terminated when mmap/mprotect is denied. Trap-only mode + remains the default; hooks veto patching when this process installs a + filter later. */ + if (p && p[0] == '1' && !skipped() && + !__atomic_load_n(&seccomp_filter_installed, __ATOMIC_ACQUIRE)) { + refresh_ranges(); + if (!__atomic_load_n(&seccomp_filter_installed, __ATOMIC_ACQUIRE)) + __atomic_store_n(&patch_enabled, 1, __ATOMIC_RELEASE); + } + + const char *lg = getenv("LSE_EMU_LOG"); // =1 -> /tmp/lse_emu.log, =/path -> that file + if (lg && lg[0] && lg[0] != '0') { + if (lg[0] == '/') { size_t l = strlen(lg); if (l < sizeof logpath) memcpy(logpath, lg, l + 1); } + logon = 1; + char b[700], exe[480]; int n = 0; + ssize_t r = readlink("/proc/self/exe", exe, sizeof exe - 1); + exe[r > 0 ? r : 0] = 0; + n = add_str(b, n, "pid="); n = add_dec(b, n, (unsigned long)getpid()); + n = add_str(b, n, " start patch="); n = add_dec(b, n, (unsigned long)patch_enabled); + n = add_str(b, n, " exe="); n = add_str(b, n, exe); + b[n++] = '\n'; + logwrite(b, n); + } +} + +__attribute__((destructor)) static void fini(void) { + if (!active) return; + logstats("exit"); + if (!stats) return; + char b[160]; int n = 0; + n = add_str(b, n, "lse_emu: pid="); n = add_dec(b, n, (unsigned long)getpid()); + n = add_str(b, n, " traps="); n = add_dec(b, n, st_traps); + n = add_str(b, n, " patched="); n = add_dec(b, n, st_patched); + n = add_str(b, n, " failed="); n = add_dec(b, n, st_failed); + b[n++] = '\n'; + (void)!write(2, b, n); +} \ No newline at end of file diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session old mode 100755 new mode 100644 index d82fb99350..10d522084d --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -11,6 +11,12 @@ if [ "${DD_RAISE_NOFILE:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ]; then unset dd_nofile_was fi export HOME=${HOME:-/root} +if grep -qs '/liblse_emu\.so$' /etc/ld.so.preload; then + if [ "${LSE_EMU+x}" != x ]; then export LSE_EMU=1; fi + # Runtime instruction rewriting is opt-in; the SIGILL emulation path remains available. + export LSE_EMU_PATCH=${LSE_EMU_PATCH:-0} + [ -n "${DD_DEBUG_DIR:-}" ] && export LSE_EMU_LOG=${LSE_EMU_LOG:-$DD_DEBUG_DIR/lse_emu.log} +fi mode=${1:-desktop} shift || true @@ -100,6 +106,7 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}" echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)" echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)" + [ "${LSE_EMU:-}" = 1 ] && echo "== cpu: no LSE atomics (ARMv8.0); liblse_emu.so emulates them (log: ${LSE_EMU_LOG:-off})" fi start_diagnostic_inventory() { diff --git a/tools/linuxfs/preload/pathcache.c b/tools/linuxfs/preload/pathcache.c index beefbfbe24..6d6a7146fb 100644 --- a/tools/linuxfs/preload/pathcache.c +++ b/tools/linuxfs/preload/pathcache.c @@ -56,27 +56,38 @@ static unsigned hash_of(const char *s, int kind, int mode, int flags) { return h; } -static struct entry *slot(unsigned h) { - return &table[(h ^ (h >> 16)) % PATH_CACHE_SLOTS]; -} - static int cacheable(const char *path) { return path != NULL && path[0] == '/' && strlen(path) < PATH_CACHE_KEY_MAX && enabled(); } static struct entry *find(const char *path, int kind, int mode, int flags, unsigned h) { - struct entry *e = slot(h); + long long now = now_ns(); - if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) return NULL; - if (now_ns() - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) return NULL; - return e; + for (int i = 0; i < PATH_CACHE_SLOTS; i++) { + struct entry *e = &table[i]; + if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) continue; + if (now - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) continue; + return e; + } + return NULL; } static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) { - struct entry *e = slot(h); + struct entry *e = find(path, kind, mode, flags, h); + long long now = now_ns(); char *copy = value != NULL ? strdup(value) : NULL; if (value != NULL && copy == NULL) return; + if (e == NULL) { + e = &table[0]; + for (int i = 0; i < PATH_CACHE_SLOTS; i++) { + if (table[i].stamp == 0 || now - table[i].stamp > PATH_CACHE_TTL_NS) { + e = &table[i]; + break; + } + if (table[i].stamp < e->stamp) e = &table[i]; + } + } free(e->value); e->value = copy; e->hash = h; @@ -84,7 +95,7 @@ static void store(const char *path, int kind, int mode, int flags, unsigned h, c e->mode = mode; e->flags = flags; memcpy(e->key, path, strlen(path) + 1); - e->stamp = now_ns(); + e->stamp = now; } __attribute__((visibility("hidden"))) diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c index d83ad87492..53f1da0f8b 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -41,9 +41,73 @@ static char **clean_env_for_system(char *const envp[]) { return new_env; } +static int preload_has_entry(const char *chain, const char *entry, size_t entry_len) { + if (!chain || !entry_len) return 0; + const char *p = chain; + while (*p) { + size_t len = strcspn(p, ": "); + if (len == entry_len && memcmp(p, entry, len) == 0) return 1; + p += len; + if (*p) p++; + } + return 0; +} + +static char *merge_preload_env(const char *host, const char *mapped) { + size_t host_len = host ? strlen(host) : 0; + char *out = malloc(11 + host_len + 1 + strlen(mapped) + 1); + if (!out) return NULL; + memcpy(out, "LD_PRELOAD=", 11); + size_t used = 11; + if (host_len) { + memcpy(out + used, host, host_len); + used += host_len; + } + for (const char *p = mapped; *p; ) { + size_t n = strcspn(p, ": "); + if (n && !preload_has_entry(host, p, n)) { + if (used > 11) out[used++] = ':'; + memcpy(out + used, p, n); + used += n; + } + p += n; + if (*p) p++; + } + out[used] = '\0'; + return out; +} + +// Filter the LSE emulator from colon/space-separated preload chains when explicitly disabled. +static char *filter_lse_emu_preloads(const char *value, int lse_emu_disabled) { + if (!value) return NULL; + size_t len = strlen(value); + char *out = malloc(len + 1); + if (!out) return NULL; + size_t used = 0; + const char *p = value; + while (*p) { + size_t n = strcspn(p, ": "); + if (n) { + const char *base = p + n; + while (base > p && base[-1] != '/' && base[-1] != ':' && base[-1] != ' ') base--; + int is_lse_emu = n - (size_t)(base - p) == strlen("liblse_emu.so") && + memcmp(base, "liblse_emu.so", strlen("liblse_emu.so")) == 0; + if (!(lse_emu_disabled && is_lse_emu)) { + if (used) out[used++] = ':'; + memcpy(out + used, p, n); + used += n; + } + } + p += n; + if (*p) p++; + } + out[used] = '\0'; + return out; +} + // LD_PRELOAD with every absolute path that is not in the rootfs yet mapped into it. Entries are // separated by ':' or ' '. free() the result. -static char *map_preload_paths(const char *value) { +static char *map_preload_paths(const char *value, int lse_emu_disabled) { if (!value) return NULL; size_t cap = strlen(value) + (g_ddnatv_root_len + 1) * 16 + 16; char *out = malloc(cap); @@ -57,6 +121,13 @@ static char *map_preload_paths(const char *value) { char entry[PATH_MAX]; memcpy(entry, p, len); entry[len] = '\0'; + const char *base = strrchr(entry, '/'); + base = base ? base + 1 : entry; + if (lse_emu_disabled && strcmp(base, "liblse_emu.so") == 0) { + p += len; + if (*p) p++; + continue; + } char buf[PATH_MAX]; const char *mapped = entry[0] == '/' ? rewrite_path_in_root(entry, buf, sizeof(buf)) : entry; size_t mlen = strlen(mapped); @@ -72,10 +143,13 @@ static char *map_preload_paths(const char *value) { return out; } +static void free_modified_env(char **modified_env, char *const orig_env[]); + static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) { init_ddnatv_hook(); int count = 0; int has_preload = 0; + int lse_emu_disabled = 0; int has_root = 0; int has_tunables = 0; int has_path = 0; @@ -105,6 +179,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const switch (e[0]) { case 'L': if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; } + else if (strncmp(e, "LSE_EMU=0", 9) == 0 && e[9] == '\0') lse_emu_disabled = 1; break; case 'G': if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1; @@ -140,6 +215,12 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const count++; } + char *filtered_host_chain = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_host, 1) : NULL; + if (lse_emu_disabled && g_preload_host && !filtered_host_chain) { + errno = ENOMEM; + return NULL; + } + const char *host_preload = lse_emu_disabled ? (filtered_host_chain ? filtered_host_chain : "") : g_preload_host; char **new_env = calloc(count + 26, sizeof(char *)); int dst = 0; // The user the program runs as (hardlinks.c): this process's, whatever the environment it passes @@ -157,23 +238,45 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) { continue; } + if (lse_emu_disabled && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_PRELOAD=", 15) == 0) { + char *filtered = filter_lse_emu_preloads(envp[i] + 15, 1); + if (!filtered) { + free_modified_env(new_env, envp); + free(filtered_host_chain); + errno = ENOMEM; + return NULL; + } + size_t len = 15 + strlen(filtered) + 1; + char *str = malloc(len); + if (!str) { + free(filtered); + free_modified_env(new_env, envp); + free(filtered_host_chain); + errno = ENOMEM; + return NULL; + } + snprintf(str, len, "DDNATV_PRELOAD=%s", filtered); + new_env[dst++] = str; + free(filtered); + continue; + } if (has_preload && envp[i][0] == 'L' && strncmp(envp[i], "LD_PRELOAD=", 11) == 0) { // ld.so opens these itself: the guest's paths are mapped to the rootfs, and the libraries every // program loads (DDNATV_PRELOAD) come first - char *mapped = map_preload_paths(preload_value); + char *mapped = map_preload_paths(preload_value, lse_emu_disabled); if (mapped) { - size_t chain = g_preload_host ? strlen(g_preload_host) : 0; - int has_chain = chain > 0 && strstr(mapped, g_preload_host) != NULL; - size_t len = 11 + chain + 1 + strlen(mapped) + 1; - char *str = malloc(len); + char *str = merge_preload_env(host_preload, mapped); + free(mapped); if (str) { - if (chain > 0 && !has_chain) snprintf(str, len, "LD_PRELOAD=%s:%s", g_preload_host, mapped); - else snprintf(str, len, "LD_PRELOAD=%s", mapped); new_env[dst++] = str; - free(mapped); continue; } - free(mapped); + } + if (lse_emu_disabled) { + free_modified_env(new_env, envp); + free(filtered_host_chain); + errno = ENOMEM; + return NULL; } } // If we have an explicit real executable, drop the inherited entry to replace with the fresh target @@ -211,13 +314,13 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL; if (hook) { size_t hook_len = strlen(hook); - size_t host_len = g_preload_host ? strlen(g_preload_host) + 1 : 0; + size_t host_len = host_preload ? strlen(host_preload) + 1 : 0; size_t size = 11 + host_len + hook_len + 1; char *str = malloc(size); if (str) { size_t n = ddnatv_append(str, size, 0, "LD_PRELOAD=", 11); if (host_len) { - n = ddnatv_append(str, size, n, g_preload_host, host_len - 1); + n = ddnatv_append(str, size, n, host_preload, host_len - 1); n = ddnatv_append(str, size, n, ":", 1); } ddnatv_append(str, size, n, hook, hook_len); @@ -225,13 +328,29 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const } } if (!has_preload_list && g_preload_guest) { - size_t len = strlen(g_preload_guest); - char *str = malloc(15 + len + 1); - if (str) { + char *filtered = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_guest, 1) : NULL; + if (lse_emu_disabled && !filtered) { + free_modified_env(new_env, envp); + free(filtered_host_chain); + errno = ENOMEM; + return NULL; + } + const char *guest_preload = lse_emu_disabled ? filtered : g_preload_guest; + if (guest_preload) { + size_t len = strlen(guest_preload); + char *str = malloc(15 + len + 1); + if (!str) { + free(filtered); + free_modified_env(new_env, envp); + free(filtered_host_chain); + errno = ENOMEM; + return NULL; + } memcpy(str, "DDNATV_PRELOAD=", 15); - memcpy(str + 15, g_preload_guest, len + 1); + memcpy(str + 15, guest_preload, len + 1); new_env[dst++] = str; } + free(filtered); } if (!has_root && g_ddnatv_root[0] != '\0') { char *str = malloc(PATH_MAX + 16); @@ -319,6 +438,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const new_env[dst++] = strdup("DEBCONF_NONINTERACTIVE_SEEN=true"); } new_env[dst] = NULL; + free(filtered_host_chain); return new_env; } diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index ede8c4354d..8ffbe4eeca 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -483,6 +483,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e return -1; } char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path); + if (!new_env) { + free(new_argv); + errno = ENOMEM; + return -1; + } int ret = run_execve(orig_execve, ld_so, new_argv, new_env); if (errno == EACCES && chmod(ld_so, 0755) == 0) { // ld.so without its exec bit (an unusual restore): fix it once and retry @@ -507,6 +512,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e if (new_argv) { prepare_static_program(static_elf); // ld.so is a static program itself char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); + if (!ddnatv_env) { + free(new_argv); + errno = ENOMEM; + return -1; + } int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -559,6 +569,10 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e if (static_elf) prepare_static_program(static_elf); char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); + if (!ddnatv_env) { + errno = ENOMEM; + return -1; + } int ret = run_execve(orig_execve, target, argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -1021,6 +1035,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL) : clean_env_for_system(orig_ep); + if (in_root && !new_envp) return ENOMEM; int ret = -1; if (via_ld_so) { diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index ed71ffa93c..01cd38c996 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -110,6 +110,7 @@ def required(): ['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']] paths += ['assets/linuxfs/usr/local/lib/droiddeck-xclipse/' + name for name in ['libVkLayer_droiddeck_xclipse.so', 'VkLayer_droiddeck_xclipse.json']] + paths += ['assets/linuxfs/usr/local/lib/droiddeck-lse/liblse_emu.so'] paths += ['assets/linuxfs/usr/local/lib/droiddeck-vr/' + name for name in ['droiddeck/bin/linuxarm64/driver_droiddeck.so', 'droiddeck/bin/linuxarm64/xr-display-mode', 'droiddeck/driver.vrdrivermanifest', diff --git a/tools/tests/lse_emu_early_dependency.c b/tools/tests/lse_emu_early_dependency.c new file mode 100644 index 0000000000..4c16a0d3ba --- /dev/null +++ b/tools/tests/lse_emu_early_dependency.c @@ -0,0 +1,17 @@ +#include +#include + +static volatile uint64_t value; + +__attribute__((constructor)) +static void use_lse_before_preload_init(void) { + uint64_t old; + uint64_t increment = 1; + __asm__ volatile("ldaddal %x1, %x0, [%2]" + : "=r"(old) + : "r"(increment), "r"(&value) + : "memory"); + if (old != 0 || value != 1) _exit(91); +} + +void lse_emu_early_dependency_anchor(void) {} diff --git a/tools/tests/lse_emu_early_main.c b/tools/tests/lse_emu_early_main.c new file mode 100644 index 0000000000..5eaba99f0a --- /dev/null +++ b/tools/tests/lse_emu_early_main.c @@ -0,0 +1,9 @@ +#include + +void lse_emu_early_dependency_anchor(void); + +int main(void) { + lse_emu_early_dependency_anchor(); + puts("early lse ok"); + return 0; +} diff --git a/tools/tests/lse_emu_test.c b/tools/tests/lse_emu_test.c new file mode 100644 index 0000000000..b63fb92462 --- /dev/null +++ b/tools/tests/lse_emu_test.c @@ -0,0 +1,300 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_THREADS 8 +#define ROUNDS 20000 + +static uint64_t counter64; +static uint32_t counter32; +static uint16_t counter16; +static uint8_t counter8; +static uint64_t spin; + +static void check(int ok, const char *what) { + if (!ok) { + printf("FAIL %s\n", what); + exit(1); + } +} + +static uint64_t ldaddal64(uint64_t *p, uint64_t v) { + uint64_t old; + __asm__ volatile("ldaddal %x1, %x0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory"); + return old; +} + +static uint32_t ldadd32(uint32_t *p, uint32_t v) { + uint32_t old; + __asm__ volatile("ldadd %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory"); + return old; +} + +static uint16_t ldaddlh(uint16_t *p, uint16_t v) { + uint16_t old; + __asm__ volatile("ldaddlh %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory"); + return old; +} + +static uint8_t ldaddab(uint8_t *p, uint8_t v) { + uint8_t old; + __asm__ volatile("ldaddab %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory"); + return old; +} + +static uint64_t casal64(uint64_t *p, uint64_t expected, uint64_t desired) { + __asm__ volatile("casal %x0, %x2, [%1]" : "+r"(expected) : "r"(p), "r"(desired) : "memory"); + return expected; +} + +static void *worker(void *arg) { + (void)arg; + for (int i = 0; i < ROUNDS; i++) { + ldaddal64(&counter64, 1); + ldadd32(&counter32, 1); + ldaddlh(&counter16, 1); + ldaddab(&counter8, 1); + uint64_t seen = __atomic_load_n(&spin, __ATOMIC_RELAXED); + while (casal64(&spin, seen, seen + 1) != seen) seen = __atomic_load_n(&spin, __ATOMIC_RELAXED); + } + return NULL; +} + +static volatile sig_atomic_t app_handler_ran; + +static void app_sigill(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + app_handler_ran = 1; + ((ucontext_t *)context)->uc_mcontext.pc += 4; +} + +static void simple_sigill(int sig) { (void)sig; } + +static volatile sig_atomic_t once_calls, persistent_calls, once_saw_default; +static void persistent_sigill(int sig) { (void)sig; persistent_calls++; } + +static void once_sigill(int sig) { + struct sigaction previous, next = {0}; + once_calls++; + if (sigaction(sig, NULL, &previous) == 0 && previous.sa_handler == SIG_DFL) + once_saw_default = 1; + next.sa_handler = persistent_sigill; + sigemptyset(&next.sa_mask); + if (sigaction(sig, &next, NULL) != 0) _Exit(2); +} + +static void check_one_shot_action(void) { + struct sigaction action = {0}; + action.sa_handler = once_sigill; + action.sa_flags = SA_RESETHAND; + sigemptyset(&action.sa_mask); + check(sigaction(SIGILL, &action, NULL) == 0, "install one-shot SIGILL"); + check(raise(SIGILL) == 0, "deliver one-shot SIGILL"); + check(once_calls == 1 && once_saw_default, "one-shot consumed before calling handler"); + check(raise(SIGILL) == 0, "deliver replacement SIGILL"); + check(once_calls == 1 && persistent_calls == 1, "replacement survives one-shot consumption"); +} + + +static void set_test_action(int variant) { + struct sigaction sa = {0}; + sigemptyset(&sa.sa_mask); + if (variant == 0) { + sa.sa_handler = simple_sigill; + sigaddset(&sa.sa_mask, SIGUSR1); + } else { + sa.sa_sigaction = app_sigill; + sa.sa_flags = SA_SIGINFO; + sigaddset(&sa.sa_mask, SIGUSR2); + } + int attempt; + for (attempt = 0; attempt < 10000; attempt++) { + if (sigaction(SIGILL, &sa, NULL) == 0) return; + check(errno == ENOMEM, "unexpected action publication failure"); + sched_yield(); + } + check(0, "action slots stayed exhausted"); +} + +static void *replace_test_action(void *unused) { + (void)unused; + for (int i = 0; i < 4096; i++) set_test_action(i & 1); + return NULL; +} + +static void *query_test_action(void *unused) { + (void)unused; + for (int i = 0; i < 4096; i++) { + struct sigaction sa; + check(sigaction(SIGILL, NULL, &sa) == 0, "query SIGILL action"); + int a = sigismember(&sa.sa_mask, SIGUSR1); + int b = sigismember(&sa.sa_mask, SIGUSR2); + if (sa.sa_flags & SA_SIGINFO) + check(sa.sa_sigaction == app_sigill && !a && b, "coherent siginfo snapshot"); + else + check(sa.sa_handler == simple_sigill && a && !b, "coherent simple snapshot"); + } + return NULL; +} + +static unsigned int fork_readers_stop; + +static void *read_during_fork(void *unused) { + (void)unused; + while (!__atomic_load_n(&fork_readers_stop, __ATOMIC_RELAXED)) { + struct sigaction out; + if (sigaction(SIGILL, NULL, &out) != 0) _Exit(4); + } + return NULL; +} + +static void check_forked_actions(void) { + struct sigaction install = {0}; + install.sa_handler = simple_sigill; + sigemptyset(&install.sa_mask); + check(sigaction(SIGILL, &install, NULL) == 0, "install SIGILL before fork"); + pthread_t readers[4]; + for (int i = 0; i < 4; i++) + check(pthread_create(&readers[i], NULL, read_during_fork, NULL) == 0, "start fork reader"); + for (int child = 0; child < 8; child++) { + pid_t pid = fork(); + check(pid >= 0, "fork SIGILL snapshot child"); + if (pid == 0) { + struct sigaction inherited; + if (sigaction(SIGILL, NULL, &inherited) != 0 || inherited.sa_handler != simple_sigill) _Exit(2); + for (int i = 0; i < 1024; i++) + if (sigaction(SIGILL, &install, NULL) != 0) _Exit(3); + _Exit(0); + } + int status = 0; + check(waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0, + "child keeps action and can recycle more than 256 slots"); + } + __atomic_store_n(&fork_readers_stop, 1, __ATOMIC_RELAXED); + for (int i = 0; i < 4; i++) check(pthread_join(readers[i], NULL) == 0, "join fork reader"); +} + +static void check_reused_actions(void) { + set_test_action(0); + pthread_t threads[4]; + for (int i = 0; i < 4; i++) + check(pthread_create(&threads[i], NULL, i < 2 ? replace_test_action : query_test_action, NULL) == 0, + "start action worker"); + for (int i = 0; i < 4; i++) check(pthread_join(threads[i], NULL) == 0, "join action worker"); +} + +static __attribute__((noinline)) void single_forms(void) { + uint64_t v = 0xF0; + uint64_t old; + register uint64_t ldap_result __asm__("x0"); + register uintptr_t ldap_address __asm__("x1") = (uintptr_t)&v; + __asm__ volatile(".inst 0xf8bfc020" : "=r"(ldap_result) : "r"(ldap_address) : "memory"); + check(ldap_result == v, "ldapr"); + __asm__ volatile("ldclral %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0x30), "r"(&v) : "memory"); + check(old == 0xF0 && v == 0xC0, "ldclral"); + __asm__ volatile("ldeora %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0xFF), "r"(&v) : "memory"); + check(old == 0xC0 && v == 0x3F, "ldeora"); + __asm__ volatile("ldsetl %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0x100), "r"(&v) : "memory"); + check(old == 0x3F && v == 0x13F, "ldsetl"); + __asm__ volatile("swpal %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)7), "r"(&v) : "memory"); + check(old == 0x13F && v == 7, "swpal"); + + int64_t s = -5; + int64_t sold; + __asm__ volatile("ldsmax %x1, %x0, [%2]" : "=r"(sold) : "r"((int64_t)-9), "r"(&s) : "memory"); + check(sold == -5 && s == -5, "ldsmax keeps the larger value"); + uint32_t u = 10; + uint32_t uold; + __asm__ volatile("ldumin %w1, %w0, [%2]" : "=r"(uold) : "r"((uint32_t)3), "r"(&u) : "memory"); + check(uold == 10 && u == 3, "ldumin"); + + uint64_t pair[2] __attribute__((aligned(16))) = {1, 2}; + register uint64_t e0 __asm__("x4") = 1, e1 __asm__("x5") = 2, d0 __asm__("x6") = 3, d1 __asm__("x7") = 4; + __asm__ volatile("caspal x4, x5, x6, x7, [%4]" : "+r"(e0), "+r"(e1) : "r"(d0), "r"(d1), "r"(pair) : "memory"); + check(e0 == 1 && e1 == 2 && pair[0] == 3 && pair[1] == 4, "caspal"); + register uint64_t m0 __asm__("x4") = 8, m1 __asm__("x5") = 9, n0 __asm__("x6") = 5, n1 __asm__("x7") = 6; + __asm__ volatile("caspal x4, x5, x6, x7, [%4]" : "+r"(m0), "+r"(m1) : "r"(n0), "r"(n1), "r"(pair) : "memory"); + check(m0 == 3 && m1 == 4 && pair[0] == 3 && pair[1] == 4, "caspal returns the current pair on a mismatch"); + + uint64_t missed = casal64(&v, 99, 1); + check(missed == 7 && v == 7, "casal leaves memory alone on a mismatch"); + + uint32_t m = 1; + uint32_t mold; + uint64_t eq; + __asm__ volatile("cmp %w3, %w3\n\tldumax %w2, %w0, [%4]\n\tcset %1, eq" + : "=&r"(mold), "=&r"(eq) : "r"((uint32_t)5), "r"((uint32_t)0), "r"(&m) : "memory", "cc"); + check(mold == 1 && m == 5 && eq == 1, "ldumax leaves the condition flags alone"); + int8_t b = -3; + int8_t bold; + __asm__ volatile("cmp %w3, %w3\n\tldsmaxb %w2, %w0, [%4]\n\tcset %1, eq" + : "=&r"(bold), "=&r"(eq) : "r"((int32_t)-7), "r"((uint32_t)0), "r"(&b) : "memory", "cc"); + check(bold == -3 && b == -3 && eq == 1, "ldsmaxb leaves the condition flags alone"); +} + +int main(int argc, char **argv) { + if (argc == 2 && strcmp(argv[1], "sigill-fork") == 0) { + check_forked_actions(); + puts("sigill fork ok"); + return 0; + } + if (argc == 2 && strcmp(argv[1], "sigill-oneshot") == 0) { + check_one_shot_action(); + puts("sigill one-shot ok"); + return 0; + } + if (argc == 2 && strcmp(argv[1], "sigill-actions") == 0) { + check_reused_actions(); + puts("sigill actions ok"); + return 0; + } + int threads_wanted = argc > 1 ? atoi(argv[1]) : 4; + check(threads_wanted >= 1 && threads_wanted <= MAX_THREADS, "thread count"); + single_forms(); + single_forms(); + + pthread_t threads[MAX_THREADS]; + int started = 0; + for (; started < threads_wanted; started++) { + int err = pthread_create(&threads[started], NULL, worker, NULL); + if (err != 0) { + for (int i = 0; i < started; i++) pthread_join(threads[i], NULL); + fprintf(stderr, "pthread_create failed: %s\n", strerror(err)); + return err; + } + } + for (int i = 0; i < started; i++) { + int err = pthread_join(threads[i], NULL); + if (err != 0) { + fprintf(stderr, "pthread_join failed: %s\n", strerror(err)); + return err; + } + } + uint64_t total = (uint64_t)threads_wanted * ROUNDS; + check(counter64 == total, "64-bit counter"); + check(counter32 == (uint32_t)total, "32-bit counter"); + check(counter16 == (uint16_t)total, "16-bit counter"); + check(counter8 == (uint8_t)total, "8-bit counter"); + check(spin == total, "casal loop"); + + struct sigaction sa; + memset(&sa, 0, sizeof sa); + sa.sa_sigaction = app_sigill; + sa.sa_flags = SA_SIGINFO; + sigaction(SIGILL, &sa, NULL); + __asm__ volatile("udf #0"); + check(app_handler_ran, "the program's own SIGILL handler still runs"); + + printf("lse ok\n"); + return 0; +} diff --git a/tools/tests/test_lse_emu.py b/tools/tests/test_lse_emu.py new file mode 100644 index 0000000000..539fb18326 --- /dev/null +++ b/tools/tests/test_lse_emu.py @@ -0,0 +1,141 @@ +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 ''}") + 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() diff --git a/tools/tests/test_native_hook_preload_list.py b/tools/tests/test_native_hook_preload_list.py new file mode 100644 index 0000000000..71911a8d0b --- /dev/null +++ b/tools/tests/test_native_hook_preload_list.py @@ -0,0 +1,53 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ENV = Path(__file__).resolve().parents[1] / "nativeguest/hook/env.c" + + +class NativeHookPreloadListTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.addClassCleanup(cls.tmp.cleanup) + p = Path(cls.tmp.name) + env = ENV.read_text() + helpers = env[env.index("static int preload_has_entry("):env.index("// Filter the LSE")] + (p / "probe.c").write_text(""" +#include +#include +#include +""" + helpers + """ +int main(int argc, char **argv) { + (void)argc; + char *out = merge_preload_env(argv[1], argv[2]); + if (!out) return 2; + puts(out); + free(out); + return 0; +} +""") + cls.probe = p / "probe" + subprocess.run([os.environ.get("CC", "cc"), "-Wall", "-Wextra", "-Werror", + str(p / "probe.c"), "-o", str(cls.probe)], check=True) + + def merge(self, host, inherited): + return subprocess.check_output([self.probe, host, inherited], text=True).strip() + + def test_nested_exec_keeps_the_same_multi_entry_chain(self): + host = "/root/session.so:/root/hook.so" + original = host + ":user.so" + for _ in range(3): + original = self.merge(host, original).removeprefix("LD_PRELOAD=") + self.assertEqual(host + ":user.so", original) + + def test_partial_chain_keeps_host_order_and_exact_matches(self): + self.assertEqual("LD_PRELOAD=/root/session.so:/root/hook.so:/root/hook.so.extra:custom.so", + self.merge("/root/session.so:/root/hook.so", + "/root/hook.so.extra /root/session.so:custom.so")) + + def test_empty_custom_chain_keeps_only_the_host_chain(self): + self.assertEqual("LD_PRELOAD=host.so", self.merge("host.so", ""))