mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae354a25a6 |
No files matched your search
@@ -307,9 +307,6 @@ 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
|
||||
@@ -955,7 +952,6 @@ jobs:
|
||||
with:
|
||||
artifact: droiddeck-signed
|
||||
variant: standard
|
||||
fail_on_detection: true
|
||||
secrets: inherit
|
||||
|
||||
packs:
|
||||
|
||||
@@ -191,6 +191,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var gamescopeRealtime by mutableStateOf(false)
|
||||
private var paceCores by mutableStateOf(true)
|
||||
private var gpuClockPin by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
private var nativeUserland by mutableStateOf(true)
|
||||
private var desktopAsUser by mutableStateOf(false)
|
||||
private var cursorComposite by mutableStateOf(true)
|
||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||
@@ -3122,7 +3125,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
fsyncFirst = fsyncFirst,
|
||||
gamescopeRealtime = gamescopeRealtime,
|
||||
gpuClockPin = gpuClockPin,
|
||||
nativeDesktopAvailable = com.droiddeck.launcher.runtime.NativeGuest.nextSession(this), desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
|
||||
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
|
||||
guestHostname = guestHostname, phantomWarning = phantomWarning,
|
||||
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
||||
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
|
||||
@@ -3136,6 +3139,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
|
||||
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
|
||||
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
|
||||
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
|
||||
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
|
||||
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
|
||||
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
|
||||
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
|
||||
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
|
||||
@@ -3458,6 +3464,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
||||
paceCores = SessionPrefs.paceCores(this)
|
||||
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
prootFastPath = SessionPrefs.prootFastPath(this)
|
||||
nativeUserland = SessionPrefs.nativeUserland(this)
|
||||
desktopAsUser = SessionPrefs.desktopAsUser(this)
|
||||
cursorComposite = SessionPrefs.cursorComposite(this)
|
||||
guestHostname = SessionPrefs.guestHostname(this)
|
||||
|
||||
@@ -3862,6 +3862,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
presentationFaultHint()?.let { return it }
|
||||
if (log == null || !log.isFile) return null
|
||||
return try {
|
||||
var enosys = 0
|
||||
var fexMissing = false
|
||||
val size = log.length()
|
||||
val text = java.io.RandomAccessFile(log, "r").use { f ->
|
||||
@@ -3872,6 +3873,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
String(bytes, Charsets.ISO_8859_1)
|
||||
}
|
||||
text.lineSequence().forEach { line ->
|
||||
if (line.contains("Function not implemented")) enosys++
|
||||
if (line.contains(FEX_MISSING)) fexMissing = true
|
||||
}
|
||||
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
|
||||
@@ -3893,6 +3895,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else if (fexMissing) {
|
||||
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
|
||||
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
|
||||
} else if (enosys >= 8) {
|
||||
EndHint(resources.getQuantityString(R.plurals.session_hint_enosys, enosys, enosys,
|
||||
getString(R.string.perf_title), getString(R.string.perf_seccomp), getString(R.string.perf_xalia)))
|
||||
} else null
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
|
||||
@@ -571,6 +571,7 @@ object AgentHost {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
|
||||
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ object AgentNative {
|
||||
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
|
||||
// with the setting off, staging leaves the rootfs as proot wants it
|
||||
if (!com.droiddeck.launcher.session.SessionPrefs.nativeUserland(context)) NativeGuest.prepare(context, root)
|
||||
if (!NativeGuest.available(root)) throw AgentException("NATIVE_UNAVAILABLE", "The rootfs has no native hook or glibc loader yet; start a session once")
|
||||
val argvJson = request.optJSONArray("argv") ?: throw AgentException("INVALID_REQUEST", "argv is required")
|
||||
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -291,12 +291,9 @@ object DeviceReport {
|
||||
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||
k("pace cores", SessionPrefs.paceCores(context))
|
||||
k("guest runtime policy", "native preferred with PRoot fallback")
|
||||
k("guest runtime", when (com.droiddeck.launcher.runtime.NativeGuest.sessionMode) {
|
||||
true -> "native"
|
||||
false -> "PRoot"
|
||||
null -> if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) "native available" else "native unavailable"
|
||||
})
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
|
||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
||||
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||
|
||||
@@ -3,6 +3,9 @@ package com.droiddeck.launcher.core
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
object FexPreset {
|
||||
const val FOLLOW_STEAM = "FOLLOW_STEAM"
|
||||
const val FOLLOW_STEAM_FALLBACK = "PERFORMANCE_TSO"
|
||||
|
||||
class Preset(val id: String, val label: Int, val detail: Int, val env: List<String>)
|
||||
|
||||
private fun tso(main: Int, vector: Int, memcpy: Int, halfBarrier: Int) = listOf(
|
||||
@@ -11,6 +14,7 @@ object FexPreset {
|
||||
|
||||
val all: List<Preset> = listOf(
|
||||
Preset("", R.string.fex_default_label, R.string.fex_default_detail, emptyList()),
|
||||
Preset(FOLLOW_STEAM, R.string.fex_follow_steam_label, R.string.fex_follow_steam_detail, emptyList()),
|
||||
Preset("STABILITY", R.string.fex_stability_label, R.string.fex_stability_detail, tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=0")),
|
||||
Preset("COMPATIBILITY", R.string.fex_compatibility_label, R.string.fex_compatibility_detail, tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=1")),
|
||||
Preset("INTERMEDIATE", R.string.fex_intermediate_label, R.string.fex_intermediate_detail, tso(1, 0, 0, 1) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")),
|
||||
@@ -26,6 +30,8 @@ object FexPreset {
|
||||
tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=full", "FEX_HIDEHYPERVISORBIT=1")),
|
||||
)
|
||||
|
||||
val forGame = all.filterNot { it.id == FOLLOW_STEAM }
|
||||
|
||||
fun byId(id: String): Preset = all.firstOrNull { it.id == id } ?: all[0]
|
||||
|
||||
fun env(id: String): List<String> = byId(id).env
|
||||
|
||||
@@ -61,7 +61,8 @@ object GameEnvironment {
|
||||
}
|
||||
|
||||
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
||||
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else knownGames[scope].orEmpty() + config.games[scope].orEmpty()
|
||||
defaults(if (preset == FexPreset.FOLLOW_STEAM) FexPreset.FOLLOW_STEAM_FALLBACK else preset, forceSsbs) +
|
||||
config.shared + if (scope.isEmpty()) emptyMap() else knownGames[scope].orEmpty() + config.games[scope].orEmpty()
|
||||
|
||||
/**
|
||||
* What some Steam games need here whatever the shared settings say; the game's own settings still win.
|
||||
@@ -89,7 +90,7 @@ object GameEnvironment {
|
||||
require(scope.isNotEmpty() && validScope(scope))
|
||||
val entries = config.games[scope].orEmpty()
|
||||
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
|
||||
return FexPreset.all.firstOrNull { preset ->
|
||||
return FexPreset.forGame.firstOrNull { preset ->
|
||||
val expected = presetFor(scope, preset.id)
|
||||
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
|
||||
}?.id ?: CUSTOM_FEX_PRESET
|
||||
@@ -97,7 +98,7 @@ object GameEnvironment {
|
||||
|
||||
fun withGameFexPreset(config: Config, scope: String, preset: String?): Config {
|
||||
require(scope.isNotEmpty() && validScope(scope))
|
||||
require(preset == null || FexPreset.all.any { it.id == preset })
|
||||
require(preset == null || FexPreset.forGame.any { it.id == preset })
|
||||
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
|
||||
if (preset != null) {
|
||||
val values = presetFor(scope, preset)
|
||||
|
||||
@@ -40,8 +40,7 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
PILL("pill", "Pill"),
|
||||
MINIMAL("minimal", "Minimal"),
|
||||
MEGA("mega", "Mega"),
|
||||
STRIP("strip", "Strip"),
|
||||
SIDE_STRIP("side_strip", "Side strip");
|
||||
STRIP("strip", "Strip");
|
||||
|
||||
fun next(): DroidDeckHudSize {
|
||||
val all = values()
|
||||
@@ -97,11 +96,6 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||
"showPower", "showDisplay", "showHdr", "showGpuModel",
|
||||
),
|
||||
SIDE_STRIP to listOf(
|
||||
"showFPS", "showFPSGraph", "showAvg", "showLow1",
|
||||
"showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp", "showRAM", "showVram",
|
||||
"showPower", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -116,7 +110,6 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
||||
MEGA to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.62f, pad = 10f, lineGap = 3.5f, labelGap = 7f,
|
||||
band = 9.5f, gutter = 16f),
|
||||
STRIP to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.8f, pad = 10f, lineGap = 0f, labelGap = 13f),
|
||||
SIDE_STRIP to DroidDeckHudStyle(row = 11.5f, unit = 9f, pad = 8f, lineGap = 4f, labelGap = 4f, key = 9f),
|
||||
)
|
||||
|
||||
fun rowsFor(size: DroidDeckHudSize, values: Map<String, String>): List<String> =
|
||||
|
||||
@@ -573,7 +573,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
if (s == null) { contentW = 0f; contentH = 0f; return }
|
||||
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
|
||||
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
|
||||
if (size == DroidDeckHudSize.SIDE_STRIP) { buildSideStrip(s); return }
|
||||
buildRows(s)
|
||||
if (contentW <= 0f || contentH <= 0f) return
|
||||
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
|
||||
@@ -685,8 +684,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
finishPanel(panel, halfRound = halfRound)
|
||||
}
|
||||
|
||||
private fun finishPanel(panel: RectF, halfRound: Boolean, maxRadius: Float = sp(56f), inset: Float = panelInset()) {
|
||||
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, maxRadius)
|
||||
private fun finishPanel(panel: RectF, halfRound: Boolean) {
|
||||
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, sp(56f))
|
||||
val margin = outlineWidth() + sp(4f)
|
||||
fun curveIn(top: Float, bottom: Float): Float {
|
||||
val d = max(max(panel.top + r - top, bottom - (panel.bottom - r)), 0f)
|
||||
@@ -704,8 +703,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
for (t in tileRects) right = max(right, t.right + curveIn(t.top, t.bottom) + margin)
|
||||
panel.right = max(right, panel.left + sp(6f) + r)
|
||||
dPanel = panel; dRadius = r
|
||||
contentW = panel.right + inset
|
||||
contentH = panel.bottom + inset
|
||||
contentW = panel.right + panelInset()
|
||||
contentH = panel.bottom + panelInset()
|
||||
}
|
||||
|
||||
private fun clockTimeString(): String = DateFormat.getTimeFormat(context).format(Date())
|
||||
@@ -937,58 +936,6 @@ class DroidDeckHudView(context: Context) : View(context) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildSideStrip(s: HudMetrics.Snapshot) {
|
||||
val style = size.style
|
||||
val inset = sp(5f)
|
||||
val panelWidth = sp(86f)
|
||||
val pad = sp(style.pad)
|
||||
val left = inset + pad
|
||||
val right = inset + panelWidth - pad
|
||||
val markHeight = sp(12f)
|
||||
val markTop = inset + sp(6f)
|
||||
val markLeft = left - DroidDeckMark.inkLeftFor(markHeight)
|
||||
headerMark = RectF(markLeft, markTop, markLeft + DroidDeckMark.widthFor(markHeight), markTop + markHeight)
|
||||
dDividerTop = markTop + markHeight + sp(6f)
|
||||
|
||||
if (showClockTime) {
|
||||
val clock = clockTimeString()
|
||||
val clockPx = sp(8.5f)
|
||||
val clockWidth = measure(clock, clockPx)
|
||||
if (right - clockWidth >= markLeft + DroidDeckMark.inkRightFor(markHeight) + sp(4f)) {
|
||||
val baseline = markTop + (markHeight + capHeight(clockPx)) / 2f
|
||||
glyphs.add(Glyph(right - clockWidth, baseline, clock, blend(colDim), clockPx))
|
||||
}
|
||||
}
|
||||
|
||||
val labelPx = sp(style.key)
|
||||
val rowPx = sp(style.row)
|
||||
val unitPx = sp(style.unit)
|
||||
val lineGap = sp(style.lineGap)
|
||||
var y = dDividerTop + sp(6f)
|
||||
for (key in size.rowsIn(storedOrder)) {
|
||||
if (!switchOn(key)) continue
|
||||
if (key == "showFPSGraph") {
|
||||
val height = sp(15f)
|
||||
graphRect = RectF(left, y, right, y + height)
|
||||
y += height + lineGap
|
||||
continue
|
||||
}
|
||||
|
||||
val valuePx = if (key == "showFPS") sp(16f) else rowPx
|
||||
val row = reading(key, s, labelPx, valuePx, unitPx)
|
||||
val available = right - left - measure(row.label.text, labelPx) - sp(style.labelGap)
|
||||
val fit = (available / runWidth(row.vals)).coerceIn(0f, 1f)
|
||||
val values = row.vals.map { Span(it.text, it.color, it.sizePx * fit, it.glow) }
|
||||
val baseline = y - ascent(valuePx)
|
||||
placeRun(left, baseline, listOf(row.label))
|
||||
placeRun(right - runWidth(values), baseline, values)
|
||||
y += lineH(valuePx) + lineGap
|
||||
}
|
||||
|
||||
val panel = RectF(inset, inset, inset + panelWidth, y + sp(7f))
|
||||
finishPanel(panel, halfRound = false, maxRadius = sp(11f), inset = inset)
|
||||
}
|
||||
|
||||
private fun buildStrip(s: HudMetrics.Snapshot) {
|
||||
val rowPx = sp(11.5f); val unitPx = rowPx * 0.8f; val fpsPx = sp(15f)
|
||||
val padX = sp(10f); val groupGap = sp(13f)
|
||||
|
||||
@@ -288,26 +288,12 @@ object BwrapSpawner {
|
||||
}
|
||||
|
||||
private fun preload(session: List<Bind>, rootfs: String, env: MutableMap<String, String>): List<Bind> {
|
||||
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 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 binds = ArrayList<Bind>()
|
||||
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
|
||||
env["LD_PRELOAD"] = (paths + inherited).joinToString(":")
|
||||
if (libs.any { it.endsWith("/liblse_emu.so") }) {
|
||||
env.putIfAbsent("LSE_EMU", "1")
|
||||
}
|
||||
env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":")
|
||||
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))
|
||||
@@ -577,15 +563,12 @@ object BwrapSpawner {
|
||||
|
||||
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
|
||||
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
||||
val nativeSession = NativeGuest.forSession(context)
|
||||
val native = if (nativeSession) nativeLaunch(context, plan) else null
|
||||
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
|
||||
val builder = if (native != null) {
|
||||
ProcessBuilder(native.first).redirectErrorStream(true)
|
||||
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
|
||||
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
|
||||
} else {
|
||||
val reason = if (nativeSession) "sandbox native launch unavailable" else "parent guest uses PRoot"
|
||||
Log.i(TAG, "Flatpak: using PRoot ($reason)")
|
||||
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
|
||||
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
|
||||
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
|
||||
@@ -602,6 +585,7 @@ object BwrapSpawner {
|
||||
putAll(prootEnvironment(plan, envTool))
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionFiles
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
@@ -66,6 +67,7 @@ object GuestCommand {
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
|
||||
@@ -22,15 +22,15 @@ object NativeGuest {
|
||||
}
|
||||
|
||||
fun enabled(context: Context): Boolean =
|
||||
available(LinuxRuntime.rootDir(context))
|
||||
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
|
||||
|
||||
/**
|
||||
* Whether the next session will start natively. The session stages the hook from the APK before
|
||||
* it starts, so the rootfs's loader decides, and a runtime still to be
|
||||
* it starts, so only the setting and the rootfs's loader decide, and a runtime still to be
|
||||
* installed will have one.
|
||||
*/
|
||||
fun nextSession(context: Context): Boolean =
|
||||
willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
|
||||
SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
|
||||
|
||||
internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null
|
||||
|
||||
@@ -39,7 +39,7 @@ object NativeGuest {
|
||||
|
||||
/**
|
||||
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
|
||||
* session's own mode while one runs, as the rootfs is only
|
||||
* session's own mode while one runs, as the setting can change under it and the rootfs is only
|
||||
* prepared for native programs at a session's start.
|
||||
*/
|
||||
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
|
||||
@@ -104,11 +104,8 @@ 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, 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" } }
|
||||
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
|
||||
val preload = preloadList(root)
|
||||
return linkedMapOf(
|
||||
"DDNATV_ROOT" to root.path,
|
||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||
@@ -116,7 +113,6 @@ 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() }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.runtime
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
@@ -11,14 +12,17 @@ object ProotFastPath {
|
||||
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
internal fun allows(source: String, native: Boolean): Boolean =
|
||||
!native && source == LinuxRuntime.PROOT_PACK
|
||||
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
|
||||
preference && !noSeccomp && !nativeUserland && source == LinuxRuntime.PROOT_PACK
|
||||
|
||||
fun enabled(context: Context, native: Boolean = NativeGuest.forSession(context)): Boolean {
|
||||
if (native) return false
|
||||
fun enabled(context: Context): Boolean {
|
||||
val preference = SessionPrefs.prootFastPath(context)
|
||||
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
|
||||
val nativeUserland = SessionPrefs.nativeUserland(context)
|
||||
val source = LinuxRuntime.prootSource(context)
|
||||
val on = allows(source, native)
|
||||
if (!on) Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
|
||||
val on = allows(preference, noSeccomp, source, nativeUserland)
|
||||
if (preference && !noSeccomp && !nativeUserland && !on)
|
||||
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
|
||||
return on
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import android.os.Process
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import java.io.DataInputStream
|
||||
import java.io.DataOutputStream
|
||||
@@ -127,6 +128,7 @@ object RootSpawner {
|
||||
clear()
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,8 +343,7 @@ object BottomDesktop {
|
||||
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||
}
|
||||
val environment = if (current.nativeUserland) {
|
||||
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)
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
|
||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
} else current.hostEnvironment
|
||||
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||
|
||||
@@ -5,7 +5,6 @@ import android.os.ParcelFileDescriptor
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONArray
|
||||
@@ -26,7 +25,6 @@ import java.nio.channels.SeekableByteChannel
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.NoSuchFileException
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.StandardOpenOption
|
||||
@@ -223,7 +221,7 @@ internal object EnhancedSessionLogShare {
|
||||
Category.values().map { category ->
|
||||
val budget = budgets.getValue(category)
|
||||
val records = ArrayList<Record>()
|
||||
val selected = candidates.filter { it.category == category }.sortedBy(::sharePriority)
|
||||
val selected = candidates.filter { it.category == category }
|
||||
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
|
||||
val names = HashSet<String>()
|
||||
@@ -618,8 +616,7 @@ internal object EnhancedSessionLogShare {
|
||||
redactionLearningComplete: Boolean,
|
||||
) {
|
||||
val entries = JSONArray()
|
||||
val (discovery, rest) = records.partition { it.origin == "discovery" }
|
||||
(discovery + rest).take(MAX_MANIFEST_RECORDS).forEach { record ->
|
||||
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
|
||||
entries.put(JSONObject().apply {
|
||||
put("entry", record.entry)
|
||||
put("origin", record.origin)
|
||||
@@ -683,15 +680,6 @@ internal object EnhancedSessionLogShare {
|
||||
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
|
||||
}
|
||||
}
|
||||
fun addRecentLogs(root: File, entryPrefix: String, origin: String) {
|
||||
val scan = walk(root, remaining(maxFiles, out.size))
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
val base = root.toPath().toAbsolutePath().normalize()
|
||||
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }.forEach { file ->
|
||||
add(file, root, "$entryPrefix/${base.relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")}", origin)
|
||||
}
|
||||
}
|
||||
CRITICAL_SESSION_FILES.forEach { name ->
|
||||
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
|
||||
}
|
||||
@@ -725,7 +713,16 @@ internal object EnhancedSessionLogShare {
|
||||
add(source.file, source.root, source.entry, "battlenet")
|
||||
}
|
||||
} else {
|
||||
battleNetRoots(context).forEach { (prefix, root) -> addRecentLogs(root, "battlenet/$prefix", "battlenet") }
|
||||
battleNetRoots(context).forEach { (prefix, root) ->
|
||||
val scan = walk(root, remaining(maxFiles, out.size))
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
|
||||
.forEach { file ->
|
||||
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
|
||||
add(file, root, "battlenet/$prefix/$relative", "battlenet")
|
||||
}
|
||||
}
|
||||
}
|
||||
val sessionScan = walk(folder, remaining(maxFiles, out.size))
|
||||
truncated = truncated || sessionScan.truncated
|
||||
@@ -736,9 +733,6 @@ internal object EnhancedSessionLogShare {
|
||||
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
|
||||
add(file, folder, "${folder.name}/$relative", "session")
|
||||
}
|
||||
val antiCheat = antiCheatRoots(context)
|
||||
partial = partial || antiCheat.partial
|
||||
antiCheat.roots.forEach { (appId, root) -> addRecentLogs(root, "anticheat/$appId", "anticheat") }
|
||||
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
|
||||
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
|
||||
val scan = directFiles(steam, remaining(maxFiles, out.size))
|
||||
@@ -754,8 +748,7 @@ internal object EnhancedSessionLogShare {
|
||||
private fun sharePriority(candidate: Candidate): Int = when {
|
||||
candidate.origin == "session-critical" -> 0
|
||||
candidate.origin == "session" && candidate.category == Category.GAMES -> 1
|
||||
candidate.origin == "anticheat" -> 2
|
||||
else -> 3
|
||||
else -> 2
|
||||
}
|
||||
|
||||
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
|
||||
@@ -829,39 +822,6 @@ internal object EnhancedSessionLogShare {
|
||||
return ScanResult(files, truncated, partial)
|
||||
}
|
||||
|
||||
private class AntiCheatRoots(val roots: List<Pair<String, File>>, val partial: Boolean)
|
||||
|
||||
private fun antiCheatRoots(context: Context): AntiCheatRoots {
|
||||
var partial = false
|
||||
val seen = HashSet<String>()
|
||||
val dirs = runCatching { Library.compatdataDirs(context) }.getOrElse { partial = true; emptyList() }
|
||||
val roots = dirs.flatMapIndexed { library, compatdata ->
|
||||
val prefixes = compatdata.listFiles() ?: run { partial = true; emptyArray() }
|
||||
prefixes.filter { !Files.isSymbolicLink(it.toPath()) }.mapNotNull { prefix ->
|
||||
val appId = steamAppId(prefix.name) ?: return@mapNotNull null
|
||||
val root = File(prefix, EAC_LOG_DIR)
|
||||
val directory = try {
|
||||
Files.readAttributes(root.toPath(), BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS).isDirectory
|
||||
} catch (_: NoSuchFileException) {
|
||||
false
|
||||
} catch (_: Exception) {
|
||||
partial = true
|
||||
false
|
||||
}
|
||||
if (!directory) return@mapNotNull null
|
||||
val base = "$appId/library${library + 1}"
|
||||
val key = base.takeIf { seen.add(it) } ?: "$base-${prefix.name}".takeIf { seen.add(it) }
|
||||
if (key != null) key to root else { partial = true; null }
|
||||
}
|
||||
}
|
||||
return AntiCheatRoots(roots, partial)
|
||||
}
|
||||
|
||||
private fun steamAppId(name: String): String? =
|
||||
name.takeIf { SIGNED_APP_ID.matches(it) }?.toLongOrNull()
|
||||
?.takeIf { it in Int.MIN_VALUE.toLong()..0xffffffffL }
|
||||
?.let { (it and 0xffffffffL).toString() }
|
||||
|
||||
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
|
||||
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
|
||||
val data = File(drive, "ProgramData/Battle.net")
|
||||
@@ -968,9 +928,7 @@ internal object EnhancedSessionLogShare {
|
||||
val normalized = name.replace('\\', '/').trimStart('/')
|
||||
val parts = normalized.split('/')
|
||||
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
|
||||
return parts.mapIndexed { index, part ->
|
||||
if (index == 1 && parts[0] == "anticheat" && APP_ID.matches(part)) part else safeComponent(part)
|
||||
}.joinToString("/")
|
||||
return parts.joinToString("/") { safeComponent(it) }
|
||||
}
|
||||
|
||||
private fun safeComponent(value: String): String {
|
||||
@@ -983,7 +941,7 @@ internal object EnhancedSessionLogShare {
|
||||
|
||||
private fun category(entry: String): Category {
|
||||
val value = entry.lowercase(Locale.US)
|
||||
if (value.startsWith("battlenet/") || value.startsWith("anticheat/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
||||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
||||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
|
||||
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
||||
@@ -992,7 +950,7 @@ internal object EnhancedSessionLogShare {
|
||||
|
||||
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
|
||||
private val KNOWN_COMPONENTS = setOf(
|
||||
"steam", "graphics", "games", "battlenet", "anticheat", "anticheatlauncher.log", "client", "agent", "setup", "stores", "tools",
|
||||
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
|
||||
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
||||
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
||||
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
||||
@@ -1003,15 +961,11 @@ internal object EnhancedSessionLogShare {
|
||||
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
||||
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
||||
Regex("steam-[0-9]+\\.(?:log|txt)"),
|
||||
Regex("library[0-9]+(?:--?[0-9]{1,10})?"),
|
||||
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
|
||||
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
|
||||
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
|
||||
Regex("library[0-9]{1,3}"),
|
||||
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
|
||||
)
|
||||
private val APP_ID = Regex("[0-9]{1,10}")
|
||||
private val SIGNED_APP_ID = Regex("-?[0-9]{1,10}")
|
||||
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
|
||||
private val CRITICAL_SESSION_FILES = listOf(
|
||||
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
|
||||
@@ -1019,7 +973,6 @@ internal object EnhancedSessionLogShare {
|
||||
)
|
||||
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
|
||||
private const val STORE_LOG_SCAN = 512
|
||||
private const val EAC_LOG_DIR = "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat"
|
||||
private const val COPY_BUFFER_BYTES = 64 * 1024
|
||||
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
|
||||
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
|
||||
import android.content.Context
|
||||
import android.util.AtomicFile
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
@@ -114,8 +115,13 @@ object GameEnvironmentStore {
|
||||
) {
|
||||
publishGameCores(context)
|
||||
val stored = config ?: read(context)
|
||||
val resolved = GameEnvironment.withKnownGames(stored).copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
|
||||
val preset = SessionPrefs.fexPreset(context)
|
||||
val resolved = GameEnvironment.withKnownGames(stored).copy(shared = GameEnvironment.defaults(preset, SessionPrefs.forceSsbs(context)) + stored.shared)
|
||||
val json = encode(resolved)
|
||||
// Keep preset values separate from raw shared overrides so the guest can replace only defaults.
|
||||
if (preset == FexPreset.FOLLOW_STEAM) {
|
||||
json.put("followSteamFex", JSONObject(FexPreset.environment(FexPreset.FOLLOW_STEAM_FALLBACK)))
|
||||
}
|
||||
val dxvk = TextureFiltering.dxvkOptions(
|
||||
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
|
||||
TextureFiltering.autoLodBias(SessionState.upscaleRatio),
|
||||
|
||||
@@ -5,7 +5,6 @@ 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
|
||||
@@ -23,10 +22,6 @@ 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")
|
||||
@@ -107,23 +102,10 @@ object SessionFiles {
|
||||
}
|
||||
|
||||
private val STAGE_LOCK = Any()
|
||||
@Volatile private var activeSessionLseEmu: String? = null
|
||||
|
||||
fun stage(context: Context, root: File, startsSession: Boolean = false) =
|
||||
stage(context, root, startsSession, lseEmu = 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, 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?) {
|
||||
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
|
||||
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)
|
||||
@@ -299,7 +281,6 @@ 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)
|
||||
@@ -362,22 +343,20 @@ 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(lsePreload(CpuFeatures.lacksAtomics, File(root, LSE_EMU).isFile, lseEmu))
|
||||
preload.append("/usr/local/lib/libddsession.so\n")
|
||||
val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
|
||||
val native = com.droiddeck.launcher.runtime.NativeGuest.available(root)
|
||||
val nativePreload = preload.toString()
|
||||
if (ProotFastPath.enabled(context, native)) {
|
||||
val nativeUserland = SessionPrefs.nativeUserland(context)
|
||||
if (nativeUserland) com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
|
||||
if (ProotFastPath.enabled(context)) {
|
||||
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
|
||||
preload.append(library + "\n")
|
||||
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
|
||||
}
|
||||
val etc = File(root, "etc").apply { mkdirs() }
|
||||
File(etc, "droiddeck").mkdirs()
|
||||
FileUtils.writeString(File(etc, "droiddeck/native-preload"), nativePreload)
|
||||
FileUtils.writeString(File(etc, "droiddeck/native-preload"), preload.toString())
|
||||
val staged = File(etc, "ld.so.preload.staged")
|
||||
if (!FileUtils.writeString(staged, preload.toString())
|
||||
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
|
||||
|
||||
@@ -1181,9 +1181,21 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("mountSharedStorage", on).apply()
|
||||
}
|
||||
|
||||
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
|
||||
|
||||
fun setProotNoSeccomp(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
|
||||
|
||||
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
|
||||
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
|
||||
|
||||
fun setNativeUserland(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("nativeUserland", on).apply()
|
||||
}
|
||||
|
||||
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
|
||||
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
|
||||
|
||||
@@ -1191,6 +1203,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
|
||||
}
|
||||
|
||||
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
|
||||
|
||||
fun setProotFastPath(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("prootFastPath", on).apply()
|
||||
}
|
||||
|
||||
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
|
||||
|
||||
fun setCursorComposite(context: Context, on: Boolean) {
|
||||
|
||||
@@ -47,7 +47,6 @@ import com.droiddeck.launcher.input.SteamControllerBle
|
||||
import com.droiddeck.launcher.runtime.BwrapSpawner
|
||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.NativeGuest
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.runtime.UserApps
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
@@ -567,7 +566,6 @@ 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)
|
||||
@@ -577,7 +575,7 @@ class SessionService : Service() {
|
||||
}
|
||||
pruneSystemVulkanRuntime()
|
||||
}
|
||||
SessionFiles.stage(this, root, startsSession = true, lseEmu = lseEmu)
|
||||
SessionFiles.stage(this, root, startsSession = true)
|
||||
} 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)
|
||||
@@ -785,13 +783,12 @@ class SessionService : Service() {
|
||||
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
|
||||
|
||||
val sharedStorage = LinuxRuntime.sharedStorage(this)
|
||||
val nativeUserland = NativeGuest.enabled(this)
|
||||
val fastPath = ProotFastPath.enabled(this, nativeUserland)
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage, fastPath)
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage)
|
||||
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
|
||||
synchronized(stopLock) {
|
||||
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionMode = nativeUserland
|
||||
}
|
||||
val fastPathKey = if (fastPath) {
|
||||
val fastPathKey = if (ProotFastPath.enabled(this)) {
|
||||
val prootBinds = LinuxRuntime.binds(
|
||||
this, sessionRoot, runtimeDir, sharedStorage, binds,
|
||||
)
|
||||
@@ -812,14 +809,16 @@ class SessionService : Service() {
|
||||
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
|
||||
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
|
||||
} else {
|
||||
val reason = if (NativeGuest.loader(root) == null) "missing glibc loader" else "missing native hook"
|
||||
Log.i(TAG, "guest runtime: using PRoot ($reason)")
|
||||
LinuxRuntime.command(this, sessionRoot, runtimeDir, sharedStorage, binds, guest)
|
||||
}
|
||||
|
||||
val prootEnv = HostEnvironment()
|
||||
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
|
||||
prootEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
|
||||
if (SessionPrefs.prootNoSeccomp(this)) {
|
||||
prootEnv["PROOT_NO_SECCOMP"] = "1"
|
||||
if (!nativeUserland) Log.i(TAG, "proot: seccomp acceleration off by request")
|
||||
}
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> prootEnv[k] = v } }
|
||||
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
|
||||
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
|
||||
@@ -831,7 +830,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), lseEmu)
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
|
||||
.forEach { (k, v) -> env[k] = v }
|
||||
} else prootEnv
|
||||
|
||||
@@ -1313,7 +1312,6 @@ class SessionService : Service() {
|
||||
sessionRoot: File,
|
||||
runtimeDir: File,
|
||||
sharedStorage: File?,
|
||||
fastPath: Boolean,
|
||||
): ArrayList<String> {
|
||||
val binds = ArrayList<String>()
|
||||
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
||||
@@ -1447,7 +1445,7 @@ class SessionService : Service() {
|
||||
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
|
||||
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
|
||||
if (gamesLibraries.isNotEmpty()) {
|
||||
var room = if (fastPath) {
|
||||
var room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
for (games in gamesLibraries) {
|
||||
@@ -1489,7 +1487,7 @@ class SessionService : Service() {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
val room = if (fastPath) {
|
||||
val room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
val content = SecondaryLibrary.contentPath(entry.host)
|
||||
@@ -1518,7 +1516,7 @@ class SessionService : Service() {
|
||||
if (problem != null) {
|
||||
Log.w(TAG, "x86-64 steam library: $problem")
|
||||
} else try {
|
||||
val room = if (fastPath) {
|
||||
val room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
val extra = SecondaryLibrary.binds(filesDir, x64, listOf(GameStorage.X64_CARD_GUEST)).drop(1)
|
||||
@@ -1540,7 +1538,7 @@ class SessionService : Service() {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
val room = if (fastPath) {
|
||||
val room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
|
||||
@@ -1576,7 +1574,7 @@ class SessionService : Service() {
|
||||
try {
|
||||
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
|
||||
val volumes = org.json.JSONArray()
|
||||
var room = if (fastPath) {
|
||||
var room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.AchievementNotifications
|
||||
@@ -148,6 +149,7 @@ object GogComet {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.core.AddonPack
|
||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import org.json.JSONObject
|
||||
import java.io.Closeable
|
||||
@@ -106,6 +107,7 @@ internal object Xodus {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
|
||||
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
|
||||
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
|
||||
@@ -1381,7 +1381,8 @@ internal fun FexPresetChip(
|
||||
focusRequester = first,
|
||||
) { onPick(null); onDismiss() }
|
||||
}
|
||||
FexPreset.all.forEachIndexed { index, option ->
|
||||
val options = if (allowInheritance) FexPreset.forGame else FexPreset.all
|
||||
options.forEachIndexed { index, option ->
|
||||
MenuItem(
|
||||
stringResource(option.label),
|
||||
checked = !inherited && option.id == preset,
|
||||
|
||||
@@ -39,8 +39,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
||||
}
|
||||
if (!a.hudOn) return@SettingsGroup
|
||||
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
||||
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size),
|
||||
stringResource(if (size == DroidDeckHudSize.SIDE_STRIP) R.string.hud_size_side_strip_hint else R.string.hud_size_hint),
|
||||
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint),
|
||||
listOf(
|
||||
DroidDeckHudSize.FULL to stringResource(R.string.hud_size_full),
|
||||
DroidDeckHudSize.TILES to stringResource(R.string.hud_size_tiles),
|
||||
@@ -48,7 +47,6 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
||||
DroidDeckHudSize.MINIMAL to stringResource(R.string.hud_size_minimal),
|
||||
DroidDeckHudSize.MEGA to stringResource(R.string.hud_size_mega),
|
||||
DroidDeckHudSize.STRIP to stringResource(R.string.hud_size_strip),
|
||||
DroidDeckHudSize.SIDE_STRIP to stringResource(R.string.hud_size_side_strip),
|
||||
),
|
||||
size, chipModifier = track("hud-size")) { a.onHudSetting("hudSize", it.token) }
|
||||
ChoiceRow(host, "hud-hold", stringResource(R.string.hud_hold), null,
|
||||
|
||||
@@ -1228,7 +1228,7 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
if (fex == com.droiddeck.launcher.core.GameEnvironment.CUSTOM_FEX_PRESET) {
|
||||
MenuItem(custom, checked = true, enabled = false) {}
|
||||
}
|
||||
com.droiddeck.launcher.core.FexPreset.all.forEach { option ->
|
||||
com.droiddeck.launcher.core.FexPreset.forGame.forEach { option ->
|
||||
MenuItem(stringResource(option.label), checked = fex == option.id, enabled = ready, detail = stringResource(option.detail)) {
|
||||
host.open = key
|
||||
save { com.droiddeck.launcher.session.GameEnvironmentStore.setGameFexPreset(it, scope, option.id) }
|
||||
|
||||
@@ -46,7 +46,9 @@ fun PerformancePage(
|
||||
fsyncFirst: Boolean,
|
||||
gamescopeRealtime: Boolean,
|
||||
gpuClockPin: Boolean,
|
||||
nativeDesktopAvailable: Boolean,
|
||||
prootNoSeccomp: Boolean,
|
||||
prootFastPath: Boolean,
|
||||
nativeUserland: Boolean,
|
||||
desktopAsUser: Boolean,
|
||||
cursorComposite: Boolean,
|
||||
guestHostname: String,
|
||||
@@ -63,6 +65,9 @@ fun PerformancePage(
|
||||
onFsyncFirst: (Boolean) -> Unit,
|
||||
onGamescopeRealtime: (Boolean) -> Unit,
|
||||
onGpuClockPin: (Boolean) -> Unit,
|
||||
onProotNoSeccomp: (Boolean) -> Unit,
|
||||
onProotFastPath: (Boolean) -> Unit,
|
||||
onNativeUserland: (Boolean) -> Unit,
|
||||
onDesktopAsUser: (Boolean) -> Unit,
|
||||
onCursorComposite: (Boolean) -> Unit,
|
||||
onGuestHostname: (String) -> Unit,
|
||||
@@ -147,6 +152,26 @@ fun PerformancePage(
|
||||
stringResource(R.string.perf_fastsync_hint),
|
||||
fastSync, onChange = onFastSync,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "seccomp", stringResource(R.string.perf_seccomp),
|
||||
stringResource(R.string.perf_seccomp_hint),
|
||||
prootNoSeccomp, onChange = onProotNoSeccomp,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "fastpath", stringResource(R.string.perf_fastpath),
|
||||
when {
|
||||
nativeUserland -> stringResource(R.string.perf_fastpath_needs_proot)
|
||||
prootNoSeccomp -> stringResource(R.string.perf_fastpath_needs_seccomp)
|
||||
else -> stringResource(R.string.perf_fastpath_hint)
|
||||
},
|
||||
prootFastPath && !prootNoSeccomp && !nativeUserland, enabled = !prootNoSeccomp && !nativeUserland,
|
||||
onChange = onProotFastPath,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "nativeuserland", stringResource(R.string.perf_native_userland),
|
||||
stringResource(R.string.perf_native_userland_hint),
|
||||
nativeUserland, onChange = onNativeUserland,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
|
||||
stringResource(R.string.perf_cursor_composite_hint),
|
||||
@@ -173,8 +198,8 @@ fun PerformancePage(
|
||||
}
|
||||
ToggleRow(
|
||||
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
|
||||
stringResource(R.string.perf_desktop_as_user_hint),
|
||||
desktopAsUser && nativeDesktopAvailable, enabled = nativeDesktopAvailable,
|
||||
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
|
||||
desktopAsUser && nativeUserland, enabled = nativeUserland,
|
||||
onChange = onDesktopAsUser,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -85,6 +85,9 @@ internal object SettingsIndex {
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_esync, "esync", "sync", "wine"),
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_fsync, "fsync", "sync", "wine"),
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_fastsync, "ntsync", "sync", "wine"),
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_seccomp, "proot"),
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_fastpath, "proot"),
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
|
||||
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
|
||||
|
||||
@@ -143,6 +143,8 @@
|
||||
<string name="game_settings_title">Games</string>
|
||||
<string name="fex_default_label">Stock FEX</string>
|
||||
<string name="fex_default_detail">No FEX tuning applied.</string>
|
||||
<string name="fex_follow_steam_label">Follow Steam</string>
|
||||
<string name="fex_follow_steam_detail">Use Steam’s available FEX hints for Proton games. Otherwise use Performance + TSO. Per-game settings still win.</string>
|
||||
<string name="fex_stability_label">Stability</string>
|
||||
<string name="fex_stability_detail">Safest, slowest settings.</string>
|
||||
<string name="fex_compatibility_label">Compatibility</string>
|
||||
@@ -737,8 +739,6 @@
|
||||
<string name="hud_size_minimal">Minimal</string>
|
||||
<string name="hud_size_mega">Mega</string>
|
||||
<string name="hud_size_strip">Strip</string>
|
||||
<string name="hud_size_side_strip">Side strip</string>
|
||||
<string name="hud_size_side_strip_hint">Drag the column to either side of the game. Tap the HUD to cycle sizes.</string>
|
||||
<string name="hud_locked">Lock in place</string>
|
||||
<string name="hud_locked_hint">Drag the HUD to move it. While it is locked, on-screen controls under it still work.</string>
|
||||
<string name="hud_hold">Long press</string>
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,17 @@ import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class GameEnvironmentTest {
|
||||
@Test
|
||||
fun followSteamIsGlobalOnlyAndKeepsThePerformanceTsoFallbackAndGameOverrides() {
|
||||
val preset = FexPreset.FOLLOW_STEAM
|
||||
val config = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "42", "PERFORMANCE")
|
||||
assertTrue(FexPreset.all.any { it.id == preset })
|
||||
assertFalse(FexPreset.forGame.any { it.id == preset })
|
||||
assertFalse(GameEnvironment.defaults(preset).containsKey("FEX_TSOENABLED"))
|
||||
assertEquals(GameEnvironment.effective(config, "PERFORMANCE_TSO", "43"), GameEnvironment.effective(config, preset, "43"))
|
||||
assertEquals("0", GameEnvironment.effective(config, preset, "42")["FEX_TSOENABLED"])
|
||||
}
|
||||
|
||||
@Test fun defaultsDetectGraphicsCapabilitiesAndKeepCaching() {
|
||||
val values = GameEnvironment.defaults("")
|
||||
assertEquals("false", values["MESA_SHADER_CACHE_DISABLE"])
|
||||
|
||||
@@ -133,38 +133,6 @@ class DroidDeckHudPanelTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun sideStripOffersOnlyTheOnePercentLow() {
|
||||
val readings = DroidDeckHudSize.SIDE_STRIP.rows
|
||||
assertEquals(listOf("showLow1"), readings.filter { it.startsWith("showLow") })
|
||||
}
|
||||
|
||||
@Test fun sideStripFitsOneSideOfAWideScreenAndUsesItsOwnReadingOrder() {
|
||||
val app = RuntimeEnvironment.getApplication()
|
||||
val view = DroidDeckHudView(app)
|
||||
val config = DroidDeckHudConfig.DEFAULTS + mapOf(
|
||||
"hudSize" to "side_strip",
|
||||
"hudOrder" to "strip:showCPUUsage|showRAM;side_strip:showRAM|showFPS|showFPSGraph",
|
||||
"showClock" to "0",
|
||||
)
|
||||
view.applyConfig(DroidDeckHudConfig.encode(config))
|
||||
view.showForTest(SNAPSHOT, "DXVK", 0L)
|
||||
|
||||
val density = app.resources.displayMetrics.density
|
||||
val height = (360 * density).toInt()
|
||||
val width = height * 21 / 9
|
||||
val sideMargin = (width - height * 16 / 9) / 2
|
||||
view.measure(
|
||||
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST),
|
||||
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST),
|
||||
)
|
||||
|
||||
assertTrue("HUD fits in one side margin", view.measuredWidth <= sideMargin)
|
||||
assertTrue("HUD is taller than it is wide", view.measuredHeight > view.measuredWidth)
|
||||
assertTrue("RAM is first", view.linesForTest().first().startsWith("RAM"))
|
||||
assertTrue("FPS is second", view.linesForTest()[1].startsWith("FPS"))
|
||||
assertTrue("The graph is inside the column", view.graphForTest()!!.right < view.measuredWidth)
|
||||
}
|
||||
|
||||
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
|
||||
val stats = FrameStats()
|
||||
var now = 1_000_000_000L
|
||||
|
||||
@@ -251,52 +251,6 @@ 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() }
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class NativeGuestDefaultsTest {
|
||||
@Test fun savedRuntimeOverridesDoNotDisableNativeExecution() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
|
||||
.putBoolean("nativeUserland", false)
|
||||
.putBoolean("prootFastPath", false)
|
||||
.putBoolean("prootNoSeccomp", true)
|
||||
.apply()
|
||||
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val hook = NativeGuest.hook(root)
|
||||
val loader = File(root, "usr/lib/ld-linux-aarch64.so.1")
|
||||
hook.parentFile?.mkdirs()
|
||||
loader.writeText("fixture")
|
||||
try {
|
||||
assertTrue(NativeGuest.nextSession(context))
|
||||
assertFalse(NativeGuest.enabled(context))
|
||||
hook.writeText("fixture")
|
||||
assertTrue(NativeGuest.enabled(context))
|
||||
assertFalse(ProotFastPath.enabled(context, native = true))
|
||||
} finally {
|
||||
hook.delete()
|
||||
loader.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,27 +94,6 @@ 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()
|
||||
|
||||
@@ -27,12 +27,14 @@ class ProotFastPathTest {
|
||||
}
|
||||
|
||||
@Test fun fastPathStaysOffForTheRootfsProot() {
|
||||
assertTrue(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = false))
|
||||
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_ROOTFS, native = false))
|
||||
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_MISSING, native = false))
|
||||
assertTrue(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
|
||||
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_ROOTFS))
|
||||
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_MISSING))
|
||||
assertFalse(ProotFastPath.allows(preference = false, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
|
||||
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = true, source = LinuxRuntime.PROOT_PACK))
|
||||
}
|
||||
|
||||
@Test fun fastPathStaysOffWithoutProot() {
|
||||
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = true))
|
||||
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK, nativeUserland = true))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.assumeFilePermissionsEnforced
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
@@ -9,7 +8,6 @@ import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.zip.ZipFile
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
@@ -146,136 +144,6 @@ class SessionLogShareZipTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theEasyAntiCheatLauncherLogsFromGamePrefixesComeAlong() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-12-05-09-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat")
|
||||
val prefix = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata/976730")
|
||||
val second = File(app.getExternalFilesDir(null), "second-library-${UUID.randomUUID()}").apply { mkdirs() }
|
||||
val library = SteamLibraries.add(app, second.path) as SteamLibraries.AddResult.Added
|
||||
try {
|
||||
File(session, "session.log").writeText("booted\n")
|
||||
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/4815162342").apply { mkdirs() }
|
||||
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 261\n")
|
||||
File(eac, "old.log").apply {
|
||||
writeText("stale\n")
|
||||
setLastModified(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))
|
||||
}
|
||||
val secondEac = File(second, "steamapps/compatdata/976730/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/b1d0a8c3").apply { mkdirs() }
|
||||
File(secondEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n")
|
||||
val signedEac = File(prefix.parentFile, "-1768546955/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
|
||||
File(signedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30005\n")
|
||||
val unsignedEac = File(prefix.parentFile, "2526420341/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
|
||||
File(unsignedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30007\n")
|
||||
|
||||
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val logs = archive.entries().toList().filter { it.name.startsWith("anticheat/976730/") }
|
||||
assertEquals(2, logs.size)
|
||||
assertTrue(logs.all { it.name.endsWith("/anticheatlauncher.log") && !it.name.contains("4815162342") })
|
||||
val texts = logs.map { archive.getInputStream(it).bufferedReader().readText() }
|
||||
assertTrue(texts.any { it.contains("Launch Error: 261") })
|
||||
assertTrue(texts.any { it.contains("Launch Error: 206") })
|
||||
val aliases = archive.entries().toList().filter { it.name.startsWith("anticheat/2526420341/") }
|
||||
assertEquals(2, aliases.size)
|
||||
assertEquals(2, aliases.map { it.name.split('/')[2] }.filter { it.startsWith("library1") }.toSet().size)
|
||||
val aliasTexts = aliases.map { archive.getInputStream(it).bufferedReader().readText() }
|
||||
assertTrue(aliasTexts.any { it.contains("Launch Error: 30005") })
|
||||
assertTrue(aliasTexts.any { it.contains("Launch Error: 30007") })
|
||||
}
|
||||
} finally {
|
||||
SteamLibraries.remove(app, library.entry.id)
|
||||
out.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
prefix.deleteRecursively()
|
||||
File(prefix.parentFile, "-1768546955").deleteRecursively()
|
||||
File(prefix.parentFile, "2526420341").deleteRecursively()
|
||||
second.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun theSessionsGameLogComesAlongWhenManyAntiCheatLogsAreFound() {
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-12-05-11-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-flood")
|
||||
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
|
||||
val prefixes = (0 until 300).map { File(compatdata, "${900000 + it}") }
|
||||
try {
|
||||
File(session, "session.log").writeText("booted\n")
|
||||
File(session, "steam-976730.log").writeText("proton: game started\n")
|
||||
prefixes.forEach { prefix ->
|
||||
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
|
||||
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n" + "x".repeat(64 * 1024))
|
||||
}
|
||||
|
||||
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val game = archive.entries().toList().single { it.name.endsWith("/steam-976730.log") }
|
||||
assertTrue(archive.getInputStream(game).bufferedReader().readText().contains("game started"))
|
||||
}
|
||||
} finally {
|
||||
out.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
prefixes.forEach { it.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aDiscoveryFailureStaysInTheManifestWhenRecordsPassTheLimit() {
|
||||
assumeFilePermissionsEnforced()
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-12-05-10-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/manifest-limit")
|
||||
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata").apply { mkdirs() }
|
||||
try {
|
||||
repeat(300) {
|
||||
File(session, "part-$it.log").writeText("line $it\n")
|
||||
File(session, "wayland-$it.log").writeText("line $it\n")
|
||||
File(session, "proton-$it.log").writeText("line $it\n")
|
||||
}
|
||||
assertTrue(compatdata.setReadable(false, false))
|
||||
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
|
||||
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
|
||||
assertTrue(entries.length() > 512)
|
||||
assertTrue(reasons.toString(), "filesystem-error" in reasons)
|
||||
}
|
||||
} finally {
|
||||
compatdata.setReadable(true, false)
|
||||
out.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aPrefixThatDeniesTheAntiCheatFolderIsRecordedAsADiscoveryFailure() {
|
||||
assumeFilePermissionsEnforced()
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
val session = File(LinuxRuntime.logDir(app), "2026-12-05-12-steam").apply { mkdirs() }
|
||||
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-denied")
|
||||
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
|
||||
val prefix = File(compatdata, "976731")
|
||||
val users = File(prefix, "pfx/drive_c/users").apply { mkdirs() }
|
||||
try {
|
||||
File(session, "session.log").writeText("booted\n")
|
||||
assertTrue(users.setExecutable(false, false))
|
||||
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
|
||||
ZipFile(zip).use { archive ->
|
||||
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
|
||||
val entries = manifest.getJSONArray("entries")
|
||||
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
|
||||
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
|
||||
assertTrue(reasons.toString(), "filesystem-error" in reasons)
|
||||
}
|
||||
} finally {
|
||||
users.setExecutable(true, false)
|
||||
out.deleteRecursively()
|
||||
session.deleteRecursively()
|
||||
prefix.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
|
||||
val logs = LinuxRuntime.logDir(app)
|
||||
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
# 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.
|
||||
@@ -252,15 +252,13 @@ self-extractor stops at "Path not found", so the values it installs are applied
|
||||
`goggame-<id>.info`, and a script's own `setRegistry` entries always win over the built-in table.
|
||||
|
||||
The script's `supportData` actions run right after: files and folders from the game folder
|
||||
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}`,
|
||||
`{localappdata}` or `{userappdata}` in the prefix, and `type: folder` without a source creates the
|
||||
folder. Mods such as one-click editions ship their `Plugins.txt` and INI files this way. The
|
||||
`savePath` action's `savePath` folder is created with the same path rules, including the common
|
||||
case where a one-click edition names it again as a `supportData` folder. Paths match without regard
|
||||
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}` and
|
||||
`{localappdata}` in the prefix, and `type: folder` without a source creates the folder. Mods such
|
||||
as one-click editions ship their `Plugins.txt` and INI files this way. Paths match without regard
|
||||
to case, links are copied as links, and a path outside those folders is refused. A file the
|
||||
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` and
|
||||
`.droiddeck-gog-save-path` in the prefix hold the actions' hashes, so they run once per script
|
||||
revision and a player's later edits stay.
|
||||
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` in
|
||||
the prefix holds the actions' hash, so they run once per script revision and a player's later
|
||||
edits stay.
|
||||
|
||||
A GOG game's exe comes from its own manifest first: `goggame-<id>.info`'s play task in category
|
||||
`game` (`isPrimary` first), or a primary `launcher` task for launcher games, whose `path` stays
|
||||
|
||||
@@ -27,6 +27,9 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
|
||||
| droiddeck-esync | Settings › Performance (`droiddeck://settings/performance`) | esync, sync, wine |
|
||||
| droiddeck-fsync first | Settings › Performance (`droiddeck://settings/performance`) | fsync, sync, wine |
|
||||
| droiddeck-ntsync | Settings › Performance (`droiddeck://settings/performance`) | ntsync, sync, wine |
|
||||
| Run proot without seccomp | Settings › Performance (`droiddeck://settings/performance`) | proot |
|
||||
| proot fast path | Settings › Performance (`droiddeck://settings/performance`) | proot |
|
||||
| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot |
|
||||
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
|
||||
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
|
||||
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
#include <elf.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
@@ -548,55 +547,3 @@ EXPORT uid_t getuid(void)
|
||||
}
|
||||
return (uid_t)raw_getuid();
|
||||
}
|
||||
|
||||
static bool read_at(int fd, void *buf, size_t n, off_t at)
|
||||
{
|
||||
return pread(fd, buf, n, at) == (ssize_t)n;
|
||||
}
|
||||
|
||||
static void load_needed_of(const char *path)
|
||||
{
|
||||
Elf64_Ehdr e;
|
||||
Elf64_Phdr ph[32];
|
||||
Elf64_Dyn dyn[128];
|
||||
uint64_t strtab = 0, strsz = 0, needed[32];
|
||||
size_t n_dyn = 0, n_needed = 0;
|
||||
off_t names_at = -1;
|
||||
char *names = NULL;
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return;
|
||||
if (!read_at(fd, &e, sizeof e, 0) || memcmp(e.e_ident, ELFMAG, SELFMAG) || e.e_ident[EI_CLASS] != ELFCLASS64 ||
|
||||
e.e_phentsize != sizeof *ph || e.e_phnum > 32 || !read_at(fd, ph, e.e_phnum * sizeof *ph, (off_t)e.e_phoff))
|
||||
goto out;
|
||||
for (int i = 0; i < e.e_phnum; i++) {
|
||||
if (ph[i].p_type != PT_DYNAMIC) continue;
|
||||
n_dyn = ph[i].p_filesz / sizeof *dyn;
|
||||
if (n_dyn > 128) n_dyn = 128;
|
||||
if (!read_at(fd, dyn, n_dyn * sizeof *dyn, (off_t)ph[i].p_offset)) goto out;
|
||||
break;
|
||||
}
|
||||
for (size_t i = 0; i < n_dyn && dyn[i].d_tag != DT_NULL; i++) {
|
||||
if (dyn[i].d_tag == DT_STRTAB) strtab = dyn[i].d_un.d_ptr;
|
||||
else if (dyn[i].d_tag == DT_STRSZ) strsz = dyn[i].d_un.d_val;
|
||||
else if (dyn[i].d_tag == DT_NEEDED && n_needed < 32) needed[n_needed++] = dyn[i].d_un.d_val;
|
||||
}
|
||||
for (int i = 0; i < e.e_phnum; i++)
|
||||
if (ph[i].p_type == PT_LOAD && strtab >= ph[i].p_vaddr && strtab - ph[i].p_vaddr + strsz <= ph[i].p_filesz)
|
||||
names_at = (off_t)(ph[i].p_offset + strtab - ph[i].p_vaddr);
|
||||
if (names_at < 0 || !strsz || strsz > (16u << 20) || !(names = malloc(strsz + 1)) ||
|
||||
!read_at(fd, names, strsz, names_at))
|
||||
goto out;
|
||||
names[strsz] = 0;
|
||||
for (size_t i = 0; i < n_needed; i++)
|
||||
if (needed[i] < strsz && !dlopen(names + needed[i], RTLD_NOW))
|
||||
say("steamshm: %s, needed by %s, did not load: %s\n", names + needed[i], path, dlerror());
|
||||
out:
|
||||
free(names);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void link_steamclient_needs_before_it(void)
|
||||
{
|
||||
const char *path = getenv("WINESTEAMCLIENTPATH64");
|
||||
if (path && *path) load_needed_of(path);
|
||||
}
|
||||
@@ -225,7 +225,6 @@ 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
|
||||
|
||||
@@ -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/linuxfs/lse-emu',
|
||||
'tools/venus/glprobe.c', 'tools/quest']
|
||||
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c',
|
||||
'tools/quest']
|
||||
|
||||
|
||||
def ci_environment(architecture, root):
|
||||
|
||||
@@ -31,9 +31,5 @@ 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"
|
||||
@@ -1,23 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,15 +0,0 @@
|
||||
#!/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
@@ -573,11 +573,11 @@ def inspector_url(url):
|
||||
|
||||
|
||||
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
|
||||
command_line_api=False, connect_timeout=5):
|
||||
command_line_api=False):
|
||||
if inspector is not None:
|
||||
url, name = inspector_url(inspector), "inspector"
|
||||
else:
|
||||
targets = [t for t in cdp_targets(agent_dir, timeout=connect_timeout) if t.get("webSocketDebuggerUrl")]
|
||||
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
|
||||
want = target or "SharedJSContext"
|
||||
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
|
||||
if not match:
|
||||
@@ -841,75 +841,6 @@ class KeyboardWatcher(threading.Thread):
|
||||
self.report(params.get("payload") == "true")
|
||||
|
||||
|
||||
NATIVE_SUSPEND_JS = r"""/* Template arguments are inserted by Python after validation. */
|
||||
async (operation, token, value, order) => {
|
||||
const root = globalThis;
|
||||
const leases = root.__droiddeckNativeSleep ??= { current: null, order: 0n, canceled: false };
|
||||
const sequence = BigInt(order);
|
||||
if (sequence < leases.order) return operation === "wake" ? "miss" : "expired";
|
||||
if (sequence > leases.order) {
|
||||
// An older renderer evaluation can arrive after a newer one. Only
|
||||
// the newest Android request may own a still-in-flight preparation,
|
||||
// including when its own preparation cannot start before deadline.
|
||||
leases.order = sequence;
|
||||
leases.canceled = false;
|
||||
if (leases.current && !leases.current.result) {
|
||||
leases.current.owner = token;
|
||||
leases.current.wake = false;
|
||||
} else {
|
||||
leases.current = null;
|
||||
}
|
||||
}
|
||||
const busy = () => root.SuspendResumeStore?.m_bSuspending === true;
|
||||
const user = root.SteamClient?.User;
|
||||
async function recover(lease) {
|
||||
if (leases.current !== lease || lease.recovered || !lease.wake || busy()) return;
|
||||
if (typeof user?.ResumeSuspendedGames !== "function") return;
|
||||
lease.recovered = true;
|
||||
try { await user.ResumeSuspendedGames(false); } catch { /* no session kick or retry */ }
|
||||
}
|
||||
|
||||
if (operation === "wake") {
|
||||
leases.canceled = true;
|
||||
const lease = leases.current;
|
||||
if (lease?.owner !== token) return "miss";
|
||||
lease.wake = true;
|
||||
// If login1 already signaled sleep and preparation had settled before
|
||||
// wake, its normal resume notification owns recovery. A late success
|
||||
// must recover again only because that notification could precede it.
|
||||
if (lease.result === "prepared" && value !== "signaled") void recover(lease);
|
||||
return "ack";
|
||||
}
|
||||
|
||||
if (leases.canceled) return "expired";
|
||||
const active = leases.current;
|
||||
// A reused in-flight call still requires wake recovery, even when
|
||||
// this request is too late to issue its own call.
|
||||
if (active && !active.result) return "coalesced";
|
||||
if (Date.now() >= value) return "expired";
|
||||
if (typeof user?.PrepareForSystemSuspend !== "function") return "unavailable";
|
||||
if (busy()) return "steam-busy";
|
||||
if (active) return active.result;
|
||||
const lease = { owner: token, result: null, wake: false, recovered: false };
|
||||
leases.current = lease;
|
||||
try {
|
||||
const reply = await user.PrepareForSystemSuspend();
|
||||
lease.result = reply?.result === 1 ? "prepared" : "rejected";
|
||||
} catch {
|
||||
lease.result = "uncertain";
|
||||
}
|
||||
if (lease.result === "prepared" && lease.wake) void recover(lease);
|
||||
return lease.result;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def native_suspend_lease(agent_dir, command, token, value, order):
|
||||
expression = "(" + NATIVE_SUSPEND_JS + ")(" + ", ".join(map(json.dumps, (command, token, value, order))) + ")"
|
||||
return cdp_eval(agent_dir, expression, timeout=1.45 if command == "prepare" else 0.75,
|
||||
connect_timeout=0.35).get("value")
|
||||
|
||||
|
||||
def steam_idle_inhibit(agent_dir, inhibit):
|
||||
expression = """(async want => {
|
||||
const toggle = () => new Promise(done => {
|
||||
@@ -1387,23 +1318,6 @@ def main(argv):
|
||||
time.sleep(0.5)
|
||||
print({True: "yes", False: "no"}.get(value, "unknown"))
|
||||
return {True: 0, False: 5}.get(value, 1)
|
||||
if argv and argv[0] in ("--steam-prepare-native-suspend", "--steam-wake-native-suspend"):
|
||||
if (len(argv) != 4 or re.fullmatch(r"[0-9a-f]{32}", argv[1]) is None or
|
||||
re.fullmatch(r"[1-9][0-9]{0,19}", argv[3]) is None):
|
||||
return 2
|
||||
prepare = argv[0] == "--steam-prepare-native-suspend"
|
||||
if prepare and (not argv[2].isascii() or not argv[2].isdigit() or len(argv[2]) > 14):
|
||||
return 2
|
||||
if not prepare and argv[2] not in ("signaled", "unsignaled", "uncertain"):
|
||||
return 2
|
||||
kind = "prepare" if prepare else "wake"
|
||||
value = int(argv[2]) if prepare else argv[2]
|
||||
try:
|
||||
result = native_suspend_lease(Path(base) / "agent", kind, argv[1], value, argv[3])
|
||||
except (AgentError, OSError, ValueError):
|
||||
result = "uncertain"
|
||||
print(result or "uncertain")
|
||||
return 0 if result in ("prepared", "ack", "miss") else 1
|
||||
if argv and argv[0] == "--steam-asleep":
|
||||
expression = """(() => {
|
||||
const store = globalThis.SuspendResumeStore;
|
||||
|
||||
@@ -803,8 +803,9 @@ def game_environment(env, command, proton=None):
|
||||
config = json.load(source)
|
||||
except FileNotFoundError:
|
||||
config = {"version": 1}
|
||||
env = game_env["apply_config"](env, config, str(app), fixes)
|
||||
if proton and len(proton) > 2 and proton[1] == "waitforexitandrun":
|
||||
steam_proton = bool(proton and len(proton) > 2 and proton[1] == "waitforexitandrun")
|
||||
env = game_env["apply_config"](env, config, str(app), fixes, steam_proton=steam_proton)
|
||||
if steam_proton:
|
||||
logged = game_env["apply_game_debug_logs"](env, config)
|
||||
if logged is not env:
|
||||
say("game debug logs enabled for this launch")
|
||||
|
||||
@@ -812,11 +812,45 @@ def game_images(env):
|
||||
return True
|
||||
|
||||
|
||||
def apply_config(env, config, app_id, fixes=None):
|
||||
STEAM_FEX_HINTS = {
|
||||
"FEX_TSOENABLED": ("STEAM_FEX_TSOENABLED", "TSOEnabled"),
|
||||
"FEX_MULTIBLOCK": ("STEAM_FEX_MULTIBLOCK", "Multiblock"),
|
||||
}
|
||||
|
||||
|
||||
def follow_steam_fex(env, fallback, app_id, steam_proton):
|
||||
if not isinstance(fallback, dict):
|
||||
raise ValueError("invalid Follow Steam FEX fallback")
|
||||
runtime_id = app_number(env.get("SteamAppId") or env.get("STEAM_COMPAT_APP_ID"))
|
||||
if not steam_proton or env.get("DROIDDECK_DIRECT_PROTON") == "1" or runtime_id != app_id \
|
||||
or runtime_id is None or int(runtime_id) >= 2**31:
|
||||
return fallback
|
||||
# A caller-supplied FEX config takes the place of Proton's generated one. Do not
|
||||
# mask it with DroidDeck defaults; explicit DroidDeck overrides are applied later.
|
||||
config = env.get("FEX_APP_CONFIG")
|
||||
if config and os.path.isfile(config):
|
||||
return {}
|
||||
result = fallback.copy()
|
||||
override = env.get("STEAM_COMPAT_FEX_CONFIG", "")
|
||||
# Use the actual launch variables, not the numeric Steam Frame metadata enums.
|
||||
# Valve's nonempty override is a bitset: absent flags mean off. Ignore an
|
||||
# unknown/malformed payload rather than treating it as an all-off override.
|
||||
names = "|".join(name for _, name in STEAM_FEX_HINTS.values())
|
||||
flags = dict(re.findall(rf"(?<![\w])({names}):([01])(?![\w])", override))
|
||||
for target, (hint, option) in STEAM_FEX_HINTS.items():
|
||||
value = flags.get(option, "0") if flags else env.get(hint)
|
||||
if value in ("0", "1"):
|
||||
result[target] = value
|
||||
return result
|
||||
|
||||
|
||||
def apply_config(env, config, app_id, fixes=None, *, steam_proton=False):
|
||||
if config.get("version") != 1:
|
||||
raise ValueError("unsupported environment configuration")
|
||||
result = env.copy()
|
||||
entries = split_game_gpu(config.get("shared", {}))
|
||||
fallback = config.get("followSteamFex")
|
||||
entries = follow_steam_fex(env, fallback, app_id, steam_proton) if fallback is not None else {}
|
||||
entries = dict(entries, **split_game_gpu(config.get("shared", {})))
|
||||
for name, value in (fixes or {}).items():
|
||||
if name == "WINEDLLOVERRIDES" and entries.get(name, env.get(name)):
|
||||
value = entries.get(name, env.get(name)) + ";" + value
|
||||
@@ -1745,7 +1779,7 @@ def main():
|
||||
launch_config_valid = False
|
||||
if launch_config_valid:
|
||||
try:
|
||||
effective_env = apply_config(env, launch_config, app_id)
|
||||
effective_env = apply_config(env, launch_config, app_id, steam_proton=True)
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
launch_config_valid = False
|
||||
if not launch_config_valid:
|
||||
@@ -1816,7 +1850,7 @@ def main():
|
||||
if launch_config_valid:
|
||||
if "vblank_mode" in config.get("shared", {}):
|
||||
fixes.pop("vblank_mode", None)
|
||||
env = apply_config(env, launch_config, app_id, fixes)
|
||||
env = apply_config(env, launch_config, app_id, fixes, steam_proton=True)
|
||||
note = keyboard_helper_off(env)
|
||||
if note:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
|
||||
@@ -7,7 +7,6 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import gi
|
||||
@@ -21,10 +20,6 @@ INTERFACE = NAME + ".Manager"
|
||||
UPOWER = "org.freedesktop.UPower"
|
||||
UPOWER_ROOT = "/org/freedesktop/UPower"
|
||||
NATIVE_PREPARE_MS = 1500
|
||||
STEAM_PREPARE_WAIT = 1.95
|
||||
STEAM_PREPARE_START_MS = 850
|
||||
STEAM_WAKE_WAIT = 1.25
|
||||
STEAM_WAKE_RETRY_DELAYS = (0, 0.2, 0.5)
|
||||
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
|
||||
ASLEEP_WAIT = 6
|
||||
INHIBIT_WAIT = 12
|
||||
@@ -60,10 +55,6 @@ class LoginManager:
|
||||
self.native_ready = self.directory / "steam-native-ready"
|
||||
self.pending = None
|
||||
self.pending_idle = False
|
||||
self.native_preparation = None
|
||||
self.native_signaled = False
|
||||
self.native_order = None
|
||||
self.native_wake_work = None
|
||||
self.waiting = set()
|
||||
self.timeout = None
|
||||
self.preparation = None
|
||||
@@ -99,7 +90,6 @@ class LoginManager:
|
||||
if self.pending:
|
||||
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
|
||||
return
|
||||
self.cancel_native_wake()
|
||||
self.pending = uuid.uuid4().hex
|
||||
self.pending_idle = False
|
||||
self.notify(True)
|
||||
@@ -143,42 +133,19 @@ class LoginManager:
|
||||
return
|
||||
self.pending = token
|
||||
self.pending_idle = words[1:] == ["idle"]
|
||||
# Idle requests never take ownership of Steam preparation. Preserve any
|
||||
# earlier wake delivery so an in-flight prepare cannot outlive its wake.
|
||||
if not self.pending_idle:
|
||||
self.cancel_native_wake()
|
||||
self.waiting = {"hold"} if self.pending_idle else {"hold", "prepare"}
|
||||
self.hold(token, self.prepared, token, "hold")
|
||||
if self.pending_idle:
|
||||
return
|
||||
self.native_preparation = "pending"
|
||||
order = self.native_order = str(time.monotonic_ns())
|
||||
deadline = int(time.time() * 1000) + STEAM_PREPARE_START_MS
|
||||
|
||||
def prepare():
|
||||
_, out = agent("--steam-prepare-native-suspend", token, str(deadline), order, timeout=STEAM_PREPARE_WAIT)
|
||||
GLib.idle_add(self.steam_prepared, token, out.strip() or "uncertain")
|
||||
|
||||
threading.Thread(target=prepare, daemon=True).start()
|
||||
|
||||
def steam_prepared(self, token, outcome):
|
||||
self.check_state()
|
||||
if self.pending != token:
|
||||
return False
|
||||
self.native_preparation = outcome
|
||||
self.native_signaled = True
|
||||
print("== login1: Steam native preparation " + outcome, flush=True)
|
||||
self.notify(True)
|
||||
self.bus.flush(None, self.prepare_after_flush, token)
|
||||
return False
|
||||
|
||||
def prepare_after_flush(self, connection, result, token):
|
||||
try:
|
||||
connection.flush_finish(result)
|
||||
except GLib.Error as error:
|
||||
print("== login1: cannot prepare native sleep: " + str(error), file=sys.stderr)
|
||||
if self.pending == token:
|
||||
self.resume()
|
||||
self.resume()
|
||||
return
|
||||
self.check_state()
|
||||
if self.pending == token:
|
||||
@@ -302,49 +269,19 @@ class LoginManager:
|
||||
self.notify(True)
|
||||
self.bus.flush(None, self.finish_recovery, None)
|
||||
return
|
||||
token = self.pending
|
||||
idle = self.pending_idle
|
||||
native = self.native_preparation
|
||||
signaled = self.native_signaled
|
||||
order = self.native_order
|
||||
self.native_order = None
|
||||
self.pending = None
|
||||
self.pending_idle = False
|
||||
self.native_preparation = None
|
||||
self.native_signaled = False
|
||||
if self.preparation is not None:
|
||||
GLib.source_remove(self.preparation)
|
||||
self.preparation = None
|
||||
if self.timeout is not None:
|
||||
GLib.source_remove(self.timeout)
|
||||
self.timeout = None
|
||||
if not idle and (native is None or signaled):
|
||||
if not idle:
|
||||
self.notify(False)
|
||||
if native in ("pending", "uncertain", "coalesced") or native == "prepared" and not signaled:
|
||||
phase = "uncertain" if signaled else "unsignaled"
|
||||
self.deliver_native_wake(token, phase, order)
|
||||
self.release_later()
|
||||
|
||||
def cancel_native_wake(self):
|
||||
if self.native_wake_work is not None:
|
||||
self.native_wake_work.set()
|
||||
self.native_wake_work = None
|
||||
|
||||
def deliver_native_wake(self, token, phase, order):
|
||||
work = self.native_wake_work = threading.Event()
|
||||
|
||||
def deliver():
|
||||
for delay in STEAM_WAKE_RETRY_DELAYS:
|
||||
if work.wait(delay):
|
||||
return
|
||||
code, outcome = agent("--steam-wake-native-suspend", token, phase, order, timeout=STEAM_WAKE_WAIT)
|
||||
if code == 0 and outcome.strip() in ("ack", "miss"):
|
||||
return
|
||||
if not work.is_set():
|
||||
print("== login1: Steam native wake recovery not acknowledged", file=sys.stderr, flush=True)
|
||||
|
||||
threading.Thread(target=deliver, daemon=True).start()
|
||||
|
||||
def finish_recovery(self, connection, result, _data):
|
||||
try:
|
||||
connection.flush_finish(result)
|
||||
|
||||
@@ -524,6 +524,8 @@ def main(argv):
|
||||
os.makedirs(target.compatdata, exist_ok=True)
|
||||
env = environment(os.environ, target, folder, root, window, game_id)
|
||||
env.update(extra)
|
||||
# The launcher synthesizes Steam IDs for direct runs: those are not client hints.
|
||||
env["DROIDDECK_DIRECT_PROTON"] = "1"
|
||||
if app is None and verb == VERB:
|
||||
env["DROIDDECK_DESKTOP_PROGRAM"] = program
|
||||
say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata,
|
||||
|
||||
Regular → Executable
-7
@@ -11,12 +11,6 @@ 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
|
||||
|
||||
@@ -106,7 +100,6 @@ 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() {
|
||||
|
||||
@@ -968,7 +968,6 @@ def prepare_gog(sidecar, compat_data, launch_dir):
|
||||
GOG_SCRIPTS = "goggame-*.script"
|
||||
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
|
||||
GOG_SUPPORT_MARK = ".droiddeck-gog-support"
|
||||
GOG_SAVE_PATH_MARK = ".droiddeck-gog-save-path"
|
||||
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
|
||||
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
|
||||
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
|
||||
@@ -1717,7 +1716,7 @@ def prepare_steam_ea(argv, compat_data, launch_dir):
|
||||
return REPLACED
|
||||
|
||||
|
||||
def gog_script_actions(folder, name):
|
||||
def gog_support_actions(folder):
|
||||
found = []
|
||||
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
|
||||
product = script.name[len("goggame-"):-len(".script")]
|
||||
@@ -1727,34 +1726,17 @@ def gog_script_actions(folder, name):
|
||||
continue
|
||||
for action in actions if isinstance(actions, list) else []:
|
||||
install = action.get("install") if isinstance(action, dict) else None
|
||||
if isinstance(install, dict) and install.get("action") == name \
|
||||
if isinstance(install, dict) and install.get("action") == "supportData" \
|
||||
and isinstance(install.get("arguments"), dict):
|
||||
found.append((product, install["arguments"]))
|
||||
return found
|
||||
|
||||
|
||||
def gog_support_actions(folder):
|
||||
return gog_script_actions(folder, "supportData")
|
||||
|
||||
|
||||
def gog_case_child(path, part):
|
||||
exact = path / part
|
||||
try:
|
||||
if not exact.exists() and path.is_dir():
|
||||
return next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
|
||||
except OSError:
|
||||
pass
|
||||
return exact
|
||||
|
||||
|
||||
def gog_support_bases(folder, product, pfx):
|
||||
user = Path(pfx) / "drive_c" / "users" / "steamuser"
|
||||
support = Path(folder) / "support" / product
|
||||
appdata = gog_case_child(user, "AppData")
|
||||
return {"app": Path(folder), "supportdir": support, "support": support,
|
||||
"userdocs": gog_case_child(user, "Documents"),
|
||||
"localappdata": gog_case_child(appdata, "Local"),
|
||||
"userappdata": gog_case_child(appdata, "Roaming")}
|
||||
"userdocs": user / "Documents", "localappdata": user / "AppData" / "Local"}
|
||||
|
||||
|
||||
def gog_inside(path, base):
|
||||
@@ -1773,7 +1755,10 @@ def gog_support_path(text, bases):
|
||||
base = bases[match.group(1).lower()]
|
||||
path = base
|
||||
for part in parts:
|
||||
path = gog_case_child(path, part)
|
||||
exact = path / part
|
||||
if not exact.exists() and path.is_dir():
|
||||
exact = next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
|
||||
path = exact
|
||||
if path != base and not gog_inside(path.parent, base):
|
||||
return None
|
||||
return path, base
|
||||
@@ -1845,44 +1830,6 @@ def gog_support_data(folder, compat_data, proton):
|
||||
return "copied=%d%s" % (copied, note)
|
||||
|
||||
|
||||
def gog_save_paths(folder, compat_data, proton):
|
||||
actions = gog_script_actions(folder, "savePath")
|
||||
if not actions:
|
||||
return "none"
|
||||
pfx = Path(compat_data) / "pfx" if compat_data else None
|
||||
if not pfx or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
|
||||
made = create_prefix(compat_data, proton)
|
||||
if made not in ("present", "created") or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
|
||||
return "no-prefix"
|
||||
stamp = hashlib.sha256(json.dumps(actions, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
marker = pfx / GOG_SAVE_PATH_MARK
|
||||
try:
|
||||
if marker.is_file() and marker.read_text() == stamp:
|
||||
return "ready"
|
||||
except OSError:
|
||||
pass
|
||||
paths = skipped = 0
|
||||
for product, arguments in actions:
|
||||
bases = gog_support_bases(folder, product, pfx)
|
||||
found = gog_support_path(arguments.get("savePath") or arguments.get("target"), bases)
|
||||
if found is None:
|
||||
skipped += 1
|
||||
continue
|
||||
target, _root = found
|
||||
try:
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
paths += 1
|
||||
except OSError:
|
||||
skipped += 1
|
||||
note = " skipped=%d" % skipped if skipped else ""
|
||||
if not skipped:
|
||||
try:
|
||||
marker.write_text(stamp)
|
||||
except OSError:
|
||||
pass
|
||||
return "paths=%d%s" % (paths, note)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
|
||||
return 0
|
||||
@@ -1929,7 +1876,6 @@ def main(argv):
|
||||
prepare_gog(sidecar, compat_data, launch_dir)
|
||||
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
log("gog save paths: " + gog_save_paths(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
||||
if store == "rockstar":
|
||||
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
|
||||
if compat_data:
|
||||
|
||||
@@ -56,38 +56,27 @@ 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) {
|
||||
long long now = now_ns();
|
||||
struct entry *e = slot(h);
|
||||
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) {
|
||||
struct entry *e = find(path, kind, mode, flags, h);
|
||||
long long now = now_ns();
|
||||
struct entry *e = slot(h);
|
||||
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;
|
||||
@@ -95,7 +84,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;
|
||||
e->stamp = now_ns();
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
|
||||
@@ -542,35 +542,7 @@ static int zr_start(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static pthread_key_t zr_key;
|
||||
static int zr_key_ready;
|
||||
static pthread_mutex_t zr_key_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static unsigned char zr_idle;
|
||||
|
||||
static void zr_key_make(void) {
|
||||
if (__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) return;
|
||||
pthread_mutex_lock(&zr_key_lock);
|
||||
if (!__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) {
|
||||
pthread_key_t key;
|
||||
if (pthread_key_create(&key, NULL) == 0) {
|
||||
if (pthread_getspecific(key) == NULL) {
|
||||
zr_key = key;
|
||||
__atomic_store_n(&zr_key_ready, 1, __ATOMIC_RELEASE);
|
||||
} else {
|
||||
pthread_key_delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&zr_key_lock);
|
||||
}
|
||||
|
||||
static void zr_key_child(void) {
|
||||
pthread_mutex_init(&zr_key_lock, NULL);
|
||||
}
|
||||
|
||||
static volatile unsigned char *zr_selector(void) {
|
||||
return __atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE) ? (volatile unsigned char *)pthread_getspecific(zr_key) : NULL;
|
||||
}
|
||||
static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec")));
|
||||
|
||||
int prctl(int option, ...) {
|
||||
va_list ap;
|
||||
@@ -580,32 +552,16 @@ int prctl(int option, ...) {
|
||||
unsigned long arg4 = va_arg(ap, unsigned long);
|
||||
unsigned long arg5 = va_arg(ap, unsigned long);
|
||||
va_end(ap);
|
||||
int arming = option == PR_SET_SYSCALL_USER_DISPATCH && arg2;
|
||||
if (arming) {
|
||||
zr_key_make();
|
||||
if (!__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) {
|
||||
errno = EAGAIN;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
volatile unsigned char *dispatch = zr_selector();
|
||||
volatile unsigned char *dispatch = zr_dispatch;
|
||||
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
||||
if (selector) *dispatch = 0;
|
||||
if (arming && pthread_setspecific(zr_key, dispatch != NULL ? (void *)dispatch : (void *)&zr_idle) != 0) {
|
||||
if (selector) *dispatch = selector;
|
||||
errno = ENOMEM;
|
||||
return -1;
|
||||
}
|
||||
long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5);
|
||||
int failed = (unsigned long)result > -4096UL;
|
||||
if (arming) pthread_setspecific(zr_key, failed ? (void *)dispatch : (void *)arg5);
|
||||
if (selector) *dispatch = selector;
|
||||
int ready = __atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE);
|
||||
if (failed) {
|
||||
if ((unsigned long)result > -4096UL) {
|
||||
errno = (int)-result;
|
||||
return -1;
|
||||
}
|
||||
if (option == PR_SET_SYSCALL_USER_DISPATCH && !arg2 && ready) pthread_setspecific(zr_key, NULL);
|
||||
if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL;
|
||||
return (int)result;
|
||||
}
|
||||
|
||||
@@ -613,7 +569,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)context;
|
||||
if (info == NULL || info->si_code != SI_USER) return;
|
||||
volatile unsigned char *dispatch = zr_selector();
|
||||
volatile unsigned char *dispatch = zr_dispatch;
|
||||
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
||||
if (selector) *dispatch = 0;
|
||||
int saved = errno;
|
||||
@@ -642,7 +598,6 @@ static void zr_paths(void) {
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void zr_init(void) {
|
||||
pthread_atfork(NULL, NULL, zr_key_child);
|
||||
zr_paths();
|
||||
int fd = zr_open(zr_ctl);
|
||||
if (fd < 0) return;
|
||||
|
||||
+16
-136
@@ -41,73 +41,9 @@ 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, int lse_emu_disabled) {
|
||||
static char *map_preload_paths(const char *value) {
|
||||
if (!value) return NULL;
|
||||
size_t cap = strlen(value) + (g_ddnatv_root_len + 1) * 16 + 16;
|
||||
char *out = malloc(cap);
|
||||
@@ -121,13 +57,6 @@ static char *map_preload_paths(const char *value, int lse_emu_disabled) {
|
||||
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);
|
||||
@@ -143,13 +72,10 @@ static char *map_preload_paths(const char *value, int lse_emu_disabled) {
|
||||
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;
|
||||
@@ -179,7 +105,6 @@ 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;
|
||||
@@ -215,12 +140,6 @@ 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
|
||||
@@ -238,45 +157,23 @@ 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, lse_emu_disabled);
|
||||
char *mapped = map_preload_paths(preload_value);
|
||||
if (mapped) {
|
||||
char *str = merge_preload_env(host_preload, mapped);
|
||||
free(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);
|
||||
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;
|
||||
}
|
||||
}
|
||||
if (lse_emu_disabled) {
|
||||
free_modified_env(new_env, envp);
|
||||
free(filtered_host_chain);
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
free(mapped);
|
||||
}
|
||||
}
|
||||
// If we have an explicit real executable, drop the inherited entry to replace with the fresh target
|
||||
@@ -314,13 +211,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 = host_preload ? strlen(host_preload) + 1 : 0;
|
||||
size_t host_len = g_preload_host ? strlen(g_preload_host) + 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, host_preload, host_len - 1);
|
||||
n = ddnatv_append(str, size, n, g_preload_host, host_len - 1);
|
||||
n = ddnatv_append(str, size, n, ":", 1);
|
||||
}
|
||||
ddnatv_append(str, size, n, hook, hook_len);
|
||||
@@ -328,29 +225,13 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
}
|
||||
}
|
||||
if (!has_preload_list && g_preload_guest) {
|
||||
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;
|
||||
}
|
||||
size_t len = strlen(g_preload_guest);
|
||||
char *str = malloc(15 + len + 1);
|
||||
if (str) {
|
||||
memcpy(str, "DDNATV_PRELOAD=", 15);
|
||||
memcpy(str + 15, guest_preload, len + 1);
|
||||
memcpy(str + 15, g_preload_guest, len + 1);
|
||||
new_env[dst++] = str;
|
||||
}
|
||||
free(filtered);
|
||||
}
|
||||
if (!has_root && g_ddnatv_root[0] != '\0') {
|
||||
char *str = malloc(PATH_MAX + 16);
|
||||
@@ -438,7 +319,6 @@ 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -483,11 +483,6 @@ 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
|
||||
@@ -512,11 +507,6 @@ 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);
|
||||
@@ -569,10 +559,6 @@ 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);
|
||||
@@ -1035,7 +1021,6 @@ 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) {
|
||||
|
||||
@@ -110,7 +110,6 @@ 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',
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
#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) {}
|
||||
@@ -1,9 +0,0 @@
|
||||
#include <stdio.h>
|
||||
|
||||
void lse_emu_early_dependency_anchor(void);
|
||||
|
||||
int main(void) {
|
||||
lse_emu_early_dependency_anchor();
|
||||
puts("early lse ok");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,300 +0,0 @@
|
||||
#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;
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
STEAMSHM = Path(__file__).resolve().parents[1] / "bionic-runtime/steamshm.c"
|
||||
|
||||
SOURCES = {
|
||||
"libsystemxml.so": ("int xml_copy(void) { return 1; }\n", []),
|
||||
"libvendor.so": ("int xml_copy(void);\nint vendor_xml_copy(void) { return xml_copy(); }\n", ["systemxml"]),
|
||||
"libframework.so": ("int framework(void) { return 0; }\n", ["vendor"]),
|
||||
"libsteam.so": ("int xml_copy(void) { return 2; }\nint CreateInterface(void) { return 0; }\n", ["framework"]),
|
||||
}
|
||||
|
||||
LOADER_PRELUDE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <elf.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#define say(...) fprintf(stderr, __VA_ARGS__)
|
||||
"""
|
||||
|
||||
|
||||
def steamclient_loader():
|
||||
source = STEAMSHM.read_text()
|
||||
return LOADER_PRELUDE + source[source.index("static bool read_at("):]
|
||||
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
int main(void) {
|
||||
if (!dlopen("libsteam.so", RTLD_NOW)) { puts(dlerror()); return 1; }
|
||||
void *vendor = dlopen("libvendor.so", RTLD_NOW | RTLD_NOLOAD);
|
||||
int (*copy)(void) = vendor ? (int (*)(void))dlsym(vendor, "vendor_xml_copy") : 0;
|
||||
if (!copy) return 1;
|
||||
printf("%d\n", copy());
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class SteamClientNeedsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
for name, (code, needs) in SOURCES.items():
|
||||
src = self.dir / (name + ".c")
|
||||
src.write_text(code)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-o", str(self.dir / name), str(src), "-L", str(self.dir),
|
||||
"-Wl,--no-as-needed", *("-l" + n for n in needs)], check=True)
|
||||
(self.dir / "main.c").write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-o", str(self.dir / "main"), str(self.dir / "main.c"), "-ldl"], check=True)
|
||||
loader = self.dir / "loader.c"
|
||||
loader.write_text(steamclient_loader())
|
||||
self.preload = self.dir / "libsteamshm.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-fvisibility=hidden",
|
||||
str(loader), "-ldl", "-o", str(self.preload)], check=True)
|
||||
|
||||
def vendor_binding(self, preload=True, steam=None):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "WINESTEAMCLIENTPATH64")}
|
||||
env["LD_LIBRARY_PATH"] = str(self.dir)
|
||||
if steam:
|
||||
env["WINESTEAMCLIENTPATH64"] = steam
|
||||
if preload:
|
||||
env["LD_PRELOAD"] = str(self.preload)
|
||||
run = subprocess.run([str(self.dir / "main")], env=env, capture_output=True, text=True, check=True)
|
||||
return run.stdout.strip()
|
||||
|
||||
def test_without_the_preload_a_framework_library_binds_to_steams_copy(self):
|
||||
self.assertEqual(self.vendor_binding(preload=False), "2")
|
||||
|
||||
def test_the_libraries_steam_needs_link_to_their_own_copy_first(self):
|
||||
self.assertEqual(self.vendor_binding(steam=str(self.dir / "libsteam.so")), "1")
|
||||
|
||||
def test_without_a_steam_library_path_nothing_is_loaded_early(self):
|
||||
self.assertEqual(self.vendor_binding(), "2")
|
||||
|
||||
def test_a_missing_or_foreign_steam_library_is_ignored(self):
|
||||
self.assertEqual(self.vendor_binding(steam=str(self.dir / "missing.so")), "2")
|
||||
self.assertEqual(self.vendor_binding(steam=str(self.dir / "main.c")), "2")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -28,6 +28,21 @@ def elf(machine, data=1, size=64):
|
||||
return bytes(head)
|
||||
|
||||
|
||||
class FollowSteamFexDispatchTest(unittest.TestCase):
|
||||
def test_arm_proton_route_resolves_steam_hints_on_the_game_not_the_client(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = Path(tmp) / "game-environment.json"
|
||||
config.write_text(json.dumps({"version": 1, "followSteamFex": {"FEX_TSOENABLED": "1"}}))
|
||||
env = {"SteamAppId": "42", "STEAM_COMPAT_DATA_PATH": "/compatdata/42", "STEAM_FEX_TSOENABLED": "0"}
|
||||
with mock.patch.dict(G, {"BIN_DIR": str(BIN), "GAME_ENVIRONMENT": str(config)}):
|
||||
game = FEX["game_environment"](env, ["/tmp/game.exe"],
|
||||
["/tmp/proton", "waitforexitandrun", "/tmp/game.exe"])
|
||||
native = FEX["game_environment"](env, ["/tmp/native-game"])
|
||||
self.assertEqual(game["FEX_TSOENABLED"], "0")
|
||||
self.assertEqual(native["FEX_TSOENABLED"], "1")
|
||||
self.assertNotIn("FEX_TSOENABLED", env)
|
||||
|
||||
|
||||
class FexTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp())
|
||||
|
||||
@@ -24,6 +24,65 @@ STATE = tempfile.TemporaryDirectory()
|
||||
COMPAT["main"].__globals__["COMPAT_DIR"] = STATE.name
|
||||
|
||||
|
||||
class FollowSteamFexTest(unittest.TestCase):
|
||||
fallback = {"FEX_TSOENABLED": "1", "FEX_MULTIBLOCK": "1", "FEX_X87REDUCEDPRECISION": "1"}
|
||||
steam = {"SteamAppId": "42", "STEAM_FEX_TSOENABLED": "0", "STEAM_FEX_MULTIBLOCK": "0"}
|
||||
|
||||
def options(self, env=None, config=None, fixes=None, app_id="42", steam_proton=True):
|
||||
result = MODULE["apply_config"](env or {}, {"version": 1, "followSteamFex": self.fallback, **(config or {})},
|
||||
app_id, fixes, steam_proton=steam_proton)
|
||||
return {key: value for key, value in result.items() if key.startswith("FEX_")}
|
||||
|
||||
def test_defaults_apply_only_valid_per_flag_hints_for_matching_steam_games(self):
|
||||
self.assertEqual(self.options(self.steam), dict(self.fallback, FEX_TSOENABLED="0", FEX_MULTIBLOCK="0"))
|
||||
self.assertEqual(self.options({**self.steam, "STEAM_FEX_MULTIBLOCK": "unknown"}),
|
||||
dict(self.fallback, FEX_TSOENABLED="0"))
|
||||
self.assertEqual(self.options({"SteamAppId": "42", "STEAM_FEX_TSOENABLED": "2"}), self.fallback)
|
||||
|
||||
def test_non_steam_and_mismatched_app_ids_use_fallback(self):
|
||||
self.assertEqual(self.options(self.steam, steam_proton=False), self.fallback)
|
||||
self.assertEqual(self.options(self.steam, app_id="99"), self.fallback)
|
||||
self.assertEqual(self.options({**self.steam, "DROIDDECK_DIRECT_PROTON": "1"}), self.fallback)
|
||||
self.assertEqual(self.options({**self.steam, "SteamAppId": "2147483648"}, app_id="2147483648"), self.fallback)
|
||||
|
||||
def test_steam_local_override_precedes_hints_without_mistaking_unknown_flags_for_off(self):
|
||||
local = {**self.steam, "STEAM_FEX_MULTIBLOCK": "1", "STEAM_COMPAT_FEX_CONFIG": "TSOEnabled:1"}
|
||||
self.assertEqual(self.options(local), dict(self.fallback, FEX_MULTIBLOCK="0"))
|
||||
self.assertEqual(self.options({**local, "STEAM_COMPAT_FEX_CONFIG": "Unknown:1"}),
|
||||
dict(self.fallback, FEX_TSOENABLED="0"))
|
||||
|
||||
def test_dd_manual_settings_and_known_fixes_keep_their_precedence(self):
|
||||
config = {"shared": {"FEX_TSOENABLED": "1"}, "games": {"42": {"FEX_MULTIBLOCK": None}}}
|
||||
result = self.options(self.steam, config, {"FEX_X87REDUCEDPRECISION": "0"})
|
||||
self.assertEqual(result, {"FEX_TSOENABLED": "1", "FEX_X87REDUCEDPRECISION": "0"})
|
||||
|
||||
def test_an_existing_fex_app_config_is_not_replaced_or_masked_by_the_fallback(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fex_config = Path(tmp) / "fex.json"
|
||||
fex_config.write_text('{"Config":{"TSOEnabled":"0"}}')
|
||||
result = self.options({**self.steam, "FEX_APP_CONFIG": str(fex_config)}, fixes={"FEX_MULTIBLOCK": "1"})
|
||||
self.assertEqual(result, {"FEX_APP_CONFIG": str(fex_config), "FEX_MULTIBLOCK": "1"})
|
||||
self.assertEqual(json.loads(fex_config.read_text()), {"Config": {"TSOEnabled": "0"}})
|
||||
|
||||
def test_real_game_wrapper_delivers_steam_values_only_for_the_proton_game_verb(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(json.dumps({"version": 1, "followSteamFex": self.fallback}))
|
||||
probe = home / "proton"
|
||||
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.getenv('FEX_TSOENABLED', 'unset'))\n")
|
||||
probe.chmod(0o755)
|
||||
env = {**os.environ, **self.steam, "HOME": tmp, "DROIDDECK_FASTEST_CORES": "0",
|
||||
"STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42")}
|
||||
env.pop("FEX_TSOENABLED", None)
|
||||
for verb, direct, expected in (("waitforexitandrun", "0", "0"), ("waitforexitandrun", "1", "1"), ("run", "0", "unset")):
|
||||
with self.subTest(verb=verb, direct=direct):
|
||||
output = subprocess.check_output([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), verb, "game.exe"],
|
||||
env={**env, "DROIDDECK_DIRECT_PROTON": direct}, text=True)
|
||||
self.assertEqual(output.strip(), expected)
|
||||
|
||||
|
||||
class ProducerAcquireGameEnvironmentTest(unittest.TestCase):
|
||||
def test_prefixed_opt_in_enters_only_the_game_environment(self):
|
||||
key = "DROIDDECK_GAME_FRAME_ACQUIRE"
|
||||
|
||||
+2
-240
@@ -1,9 +1,7 @@
|
||||
from contextlib import contextmanager
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import signal
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
@@ -148,9 +146,9 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
staged.write_text("wake\n")
|
||||
staged.replace(self.dir / "steam-wake")
|
||||
|
||||
def request_native(self, token="1" * 32, idle=False):
|
||||
def request_native(self, token="1" * 32):
|
||||
staged = self.dir / "steam-native-sleep.tmp"
|
||||
staged.write_text(token + (" idle" if idle else "") + "\n")
|
||||
staged.write_text(token + "\n")
|
||||
staged.replace(self.dir / "steam-native-sleep")
|
||||
return token
|
||||
|
||||
@@ -327,132 +325,6 @@ class AsleepSteamTest(FakeAgentCase):
|
||||
"--steam-idle-inhibit", "off"], self.asked())
|
||||
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class NativePrepareTest(FakeAgentCase):
|
||||
AGENT_EXIT = 0
|
||||
|
||||
def prepare_agent(self, delay, fail_first_wake=False, gated=False):
|
||||
script = self.dir / "bin/droiddeck-agent"
|
||||
prepare = f'sleep {delay}'
|
||||
failed_wake = ':'
|
||||
if gated:
|
||||
prepare = f'while [ ! -f "{self.dir / "release-prepare"}" ]; do sleep 0.025; done'
|
||||
failed_wake = f'while [ ! -f "{self.dir / "release-wake"}" ]; do sleep 0.025; done'
|
||||
script.write_text(
|
||||
f'#!/bin/sh\necho "$@" >> "{self.dir / "agent-calls"}"\n'
|
||||
f'case "$1" in --steam-prepare-native-suspend) {prepare}; echo prepared;;\n'
|
||||
'--steam-wake-native-suspend)\n'
|
||||
f' if [ "{int(fail_first_wake)}" -eq 1 ] && [ ! -f "{self.dir / "wake-tried"}" ]; then\n'
|
||||
f' touch "{self.dir / "wake-tried"}"; {failed_wake}; echo uncertain; exit 1; fi\n'
|
||||
' echo ack;; esac\n'
|
||||
"exit 0\n"
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def gated_agent(self, fail_first_wake=False):
|
||||
self.prepare_agent(0, fail_first_wake=fail_first_wake, gated=True)
|
||||
release_prepare = self.dir / "release-prepare"
|
||||
release_wake = self.dir / "release-wake"
|
||||
try:
|
||||
yield release_prepare, release_wake
|
||||
finally:
|
||||
release_prepare.touch()
|
||||
release_wake.touch()
|
||||
|
||||
def test_native_prepare_precedes_real_sleep_and_normal_wake_does_not_call_recovery(self):
|
||||
with self.gated_agent() as (release_prepare, _):
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.assertEqual(self.signals, [])
|
||||
release_prepare.touch()
|
||||
self.wait_for(lambda: self.signals == [True])
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
self.assertNotIn("--steam-wake-native-suspend", self.asked())
|
||||
|
||||
def test_awake_during_rpc_never_notifies_or_publishes_a_stale_pause(self):
|
||||
with self.gated_agent() as (release_prepare, _):
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: "unsignaled" in self.asked())
|
||||
release_prepare.touch()
|
||||
time.sleep(0.6)
|
||||
self.assertFalse((self.dir / "steam-native-ready").exists())
|
||||
self.assertEqual(self.signals, [])
|
||||
subsequent = self.request_native("3" * 32)
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
|
||||
self.assertEqual((self.dir / "steam-native-ready").read_text().strip(), subsequent)
|
||||
self.state(subsequent, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False])
|
||||
|
||||
def test_ambiguous_wake_retries_transient_discovery_with_same_token(self):
|
||||
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: (self.dir / "wake-tried").exists())
|
||||
release_prepare.touch()
|
||||
release_wake.touch()
|
||||
self.wait_for(lambda: self.asked().count("--steam-wake-native-suspend") == 2)
|
||||
time.sleep(0.8)
|
||||
calls = (self.dir / "agent-calls").read_text().splitlines()
|
||||
wakes = [call.split() for call in calls if call.startswith("--steam-wake-native-suspend ")]
|
||||
self.assertEqual(len(wakes), 2)
|
||||
self.assertEqual(wakes[0], wakes[1])
|
||||
self.assertEqual(wakes[0][1:3], [token, "unsignaled"])
|
||||
prepare = next(call.split() for call in calls if call.startswith("--steam-prepare-native-suspend "))
|
||||
self.assertEqual(wakes[0][3], prepare[3])
|
||||
self.assertEqual(self.signals, [])
|
||||
|
||||
def test_new_sleep_request_cancels_retry_of_older_wake(self):
|
||||
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
|
||||
first = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.state(first, "awake")
|
||||
self.wait_for(lambda: (self.dir / "wake-tried").exists())
|
||||
second = self.request_native("3" * 32)
|
||||
self.wait_for(lambda: second in self.asked())
|
||||
release_prepare.touch()
|
||||
release_wake.touch()
|
||||
time.sleep(0.9)
|
||||
self.assertEqual(self.asked().count("--steam-wake-native-suspend"), 1)
|
||||
self.state(second, "awake")
|
||||
|
||||
def test_idle_request_preserves_retry_of_older_wake(self):
|
||||
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
|
||||
first = self.request_native()
|
||||
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
|
||||
self.state(first, "awake")
|
||||
self.wait_for(lambda: (self.dir / "wake-tried").exists())
|
||||
release_prepare.touch()
|
||||
idle = self.request_native("3" * 32, idle=True)
|
||||
ready = self.dir / "steam-native-ready"
|
||||
self.wait_for(lambda: ready.exists() and ready.read_text().strip() == idle)
|
||||
self.state(idle, "paused")
|
||||
self.state(idle, "awake")
|
||||
release_wake.touch()
|
||||
self.wait_for(lambda: self.asked().count("--steam-wake-native-suspend") == 2)
|
||||
wakes = [call for call in (self.dir / "agent-calls").read_text().splitlines()
|
||||
if call.startswith("--steam-wake-native-suspend ")]
|
||||
self.assertEqual(wakes[0], wakes[1])
|
||||
self.assertEqual(wakes[0].split()[1:3], [first, "unsignaled"])
|
||||
self.assertEqual(self.asked().count("--steam-prepare-native-suspend"), 1)
|
||||
self.assertEqual(self.signals, [])
|
||||
|
||||
def test_timed_out_rpc_allows_sleep_and_wake_recovers_that_token(self):
|
||||
self.prepare_agent(6)
|
||||
token = self.request_native()
|
||||
self.wait_for(lambda: self.signals == [True], timeout=3.0)
|
||||
self.wait_for(lambda: (self.dir / "steam-native-ready").exists(), timeout=2.0)
|
||||
self.state(token, "paused")
|
||||
self.state(token, "awake")
|
||||
self.wait_for(lambda: self.signals == [True, False] and "uncertain" in self.asked())
|
||||
self.assertIn(token, self.asked())
|
||||
|
||||
|
||||
class WithNetworkManagerTest(SleepHandshakeTest):
|
||||
ARGS = ["--with-netmanager"]
|
||||
|
||||
@@ -470,115 +342,5 @@ class WithNetworkManagerTest(SleepHandshakeTest):
|
||||
self.assertEqual(self.owner(NAME), self.process.pid)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("node"), "node is not installed")
|
||||
class NativeSleepLeaseTest(unittest.TestCase):
|
||||
def test_wake_and_prepare_ordering_in_the_renderer(self):
|
||||
result = subprocess.run(["node", "-e", NATIVE_LEASE_CASES, str(SCRIPT.with_name("droiddeck-agent"))],
|
||||
text=True, capture_output=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("PASS nine native preparation lease sequences", result.stdout)
|
||||
|
||||
|
||||
NATIVE_LEASE_CASES = r'''const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const text = fs.readFileSync(process.argv[1], "utf8").match(/NATIVE_SUSPEND_JS = r"""([\s\S]*?)"""/)[1];
|
||||
const call = eval("(" + text + ")");
|
||||
const run = (op, token, value) => call(op, token, value, token === a ? "100" : "200");
|
||||
const a = "1".repeat(32);
|
||||
const b = "2".repeat(32);
|
||||
const future = () => Date.now() + 5000;
|
||||
let invoked, resumes, result;
|
||||
function setup() {
|
||||
delete globalThis.__droiddeckNativeSleep;
|
||||
globalThis.SuspendResumeStore = { m_bSuspending: false };
|
||||
invoked = resumes = 0;
|
||||
globalThis.SteamClient = { User: {
|
||||
PrepareForSystemSuspend() { invoked++; return new Promise(resolve => { result = resolve; }); },
|
||||
ResumeSuspendedGames(kick) { assert.equal(kick, false); resumes++; return Promise.resolve({ result: 1 }); }
|
||||
}};
|
||||
}
|
||||
(async () => {
|
||||
setup();
|
||||
assert.equal(await run("prepare", a, Date.now() - 1), "expired");
|
||||
assert.equal(await run("wake", a, "unsignaled"), "miss");
|
||||
assert.equal(await run("prepare", a, future()), "expired");
|
||||
assert.equal(invoked, 0);
|
||||
|
||||
setup();
|
||||
let prep = run("prepare", a, future());
|
||||
result({result: 1});
|
||||
assert.equal(await prep, "prepared");
|
||||
await run("wake", a, "signaled");
|
||||
assert.equal(resumes, 0);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
await run("wake", a, "unsignaled");
|
||||
result({result: 1});
|
||||
assert.equal(await prep, "prepared");
|
||||
await run("wake", a, "unsignaled");
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
result({result: 1});
|
||||
await prep;
|
||||
await run("wake", a, "uncertain");
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
await run("wake", a, "unsignaled");
|
||||
assert.equal(await run("prepare", b, future()), "coalesced");
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(invoked, 1);
|
||||
assert.equal(resumes, 0);
|
||||
await run("wake", b, "uncertain");
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
await run("wake", a, "unsignaled");
|
||||
globalThis.SuspendResumeStore.m_bSuspending = true;
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(resumes, 0);
|
||||
assert.equal(await run("prepare", b, future()), "steam-busy");
|
||||
assert.equal(invoked, 1);
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
assert.equal(await run("wake", a, "uncertain"), "ack");
|
||||
assert.equal(await run("prepare", b, Date.now() - 1), "coalesced");
|
||||
assert.equal(await run("wake", a, "uncertain"), "miss");
|
||||
assert.equal(await run("prepare", a, future()), "expired");
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(invoked, 1);
|
||||
assert.equal(resumes, 0);
|
||||
await run("wake", b, "uncertain");
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
assert.equal(await run("wake", b, "uncertain"), "ack");
|
||||
assert.equal(await run("prepare", b, future()), "expired");
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(invoked, 1);
|
||||
assert.equal(resumes, 1);
|
||||
|
||||
setup();
|
||||
prep = run("prepare", a, future());
|
||||
result({result: 1});
|
||||
await prep;
|
||||
assert.equal(await run("wake", a, "uncertain"), "ack");
|
||||
assert.equal(await run("wake", a, "uncertain"), "ack");
|
||||
assert.equal(resumes, 1);
|
||||
console.log("PASS nine native preparation lease sequences");
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
'''
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,141 +0,0 @@
|
||||
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()
|
||||
@@ -1,53 +0,0 @@
|
||||
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", ""))
|
||||
@@ -667,10 +667,6 @@ def support_data(**arguments):
|
||||
return {'install': {'action': 'supportData', 'arguments': arguments}, 'name': 'supportData'}
|
||||
|
||||
|
||||
def save_path(**arguments):
|
||||
return {'install': {'action': 'savePath', 'arguments': arguments}, 'name': 'saveFolders'}
|
||||
|
||||
|
||||
class GogSupportData(unittest.TestCase):
|
||||
def prefix(self, root):
|
||||
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
|
||||
@@ -854,117 +850,6 @@ class GogSupportData(unittest.TestCase):
|
||||
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
|
||||
|
||||
|
||||
class GogSavePaths(unittest.TestCase):
|
||||
def prefix(self, root):
|
||||
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
|
||||
user.mkdir(parents=True)
|
||||
return user
|
||||
|
||||
def test_the_london_script_creates_its_save_path_and_keeps_player_settings(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1897848199')
|
||||
user = self.prefix(root)
|
||||
support = folder / 'support/1897848199'
|
||||
(support / 'docs').mkdir(parents=True)
|
||||
(folder / '__AppData').mkdir()
|
||||
(folder / '__AppData/save.dat').write_text('save')
|
||||
for name in ('Fallout4Prefs.ini', 'Fallout4.ini'):
|
||||
(support / 'docs' / name).write_text('[Archive]\n')
|
||||
for name in ('DLCList.txt', 'Plugins.txt', 'UserDownloadedContent.txt'):
|
||||
(support / name).write_text('*LondonWorldSpace.esm\n')
|
||||
gog_script(folder, '1897848199', [
|
||||
save_path(savePath='{userdocs}/My Games/Fallout4', type='folder'),
|
||||
set_registry(root='HKLM', subkey='Software\\Bethesda Softworks\\Fallout4',
|
||||
valueName='Installed Path', valueData='{app}\\', valueType='string'),
|
||||
support_data(type='folder', target='{userdocs}/My Games/Fallout4'),
|
||||
support_data(type='folder', target='{localappdata}/Fallout4'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4Prefs.ini',
|
||||
target='{userdocs}/My Games/Fallout4/Fallout4Prefs.ini'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4.ini',
|
||||
target='{userdocs}/My Games/Fallout4/Fallout4.ini'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/DLCList.txt',
|
||||
target='{localappdata}/Fallout4/DLCList.txt'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/Plugins.txt',
|
||||
target='{localappdata}/Fallout4/Plugins.txt'),
|
||||
support_data(type='file', overwrite=True, source='{supportDir}/UserDownloadedContent.txt',
|
||||
target='{localappdata}/Fallout4/UserDownloadedContent.txt'),
|
||||
support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/Fallout4'),
|
||||
])
|
||||
with patch.object(store, 'create_prefix') as create:
|
||||
self.assertEqual('copied=6', store.gog_support_data(folder, root + '/compat', '/proton'))
|
||||
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
create.assert_not_called()
|
||||
saves = user / 'Documents/My Games/Fallout4'
|
||||
self.assertTrue(saves.is_dir())
|
||||
self.assertEqual('[Archive]\n', (saves / 'Fallout4.ini').read_text())
|
||||
self.assertEqual('*LondonWorldSpace.esm\n', (user / 'AppData/Local/Fallout4/Plugins.txt').read_text())
|
||||
self.assertTrue((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).is_file())
|
||||
(saves / 'my settings.ini').write_text('player')
|
||||
self.assertEqual('ready', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
self.assertEqual('player', (saves / 'my settings.ini').read_text())
|
||||
|
||||
def test_existing_prefix_base_names_keep_their_actual_case(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='9')
|
||||
user = self.prefix(root)
|
||||
(user / 'documents' / 'fixture').mkdir(parents=True)
|
||||
(user / 'aPPdATA' / 'roaming').mkdir(parents=True)
|
||||
gog_script(folder, '9', [
|
||||
save_path(savePath='{UserDocs}/Fixture/Saves'),
|
||||
save_path(savePath='{UserAppData}/Fixture/Settings'),
|
||||
])
|
||||
self.assertEqual('paths=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
self.assertTrue((user / 'documents/fixture/Saves').is_dir())
|
||||
self.assertTrue((user / 'aPPdATA/roaming/Fixture/Settings').is_dir())
|
||||
self.assertEqual({'documents', 'aPPdATA'}, {p.name for p in user.iterdir()})
|
||||
self.assertEqual({'roaming'}, {p.name for p in (user / 'aPPdATA').iterdir()})
|
||||
|
||||
def test_only_save_path_actions_create_known_folders(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='9')
|
||||
user = self.prefix(root)
|
||||
saves = user / 'Documents/My Games/Fallout4'
|
||||
saves.mkdir(parents=True)
|
||||
(saves / 'Fallout4Prefs.ini').write_text('player')
|
||||
gog_script(folder, '9', [
|
||||
set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string'),
|
||||
{'install': {'action': 'createFolder', 'arguments': {'savePath': '{userdocs}/Other'}}},
|
||||
save_path(savePath='{windir}/evil'),
|
||||
save_path(savePath='{userdocs}/../../escape'),
|
||||
save_path(savePath='{userappdata}/Ubisoft/Anno1404/Config'),
|
||||
])
|
||||
self.assertEqual('paths=1 skipped=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
self.assertTrue((user / 'AppData/Roaming/Ubisoft/Anno1404/Config').is_dir())
|
||||
self.assertFalse((user / 'Documents/Other').exists())
|
||||
self.assertFalse((Path(root) / 'escape').exists())
|
||||
self.assertEqual('player', (saves / 'Fallout4Prefs.ini').read_text())
|
||||
self.assertFalse((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).exists())
|
||||
|
||||
def test_without_save_paths_no_prefix_is_made(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='9')
|
||||
gog_script(folder, '9', [set_registry(root='HKLM', subkey='Software\\Game', valueName='a',
|
||||
valueData='b', valueType='string')])
|
||||
with patch.object(store, 'create_prefix') as create:
|
||||
self.assertEqual('none', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
create.assert_not_called()
|
||||
|
||||
def test_a_missing_prefix_is_made_first(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='9')
|
||||
gog_script(folder, '9', [save_path(savePath='{userdocs}/My Games/G')])
|
||||
with patch.object(store, 'create_prefix', return_value='failed') as create:
|
||||
self.assertEqual('no-prefix', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
create.assert_called_once_with(root + '/compat', '/proton')
|
||||
|
||||
def made(compat_data, proton):
|
||||
self.prefix(root)
|
||||
return 'created'
|
||||
with patch.object(store, 'create_prefix', side_effect=made):
|
||||
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
|
||||
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
|
||||
|
||||
|
||||
class GogRegistry(unittest.TestCase):
|
||||
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
|
||||
@@ -555,79 +555,6 @@ def swap_total_kb():
|
||||
return 0
|
||||
|
||||
|
||||
CROSS_THREAD = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef PR_SET_SYSCALL_USER_DISPATCH
|
||||
#define PR_SET_SYSCALL_USER_DISPATCH 59
|
||||
#endif
|
||||
|
||||
extern void *__libc_malloc(size_t);
|
||||
extern void *__libc_calloc(size_t, size_t);
|
||||
extern void *__libc_realloc(void *, size_t);
|
||||
|
||||
static int watching;
|
||||
static pid_t victim;
|
||||
static int allocations;
|
||||
|
||||
static void count(void) {
|
||||
if (__atomic_load_n(&watching, __ATOMIC_ACQUIRE) && gettid() == __atomic_load_n(&victim, __ATOMIC_RELAXED)) __atomic_add_fetch(&allocations, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
void *malloc(size_t n) { count(); return __libc_malloc(n); }
|
||||
void *calloc(size_t a, size_t b) { count(); return __libc_calloc(a, b); }
|
||||
void *realloc(void *p, size_t n) { count(); return __libc_realloc(p, n); }
|
||||
|
||||
static void *idle(void *arg) {
|
||||
(void)arg;
|
||||
sigset_t none;
|
||||
sigemptyset(&none);
|
||||
__atomic_store_n(&victim, gettid(), __ATOMIC_RELAXED);
|
||||
__atomic_store_n(&watching, 1, __ATOMIC_RELEASE);
|
||||
sigsuspend(&none);
|
||||
__atomic_store_n(&watching, 0, __ATOMIC_RELEASE);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
sigset_t urg;
|
||||
sigemptyset(&urg);
|
||||
sigaddset(&urg, SIGURG);
|
||||
pthread_sigmask(SIG_BLOCK, &urg, NULL);
|
||||
void *lib = dlopen(argv[1], RTLD_LAZY);
|
||||
if (lib == NULL) { puts(dlerror()); return 1; }
|
||||
int (*control)(int, ...) = (int (*)(int, ...))dlsym(lib, "prctl");
|
||||
volatile char selector = 0;
|
||||
if (argc > 2) {
|
||||
pthread_key_t key, last = 0;
|
||||
while (pthread_key_create(&key, NULL) == 0) last = key;
|
||||
int r = control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector);
|
||||
printf("refused %d %s\n", r, r != 0 && errno == EAGAIN ? "again" : "other");
|
||||
pthread_key_delete(last);
|
||||
printf("retried %d\n", control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector));
|
||||
return 0;
|
||||
}
|
||||
if (control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector) != 0) { puts("nodispatch"); return 0; }
|
||||
pthread_t thread;
|
||||
pthread_create(&thread, NULL, idle, NULL);
|
||||
while (!__atomic_load_n(&watching, __ATOMIC_ACQUIRE)) usleep(1000);
|
||||
if (write(2, "signal\n", 7) != 7) return 1;
|
||||
kill(getpid(), SIGURG);
|
||||
pthread_join(thread, NULL);
|
||||
printf("allocations %d\n", allocations);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class ZramPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
@@ -846,39 +773,6 @@ class ZramPreloadTest(unittest.TestCase):
|
||||
self.assertEqual([1], out["trimmed"], out)
|
||||
self.assertEqual([1], out["named"], out)
|
||||
|
||||
def test_a_signal_on_another_thread_allocates_nothing_after_dispatch_was_armed(self):
|
||||
source = self.dir / "crossthread.c"
|
||||
program = self.dir / "crossthread"
|
||||
source.write_text(CROSS_THREAD)
|
||||
subprocess.run(["cc", "-O2", "-pthread", "-o", str(program), str(source), "-ldl"], check=True)
|
||||
environment = dict(os.environ, GLIBC_TUNABLES="glibc.rtld.optional_static_tls=0", LD_DEBUG="bindings")
|
||||
for name in ("LD_PRELOAD", "LD_BIND_NOW"):
|
||||
environment.pop(name, None)
|
||||
result = subprocess.run([str(program), str(self.lib)], env=environment, capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
if result.stdout.strip() == "nodispatch":
|
||||
self.skipTest("kernel lacks syscall user dispatch")
|
||||
self.assertEqual("allocations 0", result.stdout.strip())
|
||||
after = result.stderr.split("signal\n", 1)[1]
|
||||
self.assertNotIn("pthread_getspecific", after)
|
||||
refused = subprocess.run([str(program), str(self.lib), "exhaust"], env=environment, capture_output=True,
|
||||
text=True, timeout=60)
|
||||
self.assertEqual("refused -1 again\nretried 0", refused.stdout.strip())
|
||||
|
||||
def test_loads_at_runtime_without_spare_static_tls(self):
|
||||
loader = self.dir / "loader"
|
||||
source = self.dir / "loader.c"
|
||||
source.write_text("#include <dlfcn.h>\n#include <stdio.h>\n"
|
||||
"int main(int c, char **v) { (void)c; void *h = dlopen(v[1], RTLD_NOW);"
|
||||
" puts(h ? \"loaded\" : dlerror()); return h == NULL; }\n")
|
||||
subprocess.run(["cc", "-O2", "-o", str(loader), str(source), "-ldl"], check=True)
|
||||
environment = dict(os.environ, GLIBC_TUNABLES="glibc.rtld.optional_static_tls=0")
|
||||
environment.pop("LD_PRELOAD", None)
|
||||
result = subprocess.run([str(loader), str(self.lib)], env=environment, capture_output=True, text=True,
|
||||
timeout=60)
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertEqual("loaded", result.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user