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>
This commit is contained in:
LunaDLandKurt Himebauch authored and GitHub committed 2026-12-05 19:09:28 -05:00
1 parent 73fac3723f
commit 88d44b0dc6
27 files changed
+2263 -40

No files matched your search

+3
View File
@@ -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
@@ -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)
}
}
@@ -288,12 +288,26 @@ object BwrapSpawner {
}
private fun preload(session: List<Bind>, rootfs: String, env: MutableMap<String, String>): List<Bind> {
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<Bind>()
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))
@@ -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<String>, program: String, hostname: String? = null): Map<String, String> {
val preload = preloadList(root)
fun sessionEnvironment(
root: File, binds: List<String>, program: String, hostname: String? = null, lseEmu: String? = null,
): Map<String, String> {
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() }
}
@@ -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(" ", "\\ ") }
@@ -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")
}
@@ -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
@@ -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))
}
}
@@ -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() }
@@ -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()
+147
View File
@@ -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.
+1
View File
@@ -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
+2 -2
View File
@@ -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):
+4
View File
@@ -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"
+23
View File
@@ -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.
+15
View File
@@ -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
File diff suppressed because it is too large. Load diff
+7
View File
@@ -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() {
+21 -10
View File
@@ -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")))
+136 -16
View File
@@ -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;
}
+15
View File
@@ -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) {
+1
View File
@@ -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',
+17
View File
@@ -0,0 +1,17 @@
#include <stdint.h>
#include <unistd.h>
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) {}
+9
View File
@@ -0,0 +1,9 @@
#include <stdio.h>
void lse_emu_early_dependency_anchor(void);
int main(void) {
lse_emu_early_dependency_anchor();
puts("early lse ok");
return 0;
}
+300
View File
@@ -0,0 +1,300 @@
#define _GNU_SOURCE
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ucontext.h>
#include <sys/wait.h>
#include <unistd.h>
#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;
}
+141
View File
@@ -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 '<missing>'}")
self.assertTrue(log.is_file(), "patch log was not created")
instructions = [
int(match, 16)
for match in re.findall(r"patched pc=0x[0-9a-f]+ insn=0x([0-9a-f]+)", log.read_text())
]
self.assertTrue(
any((insn & 0x3FFFFC00) == 0x38BFC000 for insn in instructions),
"LDAPR did not use a generated stub",
)
self.assertFalse(
any((insn & 0xBFA07C00) == 0x08207C00 for insn in instructions),
"CASP must remain on the stack-safe trap path",
)
self.assertFalse(
any(
(insn & 0x3F200C00) == 0x38200000
and ((insn >> 15) & 1) == 0
and ((insn >> 12) & 7) >= 4
for insn in instructions
),
"min/max must remain on the stack-safe trap path",
)
self.assertNotRegex(result.stderr, r"unhandled pc=.*insn=0x(?!0000000000000000(?:\n|$))[0-9a-f]{16}")
def test_patching_runs_every_form_on_an_armv8_0_cpu(self):
self.patched(threads=1)
def test_patching_stays_atomic_across_threads(self):
self.patched(threads=4)
def test_it_stays_off_without_the_switch(self):
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=0", "LSE_EMU_PATCH=0")
self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
def test_it_stays_off_on_a_cpu_with_lse(self):
result = self.run_on("neoverse-n1", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertNotIn("traps=", result.stderr)
if __name__ == "__main__":
unittest.main()
@@ -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 <stdlib.h>
#include <stdio.h>
#include <string.h>
""" + 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", ""))