mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa645396ff | ||
|
|
a02ea07386 | ||
|
|
c1d6d425fa | ||
|
|
70be3d3eea | ||
|
|
f2206893d0 | ||
|
|
ce64f5ade4 | ||
|
|
c85e82683b | ||
|
|
88d44b0dc6 | ||
|
|
73fac3723f | ||
|
|
723d78cc63 |
No files matched your search
@@ -307,6 +307,9 @@ jobs:
|
|||||||
aarch64-linux-gnu-gcc -O2 -Wall -o "$D/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
|
aarch64-linux-gnu-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"
|
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
|
- name: Check the preloads
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -952,6 +955,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
artifact: droiddeck-signed
|
artifact: droiddeck-signed
|
||||||
variant: standard
|
variant: standard
|
||||||
|
fail_on_detection: true
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
|
|
||||||
packs:
|
packs:
|
||||||
|
|||||||
@@ -191,9 +191,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
private var gamescopeRealtime by mutableStateOf(false)
|
private var gamescopeRealtime by mutableStateOf(false)
|
||||||
private var paceCores by mutableStateOf(true)
|
private var paceCores by mutableStateOf(true)
|
||||||
private var gpuClockPin by mutableStateOf(false)
|
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 desktopAsUser by mutableStateOf(false)
|
||||||
private var cursorComposite by mutableStateOf(true)
|
private var cursorComposite by mutableStateOf(true)
|
||||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||||
@@ -3125,7 +3122,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
fsyncFirst = fsyncFirst,
|
fsyncFirst = fsyncFirst,
|
||||||
gamescopeRealtime = gamescopeRealtime,
|
gamescopeRealtime = gamescopeRealtime,
|
||||||
gpuClockPin = gpuClockPin,
|
gpuClockPin = gpuClockPin,
|
||||||
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
|
nativeDesktopAvailable = com.droiddeck.launcher.runtime.NativeGuest.nextSession(this), desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
|
||||||
guestHostname = guestHostname, phantomWarning = phantomWarning,
|
guestHostname = guestHostname, phantomWarning = phantomWarning,
|
||||||
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
||||||
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
|
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
|
||||||
@@ -3139,9 +3136,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
|
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
|
||||||
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
|
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
|
||||||
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = 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 },
|
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
|
||||||
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
|
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
|
||||||
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
|
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
|
||||||
@@ -3464,9 +3458,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
||||||
paceCores = SessionPrefs.paceCores(this)
|
paceCores = SessionPrefs.paceCores(this)
|
||||||
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
||||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
|
||||||
prootFastPath = SessionPrefs.prootFastPath(this)
|
|
||||||
nativeUserland = SessionPrefs.nativeUserland(this)
|
|
||||||
desktopAsUser = SessionPrefs.desktopAsUser(this)
|
desktopAsUser = SessionPrefs.desktopAsUser(this)
|
||||||
cursorComposite = SessionPrefs.cursorComposite(this)
|
cursorComposite = SessionPrefs.cursorComposite(this)
|
||||||
guestHostname = SessionPrefs.guestHostname(this)
|
guestHostname = SessionPrefs.guestHostname(this)
|
||||||
|
|||||||
@@ -3862,7 +3862,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
presentationFaultHint()?.let { return it }
|
presentationFaultHint()?.let { return it }
|
||||||
if (log == null || !log.isFile) return null
|
if (log == null || !log.isFile) return null
|
||||||
return try {
|
return try {
|
||||||
var enosys = 0
|
|
||||||
var fexMissing = false
|
var fexMissing = false
|
||||||
val size = log.length()
|
val size = log.length()
|
||||||
val text = java.io.RandomAccessFile(log, "r").use { f ->
|
val text = java.io.RandomAccessFile(log, "r").use { f ->
|
||||||
@@ -3873,7 +3872,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
String(bytes, Charsets.ISO_8859_1)
|
String(bytes, Charsets.ISO_8859_1)
|
||||||
}
|
}
|
||||||
text.lineSequence().forEach { line ->
|
text.lineSequence().forEach { line ->
|
||||||
if (line.contains("Function not implemented")) enosys++
|
|
||||||
if (line.contains(FEX_MISSING)) fexMissing = true
|
if (line.contains(FEX_MISSING)) fexMissing = true
|
||||||
}
|
}
|
||||||
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
|
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
|
||||||
@@ -3895,9 +3893,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
} else if (fexMissing) {
|
} else if (fexMissing) {
|
||||||
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
|
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)
|
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
|
} else null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
|
|||||||
@@ -571,7 +571,6 @@ object AgentHost {
|
|||||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(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) }
|
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ object AgentNative {
|
|||||||
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
|
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
|
||||||
val root = LinuxRuntime.rootDir(context)
|
val root = LinuxRuntime.rootDir(context)
|
||||||
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
|
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")
|
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 argvJson = request.optJSONArray("argv") ?: throw AgentException("INVALID_REQUEST", "argv is required")
|
||||||
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
|
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object CpuFeatures {
|
||||||
|
internal fun lacksAtomics(cpuInfo: String): Boolean {
|
||||||
|
val cores = cpuInfo.lineSequence()
|
||||||
|
.filter { it.substringBefore(':').trim() == "Features" }
|
||||||
|
.map { it.substringAfter(':').trim().split(Regex("\\s+")) }
|
||||||
|
.toList()
|
||||||
|
return cores.isNotEmpty() && cores.any { "atomics" !in it }
|
||||||
|
}
|
||||||
|
|
||||||
|
val lacksAtomics: Boolean by lazy {
|
||||||
|
runCatching { lacksAtomics(File("/proc/cpuinfo").readText()) }.getOrDefault(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -291,9 +291,12 @@ object DeviceReport {
|
|||||||
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
||||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||||
k("pace cores", SessionPrefs.paceCores(context))
|
k("pace cores", SessionPrefs.paceCores(context))
|
||||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
k("guest runtime policy", "native preferred with PRoot fallback")
|
||||||
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
|
k("guest runtime", when (com.droiddeck.launcher.runtime.NativeGuest.sessionMode) {
|
||||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
true -> "native"
|
||||||
|
false -> "PRoot"
|
||||||
|
null -> if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) "native available" else "native unavailable"
|
||||||
|
})
|
||||||
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
||||||
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
||||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||||
|
|||||||
@@ -40,7 +40,8 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
|||||||
PILL("pill", "Pill"),
|
PILL("pill", "Pill"),
|
||||||
MINIMAL("minimal", "Minimal"),
|
MINIMAL("minimal", "Minimal"),
|
||||||
MEGA("mega", "Mega"),
|
MEGA("mega", "Mega"),
|
||||||
STRIP("strip", "Strip");
|
STRIP("strip", "Strip"),
|
||||||
|
SIDE_STRIP("side_strip", "Side strip");
|
||||||
|
|
||||||
fun next(): DroidDeckHudSize {
|
fun next(): DroidDeckHudSize {
|
||||||
val all = values()
|
val all = values()
|
||||||
@@ -96,6 +97,11 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
|
|||||||
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||||
"showPower", "showDisplay", "showHdr", "showGpuModel",
|
"showPower", "showDisplay", "showHdr", "showGpuModel",
|
||||||
),
|
),
|
||||||
|
SIDE_STRIP to listOf(
|
||||||
|
"showFPS", "showFPSGraph", "showAvg", "showLow1",
|
||||||
|
"showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp", "showRAM", "showVram",
|
||||||
|
"showPower", "showBattery", "showBatteryTemp", "showBatteryTime",
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -110,6 +116,7 @@ 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,
|
MEGA to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.62f, pad = 10f, lineGap = 3.5f, labelGap = 7f,
|
||||||
band = 9.5f, gutter = 16f),
|
band = 9.5f, gutter = 16f),
|
||||||
STRIP to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.8f, pad = 10f, lineGap = 0f, labelGap = 13f),
|
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> =
|
fun rowsFor(size: DroidDeckHudSize, values: Map<String, String>): List<String> =
|
||||||
|
|||||||
@@ -573,6 +573,7 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
if (s == null) { contentW = 0f; contentH = 0f; return }
|
if (s == null) { contentW = 0f; contentH = 0f; return }
|
||||||
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
|
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
|
||||||
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
|
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
|
||||||
|
if (size == DroidDeckHudSize.SIDE_STRIP) { buildSideStrip(s); return }
|
||||||
buildRows(s)
|
buildRows(s)
|
||||||
if (contentW <= 0f || contentH <= 0f) return
|
if (contentW <= 0f || contentH <= 0f) return
|
||||||
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
|
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
|
||||||
@@ -684,8 +685,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
finishPanel(panel, halfRound = halfRound)
|
finishPanel(panel, halfRound = halfRound)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun finishPanel(panel: RectF, halfRound: Boolean) {
|
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, sp(56f))
|
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, maxRadius)
|
||||||
val margin = outlineWidth() + sp(4f)
|
val margin = outlineWidth() + sp(4f)
|
||||||
fun curveIn(top: Float, bottom: Float): Float {
|
fun curveIn(top: Float, bottom: Float): Float {
|
||||||
val d = max(max(panel.top + r - top, bottom - (panel.bottom - r)), 0f)
|
val d = max(max(panel.top + r - top, bottom - (panel.bottom - r)), 0f)
|
||||||
@@ -703,8 +704,8 @@ class DroidDeckHudView(context: Context) : View(context) {
|
|||||||
for (t in tileRects) right = max(right, t.right + curveIn(t.top, t.bottom) + margin)
|
for (t in tileRects) right = max(right, t.right + curveIn(t.top, t.bottom) + margin)
|
||||||
panel.right = max(right, panel.left + sp(6f) + r)
|
panel.right = max(right, panel.left + sp(6f) + r)
|
||||||
dPanel = panel; dRadius = r
|
dPanel = panel; dRadius = r
|
||||||
contentW = panel.right + panelInset()
|
contentW = panel.right + inset
|
||||||
contentH = panel.bottom + panelInset()
|
contentH = panel.bottom + inset
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun clockTimeString(): String = DateFormat.getTimeFormat(context).format(Date())
|
private fun clockTimeString(): String = DateFormat.getTimeFormat(context).format(Date())
|
||||||
@@ -936,6 +937,58 @@ 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) {
|
private fun buildStrip(s: HudMetrics.Snapshot) {
|
||||||
val rowPx = sp(11.5f); val unitPx = rowPx * 0.8f; val fpsPx = sp(15f)
|
val rowPx = sp(11.5f); val unitPx = rowPx * 0.8f; val fpsPx = sp(15f)
|
||||||
val padX = sp(10f); val groupGap = sp(13f)
|
val padX = sp(10f); val groupGap = sp(13f)
|
||||||
|
|||||||
@@ -288,12 +288,26 @@ object BwrapSpawner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun preload(session: List<Bind>, rootfs: String, env: MutableMap<String, String>): List<Bind> {
|
private fun preload(session: List<Bind>, rootfs: String, env: MutableMap<String, String>): List<Bind> {
|
||||||
val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
|
val configured = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
|
||||||
?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: return emptyList()
|
?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: emptyList()
|
||||||
if (libs.isEmpty()) return emptyList()
|
val lseDisabled = env["LSE_EMU"] == "0"
|
||||||
|
val libs = configured.filterNot { lseDisabled && it.endsWith("/liblse_emu.so") }
|
||||||
|
val inherited = env["LD_PRELOAD"]?.split(Regex("[\\s:]+"))
|
||||||
|
?.filter { it.isNotEmpty() && !(lseDisabled && it.substringAfterLast('/') == "liblse_emu.so") }
|
||||||
|
?: emptyList()
|
||||||
|
if (libs.isEmpty()) {
|
||||||
|
if (lseDisabled) {
|
||||||
|
if (inherited.isEmpty()) env.remove("LD_PRELOAD")
|
||||||
|
else env["LD_PRELOAD"] = inherited.joinToString(":")
|
||||||
|
}
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
val binds = ArrayList<Bind>()
|
val binds = ArrayList<Bind>()
|
||||||
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
|
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
|
||||||
env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":")
|
env["LD_PRELOAD"] = (paths + inherited).joinToString(":")
|
||||||
|
if (libs.any { it.endsWith("/liblse_emu.so") }) {
|
||||||
|
env.putIfAbsent("LSE_EMU", "1")
|
||||||
|
}
|
||||||
File(rootfs, NET_LINK).takeIf { it.isFile }?.let { binds.add(Bind(it.path, "/$NET_LINK")) }
|
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 ->
|
env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev ->
|
||||||
binds.addAll(bindsFor(session, rootfs, dev, dev))
|
binds.addAll(bindsFor(session, rootfs, dev, dev))
|
||||||
@@ -563,12 +577,15 @@ object BwrapSpawner {
|
|||||||
|
|
||||||
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
|
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
|
||||||
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
||||||
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
|
val nativeSession = NativeGuest.forSession(context)
|
||||||
|
val native = if (nativeSession) nativeLaunch(context, plan) else null
|
||||||
val builder = if (native != null) {
|
val builder = if (native != null) {
|
||||||
ProcessBuilder(native.first).redirectErrorStream(true)
|
ProcessBuilder(native.first).redirectErrorStream(true)
|
||||||
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
|
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
|
||||||
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
|
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
|
||||||
} else {
|
} 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)
|
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
|
||||||
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
|
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
|
||||||
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
|
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
|
||||||
@@ -585,7 +602,6 @@ object BwrapSpawner {
|
|||||||
putAll(prootEnvironment(plan, envTool))
|
putAll(prootEnvironment(plan, envTool))
|
||||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(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) }
|
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import com.droiddeck.launcher.core.HostProcess
|
|||||||
import com.droiddeck.launcher.session.OrphanReaper
|
import com.droiddeck.launcher.session.OrphanReaper
|
||||||
import com.droiddeck.launcher.session.SessionFiles
|
import com.droiddeck.launcher.session.SessionFiles
|
||||||
import com.droiddeck.launcher.session.SessionPaths
|
import com.droiddeck.launcher.session.SessionPaths
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.concurrent.atomic.AtomicBoolean
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
@@ -67,7 +66,6 @@ object GuestCommand {
|
|||||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||||
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.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) } }
|
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
|
||||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,15 +22,15 @@ object NativeGuest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun enabled(context: Context): Boolean =
|
fun enabled(context: Context): Boolean =
|
||||||
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
|
available(LinuxRuntime.rootDir(context))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether the next session will start natively. The session stages the hook from the APK before
|
* Whether the next session will start natively. The session stages the hook from the APK before
|
||||||
* it starts, so only the setting and the rootfs's loader decide, and a runtime still to be
|
* it starts, so the rootfs's loader decides, and a runtime still to be
|
||||||
* installed will have one.
|
* installed will have one.
|
||||||
*/
|
*/
|
||||||
fun nextSession(context: Context): Boolean =
|
fun nextSession(context: Context): Boolean =
|
||||||
SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
|
willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
|
||||||
|
|
||||||
internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null
|
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
|
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
|
||||||
* session's own mode while one runs, as the setting can change under it and the rootfs is only
|
* session's own mode while one runs, as the rootfs is only
|
||||||
* prepared for native programs at a session's start.
|
* prepared for native programs at a session's start.
|
||||||
*/
|
*/
|
||||||
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
|
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
|
||||||
@@ -104,8 +104,11 @@ object NativeGuest {
|
|||||||
private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/"))
|
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. */
|
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
|
||||||
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
|
fun sessionEnvironment(
|
||||||
val preload = preloadList(root)
|
root: File, binds: List<String>, program: String, hostname: String? = null, lseEmu: String? = null,
|
||||||
|
): Map<String, String> {
|
||||||
|
val preload = preloadList(root).filterNot { lseEmu == "0" && it.substringAfterLast('/') == "liblse_emu.so" }
|
||||||
|
val lse = lseEmu ?: "1".takeIf { preload.any { it.substringAfterLast('/') == "liblse_emu.so" } }
|
||||||
return linkedMapOf(
|
return linkedMapOf(
|
||||||
"DDNATV_ROOT" to root.path,
|
"DDNATV_ROOT" to root.path,
|
||||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||||
@@ -113,6 +116,7 @@ object NativeGuest {
|
|||||||
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
||||||
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
||||||
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
||||||
|
"LSE_EMU" to lse.orEmpty(),
|
||||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||||
).filterValues { it.isNotEmpty() }
|
).filterValues { it.isNotEmpty() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.runtime
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.security.MessageDigest
|
import java.security.MessageDigest
|
||||||
|
|
||||||
@@ -12,17 +11,14 @@ object ProotFastPath {
|
|||||||
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
|
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
|
||||||
const val MAX_BINDS = 256
|
const val MAX_BINDS = 256
|
||||||
|
|
||||||
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
|
internal fun allows(source: String, native: Boolean): Boolean =
|
||||||
preference && !noSeccomp && !nativeUserland && source == LinuxRuntime.PROOT_PACK
|
!native && source == LinuxRuntime.PROOT_PACK
|
||||||
|
|
||||||
fun enabled(context: Context): Boolean {
|
fun enabled(context: Context, native: Boolean = NativeGuest.forSession(context)): Boolean {
|
||||||
val preference = SessionPrefs.prootFastPath(context)
|
if (native) return false
|
||||||
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
|
|
||||||
val nativeUserland = SessionPrefs.nativeUserland(context)
|
|
||||||
val source = LinuxRuntime.prootSource(context)
|
val source = LinuxRuntime.prootSource(context)
|
||||||
val on = allows(preference, noSeccomp, source, nativeUserland)
|
val on = allows(source, native)
|
||||||
if (preference && !noSeccomp && !nativeUserland && !on)
|
if (!on) Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
|
||||||
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
|
|
||||||
return on
|
return on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import android.os.Process
|
|||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.core.HostProcess
|
import com.droiddeck.launcher.core.HostProcess
|
||||||
import com.droiddeck.launcher.session.OrphanReaper
|
import com.droiddeck.launcher.session.OrphanReaper
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.DataInputStream
|
import java.io.DataInputStream
|
||||||
import java.io.DataOutputStream
|
import java.io.DataOutputStream
|
||||||
@@ -128,7 +127,6 @@ object RootSpawner {
|
|||||||
clear()
|
clear()
|
||||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(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) }
|
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -343,7 +343,8 @@ object BottomDesktop {
|
|||||||
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||||
}
|
}
|
||||||
val environment = if (current.nativeUserland) {
|
val environment = if (current.nativeUserland) {
|
||||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
|
val lseEmu = current.guest.lastOrNull { it.startsWith("LSE_EMU=") }?.substringAfter('=')
|
||||||
|
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context), lseEmu)
|
||||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||||
} else current.hostEnvironment
|
} else current.hostEnvironment
|
||||||
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import android.os.ParcelFileDescriptor
|
|||||||
import android.system.Os
|
import android.system.Os
|
||||||
import android.system.OsConstants
|
import android.system.OsConstants
|
||||||
import com.droiddeck.launcher.core.LogRedactor
|
import com.droiddeck.launcher.core.LogRedactor
|
||||||
|
import com.droiddeck.launcher.frontend.Library
|
||||||
import com.droiddeck.launcher.runtime.BattleNet
|
import com.droiddeck.launcher.runtime.BattleNet
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
@@ -25,6 +26,7 @@ import java.nio.channels.SeekableByteChannel
|
|||||||
import java.nio.file.FileVisitResult
|
import java.nio.file.FileVisitResult
|
||||||
import java.nio.file.Files
|
import java.nio.file.Files
|
||||||
import java.nio.file.LinkOption
|
import java.nio.file.LinkOption
|
||||||
|
import java.nio.file.NoSuchFileException
|
||||||
import java.nio.file.Path
|
import java.nio.file.Path
|
||||||
import java.nio.file.SimpleFileVisitor
|
import java.nio.file.SimpleFileVisitor
|
||||||
import java.nio.file.StandardOpenOption
|
import java.nio.file.StandardOpenOption
|
||||||
@@ -221,7 +223,7 @@ internal object EnhancedSessionLogShare {
|
|||||||
Category.values().map { category ->
|
Category.values().map { category ->
|
||||||
val budget = budgets.getValue(category)
|
val budget = budgets.getValue(category)
|
||||||
val records = ArrayList<Record>()
|
val records = ArrayList<Record>()
|
||||||
val selected = candidates.filter { it.category == category }
|
val selected = candidates.filter { it.category == category }.sortedBy(::sharePriority)
|
||||||
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
|
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
|
||||||
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
|
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
|
||||||
val names = HashSet<String>()
|
val names = HashSet<String>()
|
||||||
@@ -616,7 +618,8 @@ internal object EnhancedSessionLogShare {
|
|||||||
redactionLearningComplete: Boolean,
|
redactionLearningComplete: Boolean,
|
||||||
) {
|
) {
|
||||||
val entries = JSONArray()
|
val entries = JSONArray()
|
||||||
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
|
val (discovery, rest) = records.partition { it.origin == "discovery" }
|
||||||
|
(discovery + rest).take(MAX_MANIFEST_RECORDS).forEach { record ->
|
||||||
entries.put(JSONObject().apply {
|
entries.put(JSONObject().apply {
|
||||||
put("entry", record.entry)
|
put("entry", record.entry)
|
||||||
put("origin", record.origin)
|
put("origin", record.origin)
|
||||||
@@ -680,6 +683,15 @@ internal object EnhancedSessionLogShare {
|
|||||||
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
|
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 ->
|
CRITICAL_SESSION_FILES.forEach { name ->
|
||||||
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
|
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
|
||||||
}
|
}
|
||||||
@@ -713,16 +725,7 @@ internal object EnhancedSessionLogShare {
|
|||||||
add(source.file, source.root, source.entry, "battlenet")
|
add(source.file, source.root, source.entry, "battlenet")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
battleNetRoots(context).forEach { (prefix, root) ->
|
battleNetRoots(context).forEach { (prefix, root) -> addRecentLogs(root, "battlenet/$prefix", "battlenet") }
|
||||||
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))
|
val sessionScan = walk(folder, remaining(maxFiles, out.size))
|
||||||
truncated = truncated || sessionScan.truncated
|
truncated = truncated || sessionScan.truncated
|
||||||
@@ -733,6 +736,9 @@ internal object EnhancedSessionLogShare {
|
|||||||
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
|
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
|
||||||
add(file, folder, "${folder.name}/$relative", "session")
|
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()) {
|
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
|
||||||
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
|
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
|
||||||
val scan = directFiles(steam, remaining(maxFiles, out.size))
|
val scan = directFiles(steam, remaining(maxFiles, out.size))
|
||||||
@@ -748,7 +754,8 @@ internal object EnhancedSessionLogShare {
|
|||||||
private fun sharePriority(candidate: Candidate): Int = when {
|
private fun sharePriority(candidate: Candidate): Int = when {
|
||||||
candidate.origin == "session-critical" -> 0
|
candidate.origin == "session-critical" -> 0
|
||||||
candidate.origin == "session" && candidate.category == Category.GAMES -> 1
|
candidate.origin == "session" && candidate.category == Category.GAMES -> 1
|
||||||
else -> 2
|
candidate.origin == "anticheat" -> 2
|
||||||
|
else -> 3
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
|
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
|
||||||
@@ -822,6 +829,39 @@ internal object EnhancedSessionLogShare {
|
|||||||
return ScanResult(files, truncated, partial)
|
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>> {
|
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
|
||||||
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
|
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
|
||||||
val data = File(drive, "ProgramData/Battle.net")
|
val data = File(drive, "ProgramData/Battle.net")
|
||||||
@@ -928,7 +968,9 @@ internal object EnhancedSessionLogShare {
|
|||||||
val normalized = name.replace('\\', '/').trimStart('/')
|
val normalized = name.replace('\\', '/').trimStart('/')
|
||||||
val parts = normalized.split('/')
|
val parts = normalized.split('/')
|
||||||
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
|
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
|
||||||
return parts.joinToString("/") { safeComponent(it) }
|
return parts.mapIndexed { index, part ->
|
||||||
|
if (index == 1 && parts[0] == "anticheat" && APP_ID.matches(part)) part else safeComponent(part)
|
||||||
|
}.joinToString("/")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun safeComponent(value: String): String {
|
private fun safeComponent(value: String): String {
|
||||||
@@ -941,7 +983,7 @@ internal object EnhancedSessionLogShare {
|
|||||||
|
|
||||||
private fun category(entry: String): Category {
|
private fun category(entry: String): Category {
|
||||||
val value = entry.lowercase(Locale.US)
|
val value = entry.lowercase(Locale.US)
|
||||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
if (value.startsWith("battlenet/") || value.startsWith("anticheat/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
||||||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
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
|
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
|
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
||||||
@@ -950,7 +992,7 @@ internal object EnhancedSessionLogShare {
|
|||||||
|
|
||||||
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
|
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
|
||||||
private val KNOWN_COMPONENTS = setOf(
|
private val KNOWN_COMPONENTS = setOf(
|
||||||
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
|
"steam", "graphics", "games", "battlenet", "anticheat", "anticheatlauncher.log", "client", "agent", "setup", "stores", "tools",
|
||||||
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
||||||
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.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",
|
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
||||||
@@ -961,11 +1003,15 @@ internal object EnhancedSessionLogShare {
|
|||||||
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
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("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
||||||
Regex("steam-[0-9]+\\.(?:log|txt)"),
|
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("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
|
||||||
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
|
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
|
||||||
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
|
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})?"),
|
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 SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
|
||||||
private val CRITICAL_SESSION_FILES = listOf(
|
private val CRITICAL_SESSION_FILES = listOf(
|
||||||
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
|
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
|
||||||
@@ -973,6 +1019,7 @@ internal object EnhancedSessionLogShare {
|
|||||||
)
|
)
|
||||||
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
|
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
|
||||||
private const val STORE_LOG_SCAN = 512
|
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 COPY_BUFFER_BYTES = 64 * 1024
|
||||||
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
|
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
|
||||||
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
|
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import android.content.Context
|
|||||||
import android.os.Environment
|
import android.os.Environment
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.core.CpuFeatures
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import com.droiddeck.launcher.runtime.BwrapSpawner
|
import com.droiddeck.launcher.runtime.BwrapSpawner
|
||||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||||
@@ -22,6 +23,10 @@ object SessionFiles {
|
|||||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||||
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
|
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_MANIFEST = "usr/local/share/droiddeck/ime-files.json"
|
||||||
private const val IME_DEFAULT_MODE = 420
|
private const val IME_DEFAULT_MODE = 420
|
||||||
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
|
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
|
||||||
@@ -102,10 +107,23 @@ object SessionFiles {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private val STAGE_LOCK = Any()
|
private val STAGE_LOCK = Any()
|
||||||
|
@Volatile private var activeSessionLseEmu: String? = null
|
||||||
|
|
||||||
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
|
fun stage(context: Context, root: File, startsSession: Boolean = false) =
|
||||||
|
stage(context, root, startsSession, lseEmu = null)
|
||||||
|
|
||||||
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
|
fun stage(context: Context, root: File, startsSession: Boolean, lseEmu: String?) =
|
||||||
|
synchronized(STAGE_LOCK) {
|
||||||
|
val selection = if (startsSession) {
|
||||||
|
activeSessionLseEmu = lseEmu
|
||||||
|
lseEmu
|
||||||
|
} else {
|
||||||
|
lseEmu ?: activeSessionLseEmu
|
||||||
|
}
|
||||||
|
stageNow(context, root, startsSession, selection)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stageNow(context: Context, root: File, startsSession: Boolean, lseEmu: String?) {
|
||||||
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
|
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
|
||||||
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
|
||||||
GameEnvironmentStore.publish(context)
|
GameEnvironmentStore.publish(context)
|
||||||
@@ -281,6 +299,7 @@ object SessionFiles {
|
|||||||
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
|
"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/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE",
|
||||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/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, _) ->
|
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
|
||||||
val dir = asset.substringBeforeLast('/')
|
val dir = asset.substringBeforeLast('/')
|
||||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||||
@@ -343,20 +362,22 @@ object SessionFiles {
|
|||||||
stageImeFiles(context, root, ledger)
|
stageImeFiles(context, root, ledger)
|
||||||
ledger.save()
|
ledger.save()
|
||||||
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
|
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
|
||||||
val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
|
val preload = StringBuilder(lsePreload(CpuFeatures.lacksAtomics, File(root, LSE_EMU).isFile, lseEmu))
|
||||||
|
preload.append("/usr/local/lib/libddsession.so\n")
|
||||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||||
}
|
}
|
||||||
val nativeUserland = SessionPrefs.nativeUserland(context)
|
com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
|
||||||
if (nativeUserland) com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
|
val native = com.droiddeck.launcher.runtime.NativeGuest.available(root)
|
||||||
if (ProotFastPath.enabled(context)) {
|
val nativePreload = preload.toString()
|
||||||
|
if (ProotFastPath.enabled(context, native)) {
|
||||||
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
|
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
|
||||||
preload.append(library + "\n")
|
preload.append(library + "\n")
|
||||||
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
|
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
|
||||||
}
|
}
|
||||||
val etc = File(root, "etc").apply { mkdirs() }
|
val etc = File(root, "etc").apply { mkdirs() }
|
||||||
File(etc, "droiddeck").mkdirs()
|
File(etc, "droiddeck").mkdirs()
|
||||||
FileUtils.writeString(File(etc, "droiddeck/native-preload"), preload.toString())
|
FileUtils.writeString(File(etc, "droiddeck/native-preload"), nativePreload)
|
||||||
val staged = File(etc, "ld.so.preload.staged")
|
val staged = File(etc, "ld.so.preload.staged")
|
||||||
if (!FileUtils.writeString(staged, preload.toString())
|
if (!FileUtils.writeString(staged, preload.toString())
|
||||||
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
|
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
|
||||||
|
|||||||
@@ -1181,21 +1181,9 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putBoolean("mountSharedStorage", on).apply()
|
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). */
|
/** 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 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). */
|
/** 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)
|
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
|
||||||
|
|
||||||
@@ -1203,12 +1191,6 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
|
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 cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
|
||||||
|
|
||||||
fun setCursorComposite(context: Context, on: Boolean) {
|
fun setCursorComposite(context: Context, on: Boolean) {
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ import com.droiddeck.launcher.input.SteamControllerBle
|
|||||||
import com.droiddeck.launcher.runtime.BwrapSpawner
|
import com.droiddeck.launcher.runtime.BwrapSpawner
|
||||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.runtime.NativeGuest
|
||||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||||
import com.droiddeck.launcher.runtime.UserApps
|
import com.droiddeck.launcher.runtime.UserApps
|
||||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||||
@@ -566,6 +567,7 @@ class SessionService : Service() {
|
|||||||
.onFailure { Log.w(TAG, "agent environment skipped", it) }
|
.onFailure { Log.w(TAG, "agent environment skipped", it) }
|
||||||
val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList())
|
val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList())
|
||||||
val customEnvironment = extraEnv()
|
val customEnvironment = extraEnv()
|
||||||
|
val lseEmu = (customEnvironment + agentEnvironment).lastOrNull { it.startsWith("LSE_EMU=") }?.substringAfter('=')
|
||||||
try {
|
try {
|
||||||
if (systemVulkan) {
|
if (systemVulkan) {
|
||||||
SystemVulkanDriver.prepare(this)
|
SystemVulkanDriver.prepare(this)
|
||||||
@@ -575,7 +577,7 @@ class SessionService : Service() {
|
|||||||
}
|
}
|
||||||
pruneSystemVulkanRuntime()
|
pruneSystemVulkanRuntime()
|
||||||
}
|
}
|
||||||
SessionFiles.stage(this, root, startsSession = true)
|
SessionFiles.stage(this, root, startsSession = true, lseEmu = lseEmu)
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
Log.e(TAG, "Could not prepare the session graphics runtime", error)
|
Log.e(TAG, "Could not prepare the session graphics runtime", error)
|
||||||
failSession(gen, "GRAPHICS_RUNTIME_FAILED", getString(R.string.session_graphics_runtime_failed), -1)
|
failSession(gen, "GRAPHICS_RUNTIME_FAILED", getString(R.string.session_graphics_runtime_failed), -1)
|
||||||
@@ -783,12 +785,13 @@ class SessionService : Service() {
|
|||||||
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
|
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
|
||||||
|
|
||||||
val sharedStorage = LinuxRuntime.sharedStorage(this)
|
val sharedStorage = LinuxRuntime.sharedStorage(this)
|
||||||
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage)
|
val nativeUserland = NativeGuest.enabled(this)
|
||||||
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
|
val fastPath = ProotFastPath.enabled(this, nativeUserland)
|
||||||
|
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage, fastPath)
|
||||||
synchronized(stopLock) {
|
synchronized(stopLock) {
|
||||||
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionMode = nativeUserland
|
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionMode = nativeUserland
|
||||||
}
|
}
|
||||||
val fastPathKey = if (ProotFastPath.enabled(this)) {
|
val fastPathKey = if (fastPath) {
|
||||||
val prootBinds = LinuxRuntime.binds(
|
val prootBinds = LinuxRuntime.binds(
|
||||||
this, sessionRoot, runtimeDir, sharedStorage, binds,
|
this, sessionRoot, runtimeDir, sharedStorage, binds,
|
||||||
)
|
)
|
||||||
@@ -809,16 +812,14 @@ class SessionService : Service() {
|
|||||||
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
|
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
|
||||||
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
|
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
|
||||||
} else {
|
} 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)
|
LinuxRuntime.command(this, sessionRoot, runtimeDir, sharedStorage, binds, guest)
|
||||||
}
|
}
|
||||||
|
|
||||||
val prootEnv = HostEnvironment()
|
val prootEnv = HostEnvironment()
|
||||||
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
|
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
|
||||||
prootEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(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 } }
|
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> prootEnv[k] = v } }
|
||||||
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
|
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
|
||||||
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
|
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
|
||||||
@@ -830,7 +831,7 @@ class SessionService : Service() {
|
|||||||
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
|
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
|
||||||
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
|
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
|
||||||
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
|
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
|
||||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
|
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this), lseEmu)
|
||||||
.forEach { (k, v) -> env[k] = v }
|
.forEach { (k, v) -> env[k] = v }
|
||||||
} else prootEnv
|
} else prootEnv
|
||||||
|
|
||||||
@@ -1312,6 +1313,7 @@ class SessionService : Service() {
|
|||||||
sessionRoot: File,
|
sessionRoot: File,
|
||||||
runtimeDir: File,
|
runtimeDir: File,
|
||||||
sharedStorage: File?,
|
sharedStorage: File?,
|
||||||
|
fastPath: Boolean,
|
||||||
): ArrayList<String> {
|
): ArrayList<String> {
|
||||||
val binds = ArrayList<String>()
|
val binds = ArrayList<String>()
|
||||||
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
||||||
@@ -1445,7 +1447,7 @@ class SessionService : Service() {
|
|||||||
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
|
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
|
||||||
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
|
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
|
||||||
if (gamesLibraries.isNotEmpty()) {
|
if (gamesLibraries.isNotEmpty()) {
|
||||||
var room = if (ProotFastPath.enabled(this)) {
|
var room = if (fastPath) {
|
||||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||||
} else Int.MAX_VALUE
|
} else Int.MAX_VALUE
|
||||||
for (games in gamesLibraries) {
|
for (games in gamesLibraries) {
|
||||||
@@ -1487,7 +1489,7 @@ class SessionService : Service() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
val room = if (ProotFastPath.enabled(this)) {
|
val room = if (fastPath) {
|
||||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||||
} else Int.MAX_VALUE
|
} else Int.MAX_VALUE
|
||||||
val content = SecondaryLibrary.contentPath(entry.host)
|
val content = SecondaryLibrary.contentPath(entry.host)
|
||||||
@@ -1516,7 +1518,7 @@ class SessionService : Service() {
|
|||||||
if (problem != null) {
|
if (problem != null) {
|
||||||
Log.w(TAG, "x86-64 steam library: $problem")
|
Log.w(TAG, "x86-64 steam library: $problem")
|
||||||
} else try {
|
} else try {
|
||||||
val room = if (ProotFastPath.enabled(this)) {
|
val room = if (fastPath) {
|
||||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||||
} else Int.MAX_VALUE
|
} else Int.MAX_VALUE
|
||||||
val extra = SecondaryLibrary.binds(filesDir, x64, listOf(GameStorage.X64_CARD_GUEST)).drop(1)
|
val extra = SecondaryLibrary.binds(filesDir, x64, listOf(GameStorage.X64_CARD_GUEST)).drop(1)
|
||||||
@@ -1538,7 +1540,7 @@ class SessionService : Service() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
val room = if (ProotFastPath.enabled(this)) {
|
val room = if (fastPath) {
|
||||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||||
} else Int.MAX_VALUE
|
} else Int.MAX_VALUE
|
||||||
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
|
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
|
||||||
@@ -1574,7 +1576,7 @@ class SessionService : Service() {
|
|||||||
try {
|
try {
|
||||||
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
|
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
|
||||||
val volumes = org.json.JSONArray()
|
val volumes = org.json.JSONArray()
|
||||||
var room = if (ProotFastPath.enabled(this)) {
|
var room = if (fastPath) {
|
||||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||||
} else Int.MAX_VALUE
|
} else Int.MAX_VALUE
|
||||||
for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) {
|
for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) {
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import androidx.compose.runtime.setValue
|
|||||||
import com.droiddeck.launcher.core.AddonPack
|
import com.droiddeck.launcher.core.AddonPack
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.session.SessionEvents
|
import com.droiddeck.launcher.session.SessionEvents
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import com.droiddeck.launcher.stores.Store
|
import com.droiddeck.launcher.stores.Store
|
||||||
import com.droiddeck.launcher.stores.AchievementNotifications
|
import com.droiddeck.launcher.stores.AchievementNotifications
|
||||||
@@ -149,7 +148,6 @@ object GogComet {
|
|||||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(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) }
|
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import com.droiddeck.launcher.core.AddonPack
|
|||||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
|
||||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.Closeable
|
import java.io.Closeable
|
||||||
@@ -107,7 +106,6 @@ internal object Xodus {
|
|||||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(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) } }
|
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
|
||||||
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,7 +39,8 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
|||||||
}
|
}
|
||||||
if (!a.hudOn) return@SettingsGroup
|
if (!a.hudOn) return@SettingsGroup
|
||||||
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
||||||
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint),
|
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),
|
||||||
listOf(
|
listOf(
|
||||||
DroidDeckHudSize.FULL to stringResource(R.string.hud_size_full),
|
DroidDeckHudSize.FULL to stringResource(R.string.hud_size_full),
|
||||||
DroidDeckHudSize.TILES to stringResource(R.string.hud_size_tiles),
|
DroidDeckHudSize.TILES to stringResource(R.string.hud_size_tiles),
|
||||||
@@ -47,6 +48,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
|
|||||||
DroidDeckHudSize.MINIMAL to stringResource(R.string.hud_size_minimal),
|
DroidDeckHudSize.MINIMAL to stringResource(R.string.hud_size_minimal),
|
||||||
DroidDeckHudSize.MEGA to stringResource(R.string.hud_size_mega),
|
DroidDeckHudSize.MEGA to stringResource(R.string.hud_size_mega),
|
||||||
DroidDeckHudSize.STRIP to stringResource(R.string.hud_size_strip),
|
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) }
|
size, chipModifier = track("hud-size")) { a.onHudSetting("hudSize", it.token) }
|
||||||
ChoiceRow(host, "hud-hold", stringResource(R.string.hud_hold), null,
|
ChoiceRow(host, "hud-hold", stringResource(R.string.hud_hold), null,
|
||||||
|
|||||||
@@ -46,9 +46,7 @@ fun PerformancePage(
|
|||||||
fsyncFirst: Boolean,
|
fsyncFirst: Boolean,
|
||||||
gamescopeRealtime: Boolean,
|
gamescopeRealtime: Boolean,
|
||||||
gpuClockPin: Boolean,
|
gpuClockPin: Boolean,
|
||||||
prootNoSeccomp: Boolean,
|
nativeDesktopAvailable: Boolean,
|
||||||
prootFastPath: Boolean,
|
|
||||||
nativeUserland: Boolean,
|
|
||||||
desktopAsUser: Boolean,
|
desktopAsUser: Boolean,
|
||||||
cursorComposite: Boolean,
|
cursorComposite: Boolean,
|
||||||
guestHostname: String,
|
guestHostname: String,
|
||||||
@@ -65,9 +63,6 @@ fun PerformancePage(
|
|||||||
onFsyncFirst: (Boolean) -> Unit,
|
onFsyncFirst: (Boolean) -> Unit,
|
||||||
onGamescopeRealtime: (Boolean) -> Unit,
|
onGamescopeRealtime: (Boolean) -> Unit,
|
||||||
onGpuClockPin: (Boolean) -> Unit,
|
onGpuClockPin: (Boolean) -> Unit,
|
||||||
onProotNoSeccomp: (Boolean) -> Unit,
|
|
||||||
onProotFastPath: (Boolean) -> Unit,
|
|
||||||
onNativeUserland: (Boolean) -> Unit,
|
|
||||||
onDesktopAsUser: (Boolean) -> Unit,
|
onDesktopAsUser: (Boolean) -> Unit,
|
||||||
onCursorComposite: (Boolean) -> Unit,
|
onCursorComposite: (Boolean) -> Unit,
|
||||||
onGuestHostname: (String) -> Unit,
|
onGuestHostname: (String) -> Unit,
|
||||||
@@ -152,26 +147,6 @@ fun PerformancePage(
|
|||||||
stringResource(R.string.perf_fastsync_hint),
|
stringResource(R.string.perf_fastsync_hint),
|
||||||
fastSync, onChange = onFastSync,
|
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(
|
ToggleRow(
|
||||||
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
|
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
|
||||||
stringResource(R.string.perf_cursor_composite_hint),
|
stringResource(R.string.perf_cursor_composite_hint),
|
||||||
@@ -198,8 +173,8 @@ fun PerformancePage(
|
|||||||
}
|
}
|
||||||
ToggleRow(
|
ToggleRow(
|
||||||
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
|
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
|
||||||
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
|
stringResource(R.string.perf_desktop_as_user_hint),
|
||||||
desktopAsUser && nativeUserland, enabled = nativeUserland,
|
desktopAsUser && nativeDesktopAvailable, enabled = nativeDesktopAvailable,
|
||||||
onChange = onDesktopAsUser,
|
onChange = onDesktopAsUser,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,9 +85,6 @@ internal object SettingsIndex {
|
|||||||
s(SettingsSection.PERFORMANCE, R.string.perf_esync, "esync", "sync", "wine"),
|
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_fsync, "fsync", "sync", "wine"),
|
||||||
s(SettingsSection.PERFORMANCE, R.string.perf_fastsync, "ntsync", "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_cursor_composite, "mouse", "cursor"),
|
||||||
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
|
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
|
||||||
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
|
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
|
||||||
|
|||||||
@@ -737,6 +737,8 @@
|
|||||||
<string name="hud_size_minimal">Minimal</string>
|
<string name="hud_size_minimal">Minimal</string>
|
||||||
<string name="hud_size_mega">Mega</string>
|
<string name="hud_size_mega">Mega</string>
|
||||||
<string name="hud_size_strip">Strip</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">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_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>
|
<string name="hud_hold">Long press</string>
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package com.droiddeck.launcher.core
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.session.SessionFiles
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class CpuFeaturesTest {
|
||||||
|
@Test fun anArmv80CpuLacksAtomics() {
|
||||||
|
val cpuInfo = """
|
||||||
|
processor : 0
|
||||||
|
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid
|
||||||
|
processor : 1
|
||||||
|
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid
|
||||||
|
""".trimIndent()
|
||||||
|
assertTrue(CpuFeatures.lacksAtomics(cpuInfo))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun oneCoreWithoutAtomicsIsEnough() {
|
||||||
|
val cpuInfo = """
|
||||||
|
processor : 0
|
||||||
|
Features : fp asimd atomics
|
||||||
|
processor : 4
|
||||||
|
Features : fp asimd
|
||||||
|
""".trimIndent()
|
||||||
|
assertTrue(CpuFeatures.lacksAtomics(cpuInfo))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun anArmv82CpuHasAtomics() {
|
||||||
|
val cpuInfo = """
|
||||||
|
processor : 0
|
||||||
|
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
|
||||||
|
""".trimIndent()
|
||||||
|
assertFalse(CpuFeatures.lacksAtomics(cpuInfo))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun noFeatureLinesMeansNoEmulation() {
|
||||||
|
assertFalse(CpuFeatures.lacksAtomics("processor : 0\n"))
|
||||||
|
assertFalse(CpuFeatures.lacksAtomics(""))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun theEmulatorIsPreloadedFirstOnlyWhenNeededAndStaged() {
|
||||||
|
assertEquals("/usr/local/lib/droiddeck-lse/liblse_emu.so\n", SessionFiles.lsePreload(lacksAtomics = true, staged = true))
|
||||||
|
assertEquals("", SessionFiles.lsePreload(lacksAtomics = true, staged = false))
|
||||||
|
assertEquals("", SessionFiles.lsePreload(lacksAtomics = false, staged = true))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -133,6 +133,38 @@ 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() {
|
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
|
||||||
val stats = FrameStats()
|
val stats = FrameStats()
|
||||||
var now = 1_000_000_000L
|
var now = 1_000_000_000L
|
||||||
|
|||||||
@@ -251,6 +251,52 @@ class BwrapSpawnerPlanTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test fun sandboxesSwitchOnTheLseEmulatorWhenItIsPreloaded() {
|
||||||
|
val context = RuntimeEnvironment.getApplication()
|
||||||
|
val rootfs = LinuxRuntime.rootDir(context)
|
||||||
|
val emu = File(rootfs, "usr/local/lib/droiddeck-lse/liblse_emu.so").apply { parentFile?.mkdirs(); writeText("") }
|
||||||
|
val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/droiddeck-lse/liblse_emu.so\n") }
|
||||||
|
try {
|
||||||
|
val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
|
||||||
|
assertEquals("/run/droiddeck-preload/liblse_emu.so", plan.env["LD_PRELOAD"])
|
||||||
|
assertEquals("1", plan.env["LSE_EMU"])
|
||||||
|
assertFalse(plan.env.containsKey("LSE_EMU_PATCH"))
|
||||||
|
val chosen = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp"))
|
||||||
|
.apply { getJSONObject("env").put("LSE_EMU_PATCH", "0") }, dir)
|
||||||
|
assertEquals("0", chosen.env["LSE_EMU_PATCH"])
|
||||||
|
assertEquals("1", chosen.env["LSE_EMU"])
|
||||||
|
for (inherited in listOf(
|
||||||
|
"/run/droiddeck-preload/liblse_emu.so /custom.so",
|
||||||
|
"/custom.so:/run/droiddeck-preload/liblse_emu.so",
|
||||||
|
)) {
|
||||||
|
val disabled = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp"))
|
||||||
|
.apply {
|
||||||
|
getJSONObject("env").put("LSE_EMU", "0")
|
||||||
|
getJSONObject("env").put("LD_PRELOAD", inherited)
|
||||||
|
}, dir)
|
||||||
|
assertEquals("0", disabled.env["LSE_EMU"])
|
||||||
|
assertEquals("/custom.so", disabled.env["LD_PRELOAD"])
|
||||||
|
assertFalse(disabled.binds.any { it.guest == "/run/droiddeck-preload/liblse_emu.so" })
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
listOf(emu, preload).forEach { it.delete() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun sandboxesLeaveTheLseSwitchesAloneWithoutTheEmulator() {
|
||||||
|
val context = RuntimeEnvironment.getApplication()
|
||||||
|
val rootfs = LinuxRuntime.rootDir(context)
|
||||||
|
val lib = File(rootfs, "usr/local/lib/libddsession.so").apply { parentFile?.mkdirs(); writeText("") }
|
||||||
|
val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libddsession.so\n") }
|
||||||
|
try {
|
||||||
|
val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
|
||||||
|
assertFalse(plan.env.containsKey("LSE_EMU"))
|
||||||
|
assertFalse(plan.env.containsKey("LSE_EMU_PATCH"))
|
||||||
|
} finally {
|
||||||
|
listOf(lib, preload).forEach { it.delete() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test fun zypakLaunchesTheBrowserWithoutItsSandbox() {
|
@Test fun zypakLaunchesTheBrowserWithoutItsSandbox() {
|
||||||
val context = RuntimeEnvironment.getApplication()
|
val context = RuntimeEnvironment.getApplication()
|
||||||
val app = File(runtime, "app").apply { File(this, "bin").mkdirs() }
|
val app = File(runtime, "app").apply { File(this, "bin").mkdirs() }
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
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,6 +94,27 @@ class NativeGuestTest {
|
|||||||
assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so"))
|
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
|
@Test
|
||||||
fun theProgramTheLoaderRunsIsNamedInItsEnvironment() {
|
fun theProgramTheLoaderRunsIsNamedInItsEnvironment() {
|
||||||
val root = rootWithLoader()
|
val root = rootWithLoader()
|
||||||
|
|||||||
@@ -27,14 +27,12 @@ class ProotFastPathTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test fun fastPathStaysOffForTheRootfsProot() {
|
@Test fun fastPathStaysOffForTheRootfsProot() {
|
||||||
assertTrue(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
|
assertTrue(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = false))
|
||||||
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_ROOTFS))
|
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_ROOTFS, native = false))
|
||||||
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_MISSING))
|
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_MISSING, native = false))
|
||||||
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() {
|
@Test fun fastPathStaysOffWithoutProot() {
|
||||||
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK, nativeUserland = true))
|
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = true))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.droiddeck.launcher.session
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.assumeFilePermissionsEnforced
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
@@ -8,6 +9,7 @@ import java.util.Date
|
|||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
import java.util.zip.ZipFile
|
import java.util.zip.ZipFile
|
||||||
|
import org.json.JSONObject
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertFalse
|
import org.junit.Assert.assertFalse
|
||||||
import org.junit.Assert.assertNotNull
|
import org.junit.Assert.assertNotNull
|
||||||
@@ -144,6 +146,136 @@ 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() {
|
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
|
||||||
val logs = LinuxRuntime.logDir(app)
|
val logs = LinuxRuntime.logDir(app)
|
||||||
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
|
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
# Steam client on ARMv8.0 CPUs
|
||||||
|
|
||||||
|
## The crash
|
||||||
|
|
||||||
|
Valve's native arm64 Steam client stopped starting on ARMv8.0 CPUs after the April 15 2026
|
||||||
|
build (client version 1776387948). The process dies with SIGILL right away, the session log
|
||||||
|
shows `"$steam_root/steamrtarm64/steam" ... Illegal instruction` and `steam exited rc=132`,
|
||||||
|
and the screen stays black.
|
||||||
|
|
||||||
|
The faulting instruction is an ARMv8.1 LSE atomic. The GDB trace in
|
||||||
|
[ValveSoftware/steam-for-linux#13288](https://github.com/ValveSoftware/steam-for-linux/issues/13288)
|
||||||
|
stops on `ldaddal x1, x0, [x0]`, with `swpa` and `casal` next to it. Earlier builds were most
|
||||||
|
likely compiled with `-moutline-atomics`, which picks LL/SC or LSE at run time. Newer builds
|
||||||
|
inline LSE. Valve has not replied on that issue, so the cause comes from the reporter's
|
||||||
|
disassembly, not from Valve.
|
||||||
|
|
||||||
|
Affected cores are the ARMv8.0 ones without LSE: Cortex-A35, A53, A57, A72 and A73. A55, A75
|
||||||
|
and later have it. On Android that covers the Snapdragon 4xx/6xx parts built on A53/A73 (for example the
|
||||||
|
Snapdragon 685 with Adreno 610 in
|
||||||
|
[Droid-Deck/DroidDeck#380](https://github.com/Droid-Deck/DroidDeck/issues/380)), plus the
|
||||||
|
Nintendo Switch, Raspberry Pi 4 and older, and the Jetson Nano outside Android.
|
||||||
|
`/proc/cpuinfo` shows it: the `Features` line has no `atomics`.
|
||||||
|
|
||||||
|
LSE is an ARMv8.1 feature. LSE-Emu users report the current client running on a Cortex-A57,
|
||||||
|
so nothing later than LSE seems to be required yet.
|
||||||
|
|
||||||
|
## What other projects do
|
||||||
|
|
||||||
|
- [SildurFX/Switchdeck](https://github.com/SildurFX/Switchdeck) (Switch, L4T Linux) lets the
|
||||||
|
client update once, then overlays `linuxarm64`, `steamrtarm64`, `steamui` and a `steam.cfg`
|
||||||
|
from the April build. It works there because the install script controls the whole system.
|
||||||
|
For us a pinned client is replaced by the self updater on its next start, which is why #380
|
||||||
|
was closed.
|
||||||
|
- [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) is a preload library by the same
|
||||||
|
author, written to run the current arm64 client on the Switch. A SIGILL handler performs
|
||||||
|
each LSE instruction with an LL/SC loop. With `LSE_EMU_PATCH=1` the first trap at a site
|
||||||
|
writes an LL/SC stub within branch range and replaces the instruction with a `b` to it, so
|
||||||
|
the site runs natively after that. It covers the full LSE set plus `LDAPR`. The author
|
||||||
|
reports Steam, FEX, Proton games and ARMSX2 running on a Cortex-A57, with ARMSX2 close to
|
||||||
|
native ARMv8.0 speed once patched. GPL-3.0, same as this repo.
|
||||||
|
- [Azkali/proton-arm64-a57](https://github.com/Azkali/proton-arm64-a57) rebuilds Proton 11
|
||||||
|
arm64 (Wine, DXVK, vkd3d-proton, FEX's WoW64 and ARM64EC DLLs) with
|
||||||
|
`-march=armv8-a -mtune=cortex-a57`. Stock Proton 11 arm64 also SIGILLs on ARMv8.0
|
||||||
|
(`wineboot` rc=132), so the client is not the only problem for games.
|
||||||
|
- Some installers fall back to Valve's x86-64 client under FEX on CPUs without LSE. We already
|
||||||
|
have that path (`DD_STEAM_CLIENT_ARCH=x86_64`, `droiddeck-steam-x64`), but it is slower and
|
||||||
|
FEX itself has to be built without LSE.
|
||||||
|
- [FrankNat996/armor](https://github.com/FrankNat996/armor) notes a separate problem: the arm64
|
||||||
|
client's ELF segments are 4K aligned, so it SIGSEGVs at once on 16K page kernels.
|
||||||
|
|
||||||
|
## This change
|
||||||
|
|
||||||
|
The session vendors LSE-Emu (`tools/linuxfs/lse-emu`, upstream commit `8bc9548`). CI and
|
||||||
|
`tools/build_local.sh` build it as `usr/local/lib/droiddeck-lse/liblse_emu.so` with
|
||||||
|
`-march=armv8-a -mno-outline-atomics`. The build fails if the library contains LSE
|
||||||
|
instructions itself.
|
||||||
|
|
||||||
|
When `/proc/cpuinfo` reports any core without `atomics`, `SessionFiles` puts the library first
|
||||||
|
in the rootfs `/etc/ld.so.preload`. `BwrapSpawner` already turns that file into `LD_PRELOAD`
|
||||||
|
for sandboxed processes. On CPUs with LSE nothing changes: the file is staged but not
|
||||||
|
preloaded, and the library would also stay idle on its own because it checks `HWCAP_ATOMICS`.
|
||||||
|
|
||||||
|
`droiddeck-session` sees the library in `ld.so.preload` and exports `LSE_EMU=1`. Runtime
|
||||||
|
instruction rewriting is disabled by default (`LSE_EMU_PATCH=0`): the emulator uses the slower
|
||||||
|
SIGILL path rather than rewriting executable code while other threads may be running it. To
|
||||||
|
opt in to patching for testing, set `LSE_EMU_PATCH=1` explicitly. With a session debug folder,
|
||||||
|
the script also sets `LSE_EMU_LOG=$DD_DEBUG_DIR/lse_emu.log`, and `session.log` gets a line
|
||||||
|
starting with `== cpu: no LSE atomics`.
|
||||||
|
|
||||||
|
The test APK targets SDK 34. To verify the expected `mprotect` restriction, run a controlled
|
||||||
|
test executable containing a known-patchable, file-backed LSE instruction with
|
||||||
|
`LSE_EMU_PATCH=1` under this APK configuration, and confirm `mprotect-failed` for that site.
|
||||||
|
A normal Steam run alone cannot establish the restriction.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`tools/tests/test_lse_emu.py` builds the library and a program that uses every LSE family
|
||||||
|
(`ldadd` in all four sizes, `ldclr`, `ldeor`, `ldset`, `swp`, `ldsmax`, `ldumin`, `casal`,
|
||||||
|
`caspal`) from four threads, and runs it under `qemu-aarch64 -cpu cortex-a57`:
|
||||||
|
|
||||||
|
- without the library the program dies with SIGILL
|
||||||
|
- trapping alone runs every form and keeps the threaded counters exact
|
||||||
|
- patching runs every form twice, so the second run goes through the generated stubs, both
|
||||||
|
single threaded and with four threads
|
||||||
|
- condition flags survive a patched `ldumax`/`ldsmaxb`, and `caspal` returns the current pair
|
||||||
|
on a mismatch
|
||||||
|
- without `LSE_EMU=1`, and on `-cpu neoverse-n1`, the library stays out of the way
|
||||||
|
- a SIGILL handler the program installs itself still runs for an unrelated `udf`
|
||||||
|
|
||||||
|
The patch tests cannot run on an Apple Silicon Mac in an amd64 Docker container: qemu-aarch64
|
||||||
|
there segfaults whenever code is written to an executable page after code on it has run, even
|
||||||
|
in a ten line program without the library. CI runs them on x86 hardware.
|
||||||
|
|
||||||
|
## Fixes over upstream
|
||||||
|
|
||||||
|
The vendored copy carries two fixes found in review, both in the patched stubs and the
|
||||||
|
emulation path:
|
||||||
|
|
||||||
|
- `LDSMAX`/`LDSMIN`/`LDUMAX`/`LDUMIN` stubs used `cmp`/`csel` and overwrote NZCV. They now
|
||||||
|
save and restore it.
|
||||||
|
- `CASP` with a 64-bit pair returned the `ldxp` result on a mismatch without a store. A 128-bit
|
||||||
|
`ldxp` is only single-copy atomic once a `stxp` succeeds, so a concurrent update could give
|
||||||
|
one old and one new half. Both the trap path and the stub now store the loaded pair back on a
|
||||||
|
mismatch and retry if that store fails, as libatomic does.
|
||||||
|
|
||||||
|
Patching replaces an LSE instruction with a `b` while other threads may be running it.
|
||||||
|
The architecture does not guarantee safe concurrent replacement for every instruction (including
|
||||||
|
`LDADD`), so patching is opt-in and defaults to `LSE_EMU_PATCH=0`. This avoids that specific
|
||||||
|
self-modifying-code race by keeping sites on the SIGILL emulation path, at the cost of speed.
|
||||||
|
It does not eliminate all signal-handler compatibility risks: direct raw `rt_sigaction` syscalls,
|
||||||
|
complex signal masks/flags, and applications that depend on exact kernel signal semantics still
|
||||||
|
need dedicated tests. The handler forwarding is not a complete substitute for kernel delivery.
|
||||||
|
|
||||||
|
## Testing on a device
|
||||||
|
|
||||||
|
On an ARMv8.0 phone or handheld (no `atomics` in `/proc/cpuinfo`):
|
||||||
|
|
||||||
|
1. Install the test APK and start a Steam session.
|
||||||
|
2. `session.log` should have `== cpu: no LSE atomics` and no `steam exited rc=132`.
|
||||||
|
3. In the default-mode run, check that `lse_emu.log` contains a `start` record for the
|
||||||
|
affected PID and that the process remains on the trap path. While Steam is running, its
|
||||||
|
`exit` record may not exist yet: either confirm a `no-patch` record for that PID, or exit
|
||||||
|
Steam normally before checking that its `exit` record has a nonzero `traps=` value. Confirm
|
||||||
|
there are no `patched` records. Summarise events with
|
||||||
|
`cut -d' ' -f2 lse_emu.log | sort | uniq -c`.
|
||||||
|
Then repeat with `LSE_EMU_PATCH=1` explicitly set in the session environment. Do not require
|
||||||
|
`mprotect-failed` for a valid trap-path run: `no-arena` means arena allocation failed before
|
||||||
|
`mprotect` was attempted, so it is inconclusive about the SDK restriction. Check that
|
||||||
|
restriction separately using the controlled patchable site described above. `unhandled`
|
||||||
|
means an instruction the library does not cover.
|
||||||
|
4. Compare UI responsiveness against an ARMv8.2 device, and note any `lse_emu: unhandled`
|
||||||
|
lines in `session.log`.
|
||||||
|
|
||||||
|
## Still open
|
||||||
|
|
||||||
|
- Games. Proton 11 arm64 and Valve's FEX build need the same treatment. The preload reaches
|
||||||
|
them when they inherit `LD_PRELOAD`, but pressure-vessel and static binaries can drop it,
|
||||||
|
and FEX installs its own signal handlers with raw syscalls. An ARMv8.0 Proton build like
|
||||||
|
Azkali's is the cleaner fix.
|
||||||
|
- In #380 the session first died with SIGILL in the app's own `wl-compositor` thread, inside
|
||||||
|
`turnip-sdk36/vulkan.ad08XX.so`, which is the A8xx driver build loaded on an Adreno 610.
|
||||||
|
Picking the 6xx/7xx Turnip fixed it, and Auto picks that build once the driver release list
|
||||||
|
is loaded. Nobody has checked yet whether our bundled driver builds avoid LSE. The preload
|
||||||
|
cannot help there because the compositor is a bionic thread in the app process.
|
||||||
|
- JIT code (anonymous memory) is never patched and always traps.
|
||||||
|
- If Valve starts requiring something past LSE, the library prints
|
||||||
|
`lse_emu: unhandled pc=... insn=...` and the client crashes as before.
|
||||||
@@ -252,13 +252,15 @@ 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.
|
`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
|
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}` and
|
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}`,
|
||||||
`{localappdata}` in the prefix, and `type: folder` without a source creates the folder. Mods such
|
`{localappdata}` or `{userappdata}` in the prefix, and `type: folder` without a source creates the
|
||||||
as one-click editions ship their `Plugins.txt` and INI files this way. Paths match without regard
|
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
|
||||||
to case, links are copied as links, and a path outside those folders is refused. A file the
|
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` in
|
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` and
|
||||||
the prefix holds the actions' hash, so they run once per script revision and a player's later
|
`.droiddeck-gog-save-path` in the prefix hold the actions' hashes, so they run once per script
|
||||||
edits stay.
|
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
|
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
|
`game` (`isPrimary` first), or a primary `launcher` task for launcher games, whose `path` stays
|
||||||
|
|||||||
@@ -27,9 +27,6 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
|
|||||||
| droiddeck-esync | Settings › Performance (`droiddeck://settings/performance`) | esync, sync, wine |
|
| droiddeck-esync | Settings › Performance (`droiddeck://settings/performance`) | esync, sync, wine |
|
||||||
| droiddeck-fsync first | Settings › Performance (`droiddeck://settings/performance`) | fsync, sync, wine |
|
| droiddeck-fsync first | Settings › Performance (`droiddeck://settings/performance`) | fsync, sync, wine |
|
||||||
| droiddeck-ntsync | Settings › Performance (`droiddeck://settings/performance`) | ntsync, 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 |
|
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
|
||||||
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
|
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
|
||||||
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
|
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#define _GNU_SOURCE
|
#define _GNU_SOURCE
|
||||||
#include <dirent.h>
|
#include <dirent.h>
|
||||||
#include <dlfcn.h>
|
#include <dlfcn.h>
|
||||||
|
#include <elf.h>
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
#include <fcntl.h>
|
#include <fcntl.h>
|
||||||
#include <limits.h>
|
#include <limits.h>
|
||||||
@@ -547,3 +548,55 @@ EXPORT uid_t getuid(void)
|
|||||||
}
|
}
|
||||||
return (uid_t)raw_getuid();
|
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,6 +225,7 @@ else
|
|||||||
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
|
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-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"
|
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-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"
|
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
|
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.
|
# CI records identities under its runner labels and pinned NDK, not this host's.
|
||||||
RUNNER_ARCHITECTURES = ('X64', 'ARM64')
|
RUNNER_ARCHITECTURES = ('X64', 'ARM64')
|
||||||
# The components job builds these outside the recipe registry.
|
# The components job builds these outside the recipe registry.
|
||||||
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c',
|
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/linuxfs/lse-emu',
|
||||||
'tools/quest']
|
'tools/venus/glprobe.c', 'tools/quest']
|
||||||
|
|
||||||
|
|
||||||
def ci_environment(architecture, root):
|
def ci_environment(architecture, root):
|
||||||
|
|||||||
@@ -31,5 +31,9 @@ for sym in vkNegotiateLoaderLayerInterfaceVersion vkGetInstanceProcAddr vkGetDev
|
|||||||
grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; }
|
grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; }
|
||||||
done
|
done
|
||||||
test -f "$D/usr/local/lib/droiddeck-xclipse/VkLayer_droiddeck_xclipse.json"
|
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-session"
|
||||||
test -f "$D/usr/local/bin/droiddeck-proton-extra"
|
test -f "$D/usr/local/bin/droiddeck-proton-extra"
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# LSE-Emu
|
||||||
|
|
||||||
|
`lse_emu.c` is a copy of [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) at commit
|
||||||
|
`8bc9548ac6fd24a8d506b266b17ba8d0e71a9b01` (GPL-3.0-or-later) with two fixes, listed in
|
||||||
|
`docs/arm-v8.0-steam-client.md` under "Fixes over upstream": NZCV kept across the min/max
|
||||||
|
stubs, and a store-back on `CASP` mismatches so the returned pair is atomic. Carry them forward
|
||||||
|
until upstream has them.
|
||||||
|
|
||||||
|
It is an `LD_PRELOAD` library that emulates the ARMv8.1 LSE atomic instructions (and `LDAPR`)
|
||||||
|
on ARMv8.0 CPUs. A SIGILL handler performs each trapped instruction with an LL/SC loop. A GNU
|
||||||
|
IFUNC resolver installs a minimal early handler on CPUs without LSE before dependency
|
||||||
|
constructors, covering LSE instructions executed before the preload constructor. The early handler
|
||||||
|
is removed after initialization unless `LSE_EMU=1` is set. With `LSE_EMU_PATCH=1` the first trap at a site
|
||||||
|
writes an LL/SC stub nearby and replaces the instruction with a branch to it, so later runs do not trap.
|
||||||
|
Patching is off by default. It is restricted to private file-backed executable mappings whose
|
||||||
|
live file and offset still match the original mapping. Leave patching off for programs that
|
||||||
|
can remap executable pages concurrently: checking the mapping cannot lock it against a remap.
|
||||||
|
|
||||||
|
The session stages it as `/usr/local/lib/droiddeck-lse/liblse_emu.so` and only lists it in
|
||||||
|
`/etc/ld.so.preload` when `/proc/cpuinfo` has no `atomics` flag. See
|
||||||
|
`docs/arm-v8.0-steam-client.md` for why.
|
||||||
|
|
||||||
|
To update, copy `lse_emu.c` from a newer upstream commit and change the commit above.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
D=${1:?asset directory}
|
||||||
|
CC=${CC:-aarch64-linux-gnu-gcc}
|
||||||
|
STRIP=${STRIP:-aarch64-linux-gnu-strip}
|
||||||
|
here=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
out="$D/usr/local/lib/droiddeck-lse/liblse_emu.so"
|
||||||
|
mkdir -p "$(dirname "$out")"
|
||||||
|
"$CC" -shared -fPIC -O2 -march=armv8-a -mno-outline-atomics -Wall -Wextra -Wno-unused-parameter \
|
||||||
|
-Wl,-z,now,-z,max-page-size=65536 -o "$out" "$here/lse_emu.c" -ldl
|
||||||
|
"$STRIP" --strip-unneeded "$out"
|
||||||
|
disassembly=$("${OBJDUMP:-aarch64-linux-gnu-objdump}" -d "$out")
|
||||||
|
if grep -qE $'\t((ld|st)(add|clr|eor|set|smax|smin|umax|umin)|swp|cas)[a-z]*\t' <<<"$disassembly"; then
|
||||||
|
echo "::error::liblse_emu.so itself contains LSE instructions"; exit 1
|
||||||
|
fi
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -573,11 +573,11 @@ def inspector_url(url):
|
|||||||
|
|
||||||
|
|
||||||
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
|
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
|
||||||
command_line_api=False):
|
command_line_api=False, connect_timeout=5):
|
||||||
if inspector is not None:
|
if inspector is not None:
|
||||||
url, name = inspector_url(inspector), "inspector"
|
url, name = inspector_url(inspector), "inspector"
|
||||||
else:
|
else:
|
||||||
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
|
targets = [t for t in cdp_targets(agent_dir, timeout=connect_timeout) if t.get("webSocketDebuggerUrl")]
|
||||||
want = target or "SharedJSContext"
|
want = target or "SharedJSContext"
|
||||||
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
|
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
|
||||||
if not match:
|
if not match:
|
||||||
@@ -841,6 +841,75 @@ class KeyboardWatcher(threading.Thread):
|
|||||||
self.report(params.get("payload") == "true")
|
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):
|
def steam_idle_inhibit(agent_dir, inhibit):
|
||||||
expression = """(async want => {
|
expression = """(async want => {
|
||||||
const toggle = () => new Promise(done => {
|
const toggle = () => new Promise(done => {
|
||||||
@@ -1318,6 +1387,23 @@ def main(argv):
|
|||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
print({True: "yes", False: "no"}.get(value, "unknown"))
|
print({True: "yes", False: "no"}.get(value, "unknown"))
|
||||||
return {True: 0, False: 5}.get(value, 1)
|
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":
|
if argv and argv[0] == "--steam-asleep":
|
||||||
expression = """(() => {
|
expression = """(() => {
|
||||||
const store = globalThis.SuspendResumeStore;
|
const store = globalThis.SuspendResumeStore;
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import re
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
import gi
|
import gi
|
||||||
@@ -20,6 +21,10 @@ INTERFACE = NAME + ".Manager"
|
|||||||
UPOWER = "org.freedesktop.UPower"
|
UPOWER = "org.freedesktop.UPower"
|
||||||
UPOWER_ROOT = "/org/freedesktop/UPower"
|
UPOWER_ROOT = "/org/freedesktop/UPower"
|
||||||
NATIVE_PREPARE_MS = 1500
|
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")
|
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
|
||||||
ASLEEP_WAIT = 6
|
ASLEEP_WAIT = 6
|
||||||
INHIBIT_WAIT = 12
|
INHIBIT_WAIT = 12
|
||||||
@@ -55,6 +60,10 @@ class LoginManager:
|
|||||||
self.native_ready = self.directory / "steam-native-ready"
|
self.native_ready = self.directory / "steam-native-ready"
|
||||||
self.pending = None
|
self.pending = None
|
||||||
self.pending_idle = False
|
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.waiting = set()
|
||||||
self.timeout = None
|
self.timeout = None
|
||||||
self.preparation = None
|
self.preparation = None
|
||||||
@@ -90,6 +99,7 @@ class LoginManager:
|
|||||||
if self.pending:
|
if self.pending:
|
||||||
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
|
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
|
||||||
return
|
return
|
||||||
|
self.cancel_native_wake()
|
||||||
self.pending = uuid.uuid4().hex
|
self.pending = uuid.uuid4().hex
|
||||||
self.pending_idle = False
|
self.pending_idle = False
|
||||||
self.notify(True)
|
self.notify(True)
|
||||||
@@ -133,19 +143,42 @@ class LoginManager:
|
|||||||
return
|
return
|
||||||
self.pending = token
|
self.pending = token
|
||||||
self.pending_idle = words[1:] == ["idle"]
|
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.waiting = {"hold"} if self.pending_idle else {"hold", "prepare"}
|
||||||
self.hold(token, self.prepared, token, "hold")
|
self.hold(token, self.prepared, token, "hold")
|
||||||
if self.pending_idle:
|
if self.pending_idle:
|
||||||
return
|
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.notify(True)
|
||||||
self.bus.flush(None, self.prepare_after_flush, token)
|
self.bus.flush(None, self.prepare_after_flush, token)
|
||||||
|
return False
|
||||||
|
|
||||||
def prepare_after_flush(self, connection, result, token):
|
def prepare_after_flush(self, connection, result, token):
|
||||||
try:
|
try:
|
||||||
connection.flush_finish(result)
|
connection.flush_finish(result)
|
||||||
except GLib.Error as error:
|
except GLib.Error as error:
|
||||||
print("== login1: cannot prepare native sleep: " + str(error), file=sys.stderr)
|
print("== login1: cannot prepare native sleep: " + str(error), file=sys.stderr)
|
||||||
self.resume()
|
if self.pending == token:
|
||||||
|
self.resume()
|
||||||
return
|
return
|
||||||
self.check_state()
|
self.check_state()
|
||||||
if self.pending == token:
|
if self.pending == token:
|
||||||
@@ -269,19 +302,49 @@ class LoginManager:
|
|||||||
self.notify(True)
|
self.notify(True)
|
||||||
self.bus.flush(None, self.finish_recovery, None)
|
self.bus.flush(None, self.finish_recovery, None)
|
||||||
return
|
return
|
||||||
|
token = self.pending
|
||||||
idle = self.pending_idle
|
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 = None
|
||||||
self.pending_idle = False
|
self.pending_idle = False
|
||||||
|
self.native_preparation = None
|
||||||
|
self.native_signaled = False
|
||||||
if self.preparation is not None:
|
if self.preparation is not None:
|
||||||
GLib.source_remove(self.preparation)
|
GLib.source_remove(self.preparation)
|
||||||
self.preparation = None
|
self.preparation = None
|
||||||
if self.timeout is not None:
|
if self.timeout is not None:
|
||||||
GLib.source_remove(self.timeout)
|
GLib.source_remove(self.timeout)
|
||||||
self.timeout = None
|
self.timeout = None
|
||||||
if not idle:
|
if not idle and (native is None or signaled):
|
||||||
self.notify(False)
|
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()
|
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):
|
def finish_recovery(self, connection, result, _data):
|
||||||
try:
|
try:
|
||||||
connection.flush_finish(result)
|
connection.flush_finish(result)
|
||||||
|
|||||||
Executable → Regular
+7
@@ -11,6 +11,12 @@ if [ "${DD_RAISE_NOFILE:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ]; then
|
|||||||
unset dd_nofile_was
|
unset dd_nofile_was
|
||||||
fi
|
fi
|
||||||
export HOME=${HOME:-/root}
|
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}
|
mode=${1:-desktop}
|
||||||
shift || true
|
shift || true
|
||||||
|
|
||||||
@@ -100,6 +106,7 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then
|
|||||||
echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
|
echo "== 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 "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||||
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
|
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
|
fi
|
||||||
|
|
||||||
start_diagnostic_inventory() {
|
start_diagnostic_inventory() {
|
||||||
|
|||||||
@@ -968,6 +968,7 @@ def prepare_gog(sidecar, compat_data, launch_dir):
|
|||||||
GOG_SCRIPTS = "goggame-*.script"
|
GOG_SCRIPTS = "goggame-*.script"
|
||||||
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
|
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
|
||||||
GOG_SUPPORT_MARK = ".droiddeck-gog-support"
|
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",
|
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
|
||||||
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
|
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
|
||||||
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
|
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
|
||||||
@@ -1716,7 +1717,7 @@ def prepare_steam_ea(argv, compat_data, launch_dir):
|
|||||||
return REPLACED
|
return REPLACED
|
||||||
|
|
||||||
|
|
||||||
def gog_support_actions(folder):
|
def gog_script_actions(folder, name):
|
||||||
found = []
|
found = []
|
||||||
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
|
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
|
||||||
product = script.name[len("goggame-"):-len(".script")]
|
product = script.name[len("goggame-"):-len(".script")]
|
||||||
@@ -1726,17 +1727,34 @@ def gog_support_actions(folder):
|
|||||||
continue
|
continue
|
||||||
for action in actions if isinstance(actions, list) else []:
|
for action in actions if isinstance(actions, list) else []:
|
||||||
install = action.get("install") if isinstance(action, dict) else None
|
install = action.get("install") if isinstance(action, dict) else None
|
||||||
if isinstance(install, dict) and install.get("action") == "supportData" \
|
if isinstance(install, dict) and install.get("action") == name \
|
||||||
and isinstance(install.get("arguments"), dict):
|
and isinstance(install.get("arguments"), dict):
|
||||||
found.append((product, install["arguments"]))
|
found.append((product, install["arguments"]))
|
||||||
return found
|
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):
|
def gog_support_bases(folder, product, pfx):
|
||||||
user = Path(pfx) / "drive_c" / "users" / "steamuser"
|
user = Path(pfx) / "drive_c" / "users" / "steamuser"
|
||||||
support = Path(folder) / "support" / product
|
support = Path(folder) / "support" / product
|
||||||
|
appdata = gog_case_child(user, "AppData")
|
||||||
return {"app": Path(folder), "supportdir": support, "support": support,
|
return {"app": Path(folder), "supportdir": support, "support": support,
|
||||||
"userdocs": user / "Documents", "localappdata": user / "AppData" / "Local"}
|
"userdocs": gog_case_child(user, "Documents"),
|
||||||
|
"localappdata": gog_case_child(appdata, "Local"),
|
||||||
|
"userappdata": gog_case_child(appdata, "Roaming")}
|
||||||
|
|
||||||
|
|
||||||
def gog_inside(path, base):
|
def gog_inside(path, base):
|
||||||
@@ -1755,10 +1773,7 @@ def gog_support_path(text, bases):
|
|||||||
base = bases[match.group(1).lower()]
|
base = bases[match.group(1).lower()]
|
||||||
path = base
|
path = base
|
||||||
for part in parts:
|
for part in parts:
|
||||||
exact = path / part
|
path = gog_case_child(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):
|
if path != base and not gog_inside(path.parent, base):
|
||||||
return None
|
return None
|
||||||
return path, base
|
return path, base
|
||||||
@@ -1830,6 +1845,44 @@ def gog_support_data(folder, compat_data, proton):
|
|||||||
return "copied=%d%s" % (copied, note)
|
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):
|
def main(argv):
|
||||||
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
|
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
|
||||||
return 0
|
return 0
|
||||||
@@ -1876,6 +1929,7 @@ def main(argv):
|
|||||||
prepare_gog(sidecar, compat_data, launch_dir)
|
prepare_gog(sidecar, compat_data, launch_dir)
|
||||||
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
|
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 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 store == "rockstar":
|
||||||
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
|
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
|
||||||
if compat_data:
|
if compat_data:
|
||||||
|
|||||||
@@ -56,27 +56,38 @@ static unsigned hash_of(const char *s, int kind, int mode, int flags) {
|
|||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
|
|
||||||
static struct entry *slot(unsigned h) {
|
|
||||||
return &table[(h ^ (h >> 16)) % PATH_CACHE_SLOTS];
|
|
||||||
}
|
|
||||||
|
|
||||||
static int cacheable(const char *path) {
|
static int cacheable(const char *path) {
|
||||||
return path != NULL && path[0] == '/' && strlen(path) < PATH_CACHE_KEY_MAX && enabled();
|
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) {
|
static struct entry *find(const char *path, int kind, int mode, int flags, unsigned h) {
|
||||||
struct entry *e = slot(h);
|
long long now = now_ns();
|
||||||
|
|
||||||
if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) return NULL;
|
for (int i = 0; i < PATH_CACHE_SLOTS; i++) {
|
||||||
if (now_ns() - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) return NULL;
|
struct entry *e = &table[i];
|
||||||
return e;
|
if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) continue;
|
||||||
|
if (now - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) continue;
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) {
|
static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) {
|
||||||
struct entry *e = slot(h);
|
struct entry *e = find(path, kind, mode, flags, h);
|
||||||
|
long long now = now_ns();
|
||||||
char *copy = value != NULL ? strdup(value) : NULL;
|
char *copy = value != NULL ? strdup(value) : NULL;
|
||||||
|
|
||||||
if (value != NULL && copy == NULL) return;
|
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);
|
free(e->value);
|
||||||
e->value = copy;
|
e->value = copy;
|
||||||
e->hash = h;
|
e->hash = h;
|
||||||
@@ -84,7 +95,7 @@ static void store(const char *path, int kind, int mode, int flags, unsigned h, c
|
|||||||
e->mode = mode;
|
e->mode = mode;
|
||||||
e->flags = flags;
|
e->flags = flags;
|
||||||
memcpy(e->key, path, strlen(path) + 1);
|
memcpy(e->key, path, strlen(path) + 1);
|
||||||
e->stamp = now_ns();
|
e->stamp = now;
|
||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden")))
|
__attribute__((visibility("hidden")))
|
||||||
|
|||||||
@@ -542,7 +542,35 @@ static int zr_start(void) {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec")));
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
int prctl(int option, ...) {
|
int prctl(int option, ...) {
|
||||||
va_list ap;
|
va_list ap;
|
||||||
@@ -552,16 +580,32 @@ int prctl(int option, ...) {
|
|||||||
unsigned long arg4 = va_arg(ap, unsigned long);
|
unsigned long arg4 = va_arg(ap, unsigned long);
|
||||||
unsigned long arg5 = va_arg(ap, unsigned long);
|
unsigned long arg5 = va_arg(ap, unsigned long);
|
||||||
va_end(ap);
|
va_end(ap);
|
||||||
volatile unsigned char *dispatch = zr_dispatch;
|
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();
|
||||||
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
||||||
if (selector) *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);
|
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;
|
if (selector) *dispatch = selector;
|
||||||
if ((unsigned long)result > -4096UL) {
|
int ready = __atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE);
|
||||||
|
if (failed) {
|
||||||
errno = (int)-result;
|
errno = (int)-result;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL;
|
if (option == PR_SET_SYSCALL_USER_DISPATCH && !arg2 && ready) pthread_setspecific(zr_key, NULL);
|
||||||
return (int)result;
|
return (int)result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -569,7 +613,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
|
|||||||
(void)sig;
|
(void)sig;
|
||||||
(void)context;
|
(void)context;
|
||||||
if (info == NULL || info->si_code != SI_USER) return;
|
if (info == NULL || info->si_code != SI_USER) return;
|
||||||
volatile unsigned char *dispatch = zr_dispatch;
|
volatile unsigned char *dispatch = zr_selector();
|
||||||
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
||||||
if (selector) *dispatch = 0;
|
if (selector) *dispatch = 0;
|
||||||
int saved = errno;
|
int saved = errno;
|
||||||
@@ -598,6 +642,7 @@ static void zr_paths(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((constructor)) static void zr_init(void) {
|
__attribute__((constructor)) static void zr_init(void) {
|
||||||
|
pthread_atfork(NULL, NULL, zr_key_child);
|
||||||
zr_paths();
|
zr_paths();
|
||||||
int fd = zr_open(zr_ctl);
|
int fd = zr_open(zr_ctl);
|
||||||
if (fd < 0) return;
|
if (fd < 0) return;
|
||||||
|
|||||||
+136
-16
@@ -41,9 +41,73 @@ static char **clean_env_for_system(char *const envp[]) {
|
|||||||
return new_env;
|
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
|
// LD_PRELOAD with every absolute path that is not in the rootfs yet mapped into it. Entries are
|
||||||
// separated by ':' or ' '. free() the result.
|
// separated by ':' or ' '. free() the result.
|
||||||
static char *map_preload_paths(const char *value) {
|
static char *map_preload_paths(const char *value, int lse_emu_disabled) {
|
||||||
if (!value) return NULL;
|
if (!value) return NULL;
|
||||||
size_t cap = strlen(value) + (g_ddnatv_root_len + 1) * 16 + 16;
|
size_t cap = strlen(value) + (g_ddnatv_root_len + 1) * 16 + 16;
|
||||||
char *out = malloc(cap);
|
char *out = malloc(cap);
|
||||||
@@ -57,6 +121,13 @@ static char *map_preload_paths(const char *value) {
|
|||||||
char entry[PATH_MAX];
|
char entry[PATH_MAX];
|
||||||
memcpy(entry, p, len);
|
memcpy(entry, p, len);
|
||||||
entry[len] = '\0';
|
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];
|
char buf[PATH_MAX];
|
||||||
const char *mapped = entry[0] == '/' ? rewrite_path_in_root(entry, buf, sizeof(buf)) : entry;
|
const char *mapped = entry[0] == '/' ? rewrite_path_in_root(entry, buf, sizeof(buf)) : entry;
|
||||||
size_t mlen = strlen(mapped);
|
size_t mlen = strlen(mapped);
|
||||||
@@ -72,10 +143,13 @@ static char *map_preload_paths(const char *value) {
|
|||||||
return out;
|
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) {
|
static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) {
|
||||||
init_ddnatv_hook();
|
init_ddnatv_hook();
|
||||||
int count = 0;
|
int count = 0;
|
||||||
int has_preload = 0;
|
int has_preload = 0;
|
||||||
|
int lse_emu_disabled = 0;
|
||||||
int has_root = 0;
|
int has_root = 0;
|
||||||
int has_tunables = 0;
|
int has_tunables = 0;
|
||||||
int has_path = 0;
|
int has_path = 0;
|
||||||
@@ -105,6 +179,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
|||||||
switch (e[0]) {
|
switch (e[0]) {
|
||||||
case 'L':
|
case 'L':
|
||||||
if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; }
|
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;
|
break;
|
||||||
case 'G':
|
case 'G':
|
||||||
if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1;
|
if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1;
|
||||||
@@ -140,6 +215,12 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
|||||||
count++;
|
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 *));
|
char **new_env = calloc(count + 26, sizeof(char *));
|
||||||
int dst = 0;
|
int dst = 0;
|
||||||
// The user the program runs as (hardlinks.c): this process's, whatever the environment it passes
|
// The user the program runs as (hardlinks.c): this process's, whatever the environment it passes
|
||||||
@@ -157,23 +238,45 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
|||||||
if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) {
|
if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) {
|
||||||
continue;
|
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) {
|
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
|
// ld.so opens these itself: the guest's paths are mapped to the rootfs, and the libraries every
|
||||||
// program loads (DDNATV_PRELOAD) come first
|
// program loads (DDNATV_PRELOAD) come first
|
||||||
char *mapped = map_preload_paths(preload_value);
|
char *mapped = map_preload_paths(preload_value, lse_emu_disabled);
|
||||||
if (mapped) {
|
if (mapped) {
|
||||||
size_t chain = g_preload_host ? strlen(g_preload_host) : 0;
|
char *str = merge_preload_env(host_preload, mapped);
|
||||||
int has_chain = chain > 0 && strstr(mapped, g_preload_host) != NULL;
|
free(mapped);
|
||||||
size_t len = 11 + chain + 1 + strlen(mapped) + 1;
|
|
||||||
char *str = malloc(len);
|
|
||||||
if (str) {
|
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;
|
new_env[dst++] = str;
|
||||||
free(mapped);
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
free(mapped);
|
}
|
||||||
|
if (lse_emu_disabled) {
|
||||||
|
free_modified_env(new_env, envp);
|
||||||
|
free(filtered_host_chain);
|
||||||
|
errno = ENOMEM;
|
||||||
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// If we have an explicit real executable, drop the inherited entry to replace with the fresh target
|
// If we have an explicit real executable, drop the inherited entry to replace with the fresh target
|
||||||
@@ -211,13 +314,13 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
|||||||
const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL;
|
const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL;
|
||||||
if (hook) {
|
if (hook) {
|
||||||
size_t hook_len = strlen(hook);
|
size_t hook_len = strlen(hook);
|
||||||
size_t host_len = g_preload_host ? strlen(g_preload_host) + 1 : 0;
|
size_t host_len = host_preload ? strlen(host_preload) + 1 : 0;
|
||||||
size_t size = 11 + host_len + hook_len + 1;
|
size_t size = 11 + host_len + hook_len + 1;
|
||||||
char *str = malloc(size);
|
char *str = malloc(size);
|
||||||
if (str) {
|
if (str) {
|
||||||
size_t n = ddnatv_append(str, size, 0, "LD_PRELOAD=", 11);
|
size_t n = ddnatv_append(str, size, 0, "LD_PRELOAD=", 11);
|
||||||
if (host_len) {
|
if (host_len) {
|
||||||
n = ddnatv_append(str, size, n, g_preload_host, host_len - 1);
|
n = ddnatv_append(str, size, n, host_preload, host_len - 1);
|
||||||
n = ddnatv_append(str, size, n, ":", 1);
|
n = ddnatv_append(str, size, n, ":", 1);
|
||||||
}
|
}
|
||||||
ddnatv_append(str, size, n, hook, hook_len);
|
ddnatv_append(str, size, n, hook, hook_len);
|
||||||
@@ -225,13 +328,29 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!has_preload_list && g_preload_guest) {
|
if (!has_preload_list && g_preload_guest) {
|
||||||
size_t len = strlen(g_preload_guest);
|
char *filtered = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_guest, 1) : NULL;
|
||||||
char *str = malloc(15 + len + 1);
|
if (lse_emu_disabled && !filtered) {
|
||||||
if (str) {
|
free_modified_env(new_env, envp);
|
||||||
|
free(filtered_host_chain);
|
||||||
|
errno = ENOMEM;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
const char *guest_preload = lse_emu_disabled ? filtered : g_preload_guest;
|
||||||
|
if (guest_preload) {
|
||||||
|
size_t len = strlen(guest_preload);
|
||||||
|
char *str = malloc(15 + len + 1);
|
||||||
|
if (!str) {
|
||||||
|
free(filtered);
|
||||||
|
free_modified_env(new_env, envp);
|
||||||
|
free(filtered_host_chain);
|
||||||
|
errno = ENOMEM;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
memcpy(str, "DDNATV_PRELOAD=", 15);
|
memcpy(str, "DDNATV_PRELOAD=", 15);
|
||||||
memcpy(str + 15, g_preload_guest, len + 1);
|
memcpy(str + 15, guest_preload, len + 1);
|
||||||
new_env[dst++] = str;
|
new_env[dst++] = str;
|
||||||
}
|
}
|
||||||
|
free(filtered);
|
||||||
}
|
}
|
||||||
if (!has_root && g_ddnatv_root[0] != '\0') {
|
if (!has_root && g_ddnatv_root[0] != '\0') {
|
||||||
char *str = malloc(PATH_MAX + 16);
|
char *str = malloc(PATH_MAX + 16);
|
||||||
@@ -319,6 +438,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
|||||||
new_env[dst++] = strdup("DEBCONF_NONINTERACTIVE_SEEN=true");
|
new_env[dst++] = strdup("DEBCONF_NONINTERACTIVE_SEEN=true");
|
||||||
}
|
}
|
||||||
new_env[dst] = NULL;
|
new_env[dst] = NULL;
|
||||||
|
free(filtered_host_chain);
|
||||||
return new_env;
|
return new_env;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -483,6 +483,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path);
|
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);
|
int ret = run_execve(orig_execve, ld_so, new_argv, new_env);
|
||||||
if (errno == EACCES && chmod(ld_so, 0755) == 0) {
|
if (errno == EACCES && chmod(ld_so, 0755) == 0) {
|
||||||
// ld.so without its exec bit (an unusual restore): fix it once and retry
|
// ld.so without its exec bit (an unusual restore): fix it once and retry
|
||||||
@@ -507,6 +512,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
|||||||
if (new_argv) {
|
if (new_argv) {
|
||||||
prepare_static_program(static_elf); // ld.so is a static program itself
|
prepare_static_program(static_elf); // ld.so is a static program itself
|
||||||
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
|
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 ret = run_execve(orig_execve, target, new_argv, ddnatv_env);
|
||||||
int saved_errno = errno;
|
int saved_errno = errno;
|
||||||
free_modified_env(ddnatv_env, envp);
|
free_modified_env(ddnatv_env, envp);
|
||||||
@@ -559,6 +569,10 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
|||||||
|
|
||||||
if (static_elf) prepare_static_program(static_elf);
|
if (static_elf) prepare_static_program(static_elf);
|
||||||
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
|
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 ret = run_execve(orig_execve, target, argv, ddnatv_env);
|
||||||
int saved_errno = errno;
|
int saved_errno = errno;
|
||||||
free_modified_env(ddnatv_env, envp);
|
free_modified_env(ddnatv_env, envp);
|
||||||
@@ -1021,6 +1035,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
|
|||||||
build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path));
|
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)
|
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);
|
: clean_env_for_system(orig_ep);
|
||||||
|
if (in_root && !new_envp) return ENOMEM;
|
||||||
|
|
||||||
int ret = -1;
|
int ret = -1;
|
||||||
if (via_ld_so) {
|
if (via_ld_so) {
|
||||||
|
|||||||
@@ -110,6 +110,7 @@ def required():
|
|||||||
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
|
['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
|
paths += ['assets/linuxfs/usr/local/lib/droiddeck-xclipse/' + name for name in
|
||||||
['libVkLayer_droiddeck_xclipse.so', 'VkLayer_droiddeck_xclipse.json']]
|
['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
|
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/bin/linuxarm64/driver_droiddeck.so', 'droiddeck/bin/linuxarm64/xr-display-mode',
|
||||||
'droiddeck/driver.vrdrivermanifest',
|
'droiddeck/driver.vrdrivermanifest',
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#include <stdint.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
static volatile uint64_t value;
|
||||||
|
|
||||||
|
__attribute__((constructor))
|
||||||
|
static void use_lse_before_preload_init(void) {
|
||||||
|
uint64_t old;
|
||||||
|
uint64_t increment = 1;
|
||||||
|
__asm__ volatile("ldaddal %x1, %x0, [%2]"
|
||||||
|
: "=r"(old)
|
||||||
|
: "r"(increment), "r"(&value)
|
||||||
|
: "memory");
|
||||||
|
if (old != 0 || value != 1) _exit(91);
|
||||||
|
}
|
||||||
|
|
||||||
|
void lse_emu_early_dependency_anchor(void) {}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
void lse_emu_early_dependency_anchor(void);
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
lse_emu_early_dependency_anchor();
|
||||||
|
puts("early lse ok");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
#define _GNU_SOURCE
|
||||||
|
#include <pthread.h>
|
||||||
|
#include <signal.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <sched.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <ucontext.h>
|
||||||
|
#include <sys/wait.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#define MAX_THREADS 8
|
||||||
|
#define ROUNDS 20000
|
||||||
|
|
||||||
|
static uint64_t counter64;
|
||||||
|
static uint32_t counter32;
|
||||||
|
static uint16_t counter16;
|
||||||
|
static uint8_t counter8;
|
||||||
|
static uint64_t spin;
|
||||||
|
|
||||||
|
static void check(int ok, const char *what) {
|
||||||
|
if (!ok) {
|
||||||
|
printf("FAIL %s\n", what);
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint64_t ldaddal64(uint64_t *p, uint64_t v) {
|
||||||
|
uint64_t old;
|
||||||
|
__asm__ volatile("ldaddal %x1, %x0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
|
||||||
|
return old;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t ldadd32(uint32_t *p, uint32_t v) {
|
||||||
|
uint32_t old;
|
||||||
|
__asm__ volatile("ldadd %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
|
||||||
|
return old;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint16_t ldaddlh(uint16_t *p, uint16_t v) {
|
||||||
|
uint16_t old;
|
||||||
|
__asm__ volatile("ldaddlh %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
|
||||||
|
return old;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t ldaddab(uint8_t *p, uint8_t v) {
|
||||||
|
uint8_t old;
|
||||||
|
__asm__ volatile("ldaddab %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
|
||||||
|
return old;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint64_t casal64(uint64_t *p, uint64_t expected, uint64_t desired) {
|
||||||
|
__asm__ volatile("casal %x0, %x2, [%1]" : "+r"(expected) : "r"(p), "r"(desired) : "memory");
|
||||||
|
return expected;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void *worker(void *arg) {
|
||||||
|
(void)arg;
|
||||||
|
for (int i = 0; i < ROUNDS; i++) {
|
||||||
|
ldaddal64(&counter64, 1);
|
||||||
|
ldadd32(&counter32, 1);
|
||||||
|
ldaddlh(&counter16, 1);
|
||||||
|
ldaddab(&counter8, 1);
|
||||||
|
uint64_t seen = __atomic_load_n(&spin, __ATOMIC_RELAXED);
|
||||||
|
while (casal64(&spin, seen, seen + 1) != seen) seen = __atomic_load_n(&spin, __ATOMIC_RELAXED);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static volatile sig_atomic_t app_handler_ran;
|
||||||
|
|
||||||
|
static void app_sigill(int sig, siginfo_t *info, void *context) {
|
||||||
|
(void)sig;
|
||||||
|
(void)info;
|
||||||
|
app_handler_ran = 1;
|
||||||
|
((ucontext_t *)context)->uc_mcontext.pc += 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void simple_sigill(int sig) { (void)sig; }
|
||||||
|
|
||||||
|
static volatile sig_atomic_t once_calls, persistent_calls, once_saw_default;
|
||||||
|
static void persistent_sigill(int sig) { (void)sig; persistent_calls++; }
|
||||||
|
|
||||||
|
static void once_sigill(int sig) {
|
||||||
|
struct sigaction previous, next = {0};
|
||||||
|
once_calls++;
|
||||||
|
if (sigaction(sig, NULL, &previous) == 0 && previous.sa_handler == SIG_DFL)
|
||||||
|
once_saw_default = 1;
|
||||||
|
next.sa_handler = persistent_sigill;
|
||||||
|
sigemptyset(&next.sa_mask);
|
||||||
|
if (sigaction(sig, &next, NULL) != 0) _Exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void check_one_shot_action(void) {
|
||||||
|
struct sigaction action = {0};
|
||||||
|
action.sa_handler = once_sigill;
|
||||||
|
action.sa_flags = SA_RESETHAND;
|
||||||
|
sigemptyset(&action.sa_mask);
|
||||||
|
check(sigaction(SIGILL, &action, NULL) == 0, "install one-shot SIGILL");
|
||||||
|
check(raise(SIGILL) == 0, "deliver one-shot SIGILL");
|
||||||
|
check(once_calls == 1 && once_saw_default, "one-shot consumed before calling handler");
|
||||||
|
check(raise(SIGILL) == 0, "deliver replacement SIGILL");
|
||||||
|
check(once_calls == 1 && persistent_calls == 1, "replacement survives one-shot consumption");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void set_test_action(int variant) {
|
||||||
|
struct sigaction sa = {0};
|
||||||
|
sigemptyset(&sa.sa_mask);
|
||||||
|
if (variant == 0) {
|
||||||
|
sa.sa_handler = simple_sigill;
|
||||||
|
sigaddset(&sa.sa_mask, SIGUSR1);
|
||||||
|
} else {
|
||||||
|
sa.sa_sigaction = app_sigill;
|
||||||
|
sa.sa_flags = SA_SIGINFO;
|
||||||
|
sigaddset(&sa.sa_mask, SIGUSR2);
|
||||||
|
}
|
||||||
|
int attempt;
|
||||||
|
for (attempt = 0; attempt < 10000; attempt++) {
|
||||||
|
if (sigaction(SIGILL, &sa, NULL) == 0) return;
|
||||||
|
check(errno == ENOMEM, "unexpected action publication failure");
|
||||||
|
sched_yield();
|
||||||
|
}
|
||||||
|
check(0, "action slots stayed exhausted");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void *replace_test_action(void *unused) {
|
||||||
|
(void)unused;
|
||||||
|
for (int i = 0; i < 4096; i++) set_test_action(i & 1);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void *query_test_action(void *unused) {
|
||||||
|
(void)unused;
|
||||||
|
for (int i = 0; i < 4096; i++) {
|
||||||
|
struct sigaction sa;
|
||||||
|
check(sigaction(SIGILL, NULL, &sa) == 0, "query SIGILL action");
|
||||||
|
int a = sigismember(&sa.sa_mask, SIGUSR1);
|
||||||
|
int b = sigismember(&sa.sa_mask, SIGUSR2);
|
||||||
|
if (sa.sa_flags & SA_SIGINFO)
|
||||||
|
check(sa.sa_sigaction == app_sigill && !a && b, "coherent siginfo snapshot");
|
||||||
|
else
|
||||||
|
check(sa.sa_handler == simple_sigill && a && !b, "coherent simple snapshot");
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static unsigned int fork_readers_stop;
|
||||||
|
|
||||||
|
static void *read_during_fork(void *unused) {
|
||||||
|
(void)unused;
|
||||||
|
while (!__atomic_load_n(&fork_readers_stop, __ATOMIC_RELAXED)) {
|
||||||
|
struct sigaction out;
|
||||||
|
if (sigaction(SIGILL, NULL, &out) != 0) _Exit(4);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void check_forked_actions(void) {
|
||||||
|
struct sigaction install = {0};
|
||||||
|
install.sa_handler = simple_sigill;
|
||||||
|
sigemptyset(&install.sa_mask);
|
||||||
|
check(sigaction(SIGILL, &install, NULL) == 0, "install SIGILL before fork");
|
||||||
|
pthread_t readers[4];
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
check(pthread_create(&readers[i], NULL, read_during_fork, NULL) == 0, "start fork reader");
|
||||||
|
for (int child = 0; child < 8; child++) {
|
||||||
|
pid_t pid = fork();
|
||||||
|
check(pid >= 0, "fork SIGILL snapshot child");
|
||||||
|
if (pid == 0) {
|
||||||
|
struct sigaction inherited;
|
||||||
|
if (sigaction(SIGILL, NULL, &inherited) != 0 || inherited.sa_handler != simple_sigill) _Exit(2);
|
||||||
|
for (int i = 0; i < 1024; i++)
|
||||||
|
if (sigaction(SIGILL, &install, NULL) != 0) _Exit(3);
|
||||||
|
_Exit(0);
|
||||||
|
}
|
||||||
|
int status = 0;
|
||||||
|
check(waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0,
|
||||||
|
"child keeps action and can recycle more than 256 slots");
|
||||||
|
}
|
||||||
|
__atomic_store_n(&fork_readers_stop, 1, __ATOMIC_RELAXED);
|
||||||
|
for (int i = 0; i < 4; i++) check(pthread_join(readers[i], NULL) == 0, "join fork reader");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void check_reused_actions(void) {
|
||||||
|
set_test_action(0);
|
||||||
|
pthread_t threads[4];
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
check(pthread_create(&threads[i], NULL, i < 2 ? replace_test_action : query_test_action, NULL) == 0,
|
||||||
|
"start action worker");
|
||||||
|
for (int i = 0; i < 4; i++) check(pthread_join(threads[i], NULL) == 0, "join action worker");
|
||||||
|
}
|
||||||
|
|
||||||
|
static __attribute__((noinline)) void single_forms(void) {
|
||||||
|
uint64_t v = 0xF0;
|
||||||
|
uint64_t old;
|
||||||
|
register uint64_t ldap_result __asm__("x0");
|
||||||
|
register uintptr_t ldap_address __asm__("x1") = (uintptr_t)&v;
|
||||||
|
__asm__ volatile(".inst 0xf8bfc020" : "=r"(ldap_result) : "r"(ldap_address) : "memory");
|
||||||
|
check(ldap_result == v, "ldapr");
|
||||||
|
__asm__ volatile("ldclral %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0x30), "r"(&v) : "memory");
|
||||||
|
check(old == 0xF0 && v == 0xC0, "ldclral");
|
||||||
|
__asm__ volatile("ldeora %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0xFF), "r"(&v) : "memory");
|
||||||
|
check(old == 0xC0 && v == 0x3F, "ldeora");
|
||||||
|
__asm__ volatile("ldsetl %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0x100), "r"(&v) : "memory");
|
||||||
|
check(old == 0x3F && v == 0x13F, "ldsetl");
|
||||||
|
__asm__ volatile("swpal %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)7), "r"(&v) : "memory");
|
||||||
|
check(old == 0x13F && v == 7, "swpal");
|
||||||
|
|
||||||
|
int64_t s = -5;
|
||||||
|
int64_t sold;
|
||||||
|
__asm__ volatile("ldsmax %x1, %x0, [%2]" : "=r"(sold) : "r"((int64_t)-9), "r"(&s) : "memory");
|
||||||
|
check(sold == -5 && s == -5, "ldsmax keeps the larger value");
|
||||||
|
uint32_t u = 10;
|
||||||
|
uint32_t uold;
|
||||||
|
__asm__ volatile("ldumin %w1, %w0, [%2]" : "=r"(uold) : "r"((uint32_t)3), "r"(&u) : "memory");
|
||||||
|
check(uold == 10 && u == 3, "ldumin");
|
||||||
|
|
||||||
|
uint64_t pair[2] __attribute__((aligned(16))) = {1, 2};
|
||||||
|
register uint64_t e0 __asm__("x4") = 1, e1 __asm__("x5") = 2, d0 __asm__("x6") = 3, d1 __asm__("x7") = 4;
|
||||||
|
__asm__ volatile("caspal x4, x5, x6, x7, [%4]" : "+r"(e0), "+r"(e1) : "r"(d0), "r"(d1), "r"(pair) : "memory");
|
||||||
|
check(e0 == 1 && e1 == 2 && pair[0] == 3 && pair[1] == 4, "caspal");
|
||||||
|
register uint64_t m0 __asm__("x4") = 8, m1 __asm__("x5") = 9, n0 __asm__("x6") = 5, n1 __asm__("x7") = 6;
|
||||||
|
__asm__ volatile("caspal x4, x5, x6, x7, [%4]" : "+r"(m0), "+r"(m1) : "r"(n0), "r"(n1), "r"(pair) : "memory");
|
||||||
|
check(m0 == 3 && m1 == 4 && pair[0] == 3 && pair[1] == 4, "caspal returns the current pair on a mismatch");
|
||||||
|
|
||||||
|
uint64_t missed = casal64(&v, 99, 1);
|
||||||
|
check(missed == 7 && v == 7, "casal leaves memory alone on a mismatch");
|
||||||
|
|
||||||
|
uint32_t m = 1;
|
||||||
|
uint32_t mold;
|
||||||
|
uint64_t eq;
|
||||||
|
__asm__ volatile("cmp %w3, %w3\n\tldumax %w2, %w0, [%4]\n\tcset %1, eq"
|
||||||
|
: "=&r"(mold), "=&r"(eq) : "r"((uint32_t)5), "r"((uint32_t)0), "r"(&m) : "memory", "cc");
|
||||||
|
check(mold == 1 && m == 5 && eq == 1, "ldumax leaves the condition flags alone");
|
||||||
|
int8_t b = -3;
|
||||||
|
int8_t bold;
|
||||||
|
__asm__ volatile("cmp %w3, %w3\n\tldsmaxb %w2, %w0, [%4]\n\tcset %1, eq"
|
||||||
|
: "=&r"(bold), "=&r"(eq) : "r"((int32_t)-7), "r"((uint32_t)0), "r"(&b) : "memory", "cc");
|
||||||
|
check(bold == -3 && b == -3 && eq == 1, "ldsmaxb leaves the condition flags alone");
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
if (argc == 2 && strcmp(argv[1], "sigill-fork") == 0) {
|
||||||
|
check_forked_actions();
|
||||||
|
puts("sigill fork ok");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (argc == 2 && strcmp(argv[1], "sigill-oneshot") == 0) {
|
||||||
|
check_one_shot_action();
|
||||||
|
puts("sigill one-shot ok");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (argc == 2 && strcmp(argv[1], "sigill-actions") == 0) {
|
||||||
|
check_reused_actions();
|
||||||
|
puts("sigill actions ok");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int threads_wanted = argc > 1 ? atoi(argv[1]) : 4;
|
||||||
|
check(threads_wanted >= 1 && threads_wanted <= MAX_THREADS, "thread count");
|
||||||
|
single_forms();
|
||||||
|
single_forms();
|
||||||
|
|
||||||
|
pthread_t threads[MAX_THREADS];
|
||||||
|
int started = 0;
|
||||||
|
for (; started < threads_wanted; started++) {
|
||||||
|
int err = pthread_create(&threads[started], NULL, worker, NULL);
|
||||||
|
if (err != 0) {
|
||||||
|
for (int i = 0; i < started; i++) pthread_join(threads[i], NULL);
|
||||||
|
fprintf(stderr, "pthread_create failed: %s\n", strerror(err));
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < started; i++) {
|
||||||
|
int err = pthread_join(threads[i], NULL);
|
||||||
|
if (err != 0) {
|
||||||
|
fprintf(stderr, "pthread_join failed: %s\n", strerror(err));
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
uint64_t total = (uint64_t)threads_wanted * ROUNDS;
|
||||||
|
check(counter64 == total, "64-bit counter");
|
||||||
|
check(counter32 == (uint32_t)total, "32-bit counter");
|
||||||
|
check(counter16 == (uint16_t)total, "16-bit counter");
|
||||||
|
check(counter8 == (uint8_t)total, "8-bit counter");
|
||||||
|
check(spin == total, "casal loop");
|
||||||
|
|
||||||
|
struct sigaction sa;
|
||||||
|
memset(&sa, 0, sizeof sa);
|
||||||
|
sa.sa_sigaction = app_sigill;
|
||||||
|
sa.sa_flags = SA_SIGINFO;
|
||||||
|
sigaction(SIGILL, &sa, NULL);
|
||||||
|
__asm__ volatile("udf #0");
|
||||||
|
check(app_handler_ran, "the program's own SIGILL handler still runs");
|
||||||
|
|
||||||
|
printf("lse ok\n");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
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()
|
||||||
+240
-2
@@ -1,7 +1,9 @@
|
|||||||
|
from contextlib import contextmanager
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import subprocess
|
import subprocess
|
||||||
import signal
|
import signal
|
||||||
|
import shutil
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
@@ -146,9 +148,9 @@ class SleepHandshakeTest(unittest.TestCase):
|
|||||||
staged.write_text("wake\n")
|
staged.write_text("wake\n")
|
||||||
staged.replace(self.dir / "steam-wake")
|
staged.replace(self.dir / "steam-wake")
|
||||||
|
|
||||||
def request_native(self, token="1" * 32):
|
def request_native(self, token="1" * 32, idle=False):
|
||||||
staged = self.dir / "steam-native-sleep.tmp"
|
staged = self.dir / "steam-native-sleep.tmp"
|
||||||
staged.write_text(token + "\n")
|
staged.write_text(token + (" idle" if idle else "") + "\n")
|
||||||
staged.replace(self.dir / "steam-native-sleep")
|
staged.replace(self.dir / "steam-native-sleep")
|
||||||
return token
|
return token
|
||||||
|
|
||||||
@@ -325,6 +327,132 @@ class AsleepSteamTest(FakeAgentCase):
|
|||||||
"--steam-idle-inhibit", "off"], self.asked())
|
"--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):
|
class WithNetworkManagerTest(SleepHandshakeTest):
|
||||||
ARGS = ["--with-netmanager"]
|
ARGS = ["--with-netmanager"]
|
||||||
|
|
||||||
@@ -342,5 +470,115 @@ class WithNetworkManagerTest(SleepHandshakeTest):
|
|||||||
self.assertEqual(self.owner(NAME), self.process.pid)
|
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__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
TOOLS = Path(__file__).resolve().parents[1]
|
||||||
|
SYSROOT = Path("/usr/aarch64-linux-gnu")
|
||||||
|
|
||||||
|
|
||||||
|
def toolchain():
|
||||||
|
if not (shutil.which("aarch64-linux-gnu-gcc") and shutil.which("qemu-aarch64") and SYSROOT.is_dir()):
|
||||||
|
if os.environ.get("CI"):
|
||||||
|
raise AssertionError("CI must install gcc-aarch64-linux-gnu, libc6-dev-arm64-cross and qemu-user")
|
||||||
|
raise unittest.SkipTest("needs aarch64-linux-gnu-gcc, libc6-dev-arm64-cross and qemu-user")
|
||||||
|
|
||||||
|
|
||||||
|
class LseEmuTest(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
toolchain()
|
||||||
|
cls.tmp = tempfile.TemporaryDirectory(prefix="droiddeck-lse-")
|
||||||
|
out = Path(cls.tmp.name)
|
||||||
|
subprocess.run(["bash", str(TOOLS / "linuxfs/lse-emu/build.sh"), str(out)], check=True)
|
||||||
|
cls.library = out / "usr/local/lib/droiddeck-lse/liblse_emu.so"
|
||||||
|
cls.program = out / "lse-test"
|
||||||
|
subprocess.run(["aarch64-linux-gnu-gcc", "-O1", "-march=armv8.1-a", "-Wall", "-Wextra", "-Werror", "-pthread",
|
||||||
|
str(Path(__file__).with_name("lse_emu_test.c")), "-o", str(cls.program)], check=True)
|
||||||
|
cls.early_library = out / "liblse_emu_early.so"
|
||||||
|
subprocess.run(["aarch64-linux-gnu-gcc", "-shared", "-fPIC", "-O1", "-march=armv8.1-a", "-Wall", "-Wextra", "-Werror",
|
||||||
|
str(Path(__file__).with_name("lse_emu_early_dependency.c")), "-o", str(cls.early_library)], check=True)
|
||||||
|
cls.early_program = out / "lse-early-test"
|
||||||
|
subprocess.run(["aarch64-linux-gnu-gcc", "-O1", "-Wall", "-Wextra", "-Werror",
|
||||||
|
str(Path(__file__).with_name("lse_emu_early_main.c")), "-L", str(out),
|
||||||
|
"-Wl,--no-as-needed", "-llse_emu_early", "-Wl,-rpath,$ORIGIN", "-o", str(cls.early_program)], check=True)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def tearDownClass(cls):
|
||||||
|
cls.tmp.cleanup()
|
||||||
|
|
||||||
|
def run_on(self, cpu, *env, threads=4, program=None, program_args=None):
|
||||||
|
command = ["qemu-aarch64",
|
||||||
|
"-U", "LSE_EMU", "-U", "LSE_EMU_PATCH",
|
||||||
|
"-U", "LSE_EMU_STATS", "-U", "LSE_EMU_LOG", "-U", "LSE_EMU_SKIP",
|
||||||
|
"-cpu", cpu, "-L", str(SYSROOT)]
|
||||||
|
for item in env:
|
||||||
|
command += ["-E", item]
|
||||||
|
args = [str(program or self.program)]
|
||||||
|
if program_args is not None:
|
||||||
|
args.extend(program_args)
|
||||||
|
elif program is None:
|
||||||
|
args.append(str(threads))
|
||||||
|
return subprocess.run(command + args, capture_output=True, text=True, timeout=120)
|
||||||
|
|
||||||
|
def test_an_armv8_0_cpu_faults_without_the_emulator(self):
|
||||||
|
result = self.run_on("cortex-a57")
|
||||||
|
self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
|
||||||
|
|
||||||
|
def test_dependency_constructor_can_execute_lse_before_preload_init(self):
|
||||||
|
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", program=self.early_program)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
self.assertIn("early lse ok", result.stdout)
|
||||||
|
|
||||||
|
def test_trapping_alone_runs_every_form_on_an_armv8_0_cpu(self):
|
||||||
|
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
self.assertIn("lse ok", result.stdout)
|
||||||
|
self.assertRegex(result.stderr, r"traps=[1-9]\d* patched=0 ")
|
||||||
|
|
||||||
|
def test_concurrent_sigill_registrations_keep_recycled_snapshots_coherent(self):
|
||||||
|
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
|
||||||
|
program_args=["sigill-actions"])
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
self.assertIn("sigill actions ok", result.stdout)
|
||||||
|
|
||||||
|
def test_child_inherits_the_sigill_handler_but_not_other_threads_action_slots(self):
|
||||||
|
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
|
||||||
|
program_args=["sigill-fork"])
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
self.assertIn("sigill fork ok", result.stdout)
|
||||||
|
|
||||||
|
def test_oneshot_sigill_is_consumed_before_dispatch_and_replacement_survives(self):
|
||||||
|
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
|
||||||
|
program_args=["sigill-oneshot"])
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
self.assertIn("sigill one-shot ok", result.stdout)
|
||||||
|
|
||||||
|
def patched(self, threads):
|
||||||
|
log = Path(self.tmp.name) / f"patched-{threads}.log"
|
||||||
|
log.unlink(missing_ok=True)
|
||||||
|
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_PATCH=1",
|
||||||
|
"LSE_EMU_STATS=1", f"LSE_EMU_LOG={log}", threads=threads)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
self.assertIn("lse ok", result.stdout)
|
||||||
|
self.assertRegex(result.stderr, r"patched=[1-9]\d* failed=0",
|
||||||
|
f"{result.stderr}\nLSE log:\n{log.read_text() if log.is_file() else '<missing>'}")
|
||||||
|
self.assertTrue(log.is_file(), "patch log was not created")
|
||||||
|
instructions = [
|
||||||
|
int(match, 16)
|
||||||
|
for match in re.findall(r"patched pc=0x[0-9a-f]+ insn=0x([0-9a-f]+)", log.read_text())
|
||||||
|
]
|
||||||
|
self.assertTrue(
|
||||||
|
any((insn & 0x3FFFFC00) == 0x38BFC000 for insn in instructions),
|
||||||
|
"LDAPR did not use a generated stub",
|
||||||
|
)
|
||||||
|
self.assertFalse(
|
||||||
|
any((insn & 0xBFA07C00) == 0x08207C00 for insn in instructions),
|
||||||
|
"CASP must remain on the stack-safe trap path",
|
||||||
|
)
|
||||||
|
self.assertFalse(
|
||||||
|
any(
|
||||||
|
(insn & 0x3F200C00) == 0x38200000
|
||||||
|
and ((insn >> 15) & 1) == 0
|
||||||
|
and ((insn >> 12) & 7) >= 4
|
||||||
|
for insn in instructions
|
||||||
|
),
|
||||||
|
"min/max must remain on the stack-safe trap path",
|
||||||
|
)
|
||||||
|
self.assertNotRegex(result.stderr, r"unhandled pc=.*insn=0x(?!0000000000000000(?:\n|$))[0-9a-f]{16}")
|
||||||
|
|
||||||
|
def test_patching_runs_every_form_on_an_armv8_0_cpu(self):
|
||||||
|
self.patched(threads=1)
|
||||||
|
|
||||||
|
def test_patching_stays_atomic_across_threads(self):
|
||||||
|
self.patched(threads=4)
|
||||||
|
|
||||||
|
def test_it_stays_off_without_the_switch(self):
|
||||||
|
result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=0", "LSE_EMU_PATCH=0")
|
||||||
|
self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
|
||||||
|
|
||||||
|
def test_it_stays_off_on_a_cpu_with_lse(self):
|
||||||
|
result = self.run_on("neoverse-n1", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
self.assertNotIn("traps=", result.stderr)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
ENV = Path(__file__).resolve().parents[1] / "nativeguest/hook/env.c"
|
||||||
|
|
||||||
|
|
||||||
|
class NativeHookPreloadListTest(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls.tmp = tempfile.TemporaryDirectory()
|
||||||
|
cls.addClassCleanup(cls.tmp.cleanup)
|
||||||
|
p = Path(cls.tmp.name)
|
||||||
|
env = ENV.read_text()
|
||||||
|
helpers = env[env.index("static int preload_has_entry("):env.index("// Filter the LSE")]
|
||||||
|
(p / "probe.c").write_text("""
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
""" + helpers + """
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
(void)argc;
|
||||||
|
char *out = merge_preload_env(argv[1], argv[2]);
|
||||||
|
if (!out) return 2;
|
||||||
|
puts(out);
|
||||||
|
free(out);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
cls.probe = p / "probe"
|
||||||
|
subprocess.run([os.environ.get("CC", "cc"), "-Wall", "-Wextra", "-Werror",
|
||||||
|
str(p / "probe.c"), "-o", str(cls.probe)], check=True)
|
||||||
|
|
||||||
|
def merge(self, host, inherited):
|
||||||
|
return subprocess.check_output([self.probe, host, inherited], text=True).strip()
|
||||||
|
|
||||||
|
def test_nested_exec_keeps_the_same_multi_entry_chain(self):
|
||||||
|
host = "/root/session.so:/root/hook.so"
|
||||||
|
original = host + ":user.so"
|
||||||
|
for _ in range(3):
|
||||||
|
original = self.merge(host, original).removeprefix("LD_PRELOAD=")
|
||||||
|
self.assertEqual(host + ":user.so", original)
|
||||||
|
|
||||||
|
def test_partial_chain_keeps_host_order_and_exact_matches(self):
|
||||||
|
self.assertEqual("LD_PRELOAD=/root/session.so:/root/hook.so:/root/hook.so.extra:custom.so",
|
||||||
|
self.merge("/root/session.so:/root/hook.so",
|
||||||
|
"/root/hook.so.extra /root/session.so:custom.so"))
|
||||||
|
|
||||||
|
def test_empty_custom_chain_keeps_only_the_host_chain(self):
|
||||||
|
self.assertEqual("LD_PRELOAD=host.so", self.merge("host.so", ""))
|
||||||
@@ -667,6 +667,10 @@ def support_data(**arguments):
|
|||||||
return {'install': {'action': 'supportData', 'arguments': arguments}, 'name': 'supportData'}
|
return {'install': {'action': 'supportData', 'arguments': arguments}, 'name': 'supportData'}
|
||||||
|
|
||||||
|
|
||||||
|
def save_path(**arguments):
|
||||||
|
return {'install': {'action': 'savePath', 'arguments': arguments}, 'name': 'saveFolders'}
|
||||||
|
|
||||||
|
|
||||||
class GogSupportData(unittest.TestCase):
|
class GogSupportData(unittest.TestCase):
|
||||||
def prefix(self, root):
|
def prefix(self, root):
|
||||||
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
|
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
|
||||||
@@ -850,6 +854,117 @@ class GogSupportData(unittest.TestCase):
|
|||||||
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
|
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):
|
class GogRegistry(unittest.TestCase):
|
||||||
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
|
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
|
||||||
with tempfile.TemporaryDirectory() as root:
|
with tempfile.TemporaryDirectory() as root:
|
||||||
|
|||||||
@@ -555,6 +555,79 @@ def swap_total_kb():
|
|||||||
return 0
|
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")
|
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||||
class ZramPreloadTest(unittest.TestCase):
|
class ZramPreloadTest(unittest.TestCase):
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -773,6 +846,39 @@ class ZramPreloadTest(unittest.TestCase):
|
|||||||
self.assertEqual([1], out["trimmed"], out)
|
self.assertEqual([1], out["trimmed"], out)
|
||||||
self.assertEqual([1], out["named"], 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__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Reference in new issue
Block a user