From 527cb8586777a9086ed24f84d54c7fd06ae319fc Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 20:40:30 -0500 Subject: [PATCH] fix(fex): signal return restores syscall state; CurseForge runs headless (#3040) * fix(fex): signal return restores the interrupted syscall state A guest rt_sigreturn goes through FEX's syscall stub, which marks every static register as spilled. Returning to unchanged JIT code skipped the stub's reset, so later asynchronous signals skipped the register spill and guest handlers read stale registers. CoreCLR's GC suspension reads and redirects that context, which made x86-64 .NET programs fail with random access violations. Restore the value saved at signal entry. * fix(addons): run CurseForge headless from the addon browser, without a session - The CurseForge source starts the app in its own headless gamescope (droiddeck-headless, shared with the Battle.net Agent) instead of a hidden session: no SessionService, compositor output or ImageReader. - The helper's start keeps running until the app exits, so the app lives for as long as the addon browser holds that guest command; closing the dialog asks the app to quit, stops its process group and cancels the command, which ends the app, its gamescope and the guest. - An app the user already has open is reported busy and left alone. - Removes BackgroundSession and the CompositorHost start path it shared with SessionActivity, with their tests. * fix(addons): bind each CurseForge stop to its launch and keep the inspector URL out of logs A stop now only acts on the launch that registered it, so a late stop from a closed browser cannot end a newer launch, and the browser stops once. Command logs redact the inspector URL. The signal probe reports a sender thread that cannot start, sets ECX before the measured region and its test accepts a valid overshoot of the target count. * fix(fex): unblock the probe signal before sampling --- .../com/droiddeck/launcher/SessionActivity.kt | 37 +++- .../launcher/runtime/CurseForgeApp.kt | 101 ++++++--- .../launcher/runtime/GuestCommand.kt | 8 +- .../launcher/session/BackgroundSession.kt | 119 ----------- .../launcher/session/SessionFiles.kt | 1 + .../stores/gog/GogDownloadManager.java | 2 +- .../com/droiddeck/launcher/ui/AddonBrowser.kt | 44 +--- .../launcher/wayland/CompositorHost.kt | 48 ----- .../launcher/runtime/CurseForgeAppTest.kt | 142 ++++++++++++- docs/development/x86-64-steam-client.md | 10 + ...signal-return-restores-syscall-state.patch | 12 ++ tools/fex/probes/async-signal-context.c | 84 ++++++++ .../overlay/usr/local/bin/droiddeck-agent | 23 +- .../overlay/usr/local/bin/droiddeck-battlenet | 31 +-- .../usr/local/bin/droiddeck-curseforge | 65 ++---- .../overlay/usr/local/bin/droiddeck-headless | 24 +++ tools/tests/test_battlenet.py | 19 +- tools/tests/test_curseforge_helper.py | 200 +++++++++++------- tools/tests/test_droiddeck_agent.py | 22 ++ tools/tests/test_fex_signal_syscall_state.py | 76 +++++++ tools/tests/test_hdr_live_switch.py | 10 +- 21 files changed, 663 insertions(+), 415 deletions(-) delete mode 100644 app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt create mode 100644 tools/fex/patches/0008-signal-return-restores-syscall-state.patch create mode 100644 tools/fex/probes/async-signal-context.c create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-headless create mode 100644 tools/tests/test_fex_signal_syscall_state.py diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index dbbe76ac9..96aeb08be 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -2846,7 +2846,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!SessionState.running) { SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") } - val output = CompositorHost.prepare(this) + val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() } + FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb")) + com.droiddeck.launcher.input.VrControllers.publish(this) + + val turnip = TurnipDriver(this) + com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup") + if (!CompositorHost.isStarted) { + CompositorHost.displayChoice = SessionPrefs.androidDriver(this) + com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this)) + } + val driverId = if (CompositorHost.isStarted) null else turnip.install() val previous = SessionState.outputSize val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height()) @@ -2873,7 +2883,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pushCardboard(activeCardboard) WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path) com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path) - if (!SessionState.running) CompositorHost.logToSession(this) + if (!SessionState.running) { + val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log") + WaylandCompositor.setSessionLogFile(waylandLog) + try { + android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) + } catch (e: Exception) { + Log.w(TAG, "could not point the compositor's log at $waylandLog", e) + } + } val mode = hdrPrefMode() if (probe != null) { WaylandCompositor.nativeSetHdrDisplay( @@ -2893,8 +2911,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " ยท display ${probe.formats.ifEmpty { "SDR" }}") } - if (!SessionState.running) CompositorHost.applyHdr(this, mode) - CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit()) + if (!SessionState.running) { + val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode) + SessionState.hdr = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode)) + Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") + } + com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId") + CompositorHost.startOrAttach( + this, holder.surface, runtimeDir.path, + driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, + applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(), + ) onOutputAttached(holder) if (SessionState.running && size != previous) { Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface") diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt index 5477c8ede..adc211988 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -1,25 +1,29 @@ package com.droiddeck.launcher.runtime import android.content.Context -import com.droiddeck.launcher.agent.AgentException -import com.droiddeck.launcher.agent.AgentGuest +import com.droiddeck.launcher.stores.battlenet.BattleNetInstall import org.json.JSONArray import org.json.JSONObject import java.time.Instant +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean object CurseForgeApp { const val NAME = "CurseForge" const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml" internal const val WOW = 1 const val HELPER = "/usr/local/bin/droiddeck-curseforge" + internal const val AGENT = "/usr/local/bin/droiddeck-agent" private const val READY_MS = 120_000L private const val INSTALL_MS = 300_000L - enum class Start { READY, BUSY, NO_DISPLAY, FAILED } + enum class Start { READY, BUSY, FAILED } class Started(val state: Start, val inspector: String? = null) - private val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") class Failure(message: String, val code: String? = null) : Exception(message) { val gone get() = code == "DEVTOOLS_UNREACHABLE" @@ -31,14 +35,19 @@ object CurseForgeApp { internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") } - fun holdArgs(app: UserApps.App): List? = dir(app)?.let { listOf("hold", it) } + internal fun helperArgv(command: String, dir: String): List = listOf(HELPER, command, dir) + + internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List = + listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression) + + internal fun lastJson(lines: List): JSONObject? = + lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() } internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) } internal fun startState(exitCode: Int): Start = when (exitCode) { 0 -> Start.READY 3 -> Start.BUSY - 4 -> Start.NO_DISPLAY else -> Start.FAILED } @@ -137,47 +146,75 @@ object CurseForgeApp { return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet() } - private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? { - val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true) - .put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0) - return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true)) + internal var guest: (Context, List, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine -> + GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true, + cancelled = cancelled, redact = INSPECTOR, onLine = onLine) } - private fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? { - val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0) - return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull() + private val holds = ConcurrentHashMap() + + private fun lines(context: Context, argv: List): List { + val out = ArrayList() + guest(context, argv, null) { out += it } + return out } - fun start(context: Context, app: UserApps.App): Started { + private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? = + unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer")) + + private sealed class Launch { + class Url(val inspector: String) : Launch() + class Exit(val code: Int) : Launch() + } + + private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? { + val first = LinkedBlockingQueue() + Thread({ + val code = runCatching { + guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } } + }.getOrDefault(-1) + first.offer(Launch.Exit(code)) + }, "curseforge-headless").apply { isDaemon = true; start() } + return first.poll(READY_MS, TimeUnit.MILLISECONDS) + } + + fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started { val dir = dir(app) ?: return Started(Start.FAILED) - val answer = helper(context, "start", dir, 90_000) - if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) { - stop(context, app, null) - return Started(Start.FAILED) + if (hold.get()) return Started(Start.FAILED) + holds.put(dir, hold)?.takeIf { it !== hold }?.let { + it.set(true) + runCatching { lines(context, helperArgv("stop", dir)) } } - val state = startState(answer.optInt("exitCode", -1)) - if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state) - val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty()) - if (state != Start.READY || inspector == null) { - stop(context, app, null) + val inspector = when (val first = launch(context, dir, hold)) { + is Launch.Url -> first.inspector + is Launch.Exit -> if (startState(first.code) == Start.BUSY) { + holds.remove(dir, hold) + return Started(Start.BUSY) + } else null + null -> null + } + if (inspector == null) { + stop(context, app, null, hold) return Started(Start.FAILED) } val deadline = System.currentTimeMillis() + READY_MS - while (System.currentTimeMillis() < deadline) { - val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) } - if (ready.isSuccess) return Started(Start.READY, inspector) - val error = ready.exceptionOrNull() - if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break + while (System.currentTimeMillis() < deadline && !hold.get()) { + if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector) Thread.sleep(1_000) } - stop(context, app, inspector) + stop(context, app, inspector, hold) return Started(Start.FAILED) } - fun stop(context: Context, app: UserApps.App, inspector: String?) { + fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) { val dir = dir(app) ?: return + if (holds[dir] !== hold) { + hold.set(true) + return + } if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") } - helper(context, "stop", dir, 30_000) + hold.set(true) + if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) } } private fun connect(context: Context, inspector: String) { @@ -207,7 +244,7 @@ object CurseForgeApp { while (System.currentTimeMillis() < deadline) { val listed = runCatching { installed(context, inspector, guid) } val error = listed.exceptionOrNull() - if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error + if (error is Failure && error.gone) throw error if (projectId in listed.getOrDefault(emptySet())) return true Thread.sleep(1_000) } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt index 95ea5b13c..2c5fbad51 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt @@ -14,20 +14,22 @@ import java.util.concurrent.atomic.AtomicBoolean object GuestCommand { fun run(context: Context, argv: List, fakeRoot: Boolean = false, logName: String? = null, linkDir: File? = null, extraBinds: List? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null, - onLine: (String) -> Unit): Int { + redact: Regex? = null, onLine: (String) -> Unit): Int { val log = logName?.let { try { File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter() } catch (e: Exception) { null } } - log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}") + log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}") try { - return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) } + return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) } } finally { log?.close() } } + internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "") ?: text + private fun runLogged(context: Context, argv: List, fakeRoot: Boolean, linkDir: File?, extraBinds: List?, fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int { val root = LinuxRuntime.rootDir(context) diff --git a/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt b/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt deleted file mode 100644 index 50c60f574..000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt +++ /dev/null @@ -1,119 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.Context -import android.graphics.PixelFormat -import android.media.ImageReader -import android.os.Handler -import android.os.Looper -import android.util.Log -import com.droiddeck.launcher.agent.AgentGuest -import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller -import com.droiddeck.launcher.storage.StorageState -import com.droiddeck.launcher.wayland.CompositorHost -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicBoolean - -object BackgroundSession { - private const val TAG = "BackgroundSession" - private const val WIDTH = 1280 - private const val HEIGHT = 720 - private const val REFRESH_HZ = 60f - private const val BEGIN_MS = 30_000L - private const val AGENT_MS = 120_000L - private const val STOP_MS = 30_000L - private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED) - private val main by lazy { Handler(Looper.getMainLooper()) } - private var reader: ImageReader? = null - - fun start(context: Context, program: String, args: List): String? { - val app = context.applicationContext - val claim = AtomicBoolean(false) - val began = CountDownLatch(1) - var own: String? = null - main.post { - if (claim.compareAndSet(false, true)) { - own = runCatching { begin(app, program, args) } - .onFailure { Log.w(TAG, "could not start a hidden session for $program", it) } - .getOrNull() - } - began.countDown() - } - if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null - began.await() - val session = own ?: return null - val deadline = System.currentTimeMillis() + AGENT_MS - val settle = System.currentTimeMillis() + 5_000 - while (System.currentTimeMillis() < deadline) { - if (SessionState.sessionId != session) return null - if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session - if (SessionState.phase == SessionPhase.FAILED) break - if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break - Thread.sleep(250) - } - stop(app, session) - return null - } - - fun stop(context: Context, session: String) { - val app = context.applicationContext - if (SessionState.sessionId != session) return - main.post { if (SessionState.sessionId == session) SessionService.stop(app) } - val deadline = System.currentTimeMillis() + STOP_MS - while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250) - if (!live(session)) { - main.post { release() } - return - } - Thread { - while (live(session)) Thread.sleep(1_000) - main.post { release() } - }.start() - } - - private fun live(session: String) = - SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended) - - private fun begin(context: Context, program: String, args: List): String? { - if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() || - SessionState.installing != null || StorageState.cleaning) return null - release() - SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program)) - val session = SessionState.sessionId ?: return null - SessionState.stopRequested = false - SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") - var requested = false - try { - val output = CompositorHost.prepare(context) - val size = WIDTH to HEIGHT - SessionState.outputSize = size - SessionState.refreshHz = REFRESH_HZ - CompositorHost.logToSession(context) - CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN)) - val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2) - reader = offscreen - offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main) - CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0) - CompositorHost.detach(offscreen.surface) - SessionEvents.record("compositor.started") - SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting") - requested = true - SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray()) - return session - } catch (e: Exception) { - if (requested) SessionService.stop(context) - if (!SessionState.running) { - reader?.close() - reader = null - SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString())) - } - throw e - } - } - - private fun release() { - if (SessionState.running) return - reader?.close() - reader = null - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index afb8fcb8d..34d96eab4 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -181,6 +181,7 @@ object SessionFiles { "usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run", "usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec", "usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge", + "usr/local/bin/droiddeck-headless" to "usr/local/bin/droiddeck-headless", "usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run", "usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open", "usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run", diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java index a09629bc4..8864bdaf7 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java @@ -330,7 +330,7 @@ public final class GogDownloadManager { rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList( "/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", guestDir, guestSetup), - false, "gog-innoextract", null, null, false, cancelled, + false, "gog-innoextract", null, null, false, cancelled, null, line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; }); } catch (Exception e) { throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName()); diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index b8fa6c627..514677364 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -67,14 +67,13 @@ import com.droiddeck.launcher.runtime.CurseForgeApp import com.droiddeck.launcher.runtime.UserApps import com.droiddeck.launcher.runtime.WowAddonCatalog import com.droiddeck.launcher.runtime.WowAddons -import com.droiddeck.launcher.session.BackgroundSession -import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File +import java.util.concurrent.atomic.AtomicBoolean private class AddonResults { val items = mutableStateListOf() @@ -95,10 +94,7 @@ private class CurseLink(val app: UserApps.App) { private val lock = Object() @Volatile private var closed = false - private var held = false - private var ownSession: String? = null - private var started = false - @Volatile private var launching = false + @Volatile private var hold: AtomicBoolean? = null @Volatile private var inspector: String? = null private val guids = HashMap() @@ -119,29 +115,13 @@ private class CurseLink(val app: UserApps.App) { private fun link(context: Context, target: WowAddons.Target): Linked { if (closed) throw CurseState() - if (!SessionState.running) { - started = false - launching = false - held = false - ownSession = null - inspector = null - guids.clear() - val args = CurseForgeApp.holdArgs(app) ?: throw CurseState() - ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState() - } - if (closed) throw CurseState() - if (!held) { - held = true - SessionService.holdForSignIn(context, true) - } - val awake = System.currentTimeMillis() + 30_000 - while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250) val url = inspector ?: run { - launching = true - val done = CurseForgeApp.start(context, app) + val launch = AtomicBoolean(false) + hold = launch + if (closed) throw CurseState() + val done = CurseForgeApp.start(context, app, launch) when (done.state) { CurseForgeApp.Start.READY -> { - started = true inspector = done.inspector done.inspector ?: throw CurseState() } @@ -160,17 +140,11 @@ private class CurseLink(val app: UserApps.App) { fun close(context: Context) { closed = true + val launch = hold ?: return Thread { - if (launching) CurseForgeApp.stop(context, app, inspector) + CurseForgeApp.stop(context, app, inspector, launch) synchronized(lock) { - if (started) CurseForgeApp.stop(context, app, inspector) - val owned = ownSession - if (owned != null) BackgroundSession.stop(context, owned) - else if (held) SessionService.holdForSignIn(context, false) - started = false - launching = false - ownSession = null - held = false + hold = null inspector = null } }.start() diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 89ae2b1cb..8d43d09c7 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -10,8 +10,6 @@ import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionState object CompositorHost { - private const val TAG = "DroidDeck" - @Volatile private var started = false @@ -57,52 +55,6 @@ object CompositorHost { } } - class Output internal constructor( - internal val runtimeDir: java.io.File, - internal val turnip: com.droiddeck.launcher.gpu.TurnipDriver, - internal val driverId: String?, - ) - - fun prepare(context: android.content.Context): Output { - val runtimeDir = java.io.File(context.filesDir, ".wayland-rt").apply { mkdirs() } - com.droiddeck.launcher.core.FileUtils.copyAsset(context, "wayland/keymap.xkb", java.io.File(runtimeDir, "keymap.xkb")) - com.droiddeck.launcher.input.VrControllers.publish(context) - val turnip = com.droiddeck.launcher.gpu.TurnipDriver(context) - com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "surface.driver-setup") - if (!started) { - displayChoice = SessionPrefs.androidDriver(context) - com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(context, SessionPrefs.androidDriver(context)) - } - return Output(runtimeDir, turnip, if (started) null else turnip.install()) - } - - fun logToSession(context: android.content.Context) { - val waylandLog = java.io.File(com.droiddeck.launcher.session.SessionPaths.beginOrCurrent(context), "wayland.log") - WaylandCompositor.setSessionLogFile(waylandLog) - try { - android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) - } catch (e: Exception) { - android.util.Log.w(TAG, "could not point the compositor's log at $waylandLog", e) - } - } - - fun applyHdr(context: android.content.Context, mode: String) { - val on = SessionState.hdrCapable && SessionPrefs.hdr(context, mode) - SessionState.hdr = on - WaylandCompositor.nativeSetHdrOutput(on) - WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode)) - android.util.Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") - } - - fun start(context: android.content.Context, output: Output, surface: Surface, size: Pair, refreshHz: Float, fpsLimit: Int): Boolean { - com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "compositor.start driver=${output.driverId}") - return startOrAttach( - context, surface, output.runtimeDir.path, - output.driverId?.let { output.turnip.driverPath(it) }, output.driverId?.let { output.turnip.libraryName(it) }, - context.applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz, fpsLimit, - ) - } - @Synchronized fun startOrAttach( context: android.content.Context, diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt index 98cdd9376..e3cb7ef50 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -8,6 +8,7 @@ import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue +import org.junit.After import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -21,6 +22,47 @@ import java.io.File class CurseForgeAppTest { @get:Rule val temp = TemporaryFolder() + private val original = CurseForgeApp.guest + private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED) + + @After + fun restoreGuest() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + launches.forEach { CurseForgeApp.stop(context, app, null, it) } + holder.get()?.set(true) + CurseForgeApp.guest = original + } + + private val launches = mutableListOf() + + private fun launch(): java.util.concurrent.atomic.AtomicBoolean = java.util.concurrent.atomic.AtomicBoolean(false).also { launches += it } + + private val holder = java.util.concurrent.atomic.AtomicReference() + private val released = java.util.concurrent.CountDownLatch(1) + + private fun fakeGuest(startExit: Int, ready: Boolean = true): MutableList> { + val calls = java.util.Collections.synchronizedList(mutableListOf>()) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + calls += argv + when { + argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> { + if (startExit == 0) { + holder.set(cancelled) + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + released.countDown() + } else onLine("busy") + startExit + } + argv[0] == CurseForgeApp.HELPER -> 0 + ready -> { onLine(JSONObject().put("ok", true).put("value", """{"value":true}""").toString()); 0 } + else -> { onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "no")).toString()); 0 } + } + } + return calls + } + private val search = """{"success":true,"injectedCount":0, "pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150}, "mods":[ @@ -129,7 +171,7 @@ class CurseForgeAppTest { assertEquals(emptySet(), CurseForgeApp.projectIds(JSONObject())) assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0)) assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3)) - assertEquals(CurseForgeApp.Start.NO_DISPLAY, CurseForgeApp.startState(4)) + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(4)) assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5)) } @@ -158,4 +200,102 @@ class CurseForgeAppTest { assertEquals(File(root, target.flavor), WowAddons.flavorDir(target)) } } + + @Test + fun theAppStartsInTheGuestWithoutASessionAndIsAskedThroughItsInspector() { + val calls = fakeGuest(0) + val started = CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()) + assertEquals(CurseForgeApp.Start.READY, started.state) + assertEquals(url, started.inspector) + assertEquals(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge"), calls.first()) + val probe = calls[1] + assertEquals(listOf(CurseForgeApp.AGENT, "--cdp-inspector", url), probe.take(3)) + assertEquals("10.0", probe[3]) + assertTrue(probe[4].contains("InstalledProjectsAppService")) + } + + @Test + fun theLaunchLivesUntilItIsStopped() { + fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val hold = launch() + assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.start(context, app, hold).state) + assertEquals(false, holder.get()?.get()) + assertEquals(1L, released.count) + CurseForgeApp.stop(context, app, url, hold) + assertTrue(released.await(5, java.util.concurrent.TimeUnit.SECONDS)) + } + + @Test + fun anAppThatIsAlreadyOpenIsNeitherUsedNorStopped() { + val calls = fakeGuest(3) + assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()).state) + assertEquals(listOf(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge")), calls) + } + + @Test + fun stoppingAsksTheAppToQuitThenStopsItsHeadlessLaunchOnce() { + val calls = fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val hold = launch() + CurseForgeApp.start(context, app, hold) + calls.clear() + CurseForgeApp.stop(context, app, url, hold) + assertEquals(CurseForgeApp.AGENT, calls[0][0]) + assertTrue(calls[0][4].contains("shutdown")) + assertEquals(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge"), calls[1]) + assertTrue(hold.get()) + calls.clear() + CurseForgeApp.stop(context, app, url, hold) + assertTrue(calls.isEmpty()) + } + + @Test + fun aLateStopLeavesTheNewerLaunchRunning() { + val calls = fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val old = launch() + val newer = launch() + CurseForgeApp.start(context, app, old) + CurseForgeApp.start(context, app, newer) + assertTrue(old.get()) + calls.clear() + CurseForgeApp.stop(context, app, url, old) + assertTrue(calls.isEmpty()) + assertEquals(false, newer.get()) + CurseForgeApp.stop(context, app, null, newer) + assertEquals(listOf(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge")), calls) + } + + @Test + fun aStoppedLaunchNeverStarts() { + val calls = fakeGuest(0) + val hold = launch().apply { set(true) } + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, hold).state) + assertTrue(calls.isEmpty()) + } + + @Test + fun anAppWithoutADirectoryIsNeverLaunched() { + val calls = fakeGuest(0) + val bare = UserApps.App("appimage:d", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED) + val hold = launch() + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), bare, hold).state) + CurseForgeApp.stop(org.robolectric.RuntimeEnvironment.getApplication(), bare, url, hold) + assertTrue(calls.isEmpty()) + } + + @Test + fun theInspectorUrlIsRedactedFromCommandLogs() { + val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ") + assertTrue(line.contains(url)) + assertTrue(!GuestCommand.redacted(line, CurseForgeApp.INSPECTOR).contains("127.0.0.1")) + assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url)) + } + + @Test + fun theAgentAnswerIsTheLastJsonLine() { + assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v")) + assertNull(CurseForgeApp.lastJson(listOf("noise"))) + } } diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 87b92e5ac..3d7876c2f 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -219,6 +219,16 @@ alone would then read as an installed client. - `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to `install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure. The guest libraries are external projects in the default build, which `install` already follows. + - `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's + syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler + left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and + the mark stayed. Every asynchronous signal after that (until the next system call ended) skipped the + register spill and handed the guest handler stale registers from the last system call: only RIP was + right. CoreCLR suspends threads for the GC with such signals and reads or redirects the interrupted + context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran + next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in + 2000 carried the interrupted registers, natively all of them. The return now restores the value saved + when the signal arrived. - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch new file mode 100644 index 000000000..6a8e14e1d --- /dev/null +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -0,0 +1,12 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index b4c7b24..e6777aa 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -262,6 +262,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + + if (Context->UContextLocation) { + auto Frame = Thread->CurrentFrame; ++ Frame->InSyscallInfo = Context->InSyscallInfo; + + if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { + // XXX: Unsupported since it needs state reconstruction diff --git a/tools/fex/probes/async-signal-context.c b/tools/fex/probes/async-signal-context.c new file mode 100644 index 000000000..9c2c262a5 --- /dev/null +++ b/tools/fex/probes/async-signal-context.c @@ -0,0 +1,84 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +volatile long base; +static volatile long hits, matched, stale, stop; +static long want; +static pid_t target; +extern char probe_loop_start[], probe_loop_end[]; + +static void handler(int sig, siginfo_t *info, void *context) { + greg_t *g = ((ucontext_t *)context)->uc_mcontext.gregs; + (void)sig; + (void)info; + if (g[REG_RIP] >= (greg_t)probe_loop_start && g[REG_RIP] < (greg_t)probe_loop_end) { + long below = base - g[REG_RSP]; + if (g[REG_RBX] == 0x1111111111111111L && g[REG_R12] == 0x2222222222222222L && g[REG_R13] == 0x3333333333333333L && + g[REG_R14] == 0x4444444444444444L && g[REG_R15] == 0x5555555555555555L && (unsigned long)g[REG_RCX] <= 4096 && + (below == 0 || below == 8)) + matched++; + else + stale++; + } + hits++; +} + +static void *sender(void *arg) { + (void)arg; + while (!stop) { + syscall(SYS_tgkill, getpid(), target, SIGUSR1); + usleep(50); + } + return NULL; +} + +int main(int argc, char **argv) { + struct sigaction action = {0}; + pthread_t thread; + want = argc > 1 ? atol(argv[1]) : 2000; + action.sa_sigaction = handler; + action.sa_flags = SA_SIGINFO | SA_RESTART; + sigaction(SIGUSR1, &action, NULL); + sigset_t usr1; + sigemptyset(&usr1); + sigaddset(&usr1, SIGUSR1); + pthread_sigmask(SIG_UNBLOCK, &usr1, NULL); + target = syscall(SYS_gettid); + if (pthread_create(&thread, NULL, sender, NULL) != 0) { + fprintf(stderr, "cannot start the signal sender\n"); + return 2; + } + while (matched + stale < want) { + __asm__ volatile("mov $0x1111111111111111, %%rbx\n" + "mov $0x2222222222222222, %%r12\n" + "mov $0x3333333333333333, %%r13\n" + "mov $0x4444444444444444, %%r14\n" + "mov $0x5555555555555555, %%r15\n" + "mov %%rsp, base(%%rip)\n" + "mov $4096, %%ecx\n" + ".globl probe_loop_start\n" + "probe_loop_start:\n" + "push %%rax\n" + "1: dec %%ecx\n" + "jnz 1b\n" + "pop %%rax\n" + "mov $4096, %%ecx\n" + "2: dec %%ecx\n" + "jnz 2b\n" + ".globl probe_loop_end\n" + "probe_loop_end:\n" + : + : + : "rbx", "rcx", "r12", "r13", "r14", "r15", "memory"); + } + stop = 1; + pthread_join(thread, NULL); + printf("signals=%ld matched=%ld stale=%ld\n", hits, matched, stale); + return stale ? 1 : 0; +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 4edfc22cb..df0f4cedf 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -1206,6 +1206,15 @@ def handle(agent_dir, req): raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind) +def reply(agent_dir, req): + try: + return dict(handle(agent_dir, req), ok=True) + except AgentError as e: + return {"ok": False, "error": {"code": e.code, "message": str(e)}} + except Exception as e: + return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}} + + def answer(agent_dir, path): rid = path.stem try: @@ -1225,12 +1234,7 @@ def answer(agent_dir, path): except OSError: pass if req is not None: - try: - result = dict(handle(agent_dir, req), ok=True) - except AgentError as e: - result = {"ok": False, "error": {"code": e.code, "message": str(e)}} - except Exception as e: - result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}} + result = reply(agent_dir, req) write_json(agent_dir / "resp" / (rid + ".json"), result) @@ -1257,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1): def main(argv): + if argv and argv[0] == "--cdp-inspector": + if len(argv) != 4: + print("usage: droiddeck-agent --cdp-inspector ", file=sys.stderr) + return 2 + print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2], + "expression": argv[3], "commandLineApi": True}))) + return 0 base = os.environ.get("DD_LAUNCH_DIR") if not base: print("DD_LAUNCH_DIR is not set", file=sys.stderr) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 0cddb3fb4..d24ead6eb 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -79,8 +79,7 @@ AGENT_START = 90 AGENT_HELPER = "agent.js" AGENT_RUNTIME = "agent-runtime" AGENT_LOG = "agent.log" -AGENT_LOG_LIMIT = 4 << 20 -HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"] +HEADLESS = "/usr/local/bin/droiddeck-headless" PRODUCT = re.compile(r"[a-z0-9_]{1,32}") LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}") COUNTRY = re.compile(r"[A-Z]{3}") @@ -1416,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country=" windows = install_path(root, folder) emit("STATE", "starting") base = os.path.join(CACHE, "agent-%s" % uid) + os.makedirs(CACHE, exist_ok=True) for suffix in (".json", ".game", ".form", ".error"): try: os.unlink(base + suffix) except OSError: pass - runtime = os.path.join(CACHE, AGENT_RUNTIME) - os.makedirs(runtime, mode=0o700, exist_ok=True) env = agent_env() - for name in ("DISPLAY", "WAYLAND_DISPLAY"): - env.pop(name, None) - env["XDG_RUNTIME_DIR"] = runtime - cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", - windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] + cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--", + os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", + windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd))) - output = os.path.join(CACHE, AGENT_LOG) - try: - if os.path.getsize(output) > AGENT_LOG_LIMIT: - os.replace(output, output + ".1") - except OSError: - pass before = {pid for pid, _ in wine_processes(pfx)} - with open(output, "ab") as log: - try: - child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env) - except OSError as error: - emit("ERROR", "stopped gamescope: %s" % error) - return 1 + try: + child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) + except OSError as error: + emit("ERROR", "stopped gamescope: %s" % error) + return 1 seen = None mark = None moved = time.monotonic() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge index a329c1586..de334b745 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge @@ -5,39 +5,17 @@ self=${BASH_SOURCE[0]} proc=${DD_PROC:-/proc} state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge} runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run} +headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless} wait_s=${DD_CURSEFORGE_WAIT:-60} cmd=${1:-} dir=${2:-} flag=--inspect-publish-uid=stderr -case $cmd in start|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display " >&2; exit 2 ;; esac -if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then +case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop " >&2; exit 2 ;; esac +if [ ! -d "$dir/app" ]; then echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2 exit 2 fi -x_display() { - if [ -n "${DISPLAY:-}" ]; then - printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}" - return 0 - fi - local p name a prev display auth - for p in "$proc"/[0-9]*; do - name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1) - case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac - display= auth= prev= - while IFS= read -r a; do - case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac - [ "$prev" = -auth ] && auth=$a - prev=$a - done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline") - if [ -n "$display" ]; then - printf '%s\n%s\n' "$display" "$auth" - return 0 - fi - done - return 1 -} - running() { local p for p in "$proc"/[0-9]*; do @@ -79,7 +57,7 @@ inspector() { } start() { - local shown display auth url pid + local url pid child= lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; } if ! ours >/dev/null; then if tracked >/dev/null || running; then @@ -87,18 +65,18 @@ start() { echo busy return 3 fi - shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; } - display=$(sed -n 1p <<<"$shown") - auth=$(sed -n 2p <<<"$shown") - env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \ - setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" "$state/log" 2>&1 9>&- & + mv -f "$state/log" "$state/log.1" 2>/dev/null + env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \ + "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" /dev/null 2>&1 9>&- & pid=$! + child=$pid printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid" fi exec 9>&- for _ in $(seq 1 $((wait_s * 2))); do if url=$(inspector); then echo "$url" + hold "$child" return 0 fi ours >/dev/null || break @@ -108,6 +86,18 @@ start() { return 5 } +hold() { + local pid + if [ -n "$1" ]; then + wait "$1" + return 0 + fi + pid=$(ours) || return 0 + while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do + sleep 1 + done +} + stop() { local pid p lock || return 1 @@ -118,6 +108,7 @@ stop() { sleep 0.5 done kill -KILL -- "-$pid" 2>/dev/null + kill -KILL "$pid" 2>/dev/null for p in "$proc"/[0-9]*; do tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null done @@ -127,22 +118,10 @@ stop() { } case $cmd in - display) - x_display || exit 4 - ;; start) start exit $? ;; - hold) - start >/dev/null || exit $? - trap 'stop; exit 0' TERM INT HUP - while ours >/dev/null; do - sleep 1 & - wait $! - done - exit 0 - ;; stop) stop exit 0 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless b/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless new file mode 100755 index 000000000..c8bc6cee0 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless @@ -0,0 +1,24 @@ +#!/bin/bash +set -u +runtime=${1:-} +shift +log= +if [ "${1:-}" = --log ]; then + log=${2:-} + shift 2 +fi +if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then + echo "usage: droiddeck-headless [--log ] -- [args...]" >&2 + exit 2 +fi +shift +umask 077 +mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1 +if [ -n "$log" ]; then + size=$(stat -c %s "$log" 2>/dev/null || echo 0) + [ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1" + exec >>"$log" 2>&1 +fi +unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY +export XDG_RUNTIME_DIR=$runtime +exec gamescope --backend headless -w 640 -h 480 -- "$@" diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index 52ba9e8d4..b7bbafa3b 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -1413,7 +1413,8 @@ class AgentJobTest(Harness): self.assertEqual(code, 0) self.assertTrue(os.path.isdir(folder)) cmd = self.started[0] - self.assertEqual(cmd[:6], ["gamescope", "--backend", "headless", "-w", "640", "-h"]) + self.assertEqual(cmd[:4], ["/usr/local/bin/droiddeck-headless", str(self.tmp / "cache" / "agent-runtime"), "--log", + str(self.tmp / "cache" / "agent.log")]) self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"]) self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"]) self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"}) @@ -1641,16 +1642,6 @@ class AgentJobTest(Harness): path.write_bytes(json.dumps({"state": 1004}).encode("utf-8")) self.assertEqual(BNET["read_status"](str(path)), {"state": 1004}) - def test_a_large_agent_log_is_rotated_before_a_job(self): - self.install() - os.makedirs(self.tmp / "cache") - log = self.tmp / "cache" / "agent.log" - log.write_bytes(b"x" * (BNET["AGENT_LOG_LIMIT"] + 1)) - self.files = {".game": json.dumps({"installed": False})} - BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) - self.assertEqual((self.tmp / "cache" / "agent.log.1").stat().st_size, BNET["AGENT_LOG_LIMIT"] + 1) - self.assertEqual(log.stat().st_size, 0) - def test_it_queues_behind_another_battle_net_job(self): self.install() self.files = {".game": json.dumps({"installed": False})} @@ -1681,13 +1672,11 @@ class AgentJobTest(Harness): self.assertEqual(self.lines[0], ("STATE", "waiting")) self.assertEqual(self.lines[1], ("STATE", "starting")) - def test_gamescope_gets_no_display_but_the_agent_keeps_the_one_gamescope_gives_it(self): + def test_the_agent_keeps_the_display_gamescope_gives_it_and_launches_through_the_shared_headless_helper(self): self.install() - os.environ.update(DISPLAY=":5", WAYLAND_DISPLAY="wayland-1") self.files = {".game": json.dumps({"installed": False})} BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) - self.assertNotIn("DISPLAY", self.envs[0]) - self.assertNotIn("WAYLAND_DISPLAY", self.envs[0]) + self.assertEqual(self.started[0][0], BNET["HEADLESS"]) self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0") os.environ["DISPLAY"] = ":0" self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0") diff --git a/tools/tests/test_curseforge_helper.py b/tools/tests/test_curseforge_helper.py index 4dd25790d..e65388405 100644 --- a/tools/tests/test_curseforge_helper.py +++ b/tools/tests/test_curseforge_helper.py @@ -1,17 +1,67 @@ import os import shlex import shutil -import signal import subprocess import tempfile import time import unittest from pathlib import Path -HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-curseforge" +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +HELPER = BIN / "droiddeck-curseforge" +HEADLESS = BIN / "droiddeck-headless" URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" +class HeadlessTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.bin = self.tmp / "bin" + self.bin.mkdir() + self.seen = self.tmp / "seen" + gamescope = self.bin / "gamescope" + gamescope.write_text( + "#!/bin/bash\n" + "printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"GAMESCOPE=${GAMESCOPE_WAYLAND_DISPLAY-}\" " + "\"XAUTH=${XAUTHORITY-}\" \"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n" + "echo logged-by-gamescope\n" % shlex.quote(str(self.seen))) + gamescope.chmod(0o755) + + def env(self, extra=None): + base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", + GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", XAUTHORITY="/run/xauth") + base.update(extra or {}) + return base + + def run_headless(self, *args, env=None): + return subprocess.run(["bash", str(HEADLESS), *args], env=self.env(env), capture_output=True, text=True, timeout=30) + + def test_it_runs_the_command_in_headless_gamescope_with_a_private_runtime_and_no_session_display(self): + runtime = self.tmp / "runtime" + out = self.run_headless(str(runtime), "--", "prog", "arg one") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual(["DISPLAY=", "WAYLAND=", "GAMESCOPE=", "XAUTH=", "RUNTIME=%s" % runtime, "--backend", "headless", + "-w", "640", "-h", "480", "--", "prog", "arg one"], self.seen.read_text().splitlines()) + self.assertEqual(0o700, runtime.stat().st_mode & 0o777) + + def test_output_goes_to_the_log_which_rotates_when_large(self): + log = self.tmp / "agent.log" + log.write_bytes(b"x" * 100) + self.assertEqual(0, self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog").returncode) + self.assertTrue(log.read_text().endswith("logged-by-gamescope\n")) + self.assertEqual(100, log.stat().st_size - len("logged-by-gamescope\n")) + self.assertFalse((self.tmp / "agent.log.1").exists()) + self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog", env={"DD_HEADLESS_LOG_LIMIT": "50"}) + self.assertEqual(100 + len("logged-by-gamescope\n"), (self.tmp / "agent.log.1").stat().st_size) + self.assertEqual("logged-by-gamescope\n", log.read_text()) + + def test_bad_arguments_are_refused(self): + self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "prog").returncode) + self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "--").returncode) + self.assertEqual(2, self.run_headless().returncode) + + class CurseForgeHelperTest(unittest.TestCase): def setUp(self): self.tmp = Path(tempfile.mkdtemp()) @@ -21,18 +71,23 @@ class CurseForgeHelperTest(unittest.TestCase): self.dir = self.tmp / "curseforge" (self.dir / "app").mkdir(parents=True) self.state = self.tmp / "state" + self.bin = self.tmp / "bin" + self.bin.mkdir() self.runner = self.tmp / "runner" self.seen = self.tmp / "seen" self.runner.write_text( "#!/bin/bash\n" - "printf '%%s\\n' \"DISPLAY=$DISPLAY\" \"XAUTHORITY=${XAUTHORITY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" " - "\"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" \"$@\" > %s\n" + "printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" " + "\"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n" "mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" - "echo 'Debugger listening on %s'\n" - "echo 'For help, see: https://nodejs.org/en/docs/inspector'\n" - "exec sleep 60\n" + "echo 'Debugger listening on %s' >&2\n" + "echo 'For help, see: https://nodejs.org/en/docs/inspector' >&2\n" + "sleep 60\n" % (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL)) self.runner.chmod(0o755) + gamescope = self.bin / "gamescope" + gamescope.write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@"\n') + gamescope.chmod(0o755) def fake(self, pid, *argv): d = self.proc / str(pid) @@ -40,15 +95,27 @@ class CurseForgeHelperTest(unittest.TestCase): (d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv)) def env(self, extra=None): - base = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "XAUTHORITY")} - base.update(DD_PROC=str(self.proc), DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), - DD_CURSEFORGE_WAIT="10", WAYLAND_DISPLAY="wayland-0", DBUS_SESSION_BUS_ADDRESS="unix:path=/x") + base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DD_PROC=str(self.proc), + DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), DD_HEADLESS_RUN=str(HEADLESS), + DD_CURSEFORGE_WAIT="10", DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", XDG_RUNTIME_DIR="/run/user/session", + DBUS_SESSION_BUS_ADDRESS="unix:path=/x") base.update(extra or {}) return base def run_helper(self, *args, env=None): return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60) + def launch(self, directory=None): + holder = subprocess.Popen(["bash", str(HELPER), "start", str(directory or self.dir)], env=self.env(), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + self.addCleanup(self.finish, holder) + return holder, holder.stdout.readline().strip() + + def finish(self, holder): + if holder.poll() is None: + holder.kill() + holder.communicate() + def stop(self): self.run_helper("stop", str(self.dir)) @@ -64,86 +131,56 @@ class CurseForgeHelperTest(unittest.TestCase): time.sleep(0.1) return False - def test_the_desktop_x_display_is_found_from_xwayland(self): - self.fake(40, "/usr/bin/kwin_wayland", ":9") - self.fake(41, "/usr/bin/Xwayland", ":0", "-rootless", "-auth", "/run/droiddeck/xauth_abc", "-listenfd", "5") - out = self.run_helper("display", "") - self.assertEqual(0, out.returncode, out.stderr) - self.assertEqual([":0", "/run/droiddeck/xauth_abc"], out.stdout.splitlines()) - - def test_the_session_display_wins(self): - self.fake(41, "/usr/bin/Xwayland", ":3") - out = self.run_helper("display", "", env={"DISPLAY": ":0"}) - self.assertEqual(":0", out.stdout.splitlines()[0]) - - def test_no_display_is_reported(self): - out = self.run_helper("start", str(self.dir)) - self.assertEqual(4, out.returncode) - def test_a_running_instance_without_the_inspector_is_busy(self): self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox") - out = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"}) + out = self.run_helper("start", str(self.dir)) self.assertEqual(3, out.returncode) self.assertEqual("busy", out.stdout.strip()) self.stop() self.assertTrue((self.proc / "50").exists()) - def test_start_uses_a_random_port_and_a_secret_inspector_url_kept_private(self): - self.fake(41, "/usr/bin/Xwayland", ":0", "-auth", "/run/droiddeck/xauth_abc") - out = self.run_helper("start", str(self.dir)) + def test_start_runs_the_app_in_headless_gamescope_with_a_secret_inspector_and_no_session_display(self): + holder, url = self.launch() self.addCleanup(self.stop) - self.assertEqual(0, out.returncode, out.stderr) - self.assertEqual(URL, out.stdout.strip()) + self.assertEqual(URL, url) seen = self.seen.read_text().splitlines() - self.assertEqual(["DISPLAY=:0", "XAUTHORITY=/run/droiddeck/xauth_abc", "WAYLAND=", "DBUS=", str(self.dir), - "--minimized", "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen) + self.assertEqual(["DISPLAY=", "WAYLAND=", "DBUS=", "RUNTIME=%s/runtime" % self.state, str(self.dir), "--minimized", + "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen) self.assertEqual(0o700, self.state.stat().st_mode & 0o777) + self.assertEqual(0o700, (self.state / "runtime").stat().st_mode & 0o777) self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777) - again = self.run_helper("start", str(self.dir)) - self.assertEqual(URL, again.stdout.strip()) - pid = self.pid() + _, again = self.launch() + self.assertEqual(URL, again) + + def test_start_holds_the_app_until_it_is_stopped(self): + holder, url = self.launch() + self.assertEqual(URL, url) + app = self.pid() + time.sleep(1) + self.assertIsNone(holder.poll()) + os.kill(app, 0) + self.stop() + self.assertEqual(0, holder.wait(timeout=30)) + self.assertTrue(self.gone(app), "the app is still running") + + def test_stop_ends_the_app_and_the_gamescope_it_ran_in(self): + (self.bin / "gamescope").write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@" &\nwait\n') + self.assertEqual(URL, self.launch()[1]) + gamescope = self.pid() + app = int(next(self.proc.iterdir()).name) + self.assertNotEqual(gamescope, app) + os.kill(app, 0) self.stop() self.assertFalse((self.state / "pid").exists()) - self.assertTrue(self.gone(pid), "the started instance is still running") + self.assertTrue(self.gone(gamescope), "gamescope is still running") + self.assertTrue(self.gone(app), "the app is still running") - def test_hold_keeps_the_app_until_it_is_signalled(self): - held = subprocess.Popen(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}), - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - self.addCleanup(self.end, held) - for _ in range(100): - if (self.state / "pid").exists() and self.seen.exists(): - break - time.sleep(0.1) - pid = self.pid() - time.sleep(1) - self.assertIsNone(held.poll()) - held.send_signal(signal.SIGTERM) - self.assertEqual(0, held.wait(timeout=30)) - self.assertTrue(self.gone(pid), "hold left the app running") - self.assertFalse((self.state / "pid").exists()) - - def end(self, held): - if held.poll() is None: - held.send_signal(signal.SIGTERM) - try: - held.wait(timeout=15) - except subprocess.TimeoutExpired: - held.kill() - held.wait() - record = self.state / "pid" - if record.exists(): - try: - os.killpg(self.pid(), signal.SIGKILL) - except (ProcessLookupError, PermissionError): - pass - - def test_a_launch_for_another_directory_is_busy(self): + def test_a_launch_for_another_directory_is_busy_and_left_alone(self): other = self.tmp / "other" (other / "app").mkdir(parents=True) - first = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"}) self.addCleanup(self.stop) - self.assertEqual(0, first.returncode, first.stderr) - out = self.run_helper("start", str(other), env={"DISPLAY": ":0"}) + self.assertEqual(URL, self.launch()[1]) + out = self.run_helper("start", str(other)) self.assertEqual(3, out.returncode) self.assertEqual("busy", out.stdout.strip()) pid = self.pid() @@ -151,22 +188,25 @@ class CurseForgeHelperTest(unittest.TestCase): self.assertEqual(pid, self.pid()) os.kill(pid, 0) - def test_hold_ends_when_the_app_exits(self): - proc = shlex.quote(str(self.proc)) - self.runner.write_text("#!/bin/bash\nmkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" - "echo 'Debugger listening on %s'\nsleep 2\nrm -r %s/$$\n" % (proc, proc, URL, proc)) - out = subprocess.run(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}), - capture_output=True, text=True, timeout=60) - self.assertEqual(0, out.returncode, out.stderr) + def test_each_launch_starts_a_fresh_log(self): + first, _ = self.launch() + self.stop() + first.wait(timeout=30) + self.addCleanup(self.stop) + self.assertEqual(URL, self.launch()[1]) + self.assertEqual(1, (self.state / "log").read_text().count("Debugger listening")) + self.assertTrue((self.state / "log.1").exists()) def test_stop_without_a_launch_is_quiet(self): out = self.run_helper("stop", str(self.dir)) self.assertEqual(0, out.returncode) self.assertEqual("", out.stderr) + self.assertEqual("", out.stdout) def test_bad_arguments_are_refused(self): self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode) self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode) + self.assertEqual(2, self.run_helper("hold", str(self.dir)).returncode) if __name__ == "__main__": diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index 6bf1b0da8..72931860b 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -348,6 +348,28 @@ class AgentTest(unittest.TestCase): self.assertEqual("INVALID_TARGET", caught.exception.code) connect.assert_not_called() + def test_one_shot_inspector_eval_prints_the_session_answer_without_a_launch_dir(self): + import contextlib + import io + url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + seen = {} + + def evaluate(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, command_line_api=False): + seen.update(expression=expression, timeout=timeout, inspector=inspector, api=command_line_api) + return {"target": "inspector", "type": "string", "value": "ok", "description": None} + + out = io.StringIO() + with patch.dict(os.environ, {}, clear=False), patch.object(agent, "cdp_eval", evaluate), contextlib.redirect_stdout(out): + os.environ.pop("DD_LAUNCH_DIR", None) + self.assertEqual(0, agent.main(["--cdp-inspector", url, "12.5", "1 + 1"])) + self.assertEqual({"target": "inspector", "type": "string", "value": "ok", "description": None, "ok": True}, json.loads(out.getvalue())) + self.assertEqual({"expression": "1 + 1", "timeout": 12.5, "inspector": url, "api": True}, seen) + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(0, agent.main(["--cdp-inspector", "ws://example.com:9229/x", "5", "1"])) + self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"]) + self.assertEqual(2, agent.main(["--cdp-inspector", url])) + def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self): class Lost: def __init__(self, *args, **kwargs): diff --git a/tools/tests/test_fex_signal_syscall_state.py b/tools/tests/test_fex_signal_syscall_state.py new file mode 100644 index 000000000..1aaa03feb --- /dev/null +++ b/tools/tests/test_fex_signal_syscall_state.py @@ -0,0 +1,76 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0008-signal-return-restores-syscall-state.patch" +PROBE = FEX / "probes/async-signal-context.c" +RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;" + + +def hunks(): + text = PATCH.read_text() + files = re.findall(r"^diff --git a/(\S+) ", text, re.M) + return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M) + + +class SignalReturnSyscallStateTest(unittest.TestCase): + def test_only_the_signal_delegator_changes(self): + files, found = hunks() + self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"]) + self.assertEqual(len(found), 1) + + def test_every_guest_frame_return_restores_the_interrupted_syscall_state(self): + _, found = hunks() + function, body = found[0] + self.assertIn("SignalDelegator::RestoreThreadState", function) + lines = body.splitlines() + added = [line[1:].strip() for line in lines if line.startswith("+")] + removed = [line for line in lines if line.startswith("-")] + self.assertEqual(added, [RESTORE]) + self.assertEqual(removed, []) + context = [line[1:].strip() for line in lines] + guest_frame = context.index("if (Context->UContextLocation) {") + self.assertEqual(context[guest_frame + 1], "auto Frame = Thread->CurrentFrame;") + self.assertEqual(context[guest_frame + 2], RESTORE) + self.assertLess(context.index(RESTORE), context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")) + + def test_thread_pause_returns_are_untouched(self): + _, found = hunks() + body = found[0][1] + self.assertNotIn("TYPE_PAUSE", "".join(line for line in body.splitlines() if line.startswith("+"))) + + def test_patch_is_applied_to_every_release(self): + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class AsyncSignalContextProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-async-signal-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-pthread", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_reports_the_interrupted_registers(self): + result = subprocess.run([str(self.binary), "500"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertGreaterEqual(int(counts["matched"]), 500) + self.assertEqual(counts["stale"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_live_switch.py b/tools/tests/test_hdr_live_switch.py index 41e30ebc7..4468be504 100644 --- a/tools/tests/test_hdr_live_switch.py +++ b/tools/tests/test_hdr_live_switch.py @@ -43,15 +43,11 @@ class HdrLiveSwitchTest(unittest.TestCase): def test_the_gate_follows_the_display_not_the_setting(self): text = (APP / "SessionActivity.kt").read_text() start = text.index("val attached = CompositorHost.isStarted") - block = text[start:text.index("CompositorHost.start(", start)] + block = text[start:text.index("DriverSetupLog.write", start)] request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))] - self.assertNotIn("SessionPrefs.hdr", block) + self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")]) self.assertIn("capable, false", request) - self.assertIn("if (!SessionState.running) CompositorHost.applyHdr(this, mode)", block) - host = (APP / "wayland/CompositorHost.kt").read_text() - gate = host[host.index("fun applyHdr("):] - gate = gate[:gate.index("\n }")] - self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(context, mode)", gate) + self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block) def test_both_switches_apply_to_the_running_session(self): helper = (APP / "session/SessionHdr.kt").read_text()