From 565bd7c6b148b70ced51bd56ee0a8f3ee681b6d6 Mon Sep 17 00:00:00 2001
From: The412Banner <205237651+The412Banner@users.noreply.github.com>
Date: Sat, 5 Dec 2026 16:24:52 -0500
Subject: [PATCH 1/8] fix(storage): record all-files access in session logs and
warn when added games need it (#3470)
* fix(storage): record all-files access in session logs and warn when added games need it
* Cover all added games in storage access diagnostics
---------
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
---
.../droiddeck/launcher/core/DeviceReport.kt | 1 +
.../launcher/files/AllFilesAccess.kt | 9 ++++++++
.../launcher/session/SessionService.kt | 11 +++++++--
.../launcher/files/AllFilesAccessTest.kt | 23 +++++++++++++++++++
4 files changed, 42 insertions(+), 2 deletions(-)
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
index d94fbbb587..4beeec8d45 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
@@ -192,6 +192,7 @@ object DeviceReport {
val fs = StatFs(Environment.getExternalStorageDirectory().path)
k("Shared storage free", FileUtils.sizeToString(fs.availableBlocksLong * fs.blockSizeLong))
}
+ k("All files access", runCatching { com.droiddeck.launcher.files.AllFilesAccess.state() }.getOrNull())
h("GPU")
k("KGSL gpu_model", readSys("/sys/class/kgsl/kgsl-3d0/gpu_model"))
diff --git a/app/src/main/java/com/droiddeck/launcher/files/AllFilesAccess.kt b/app/src/main/java/com/droiddeck/launcher/files/AllFilesAccess.kt
index 2c9529f4ed..94ea2e33f9 100644
--- a/app/src/main/java/com/droiddeck/launcher/files/AllFilesAccess.kt
+++ b/app/src/main/java/com/droiddeck/launcher/files/AllFilesAccess.kt
@@ -14,6 +14,15 @@ object AllFilesAccess {
fun missing(sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { Environment.isExternalStorageManager() }): Boolean =
sdk >= Build.VERSION_CODES.R && !granted()
+ fun state(sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { Environment.isExternalStorageManager() }): String = when {
+ sdk < Build.VERSION_CODES.R -> "not needed"
+ granted() -> "granted"
+ else -> "missing"
+ }
+
+ fun mayHideFilesIn(path: String, sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { Environment.isExternalStorageManager() }): Boolean =
+ covers(path) && missing(sdk, granted)
+
/** Whether reading [path] takes all-files access: shared storage, outside the per-app folders directly under a volume's root, which Android always lets the app use. */
fun covers(path: String): Boolean {
val inside = VOLUME.matchEntire(path)?.groupValues?.get(2) ?: return false
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
index 67992024db..5ad8fe253e 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
@@ -1355,10 +1355,17 @@ class SessionService : Service() {
if (controllersOn) components.add(RumbleComponent().also { it.attach(this) })
val home = File(LinuxRuntime.rootDir(this), "root")
File(home, "Storage").mkdirs()
+ val addedExeFolders = com.droiddeck.launcher.frontend.AddedExes.list(this).map { File(it.folder) }.distinctBy { it.path }
+ val addedGameRoots = com.droiddeck.launcher.frontend.AddedGames.roots(this)
+ val addedFolders = (addedExeFolders + addedGameRoots.map { it.host }).distinctBy { it.path }
+ for (folder in addedFolders) {
+ if (com.droiddeck.launcher.files.AllFilesAccess.mayHideFilesIn(folder.path))
+ Log.w(TAG, "added games: Android may hide .exe files in $folder because All files access is missing")
+ }
if (sharedStorage != null) {
binds.add(sharedStorage.path + ":/root/Storage")
} else {
- for (folder in com.droiddeck.launcher.frontend.AddedExes.list(this).map { File(it.folder) }.distinctBy { it.path }) {
+ for (folder in addedExeFolders) {
val guest = com.droiddeck.launcher.frontend.AddedGames.guestPath(this, folder) ?: continue
if (!guest.startsWith("/root/Storage/") || !folder.isDirectory) continue
File(LinuxRuntime.rootDir(this), guest.removePrefix("/")).mkdirs()
@@ -1409,7 +1416,7 @@ class SessionService : Service() {
Log.w(TAG, "storage diagnostics: selected library could not be identified; metadata snapshot only")
}
}
- for (root in com.droiddeck.launcher.frontend.AddedGames.roots(this)) {
+ for (root in addedGameRoots) {
if (root.host.isDirectory && root.host.canRead()) {
File(LinuxRuntime.rootDir(this), root.guest.removePrefix("/")).mkdirs()
binds.add(root.host.path + ":" + root.guest)
diff --git a/app/src/test/java/com/droiddeck/launcher/files/AllFilesAccessTest.kt b/app/src/test/java/com/droiddeck/launcher/files/AllFilesAccessTest.kt
index 0737cac0f7..25655e7547 100644
--- a/app/src/test/java/com/droiddeck/launcher/files/AllFilesAccessTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/files/AllFilesAccessTest.kt
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.files
+import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -37,4 +38,26 @@ class AllFilesAccessTest {
assertFalse(AllFilesAccess.covers("/storage/1A2B-3C4D/Android/obb/com.droiddeck.launcher"))
assertFalse(AllFilesAccess.covers("/data/user/0/com.droiddeck.launcher/files"))
}
+
+ @Test
+ fun stateNamesWhatTheReportShows() {
+ assertEquals("not needed", AllFilesAccess.state(sdk = 29) { false })
+ assertEquals("missing", AllFilesAccess.state(sdk = 34) { false })
+ assertEquals("granted", AllFilesAccess.state(sdk = 34) { true })
+ }
+
+ @Test
+ fun sharedStorageMayHideFilesOnlyWithoutAccess() {
+ assertTrue(AllFilesAccess.mayHideFilesIn("/storage/emulated/0", sdk = 34) { false })
+ assertTrue(AllFilesAccess.mayHideFilesIn("/storage/1A2B-3C4D/Games", sdk = 34) { false })
+ assertFalse(AllFilesAccess.mayHideFilesIn("/storage/emulated/0", sdk = 34) { true })
+ assertFalse(AllFilesAccess.mayHideFilesIn("/storage/emulated/0", sdk = 29) { false })
+ }
+
+ @Test
+ fun appFoldersAndPrivateStorageNeverHideFiles() {
+ assertFalse(AllFilesAccess.mayHideFilesIn("/storage/emulated/0/Android/data/com.droiddeck.launcher/files", sdk = 34) { false })
+ assertFalse(AllFilesAccess.mayHideFilesIn("/data/user/0/com.droiddeck.launcher/files/Games", sdk = 34) { false })
+ assertFalse(AllFilesAccess.mayHideFilesIn("/mnt/media_rw/1A2B-3C4D", sdk = 34) { false })
+ }
}
From 3b0c0d3496fe8c5ae82d9048b8dac1eaa8035dd4 Mon Sep 17 00:00:00 2001
From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Date: Sat, 5 Dec 2026 16:30:37 -0500
Subject: [PATCH 2/8] Add landscape-only fullscreen for launcher and sessions
(#3764)
Add portrait-aware fullscreen for launcher and sessions
---
.../droiddeck/launcher/FrontEndActivity.kt | 31 +++++++++++++----
.../com/droiddeck/launcher/SessionActivity.kt | 33 ++++++++++++++-----
.../launcher/session/FullscreenMode.kt | 18 ++++++++++
.../launcher/session/SessionPrefs.kt | 17 ++++++++--
.../launcher/session/SettingsReset.kt | 2 +-
.../droiddeck/launcher/ui/FrontEndScreen.kt | 12 +++++--
.../droiddeck/launcher/ui/FrontEndSetup.kt | 17 +++++++---
.../droiddeck/launcher/ui/SessionOverlay.kt | 7 ++++
.../droiddeck/launcher/ui/SettingsIndex.kt | 3 +-
app/src/main/res/values/strings.xml | 3 ++
docs/settings-map.md | 3 +-
11 files changed, 117 insertions(+), 29 deletions(-)
create mode 100644 app/src/main/java/com/droiddeck/launcher/session/FullscreenMode.kt
diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
index 8c9657f1f5..9a109df4d2 100644
--- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
@@ -52,6 +52,7 @@ import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPaths
+import com.droiddeck.launcher.session.FullscreenMode
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.session.LaunchCoordinator
@@ -208,7 +209,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM)
- private var launcherFullscreen by mutableStateOf(true)
+ private var launcherFullscreenMode by mutableStateOf(FullscreenMode.ALWAYS)
+ private var sessionFullscreenMode by mutableStateOf(FullscreenMode.ALWAYS)
private var launcherFrost by mutableStateOf(false)
private var frostWallpaper by mutableStateOf(true)
private var frostCards by mutableStateOf(true)
@@ -1366,8 +1368,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
orientation = SessionPrefs.orientation(this)
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
+ launcherFullscreenMode = SessionPrefs.launcherFullscreenMode(this)
+ sessionFullscreenMode = SessionPrefs.sessionFullscreenMode(this)
+ applyLauncherFullscreen()
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
- launcherFullscreen = SessionPrefs.launcherFullscreen(this)
+ launcherFullscreenMode = SessionPrefs.launcherFullscreenMode(this)
+ sessionFullscreenMode = SessionPrefs.sessionFullscreenMode(this)
launcherFrost = SessionPrefs.launcherFrost(this)
frostWallpaper = SessionPrefs.frostWallpaper(this)
frostCards = SessionPrefs.frostCards(this)
@@ -1482,7 +1488,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
orientation = orientation,
launcherOrientation = launcherOrientation,
homePage = homePage,
- launcherFullscreen = launcherFullscreen,
+ launcherFullscreenMode = launcherFullscreenMode,
+ sessionFullscreenMode = sessionFullscreenMode,
launcherFrost = launcherFrost,
frostWallpaper = frostWallpaper,
frostCards = frostCards,
@@ -1816,11 +1823,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
homePage = value
},
onControllerHaptics = { on -> SessionPrefs.setControllerHaptics(this, on); controllerHaptics = on },
- onLauncherFullscreen = { on ->
- SessionPrefs.setLauncherFullscreen(this, on)
- launcherFullscreen = on
+ onLauncherFullscreenMode = { mode ->
+ SessionPrefs.setLauncherFullscreenMode(this, mode)
+ launcherFullscreenMode = mode
applyLauncherFullscreen()
},
+ onSessionFullscreenMode = { mode ->
+ SessionPrefs.setSessionFullscreenMode(this, mode)
+ sessionFullscreenMode = mode
+ },
onLauncherFrost = { on ->
SessionPrefs.setLauncherFrost(this, on)
launcherFrost = on
@@ -2152,7 +2163,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun frostShown(): Boolean =
launcherFrost && frostWallpaper && frost.prepared && frost.available && theme != com.droiddeck.launcher.ui.Themes.TRUE_BLACK
- private fun applyLauncherFullscreen() {
+ override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
+ super.onConfigurationChanged(newConfig)
+ applyLauncherFullscreen(newConfig)
+ }
+
+ private fun applyLauncherFullscreen(config: android.content.res.Configuration = resources.configuration) {
+ val launcherFullscreen = launcherFullscreenMode.hidesSystemBars(config.orientation)
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = if (launcherFullscreen) {
(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index 732b26620a..371d200f47 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -128,6 +128,7 @@ import com.droiddeck.launcher.session.GpuClockPin
import com.droiddeck.launcher.session.GameProfileFollowState
import com.droiddeck.launcher.session.GameProfileInventoryCache
import com.droiddeck.launcher.session.GameProfileRefreshState
+import com.droiddeck.launcher.session.FullscreenMode
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionArtifacts
@@ -643,6 +644,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var drawerControllerActive by mutableStateOf(false)
private var backHold by mutableStateOf(true)
private var dockedMenuController by mutableStateOf(false)
+ private var sessionFullscreenMode by mutableStateOf(FullscreenMode.ALWAYS)
private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var dualScreenSessionMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
private var backActionsInverted by mutableStateOf(false)
@@ -940,7 +942,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
applyFollowChoice()
applyFollowOrientation(resources.configuration)
- goFullscreen()
+ sessionFullscreenMode = SessionPrefs.sessionFullscreenMode(this)
+ applySessionFullscreen()
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshSecondScreenDisplays()
@@ -2103,6 +2106,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onPause = ::pauseNow,
paused = SessionState.suspended || SessionState.manualPause,
onResume = { SessionService.resume(this@SessionActivity) },
+ fullscreenMode = sessionFullscreenMode,
+ onFullscreenMode = { mode ->
+ SessionPrefs.setSessionFullscreenMode(this@SessionActivity, mode)
+ sessionFullscreenMode = mode
+ applySessionFullscreen()
+ },
orientation = sessionOrientation,
onOrientation = { value ->
when (SessionState.mode) {
@@ -3309,6 +3318,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
+ if (!pipUi && !isInPictureInPictureMode) applySessionFullscreen(newConfig)
picturePosition = SessionPrefs.picturePosition(this, picturePortrait(newConfig))
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
@@ -6669,6 +6679,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
uiHandler.removeCallbacks(questSteamVrRequest)
if (com.droiddeck.launcher.session.QuestExperimental.isSupported()) uiHandler.post(questSteamVrRequest)
if (runtimeRemovalBlocked) return
+ sessionFullscreenMode = SessionPrefs.sessionFullscreenMode(this)
+ if (!pipUi && !isInPictureInPictureMode) applySessionFullscreen()
if (!SessionState.suspended) pausedFrame = null
com.droiddeck.launcher.ui.Motion.refresh(this)
refreshHomeApp()
@@ -7382,7 +7394,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (hasFocus && airTriggersOpen) RedMagicAirTriggers.open(this)
if (hasFocus && !pipUi) {
retryFieldKeyboard(true)
- goFullscreen()
+ applySessionFullscreen()
refreshClipboard()
}
updatePointerCapture()
@@ -7392,19 +7404,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (resumed) sessionClipboard.refresh()
}
- private fun goFullscreen() {
+ private fun applySessionFullscreen(config: android.content.res.Configuration = resources.configuration) {
+ val fullscreen = sessionFullscreenMode.hidesSystemBars(config.orientation)
+ if (fullscreen) window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
+ else window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
@Suppress("DEPRECATION")
- window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+ window.decorView.systemUiVisibility = if (fullscreen) (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
- or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
+ or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) else View.SYSTEM_UI_FLAG_LAYOUT_STABLE
if (Build.VERSION.SDK_INT >= 28) {
window.attributes = window.attributes.apply {
- layoutInDisplayCutoutMode = if (Build.VERSION.SDK_INT >= 30)
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
- else WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ layoutInDisplayCutoutMode = when {
+ !fullscreen -> WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
+ Build.VERSION.SDK_INT >= 30 -> WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
+ else -> WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ }
}
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/FullscreenMode.kt b/app/src/main/java/com/droiddeck/launcher/session/FullscreenMode.kt
new file mode 100644
index 0000000000..9d3cdd2e21
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/FullscreenMode.kt
@@ -0,0 +1,18 @@
+package com.droiddeck.launcher.session
+
+import android.content.res.Configuration
+import androidx.annotation.StringRes
+import com.droiddeck.launcher.R
+
+enum class FullscreenMode(@StringRes val label: Int) {
+ ALWAYS(R.string.widgets_on),
+ LANDSCAPE_ONLY(R.string.setup_fullscreen_landscape_only),
+ OFF(R.string.widgets_off);
+
+ fun hidesSystemBars(orientation: Int): Boolean =
+ this == ALWAYS || (this == LANDSCAPE_ONLY && orientation == Configuration.ORIENTATION_LANDSCAPE)
+
+ companion object {
+ fun fromStored(value: String?): FullscreenMode? = entries.firstOrNull { it.name == value }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
index 24ed5f199b..e42c8f48a5 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
@@ -112,10 +112,21 @@ object SessionPrefs {
else -> false
}
- fun launcherFullscreen(context: Context): Boolean = prefs(context).getBoolean("launcherFullscreen", true)
+ fun launcherFullscreenMode(context: Context): FullscreenMode {
+ val preferences = prefs(context)
+ return FullscreenMode.fromStored(preferences.getString("launcherFullscreenMode", null))
+ ?: if (preferences.getBoolean("launcherFullscreen", true)) FullscreenMode.ALWAYS else FullscreenMode.OFF
+ }
- fun setLauncherFullscreen(context: Context, on: Boolean) {
- prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
+ fun setLauncherFullscreenMode(context: Context, mode: FullscreenMode) {
+ prefs(context).edit().putString("launcherFullscreenMode", mode.name).apply()
+ }
+
+ fun sessionFullscreenMode(context: Context): FullscreenMode =
+ FullscreenMode.fromStored(prefs(context).getString("sessionFullscreenMode", null)) ?: FullscreenMode.ALWAYS
+
+ fun setSessionFullscreenMode(context: Context, mode: FullscreenMode) {
+ prefs(context).edit().putString("sessionFullscreenMode", mode.name).apply()
}
fun launcherFrost(context: Context): Boolean = prefs(context).getBoolean("launcherFrost", false)
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt
index e4fb6ed9c3..c9852d4b8b 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt
@@ -12,7 +12,7 @@ object SettingsReset {
private const val TAG = "SettingsReset"
internal val SESSION_KEYS = setOf(
- "orientation", "launcherFullscreen", "launcherFrost", "frostWallpaper", "frostCards", "frostTransparency", "frostCardTransparency", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
+ "orientation", "launcherFullscreen", "launcherFullscreenMode", "sessionFullscreenMode", "launcherFrost", "frostWallpaper", "frostCards", "frostTransparency", "frostCardTransparency", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
index 917a46e71d..ff50841c75 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
@@ -88,6 +88,7 @@ import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.core.DownloadSource
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
+import com.droiddeck.launcher.session.FullscreenMode
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.roundToInt
import kotlinx.coroutines.withTimeoutOrNull
@@ -176,7 +177,8 @@ class FrontEndState(
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM,
- val launcherFullscreen: Boolean = true,
+ val launcherFullscreenMode: FullscreenMode = FullscreenMode.ALWAYS,
+ val sessionFullscreenMode: FullscreenMode = FullscreenMode.ALWAYS,
val launcherFrost: Boolean = false,
val frostWallpaper: Boolean = true,
val frostCards: Boolean = true,
@@ -288,7 +290,8 @@ class FrontEndActions(
val onOrientation: (Int) -> Unit = {},
val onLauncherOrientation: (Int) -> Unit = {},
val onHomePage: (String) -> Unit = {},
- val onLauncherFullscreen: (Boolean) -> Unit = {},
+ val onLauncherFullscreenMode: (FullscreenMode) -> Unit = {},
+ val onSessionFullscreenMode: (FullscreenMode) -> Unit = {},
val onLauncherFrost: (Boolean) -> Unit = {},
val onFrostWallpaper: (Boolean) -> Unit = {},
val onFrostCards: (Boolean) -> Unit = {},
@@ -711,9 +714,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
if (anyFocused) return
}
}
+ val launcherFullscreen = s.launcherFullscreenMode.hidesSystemBars(
+ androidx.compose.ui.platform.LocalConfiguration.current.orientation,
+ )
androidx.compose.foundation.layout.BoxWithConstraints(
modifier = Modifier.fillMaxSize().background(if (LocalFrost.current != null) Color.Transparent else colors.background)
- .windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
+ .windowInsetsPadding(if (launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
.onFocusChanged { anyFocused = it.hasFocus },
) {
val bottomNavigation = maxHeight > maxWidth
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
index 4047781350..0cda817452 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
@@ -85,6 +85,7 @@ import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.DownloadSource
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
+import com.droiddeck.launcher.session.FullscreenMode
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.R
@@ -586,11 +587,17 @@ internal fun SetupPanel(
SessionPrefs.setOrientation(ctx, "desktop", value)
},
)
- ToggleRow(
- host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen),
- if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off),
- s.launcherFullscreen,
- ) { a.onLauncherFullscreen(it) }
+ val fullscreenModes = FullscreenMode.entries.map { it to stringResource(it.label) }
+ ChoiceRow(
+ host, "launcher-fullscreen", stringResource(R.string.setup_launcher_fullscreen),
+ stringResource(R.string.setup_fullscreen_on),
+ fullscreenModes, s.launcherFullscreenMode, onPick = a.onLauncherFullscreenMode,
+ )
+ ChoiceRow(
+ host, "session-fullscreen", stringResource(R.string.setup_session_fullscreen),
+ stringResource(R.string.setup_fullscreen_on),
+ fullscreenModes, s.sessionFullscreenMode, onPick = a.onSessionFullscreenMode,
+ )
ToggleRow(
host, "page-swipe", stringResource(R.string.setup_page_swipe),
stringResource(R.string.setup_page_swipe_hint), PageSwipe.on,
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
index a2647da77f..6e843c212d 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
@@ -177,6 +177,7 @@ import com.droiddeck.launcher.gpu.ScreenEffectLooks
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.SteamVr
import com.droiddeck.launcher.gpu.ScreenEffects
+import com.droiddeck.launcher.session.FullscreenMode
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.input.PC_KEY_GROUP_IDS
@@ -406,6 +407,8 @@ class DrawerActions(
val paused: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val onOrientation: (Int) -> Unit = {},
+ val fullscreenMode: FullscreenMode = FullscreenMode.ALWAYS,
+ val onFullscreenMode: (FullscreenMode) -> Unit = {},
val onResume: () -> Unit = {},
val onPipAutoEnter: (Boolean) -> Unit = {},
val unfoldedControls: Boolean? = null,
@@ -1009,6 +1012,10 @@ private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String)
if (a.gameZoomAvailable) GameZoomRow(a.gameZoom, track, a.onGameZoom)
ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null,
orientations, a.orientation, chipModifier = track("orientation"), onPick = a.onOrientation)
+ ChoiceRow(host, "session-fullscreen", stringResource(R.string.setup_session_fullscreen),
+ stringResource(R.string.setup_fullscreen_on),
+ FullscreenMode.entries.map { it to stringResource(it.label) }, a.fullscreenMode,
+ chipModifier = track("session-fullscreen"), onPick = a.onFullscreenMode)
if (a.steam) PicturePositionRow(host, a.picturePosition, track("picture-position"), onPick = a.onPicturePosition)
}
val filters = SessionPrefs.upscalerChoices(LocalContext.current)
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
index 5983063e1e..f9bc7c1663 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
@@ -116,7 +116,8 @@ internal object SettingsIndex {
s(SettingsSection.LAUNCHER, R.string.setup_home, "home screen", "launcher"),
s(SettingsSection.LAUNCHER, R.string.setup_launcher_orientation, "rotate", "portrait"),
s(SettingsSection.LAUNCHER, R.string.setup_session_orientation, "rotate", "portrait"),
- s(SettingsSection.LAUNCHER, R.string.setup_fullscreen),
+ s(SettingsSection.LAUNCHER, R.string.setup_launcher_fullscreen, "status bar", "navigation bar", "portrait"),
+ s(SettingsSection.LAUNCHER, R.string.setup_session_fullscreen, "status bar", "navigation bar", "portrait"),
s(SettingsSection.LAUNCHER, R.string.setup_page_swipe, "gesture"),
s(SettingsSection.LAUNCHER, R.string.setup_controller_haptics, "vibration", "rumble"),
s(SettingsSection.LAUNCHER, R.string.setup_dual_screen_launcher, "thor", "second screen", "bottom screen"),
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index c9a8dd1d3d..26c5d04baa 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1042,6 +1042,9 @@
Landscape
Reverse landscape
Fullscreen
+ Launcher fullscreen
+ Session fullscreen
+ Landscape only
Hides the Android status and navigation bars
Shows the Android status and navigation bars
Swipe between pages
diff --git a/docs/settings-map.md b/docs/settings-map.md
index aface4f407..e3138eee65 100644
--- a/docs/settings-map.md
+++ b/docs/settings-map.md
@@ -45,7 +45,8 @@ Links of the form `droiddeck://settings/` open a Settings section direc
| Use as Home screen | Settings › Launcher (`droiddeck://settings/launcher`) | home screen, launcher |
| Launcher orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait |
| Session orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait |
-| Fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | |
+| Launcher fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | status bar, navigation bar, portrait |
+| Session fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | status bar, navigation bar, portrait |
| Swipe between pages | Settings › Launcher (`droiddeck://settings/launcher`) | gesture |
| Controller haptics | Settings › Launcher (`droiddeck://settings/launcher`) | vibration, rumble |
| Dual screen launcher | Settings › Launcher (`droiddeck://settings/launcher`) | thor, second screen, bottom screen |
From 423f600d4b9aeafbd3afdd4f5c2535192ea94a5b Mon Sep 17 00:00:00 2001
From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Date: Sat, 5 Dec 2026 16:31:37 -0500
Subject: [PATCH 3/8] Match the Dev Harness dropdown to the usage tracker
(#3762)
Match the agent model picker to the usage panel
---
.../java/com/droiddeck/launcher/ui/AgentPanels.kt | 13 +++++++------
1 file changed, 7 insertions(+), 6 deletions(-)
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt
index a462fca130..db538977f5 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt
@@ -67,13 +67,18 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
+@Composable
+private fun agentPanelFrame(): Modifier =
+ Modifier.fillMaxWidth().clip(Shape14).background(MaterialTheme.colorScheme.surface)
+ .border(1.dp, LocalPalette.current.line, Shape14).padding(horizontal = 14.dp, vertical = 10.dp)
+
/** The model, reasoning effort, permissions and plan mode for the next turns; a conversation keeps going with whatever is chosen. */
@Composable
internal fun AgentModelPicker() {
val context = LocalContext.current
val pal = LocalPalette.current
val models = remember(AgentHost.harness) { AgentHost.models(context) }
- Column(Modifier.fillMaxWidth().padding(bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Column(agentPanelFrame(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) {
val choices = listOf(AgentHarness.Model("", stringResource(R.string.agent_model_default))) + models
for (choice in choices) {
@@ -269,12 +274,8 @@ internal fun AgentProcessList(modifier: Modifier) {
@Composable
internal fun AgentUsage() {
val context = LocalContext.current
- val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
- Column(
- Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(horizontal = 14.dp, vertical = 10.dp),
- verticalArrangement = Arrangement.spacedBy(8.dp),
- ) {
+ Column(agentPanelFrame(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (AgentHost.window > 0) UsageRow(
stringResource(R.string.agent_usage_context),
stringResource(R.string.agent_usage_of, tokens(AgentHost.context), tokens(AgentHost.window)),
From 16ea8d9168c9b2cdbb21c2c071c1757f7b88c311 Mon Sep 17 00:00:00 2001
From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Date: Sat, 5 Dec 2026 17:19:51 -0500
Subject: [PATCH 4/8] Use a keypad for wireless debugging pairing codes (#3766)
* Use a keypad for wireless debugging pairing codes
* Make wireless pairing keys legible in SystemUI
* Fit both keypad rows in the heads-up notification
* Find the verified loopback ADB port after pairing
* Post the pairing keypad as a separate heads-up alert
* Keep the pairing keypad accessible and recover rotated ADB ports
* Show how to keep the pairing popup open
---
README.md | 7 +
.../droiddeck/launcher/core/WirelessAdbFix.kt | 32 ++++-
.../core/WirelessAdbPairingService.kt | 129 ++++++++++++++----
.../launcher/core/WirelessPairingKeypad.kt | 29 ++++
.../res/color/wireless_pairing_key_text.xml | 5 +
.../res/drawable/wireless_pairing_key.xml | 15 ++
.../res/drawable/wireless_pairing_panel.xml | 5 +
.../res/layout/wireless_pairing_keypad.xml | 38 ++++++
app/src/main/res/values-ar/strings.xml | 1 -
app/src/main/res/values-b+es+419/strings.xml | 1 -
app/src/main/res/values-bg/strings.xml | 1 -
app/src/main/res/values-cs/strings.xml | 1 -
app/src/main/res/values-da/strings.xml | 1 -
app/src/main/res/values-de/strings.xml | 1 -
app/src/main/res/values-el/strings.xml | 1 -
app/src/main/res/values-es/strings.xml | 1 -
app/src/main/res/values-fi/strings.xml | 1 -
app/src/main/res/values-fr/strings.xml | 1 -
app/src/main/res/values-hi/strings.xml | 1 -
app/src/main/res/values-hu/strings.xml | 1 -
app/src/main/res/values-in/strings.xml | 1 -
app/src/main/res/values-it/strings.xml | 1 -
app/src/main/res/values-ja/strings.xml | 1 -
app/src/main/res/values-ko/strings.xml | 1 -
app/src/main/res/values-ms/strings.xml | 1 -
app/src/main/res/values-nb/strings.xml | 1 -
app/src/main/res/values-nl/strings.xml | 1 -
app/src/main/res/values-pl/strings.xml | 1 -
app/src/main/res/values-pt-rPT/strings.xml | 1 -
app/src/main/res/values-pt/strings.xml | 1 -
app/src/main/res/values-ro/strings.xml | 1 -
app/src/main/res/values-ru/strings.xml | 1 -
app/src/main/res/values-sv/strings.xml | 1 -
app/src/main/res/values-th/strings.xml | 1 -
app/src/main/res/values-tr/strings.xml | 1 -
app/src/main/res/values-uk/strings.xml | 1 -
app/src/main/res/values-vi/strings.xml | 1 -
app/src/main/res/values-zh-rCN/strings.xml | 1 -
app/src/main/res/values-zh-rHK/strings.xml | 1 -
app/src/main/res/values-zh-rTW/strings.xml | 1 -
.../main/res/values/pairing_keypad_styles.xml | 19 +++
app/src/main/res/values/strings.xml | 7 +-
.../launcher/core/WirelessAdbReconnectTest.kt | 57 ++++++++
.../core/WirelessPairingKeypadTest.kt | 38 ++++++
44 files changed, 346 insertions(+), 67 deletions(-)
create mode 100644 app/src/main/java/com/droiddeck/launcher/core/WirelessPairingKeypad.kt
create mode 100644 app/src/main/res/color/wireless_pairing_key_text.xml
create mode 100644 app/src/main/res/drawable/wireless_pairing_key.xml
create mode 100644 app/src/main/res/drawable/wireless_pairing_panel.xml
create mode 100644 app/src/main/res/layout/wireless_pairing_keypad.xml
create mode 100644 app/src/main/res/values/pairing_keypad_styles.xml
create mode 100644 app/src/test/java/com/droiddeck/launcher/core/WirelessAdbReconnectTest.kt
create mode 100644 app/src/test/java/com/droiddeck/launcher/core/WirelessPairingKeypadTest.kt
diff --git a/README.md b/README.md
index 021fed17b3..d6616b1ab7 100644
--- a/README.md
+++ b/README.md
@@ -157,6 +157,13 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
+
+Setup and tools
+
+- The wireless debugging pairing keypad was inspired by Ryan Retro’s Handheld Toolkit.
+
+
+
## Star history
diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt
index 64087a24f3..e9f8bbdfaa 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt
@@ -119,7 +119,7 @@ object WirelessAdbFix {
* socket table, and mDNS often advertises nothing, so the ephemeral range Linux gives adbd is
* scanned on loopback (closed ports refuse at once) and the open ports are tried with our key.
*/
- private fun loopbackAdbPort(app: Context): Int? {
+ private fun loopbackAdbPort(app: Context, exclude: Int? = null): Int? {
val open = java.util.concurrent.ConcurrentLinkedQueue()
val workers = 32
val range = EPHEMERAL_PORTS
@@ -127,7 +127,7 @@ object WirelessAdbFix {
Thread {
var port = range.first + worker
while (port <= range.last) {
- if (answers(LOOPBACK, port, 150)) open += port
+ if (port != exclude && answers(LOOPBACK, port, 150)) open += port
port += workers
}
}.apply { start() }
@@ -162,8 +162,28 @@ object WirelessAdbFix {
}.getOrDefault(address is Inet4Address)
fun localConnectPort(context: Context): Int? =
- tlsPortProperty()
- ?: findConnectPort(context, LOOPBACK)
+ discoverConnectPort(context, LOOPBACK)
+
+ private fun discoverConnectPort(context: Context, host: String, exclude: Int? = null): Int? =
+ chooseConnectPort(host, exclude,
+ property = ::tlsPortProperty,
+ advertised = { acceptable -> findConnectPort(context, host, accept = acceptable) },
+ answers = { port -> answers(host, port) },
+ // Some local devices never advertise their connect port. Try only
+ // loopback and require the app's existing paired key to authenticate.
+ authenticatedLocal = { loopbackAdbPort(context.applicationContext, exclude) },
+ )
+
+ internal fun chooseConnectPort(
+ host: String, exclude: Int?,
+ property: () -> Int?, advertised: ((Int) -> Boolean) -> Int?,
+ answers: (Int) -> Boolean, authenticatedLocal: () -> Int?,
+ ): Int? {
+ val local = host == LOOPBACK
+ val acceptable: (Int) -> Boolean = { port -> port != exclude && (!local || answers(port)) }
+ val propertyPort = if (local) property()?.takeIf(acceptable) else null
+ return propertyPort ?: advertised(acceptable) ?: if (local) authenticatedLocal() else null
+ }
private fun tlsPortProperty(): Int? = runCatching {
Class.forName("android.os.SystemProperties").getMethod("get", String::class.java)
@@ -301,14 +321,14 @@ object WirelessAdbFix {
if (cachedPort != null) {
val cachedResult = runCatching { action(appContext, saved.host, cachedPort) }
if (cachedResult.isSuccess) return
- val discoveredPort = findConnectPort(appContext, saved.host)
+ val discoveredPort = discoverConnectPort(appContext, saved.host, exclude = cachedPort)
if (discoveredPort != null && discoveredPort != cachedPort) {
action(appContext, saved.host, discoveredPort)
} else {
cachedResult.getOrThrow()
}
} else {
- val discoveredPort = findConnectPort(appContext, saved.host)
+ val discoveredPort = discoverConnectPort(appContext, saved.host)
?: error(appContext.getString(R.string.adbfix_enter_address))
action(appContext, saved.host, discoveredPort)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt
index f7097dce7c..d1e2d911e8 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt
@@ -4,20 +4,23 @@ import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
-import android.app.RemoteInput
import android.app.Service
import android.content.Context
import android.content.Intent
+import android.net.Uri
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
+import android.util.TypedValue
+import android.widget.RemoteViews
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
+import java.util.UUID
class WirelessAdbPairingService : Service() {
override fun attachBaseContext(newBase: android.content.Context) =
@@ -37,6 +40,8 @@ class WirelessAdbPairingService : Service() {
private var discovery: NsdManager.DiscoveryListener? = null
private var pairingHost: String? = null
private var pairingPort: Int? = null
+ private val keypad = WirelessPairingKeypad()
+ private var keypadToken = UUID.randomUUID().toString()
@Volatile private var working = false
@Volatile private var limitEnabled = false
@Volatile private var session = 0
@@ -46,13 +51,21 @@ class WirelessAdbPairingService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
- ACTION_CODE -> {
- val code = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_CODE)
- ?.filter(Char::isDigit)?.toString().orEmpty()
- onCode(code)
+ ACTION_KEYPAD -> {
+ if (intent.data?.host == keypadToken && current.value is Stage.CodeNeeded && !working) {
+ val key = intent.data?.lastPathSegment?.toIntOrNull()
+ if (key == WirelessPairingKeypad.SUBMIT) {
+ if (keypad.ready && pairingPort != null) onCode(keypad.digits)
+ } else if (key != null && keypad.press(key)) {
+ show(current.value, quietUpdate = true)
+ }
+ } else if (current.value == Stage.Idle) {
+ stopSelf(startId)
+ }
}
ACTION_CANCEL -> finish(Stage.Idle)
- else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
+ null -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
+ else -> if (discovery == null && !working) stopSelf(startId)
}
return START_NOT_STICKY
}
@@ -60,11 +73,13 @@ class WirelessAdbPairingService : Service() {
private fun begin(enableLimit: Boolean) {
if (working) return
session++
+ resetKeypad()
limitEnabled = enableLimit
pairingHost = null
pairingPort = null
working = false
publish(Stage.Waiting)
+ getSystemService(NotificationManager::class.java)?.cancel(KEYPAD_NOTIFICATION_ID)
startForeground(NOTIFICATION_ID, notification(Stage.Waiting))
startDiscovery()
main.removeCallbacks(timeout)
@@ -101,9 +116,13 @@ class WirelessAdbPairingService : Service() {
if (!WirelessAdbFix.isLocalAddress(address)) return
main.post {
if (owner != session || working || current.value == Stage.Done) return@post
+ val endpointChanged = pairingHost != address.hostAddress || pairingPort != serviceInfo.port
pairingHost = address.hostAddress
pairingPort = serviceInfo.port
- if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
+ if (endpointChanged) {
+ resetKeypad()
+ show(Stage.CodeNeeded())
+ }
}
}
}
@@ -117,11 +136,12 @@ class WirelessAdbPairingService : Service() {
show(Stage.Waiting)
return
}
- if (code.length != 6) {
+ if (code.length != WirelessPairingKeypad.LENGTH) {
show(Stage.CodeNeeded(getString(R.string.adbpair_six_digits)))
return
}
working = true
+ resetKeypad()
val owner = session
val enable = limitEnabled
show(Stage.Working(getString(R.string.adbpair_pairing)))
@@ -155,17 +175,34 @@ class WirelessAdbPairingService : Service() {
}, "wireless-adb-pairing").start()
}
- private fun show(stage: Stage) {
+ private fun show(stage: Stage, quietUpdate: Boolean = false) {
publish(stage)
- getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, notification(stage))
+ val manager = getSystemService(NotificationManager::class.java) ?: return
+ if (stage is Stage.CodeNeeded) {
+ // A new high-priority notification can pop over Settings. Updating the
+ // quiet foreground-service notification can leave the keypad in the shade.
+ // End any previous indeterminate progress even if this is a code retry.
+ if (!quietUpdate) manager.notify(NOTIFICATION_ID, notification(stage, foregroundCodeEntry = true))
+ manager.notify(KEYPAD_NOTIFICATION_ID, notification(stage, quietUpdate))
+ } else {
+ manager.cancel(KEYPAD_NOTIFICATION_ID)
+ manager.notify(NOTIFICATION_ID, notification(stage, quietUpdate))
+ }
+ }
+
+ private fun resetKeypad() {
+ keypad.clear()
+ keypadToken = UUID.randomUUID().toString()
}
private fun finish(stage: Stage) {
session++
+ resetKeypad()
main.removeCallbacks(timeout)
stopDiscovery()
publish(stage)
val manager = getSystemService(NotificationManager::class.java)
+ manager?.cancel(KEYPAD_NOTIFICATION_ID)
if (stage is Stage.Done || stage is Stage.Failed) {
manager?.notify(NOTIFICATION_ID, notification(stage))
stopForeground(STOP_FOREGROUND_DETACH)
@@ -183,13 +220,16 @@ class WirelessAdbPairingService : Service() {
}
override fun onDestroy() {
+ getSystemService(NotificationManager::class.java)?.cancel(KEYPAD_NOTIFICATION_ID)
main.removeCallbacks(timeout)
stopDiscovery()
if (current.value.let { it is Stage.Waiting || it is Stage.CodeNeeded || it is Stage.Working }) publish(Stage.Idle)
super.onDestroy()
}
- private fun notification(stage: Stage): Notification {
+ private fun notification(
+ stage: Stage, quietUpdate: Boolean = false, foregroundCodeEntry: Boolean = false,
+ ): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.adbpair_channel_name),
NotificationManager.IMPORTANCE_HIGH).apply {
@@ -205,7 +245,7 @@ class WirelessAdbPairingService : Service() {
PendingIntent.FLAG_IMMUTABLE)
val cancel = PendingIntent.getService(this, 1,
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
- val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
+ val quiet = foregroundCodeEntry || stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentIntent(open)
@@ -220,19 +260,31 @@ class WirelessAdbPairingService : Service() {
.setOnlyAlertOnce(true)
.addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build())
is Stage.CodeNeeded -> {
- val reply = PendingIntent.getService(this, 2,
- Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CODE),
- if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
- else PendingIntent.FLAG_UPDATE_CURRENT)
- val input = RemoteInput.Builder(KEY_CODE).setLabel(getString(R.string.adbpair_code_label)).build()
- val text = stage.error ?: getString(R.string.adbpair_code_hint)
builder
- .setContentTitle(getString(if (stage.error == null) R.string.adbpair_title_code else R.string.adbpair_title_retry))
- .setContentText(text)
- .setStyle(Notification.BigTextStyle().bigText(text))
+ .setContentTitle(getString(if (foregroundCodeEntry) R.string.adbpair_title_pair
+ else if (stage.error == null) R.string.adbpair_title_code else R.string.adbpair_title_retry))
+ .setContentIntent(null)
+ .setVisibility(Notification.VISIBILITY_SECRET)
+ .setLocalOnly(true)
.setOngoing(true)
- .addAction(Notification.Action.Builder(null, getString(R.string.adbpair_enter_code), reply).addRemoteInput(input).build())
- .addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build())
+ .setOnlyAlertOnce(foregroundCodeEntry || quietUpdate)
+ if (!foregroundCodeEntry) {
+ // Keep the keypad separate from status/install notifications. Android owns
+ // the heads-up timeout; the drawer remains usable without expanding a group.
+ builder.setGroup(KEYPAD_GROUP)
+ .addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build())
+ if (stage.error != null && pairingPort == null) {
+ builder.setContentText(stage.error)
+ .setStyle(Notification.BigTextStyle().bigText(stage.error))
+ } else {
+ builder.setStyle(Notification.DecoratedCustomViewStyle())
+ .setCustomBigContentView(pairingKeypad())
+ .setCustomHeadsUpContentView(pairingKeypad(keyHeightDp = 24))
+ if (Build.VERSION.SDK_INT >= 31) {
+ builder.setCustomContentView(pairingKeypad(keyHeightDp = 21))
+ }
+ }
+ }
}
is Stage.Working -> builder
.setContentTitle(getString(R.string.adbpair_title_working))
@@ -254,14 +306,39 @@ class WirelessAdbPairingService : Service() {
return builder.build()
}
+ private fun pairingKeypad(keyHeightDp: Int? = null): RemoteViews = RemoteViews(packageName, R.layout.wireless_pairing_keypad).apply {
+ val ids = intArrayOf(R.id.pair_key_0, R.id.pair_key_1, R.id.pair_key_2, R.id.pair_key_3, R.id.pair_key_4,
+ R.id.pair_key_5, R.id.pair_key_6, R.id.pair_key_7, R.id.pair_key_8, R.id.pair_key_9,
+ R.id.pair_key_delete, R.id.pair_key_submit)
+ ids.forEachIndexed { key, id ->
+ if (keyHeightDp != null && Build.VERSION.SDK_INT >= 31) {
+ // Fit both rows inside the system template's heads-up or collapsed height.
+ setViewLayoutHeight(id, keyHeightDp.toFloat(), TypedValue.COMPLEX_UNIT_DIP)
+ setViewLayoutMargin(id, RemoteViews.MARGIN_TOP, 1f, TypedValue.COMPLEX_UNIT_DIP)
+ setViewLayoutMargin(id, RemoteViews.MARGIN_BOTTOM, 1f, TypedValue.COMPLEX_UNIT_DIP)
+ setTextViewTextSize(id, TypedValue.COMPLEX_UNIT_SP, if (keyHeightDp < 24) 14f else 15f)
+ }
+ val intent = Intent(this@WirelessAdbPairingService, WirelessAdbPairingService::class.java)
+ .setAction(ACTION_KEYPAD)
+ .setData(Uri.Builder().scheme("droiddeck-pairing").authority(keypadToken).appendPath(key.toString()).build())
+ val press = PendingIntent.getService(this@WirelessAdbPairingService, key, intent, PendingIntent.FLAG_IMMUTABLE)
+ setOnClickPendingIntent(id, press)
+ }
+ setTextViewText(R.id.pair_key_code, keypad.display)
+ setContentDescription(R.id.pair_key_code, getString(R.string.adbpair_keypad_entered, keypad.digits.length))
+ setBoolean(R.id.pair_key_delete, "setEnabled", keypad.digits.isNotEmpty())
+ setBoolean(R.id.pair_key_submit, "setEnabled", keypad.ready && pairingPort != null)
+ }
+
companion object {
private const val CHANNEL_ID = "wireless-adb-pairing"
private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress"
private const val NOTIFICATION_ID = 3
+ private const val KEYPAD_NOTIFICATION_ID = 3403
+ private const val KEYPAD_GROUP = "wireless-adb-keypad"
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
- private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
+ private const val ACTION_KEYPAD = "com.droiddeck.launcher.action.WIRELESS_ADB_KEYPAD"
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
- private const val KEY_CODE = "code"
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
private const val TIMEOUT_MS = 5 * 60_000L
@@ -288,7 +365,7 @@ class WirelessAdbPairingService : Service() {
fun notificationsEnabled(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context)
- /** The code is typed into a notification on this channel; a channel the user switched off leaves pairing with nothing to type into. */
+ /** Pairing needs this notification channel to show the keypad over Android Settings. */
fun channelBlocked(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessPairingKeypad.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessPairingKeypad.kt
new file mode 100644
index 0000000000..942911a78d
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessPairingKeypad.kt
@@ -0,0 +1,29 @@
+package com.droiddeck.launcher.core
+
+internal class WirelessPairingKeypad {
+ var digits = ""
+ private set
+ val ready: Boolean get() = digits.length == LENGTH
+ val display: String get() = digits.padEnd(LENGTH, '–')
+
+ fun press(key: Int): Boolean {
+ val next = when {
+ key == DELETE -> digits.dropLast(1)
+ key in 0..9 && !ready -> digits + key
+ else -> digits
+ }
+ if (next == digits) return false
+ digits = next
+ return true
+ }
+
+ fun clear() {
+ digits = ""
+ }
+
+ companion object {
+ const val LENGTH = 6
+ const val DELETE = 10
+ const val SUBMIT = 11
+ }
+}
diff --git a/app/src/main/res/color/wireless_pairing_key_text.xml b/app/src/main/res/color/wireless_pairing_key_text.xml
new file mode 100644
index 0000000000..62b63fbefb
--- /dev/null
+++ b/app/src/main/res/color/wireless_pairing_key_text.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/app/src/main/res/drawable/wireless_pairing_key.xml b/app/src/main/res/drawable/wireless_pairing_key.xml
new file mode 100644
index 0000000000..51bffe4ff2
--- /dev/null
+++ b/app/src/main/res/drawable/wireless_pairing_key.xml
@@ -0,0 +1,15 @@
+
+
+ -
+
+
+ -
+
+
+ -
+
+
+ -
+
+
+
diff --git a/app/src/main/res/drawable/wireless_pairing_panel.xml b/app/src/main/res/drawable/wireless_pairing_panel.xml
new file mode 100644
index 0000000000..4e88b9b826
--- /dev/null
+++ b/app/src/main/res/drawable/wireless_pairing_panel.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/app/src/main/res/layout/wireless_pairing_keypad.xml b/app/src/main/res/layout/wireless_pairing_keypad.xml
new file mode 100644
index 0000000000..159a4e75fd
--- /dev/null
+++ b/app/src/main/res/layout/wireless_pairing_keypad.xml
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml
index f72526ba2e..482a0b7393 100644
--- a/app/src/main/res/values-ar/strings.xml
+++ b/app/src/main/res/values-ar/strings.xml
@@ -2419,7 +2419,6 @@
فعِّل تصحيح الأخطاء اللاسلكي، ثم اضغط على «إقران الجهاز برمز الإقران».
فعِّل تصحيح الأخطاء اللاسلكي، ثم اضغط على «إقران الجهاز برمز الإقران». ابقَ في الإعدادات: يُكتب الرمز في هذا الإشعار.
رمز الإقران المكوَّن من 6 أرقام
- اضغط على «إدخال الرمز» وأدخِل الأرقام الستة الظاهرة في الإعدادات.
أدخِل رمز إقران Wi-Fi
أعِد تجربة الرمز
إدخال الرمز
diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml
index 1a4a746fa1..9f443f72ef 100644
--- a/app/src/main/res/values-b+es+419/strings.xml
+++ b/app/src/main/res/values-b+es+419/strings.xml
@@ -2411,7 +2411,6 @@
Activa la Depuración inalámbrica y toca “Vincular dispositivo con código de vinculación”.
Activa la Depuración inalámbrica y toca “Vincular dispositivo con código de vinculación”. Quédate en Ajustes: el código se ingresa en esta notificación.
Código de vinculación de 6 dígitos
- Toca Ingresar código y escribe los 6 dígitos que muestra Ajustes.
Ingresa el código de vinculación Wi-Fi
Vuelve a probar el código
Ingresar código
diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml
index f1ccdd13bc..7e60a6b97b 100644
--- a/app/src/main/res/values-bg/strings.xml
+++ b/app/src/main/res/values-bg/strings.xml
@@ -2315,7 +2315,6 @@
Включи безжичното отстраняване на грешки, после докосни „Чифтосване на устройство с код за чифтосване“.
Включи безжичното отстраняване на грешки, после докосни „Чифтосване на устройство с код за чифтосване“. Остани в Настройки: кодът ще се появи в това известие.
6-цифрен код за чифтосване
- Докосни „Въвеждане на код“ и напиши 6-те цифри, показани в Настройки.
Въведи кода за чифтосване по Wi-Fi
Опитай кода отново
Въвеждане на код
diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml
index 0b68d95cf7..1ce3b8dc74 100644
--- a/app/src/main/res/values-cs/strings.xml
+++ b/app/src/main/res/values-cs/strings.xml
@@ -2367,7 +2367,6 @@
Zapněte bezdrátové ladění a pak klepněte na „Párování zařízení pomocí párovacího kódu“.
Zapněte bezdrátové ladění a pak klepněte na „Párování zařízení pomocí párovacího kódu“. Zůstaňte v Nastavení: kód se zobrazí v tomto oznámení.
6místný párovací kód
- Klepněte na Zadat kód a napište 6 číslic zobrazených v Nastavení.
Zadejte párovací kód Wi-Fi
Zkusit kód znovu
Zadat kód
diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml
index a15253a46f..5d6672677e 100644
--- a/app/src/main/res/values-da/strings.xml
+++ b/app/src/main/res/values-da/strings.xml
@@ -2315,7 +2315,6 @@
Tænd Trådløs fejlretning, og tryk derefter på „Par enhed med parringskode“.
Tænd Trådløs fejlretning, og tryk derefter på „Par enhed med parringskode“. Bliv i Indstillinger: koden vises i denne notifikation.
6-cifret parringskode
- Tryk på Indtast kode, og skriv de 6 cifre, der vises i Indstillinger.
Indtast Wi-Fi-parringskoden
Forsøg koden igen
Indtast kode
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index a050e14efe..d619b039fd 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -2307,7 +2307,6 @@
Aktiviere Debugging über WLAN und tippe dann auf „Gerät mit Kopplungscode koppeln“.
Aktiviere Debugging über WLAN und tippe dann auf „Gerät mit Kopplungscode koppeln“. Bleib in den Einstellungen: Der Code wird in dieser Benachrichtigung eingegeben.
6-stelliger Kopplungscode
- Tippe auf „Code eingeben“ und gib die 6 Ziffern aus den Einstellungen ein.
WLAN-Kopplungscode eingeben
Code noch einmal eingeben
Code eingeben
diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml
index bb2561f6b1..6ce8a1b5c4 100644
--- a/app/src/main/res/values-el/strings.xml
+++ b/app/src/main/res/values-el/strings.xml
@@ -2315,7 +2315,6 @@
Ενεργοποιήστε τον ασύρματο εντοπισμό σφαλμάτων και πατήστε «Σύζευξη συσκευής με κωδικό σύζευξης».
Ενεργοποιήστε τον ασύρματο εντοπισμό σφαλμάτων και πατήστε «Σύζευξη συσκευής με κωδικό σύζευξης». Παραμείνετε στις Ρυθμίσεις: ο κωδικός εμφανίζεται σε αυτή την ειδοποίηση.
Εξαψήφιος κωδικός σύζευξης
- Πατήστε Εισαγωγή κωδικού και πληκτρολογήστε τα 6 ψηφία που εμφανίζονται στις Ρυθμίσεις.
Εισαγάγετε τον κωδικό σύζευξης Wi-Fi
Δοκιμάστε ξανά τον κωδικό
Εισαγωγή κωδικού
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 0e1d1ae717..abe9f2a9b2 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -2341,7 +2341,6 @@
Activa la Depuración inalámbrica y toca “Vincular dispositivo con código de vinculación”.
Activa la Depuración inalámbrica y toca “Vincular dispositivo con código de vinculación”. Quédate en Ajustes: el código se introduce en esta notificación.
Código de vinculación de 6 dígitos
- Toca Introducir código y escribe los 6 dígitos que muestra Ajustes.
Introduce el código de vinculación Wi-Fi
Vuelve a probar el código
Introducir código
diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml
index f50c60b125..113ef7fecb 100644
--- a/app/src/main/res/values-fi/strings.xml
+++ b/app/src/main/res/values-fi/strings.xml
@@ -2315,7 +2315,6 @@
Ota langaton virheenkorjaus käyttöön ja napauta ”Yhdistä laite paritunnuksella”.
Ota langaton virheenkorjaus käyttöön ja napauta ”Yhdistä laite paritunnuksella”. Pysy Asetuksissa: koodi syötetään tähän ilmoitukseen.
6-numeroinen paritunnus
- Napauta Syötä koodi ja kirjoita Asetuksissa näkyvät 6 numeroa.
Anna Wi-Fi-paritunnus
Yritä koodia uudelleen
Syötä koodi
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index fa2b370772..51b795bc84 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -2340,7 +2340,6 @@
Activez le débogage sans fil, puis appuyez sur « Associer l\'appareil avec un code d\'appairage ».
Activez le débogage sans fil, puis appuyez sur « Associer l\'appareil avec un code d\'appairage ». Restez dans les paramètres : le code se saisit dans cette notification.
Code d\'appairage à 6 chiffres
- Appuyez sur « Saisir le code » et tapez les 6 chiffres affichés dans les paramètres.
Saisissez le code d\'appairage Wi-Fi
Saisissez à nouveau le code
Saisir le code
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 57ece37715..d70b2892c8 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -2315,7 +2315,6 @@
वायरलेस डीबगिंग चालू करें, फिर “Pair device with pairing code” पर टैप करें।
वायरलेस डीबगिंग चालू करें, फिर “Pair device with pairing code” पर टैप करें। Settings में बने रहें: कोड इस नोटिफ़िकेशन में आता है।
6 अंकों का पेयरिंग कोड
- Enter code पर टैप करें और Settings में दिखाए गए 6 अंक टाइप करें।
Wi-Fi पेयरिंग कोड डालें
कोड फिर से आज़माएं
कोड डालें
diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml
index 93e0bd906a..f37bbe9b47 100644
--- a/app/src/main/res/values-hu/strings.xml
+++ b/app/src/main/res/values-hu/strings.xml
@@ -2315,7 +2315,6 @@
Kapcsolja be a vezeték nélküli hibakeresést, majd koppintson az „Eszköz párosítása párosítási kóddal” lehetőségre.
Kapcsolja be a vezeték nélküli hibakeresést, majd koppintson az „Eszköz párosítása párosítási kóddal” lehetőségre. Maradjon a Beállításokban: a kód ebbe az értesítésbe kerül.
6 számjegyű párosítási kód
- Koppintson a Kód megadására, és írja be a Beállításokban megjelenő 6 számjegyet.
Adja meg a Wi-Fi párosítási kódot
Próbálja meg újra a kódot
Kód megadása
diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml
index 51741a52d4..16a387909e 100644
--- a/app/src/main/res/values-in/strings.xml
+++ b/app/src/main/res/values-in/strings.xml
@@ -2290,7 +2290,6 @@
Aktifkan Debugging nirkabel, lalu ketuk “Pasangkan perangkat dengan kode pemasangan”.
Aktifkan Debugging nirkabel, lalu ketuk “Pasangkan perangkat dengan kode pemasangan”. Tetap di Setelan: kodenya akan muncul di notifikasi ini.
Kode pemasangan 6 digit
- Ketuk Masukkan kode dan ketikkan 6 digit yang ditampilkan di Setelan.
Masukkan kode pemasangan Wi-Fi
Coba kode lagi
Masukkan kode
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index f8972c12bf..19391afb90 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -2332,7 +2332,6 @@
Attiva Debug wireless, poi tocca “Accoppia dispositivo con codice di accoppiamento”.
Attiva Debug wireless, poi tocca “Accoppia dispositivo con codice di accoppiamento”. Resta in Impostazioni: il codice va inserito in questa notifica.
Codice di accoppiamento a 6 cifre
- Tocca Inserisci codice e digita le 6 cifre mostrate in Impostazioni.
Inserisci il codice di accoppiamento Wi-Fi
Riprova con il codice
Inserisci codice
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index 6ed0728576..d59e899b39 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -2290,7 +2290,6 @@
ワイヤレスデバッグをオンにして、「ペアリングコードでデバイスをペア設定」をタップしてください。
ワイヤレスデバッグをオンにして、「ペアリングコードでデバイスをペア設定」をタップしてください。設定画面のままにしてください:コードはこの通知に入力します。
6桁のペアリングコード
- 「コードを入力」をタップし、設定に表示された6桁の数字を入力してください。
Wi-Fiペアリングコードを入力
コードをもう一度入力
コードを入力
diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml
index 73d71c6e11..ce421947f1 100644
--- a/app/src/main/res/values-ko/strings.xml
+++ b/app/src/main/res/values-ko/strings.xml
@@ -2290,7 +2290,6 @@
무선 디버깅을 켠 다음 “페어링 코드로 기기 페어링”을 탭하세요.
무선 디버깅을 켠 다음 “페어링 코드로 기기 페어링”을 탭하세요. 코드는 이 알림에 입력하므로 설정 화면에 머물러 있으세요.
6자리 페어링 코드
- \"코드 입력\"을 탭하고 설정에 표시된 6자리 숫자를 입력하세요.
Wi-Fi 페어링 코드 입력
코드를 다시 입력하세요
코드 입력
diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml
index 1272676fb4..3f6880ad2f 100644
--- a/app/src/main/res/values-ms/strings.xml
+++ b/app/src/main/res/values-ms/strings.xml
@@ -2290,7 +2290,6 @@
Hidupkan Debugging Wayarles, kemudian ketik “Gandingkan peranti dengan kod gandingan”.
Hidupkan Debugging Wayarles, kemudian ketik “Gandingkan peranti dengan kod gandingan”. Kekal dalam Tetapan: kod akan masuk dalam pemberitahuan ini.
Kod gandingan 6 digit
- Ketik Masukkan kod dan taip 6 digit yang dipaparkan dalam Tetapan.
Masukkan kod gandingan Wi-Fi
Cuba kod itu sekali lagi
Masukkan kod
diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml
index b0ed7518e9..da7973003d 100644
--- a/app/src/main/res/values-nb/strings.xml
+++ b/app/src/main/res/values-nb/strings.xml
@@ -2315,7 +2315,6 @@
Slå på trådløs feilsøking, og trykk så på «Par enhet med koblingskode».
Slå på trådløs feilsøking, og trykk så på «Par enhet med koblingskode». Hold deg i Innstillinger: koden kommer i denne varslingen.
6-tallers koblingskode
- Trykk på Skriv inn kode og skriv de 6 tallene som vises i Innstillinger.
Skriv inn Wi-Fi-koblingskoden
Prøv koden igjen
Skriv inn kode
diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml
index 51faec8331..529163c725 100644
--- a/app/src/main/res/values-nl/strings.xml
+++ b/app/src/main/res/values-nl/strings.xml
@@ -2315,7 +2315,6 @@
Schakel draadloze foutopsporing in en tik vervolgens op “Apparaat koppelen met koppelcode”.
Schakel draadloze foutopsporing in en tik vervolgens op “Apparaat koppelen met koppelcode”. Blijf in Instellingen: de code komt in deze melding.
Koppelcode van 6 cijfers
- Tik op Code invoeren en typ de 6 cijfers die in Instellingen worden getoond.
Voer de Wi-Fi-koppelcode in
Probeer de code opnieuw
Code invoeren
diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml
index c58ee37170..594dd86aed 100644
--- a/app/src/main/res/values-pl/strings.xml
+++ b/app/src/main/res/values-pl/strings.xml
@@ -2367,7 +2367,6 @@
Włącz Debugowanie bezprzewodowe, a potem dotknij „Sparuj urządzenie za pomocą kodu parowania”.
Włącz Debugowanie bezprzewodowe, a potem dotknij „Sparuj urządzenie za pomocą kodu parowania”. Pozostań w Ustawieniach: kod wpiszesz w tym powiadomieniu.
6-cyfrowy kod parowania
- Dotknij „Wpisz kod” i podaj 6 cyfr widocznych w Ustawieniach.
Wpisz kod parowania Wi-Fi
Spróbuj wpisać kod ponownie
Wpisz kod
diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml
index 28e0cbd71f..65c9cdbebf 100644
--- a/app/src/main/res/values-pt-rPT/strings.xml
+++ b/app/src/main/res/values-pt-rPT/strings.xml
@@ -2347,7 +2347,6 @@
Ative a depuração sem fios e toque em «Sincronizar dispositivo com código de sincronização».
Ative a depuração sem fios e toque em «Sincronizar dispositivo com código de sincronização». Fique nas Definições: o código é introduzido nesta notificação.
Código de sincronização de 6 dígitos
- Toque em Introduzir código e escreva os 6 dígitos mostrados nas Definições.
Introduza o código de sincronização Wi-Fi
Introduza o código novamente
Introduzir código
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 0008c90bba..c5a841b99d 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -2355,7 +2355,6 @@
Ative a depuração por Wi-Fi e toque em “Parear o dispositivo com um código de pareamento”.
Ative a depuração por Wi-Fi e toque em “Parear o dispositivo com um código de pareamento”. Fique nas Configurações: o código é digitado nesta notificação.
Código de pareamento de 6 dígitos
- Toque em Digitar código e insira os 6 dígitos mostrados nas Configurações.
Digite o código de pareamento por Wi-Fi
Tente o código de novo
Digitar código
diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml
index fd3323ac71..bb3ba2645a 100644
--- a/app/src/main/res/values-ro/strings.xml
+++ b/app/src/main/res/values-ro/strings.xml
@@ -2341,7 +2341,6 @@
Activează Depanarea wireless, apoi apasă „Asociază dispozitivul cu un cod de asociere”.
Activează Depanarea wireless, apoi apasă „Asociază dispozitivul cu un cod de asociere”. Rămâi în Setări: codul apare în această notificare.
Cod de asociere din 6 cifre
- Apasă Introdu codul și scrie cele 6 cifre arătate în Setări.
Introdu codul de asociere Wi-Fi
Încearcă codul din nou
Introdu codul
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index a831dcfd41..cb5131c8de 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -2368,7 +2368,6 @@
Включите отладку по Wi-Fi и нажмите «Сопряжение устройства с помощью кода».
Включите отладку по Wi-Fi и нажмите «Сопряжение устройства с помощью кода». Не выходите из Настроек: код вводится в этом уведомлении.
6-значный код сопряжения
- Нажмите «Ввести код» и введите 6 цифр, показанных в Настройках.
Введите код сопряжения Wi-Fi
Введите код еще раз
Ввести код
diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml
index 4bbd572c0a..5ffcf3e027 100644
--- a/app/src/main/res/values-sv/strings.xml
+++ b/app/src/main/res/values-sv/strings.xml
@@ -2315,7 +2315,6 @@
Slå på trådlös felsökning och tryck sedan på ”Parkoppla enhet med parkopplingskod”.
Slå på trådlös felsökning och tryck sedan på ”Parkoppla enhet med parkopplingskod”. Stanna kvar i Inställningar: koden skrivs in i den här aviseringen.
6-siffrig parkopplingskod
- Tryck på Ange kod och skriv de 6 siffrorna som visas i Inställningar.
Ange Wi-Fi-parkopplingskoden
Försök med koden igen
Ange kod
diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml
index 9a8d17b824..afc6037646 100644
--- a/app/src/main/res/values-th/strings.xml
+++ b/app/src/main/res/values-th/strings.xml
@@ -2290,7 +2290,6 @@
เปิด Wireless debugging แล้วแตะ “Pair device with pairing code”
เปิด Wireless debugging แล้วแตะ “Pair device with pairing code” อยู่ในการตั้งค่าต่อไป: รหัสจะอยู่ในการแจ้งเตือนนี้
รหัสจับคู่ 6 หลัก
- แตะกรอกรหัสแล้วพิมพ์ตัวเลข 6 หลักที่แสดงในการตั้งค่า
กรอกรหัสจับคู่ Wi-Fi
ลองกรอกรหัสอีกครั้ง
กรอกรหัส
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 4b42db49c9..8986422061 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -2307,7 +2307,6 @@
Kablosuz hata ayıklamayı açın, sonra “Eşleştirme koduyla cihaz eşle” seçeneğine dokunun.
Kablosuz hata ayıklamayı açın, sonra “Eşleştirme koduyla cihaz eşle” seçeneğine dokunun. Ayarlar\'dan çıkmayın: kod bu bildirime gelir.
6 haneli eşleştirme kodu
- Kodu gir\'e dokunun ve Ayarlar\'da gösterilen 6 haneyi yazın.
Wi-Fi eşleştirme kodunu girin
Kodu yeniden deneyin
Kodu gir
diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml
index 90903be02d..1acda2257b 100644
--- a/app/src/main/res/values-uk/strings.xml
+++ b/app/src/main/res/values-uk/strings.xml
@@ -2367,7 +2367,6 @@
Увімкніть бездротове налагодження, потім торкніться «Прив’язати пристрій за кодом прив’язки».
Увімкніть бездротове налагодження, потім торкніться «Прив’язати пристрій за кодом прив’язки». Залишайтеся в «Налаштуваннях»: код з’явиться в цьому сповіщенні.
6-значний код прив’язки
- Торкніться «Ввести код» і введіть 6 цифр, показаних у «Налаштуваннях».
Введіть код прив’язки Wi-Fi
Спробуйте код ще раз
Ввести код
diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml
index 47a25c8975..62b8003f40 100644
--- a/app/src/main/res/values-vi/strings.xml
+++ b/app/src/main/res/values-vi/strings.xml
@@ -2290,7 +2290,6 @@
Bật Gỡ lỗi qua mạng không dây, rồi nhấn “Pair device with pairing code”.
Bật Gỡ lỗi qua mạng không dây, rồi nhấn “Pair device with pairing code”. Ở lại trong Settings: mã sẽ hiện trong thông báo này.
Mã ghép nối 6 số
- Nhấn Enter code và nhập 6 số hiện trong Settings.
Nhập mã ghép nối Wi-Fi
Thử lại mã
Nhập mã
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index 531a9c00ec..c92dd86eac 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -2367,7 +2367,6 @@
开启无线调试,然后点按“使用配对码配对设备”。
开启无线调试,然后点按“使用配对码配对设备”。请停留在“设置”中:配对码在此通知中输入。
6 位配对码
- 点按“输入配对码”,然后输入“设置”中显示的 6 位数字。
输入 Wi-Fi 配对码
请重新输入配对码
输入配对码
diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml
index f497ca0fc6..84dc0fd288 100644
--- a/app/src/main/res/values-zh-rHK/strings.xml
+++ b/app/src/main/res/values-zh-rHK/strings.xml
@@ -2289,7 +2289,6 @@
開啟無線偵錯,然後輕按「使用配對碼配對裝置」。
開啟無線偵錯,然後輕按「使用配對碼配對裝置」。請留在「設定」中:配對碼需在此通知中輸入。
6 位數配對碼
- 輕按「輸入配對碼」,然後輸入「系統設定」中顯示的 6 位數字。
輸入 Wi-Fi 配對碼
請再次輸入配對碼
輸入配對碼
diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml
index 1c0a3db86f..2c71886340 100644
--- a/app/src/main/res/values-zh-rTW/strings.xml
+++ b/app/src/main/res/values-zh-rTW/strings.xml
@@ -2289,7 +2289,6 @@
開啟無線偵錯,然後點擊「使用配對碼配對裝置」。
開啟無線偵錯,然後點擊「使用配對碼配對裝置」。請留在「設定」中:配對碼要輸入在這則通知裡。
6 位數配對碼
- 點擊「輸入配對碼」,然後輸入「Android 設定」中顯示的 6 位數字。
輸入 Wi-Fi 配對碼
請再次輸入配對碼
輸入配對碼
diff --git a/app/src/main/res/values/pairing_keypad_styles.xml b/app/src/main/res/values/pairing_keypad_styles.xml
new file mode 100644
index 0000000000..6d1b8cd50b
--- /dev/null
+++ b/app/src/main/res/values/pairing_keypad_styles.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 26c5d04baa..37832231c0 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1471,7 +1471,7 @@
Wireless debugging needs Wi-Fi. Any network works; it doesn\'t need internet.
Open Settings → Developer options → Wireless debugging and turn it on
Tap “Pair device with pairing code”
- Type the code into the DroidDeck notification
+ Tap ▼ to keep the keypad open. Swipe down if it closes.
In About phone, tap Build number 7 times
Turn on Wireless debugging
Open Wireless debugging, then tap “Pair device with pairing code”
@@ -2642,10 +2642,11 @@
Turn on Wireless debugging, then tap “Pair device with pairing code”.
Turn on Wireless debugging, then tap “Pair device with pairing code”. Stay in Settings: the code goes in this notification.
6-digit pairing code
- Tap Enter code and type the 6 digits shown in Settings.
+ %1$d of 6 digits entered
+ Delete last digit
Enter the Wi-Fi pairing code
Try the code again
- Enter code
+ Tap ✓ to pair
Setting up Steam
Steam is ready
Tap to go back to DroidDeck. You can turn Wireless debugging off now.
diff --git a/app/src/test/java/com/droiddeck/launcher/core/WirelessAdbReconnectTest.kt b/app/src/test/java/com/droiddeck/launcher/core/WirelessAdbReconnectTest.kt
new file mode 100644
index 0000000000..71efb6614e
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/core/WirelessAdbReconnectTest.kt
@@ -0,0 +1,57 @@
+package com.droiddeck.launcher.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class WirelessAdbReconnectTest {
+ private val local = WirelessAdbFix.LOOPBACK
+ private val old = 35555
+ private val current = 36666
+
+ @Test
+ fun localPortRotationWithoutMdnsUsesPairedKeyFallback() {
+ var scanned = false
+ val result = WirelessAdbFix.chooseConnectPort(
+ local, old, property = { old }, advertised = { accept ->
+ check(!accept(old))
+ null
+ }, answers = { it == old }, authenticatedLocal = {
+ scanned = true
+ current
+ },
+ )
+ assertEquals(current, result)
+ check(scanned)
+ }
+
+ @Test
+ fun localPortFromPropertyAvoidsDiscoveryAndScan() {
+ val result = WirelessAdbFix.chooseConnectPort(
+ local, old, property = { current }, advertised = { error("unexpected NSD") },
+ answers = { it == current }, authenticatedLocal = { error("unexpected scan") },
+ )
+ assertEquals(current, result)
+ }
+
+ @Test
+ fun staleLocalAdvertisementDoesNotBlockNextValidPort() {
+ val result = WirelessAdbFix.chooseConnectPort(
+ local, old, property = { null },
+ advertised = { accept -> listOf(old, 35000, current).firstOrNull(accept) },
+ answers = { it == current }, authenticatedLocal = { error("unexpected scan") },
+ )
+ assertEquals(current, result)
+ }
+
+ @Test
+ fun remoteSavedConnectNeverUsesLocalPropertyOrScan() {
+ val result = WirelessAdbFix.chooseConnectPort(
+ "203.0.113.10", old, property = { error("unexpected local property") },
+ advertised = { accept -> listOf(old).firstOrNull(accept) },
+ answers = { error("unexpected local reachability check") },
+ authenticatedLocal = { error("unexpected loopback scan") },
+ )
+ assertNull(result)
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/core/WirelessPairingKeypadTest.kt b/app/src/test/java/com/droiddeck/launcher/core/WirelessPairingKeypadTest.kt
new file mode 100644
index 0000000000..975a962b15
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/core/WirelessPairingKeypadTest.kt
@@ -0,0 +1,38 @@
+package com.droiddeck.launcher.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class WirelessPairingKeypadTest {
+ @Test fun sixDigitsKeepLeadingZeroesAndRejectExtraKeys() {
+ val pad = WirelessPairingKeypad()
+ assertFalse(pad.ready)
+ listOf(0, 0, 1, 2, 3, 4).forEach { assertTrue(pad.press(it)) }
+ assertTrue(pad.ready)
+ assertFalse(pad.press(5))
+ assertFalse(pad.press(WirelessPairingKeypad.SUBMIT))
+ assertEquals("001234", pad.digits)
+ }
+
+ @Test fun deleteLetsYouCorrectTheLastDigit() {
+ val pad = WirelessPairingKeypad()
+ assertFalse(pad.press(WirelessPairingKeypad.DELETE))
+ "321987".forEach { pad.press(it.digitToInt()) }
+ assertTrue(pad.press(WirelessPairingKeypad.DELETE))
+ assertFalse(pad.ready)
+ assertEquals("32198–", pad.display)
+ assertTrue(pad.press(6))
+ assertEquals("321986", pad.digits)
+ }
+
+ @Test fun startingAnotherAttemptClearsTheCode() {
+ val pad = WirelessPairingKeypad()
+ assertFalse(pad.press(-1))
+ pad.press(7)
+ pad.clear()
+ assertEquals("", pad.digits)
+ assertEquals("––––––", pad.display)
+ }
+}
From 1596e2966d2fd6937066cd979e6c84c3de9885f9 Mon Sep 17 00:00:00 2001
From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Date: Sat, 5 Dec 2026 17:28:14 -0500
Subject: [PATCH 5/8] Organize Developer settings and label droiddeckctl
(#3770)
---
.../droiddeck/launcher/FrontEndActivity.kt | 3 +-
.../droiddeck/launcher/agent/AgentAccess.kt | 2 +-
.../droiddeck/launcher/ui/FrontEndScreen.kt | 2 +-
.../droiddeck/launcher/ui/FrontEndSetup.kt | 143 ++++++++++--------
.../droiddeck/launcher/ui/SettingsIndex.kt | 3 +-
.../droiddeck/launcher/ui/SettingsWidgets.kt | 16 +-
app/src/main/res/values-ar/strings.xml | 1 -
app/src/main/res/values-b+es+419/strings.xml | 1 -
app/src/main/res/values-bg/strings.xml | 1 -
app/src/main/res/values-cs/strings.xml | 1 -
app/src/main/res/values-da/strings.xml | 1 -
app/src/main/res/values-de/strings.xml | 1 -
app/src/main/res/values-el/strings.xml | 1 -
app/src/main/res/values-es/strings.xml | 1 -
app/src/main/res/values-fi/strings.xml | 1 -
app/src/main/res/values-fr/strings.xml | 1 -
app/src/main/res/values-hi/strings.xml | 1 -
app/src/main/res/values-hu/strings.xml | 1 -
app/src/main/res/values-in/strings.xml | 1 -
app/src/main/res/values-it/strings.xml | 1 -
app/src/main/res/values-ja/strings.xml | 1 -
app/src/main/res/values-ko/strings.xml | 1 -
app/src/main/res/values-ms/strings.xml | 1 -
app/src/main/res/values-nb/strings.xml | 1 -
app/src/main/res/values-nl/strings.xml | 1 -
app/src/main/res/values-pl/strings.xml | 1 -
app/src/main/res/values-pt-rPT/strings.xml | 1 -
app/src/main/res/values-pt/strings.xml | 1 -
app/src/main/res/values-ro/strings.xml | 1 -
app/src/main/res/values-ru/strings.xml | 1 -
app/src/main/res/values-sv/strings.xml | 1 -
app/src/main/res/values-th/strings.xml | 1 -
app/src/main/res/values-tr/strings.xml | 1 -
app/src/main/res/values-uk/strings.xml | 1 -
app/src/main/res/values-vi/strings.xml | 1 -
app/src/main/res/values-zh-rCN/strings.xml | 1 -
app/src/main/res/values-zh-rHK/strings.xml | 1 -
app/src/main/res/values-zh-rTW/strings.xml | 1 -
app/src/main/res/values/strings.xml | 13 +-
docs/agent-control.md | 8 +-
docs/development/boot-movies.md | 2 +-
docs/development/proot-performance.md | 2 +-
docs/phantom-processes.md | 2 +-
docs/settings-map.md | 3 +-
tools/droiddeckctl | 2 +-
tools/tests/test_droiddeckctl.py | 2 +-
46 files changed, 114 insertions(+), 121 deletions(-)
diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
index 9a109df4d2..08b966e98b 100644
--- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
@@ -1765,13 +1765,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}, "delete-session-logs").start()
},
- onClearLogs = {
+ onClearLogs = { done ->
Thread({
val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0)
ui.post {
android.widget.Toast.makeText(this,
if (cleared == 0) getString(R.string.main_no_logs_to_clear) else resources.getQuantityString(R.plurals.main_logs_cleared, cleared, cleared),
android.widget.Toast.LENGTH_SHORT).show()
+ done()
}
}, "clear-logs").start()
},
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentAccess.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentAccess.kt
index 2113161467..9c4659a550 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentAccess.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentAccess.kt
@@ -23,7 +23,7 @@ object AgentAccess {
fun requireCommands(context: Context) {
if (!commandsAllowed(context)) throw AgentException(
"AGENT_COMMANDS_DISABLED",
- "Debugging tools are off: turn on Setup > Developer > Debugging tools on the device",
+ "droiddeckctl is off: turn on Setup > Developer > droiddeckctl on the device",
)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
index ff50841c75..b7bf1caaa0 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
@@ -278,7 +278,7 @@ class FrontEndActions(
val onShareSessionLog: (File) -> Unit = {},
val onSaveSessionLog: (File) -> Unit = {},
val onDeleteSessionLog: (File, () -> Unit) -> Unit = { _, done -> done() },
- val onClearLogs: () -> Unit = {},
+ val onClearLogs: (() -> Unit) -> Unit = {},
val onResetSettings: () -> Unit = {},
val onOffline: () -> Unit,
val onOfflineAuto: () -> Unit = {},
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
index 0cda817452..b2e989f568 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
@@ -685,89 +685,102 @@ internal fun SetupPanel(
}
}
DEVELOPER_TAB -> {
- val devContext = LocalContext.current
+ var manageLogs by rememberSaveable { mutableStateOf(false) }
SettingsGroup(stringResource(R.string.dev_tools_title)) {
- ToggleRow(host, "developer-tools", stringResource(R.string.dev_tools_title), stringResource(R.string.dev_tools_hint), DeveloperTools.on) {
- DeveloperTools.set(devContext, it)
+ ToggleRow(host, "developer-tools", stringResource(R.string.dev_tools_show), stringResource(R.string.dev_tools_hint), DeveloperTools.on, sideBySide = true) {
+ DeveloperTools.set(ctx, it)
+ }
+ if (DeveloperTools.on) ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), stringResource(R.string.setup_agent_commands_hint), s.agentCommands, sideBySide = true) { a.onAgentCommands() }
+ if (DeveloperTools.on && com.droiddeck.launcher.agent.AgentHost.available) {
+ ToggleRow(host, "agent-pet", stringResource(R.string.rail_agent), stringResource(R.string.dev_harness_overlay_hint), AgentPet.enabled, sideBySide = true) {
+ AgentPet.set(ctx, it)
+ }
+ if (AgentPet.enabled && !AgentPet.allowed && AgentPet.usesOverlayWindows(com.droiddeck.launcher.session.QuestExperimental.isSupported())) ActionRow(
+ stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint),
+ stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(ctx) }, sideBySide = true,
+ )
}
- if (DeveloperTools.on) ActionRow(
- stringResource(R.string.dev_ui_zoo), stringResource(R.string.dev_ui_zoo_hint), stringResource(R.string.dev_ui_zoo_open),
- onClick = { DevPreview.zoo = true }, modifier = Modifier.testTag("dev-ui-zoo"),
- )
- if (DeveloperTools.on) ToggleRow(
- host, "preview-shortcuts", stringResource(R.string.dev_preview_shortcuts), stringResource(R.string.dev_preview_shortcuts_hint),
- DevPreview.shortcuts,
- ) { DevPreview.setShortcuts(devContext, it) }
}
- SettingsGroup(stringResource(R.string.dev_group_logs)) {
- ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
+ if (DeveloperTools.on) SettingsGroup(stringResource(R.string.dev_group_previews)) {
+ ActionRow(
+ stringResource(R.string.dev_ui_zoo), stringResource(R.string.dev_ui_zoo_hint), stringResource(R.string.dev_ui_zoo_open),
+ onClick = { DevPreview.zoo = true }, modifier = Modifier.testTag("dev-ui-zoo"), sideBySide = true,
+ )
+ ToggleRow(
+ host, "preview-shortcuts", stringResource(R.string.dev_preview_shortcuts), stringResource(R.string.dev_preview_shortcuts_hint),
+ DevPreview.shortcuts, sideBySide = true,
+ ) { DevPreview.setShortcuts(ctx, it) }
+ }
+ SettingsGroup(stringResource(R.string.dev_group_diagnostics)) {
+ ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled, sideBySide = true) { a.onLogs() }
if (DeveloperTools.on) ToggleRow(
host, "enhanced-diagnostics", stringResource(R.string.setup_enhanced_diagnostics),
- stringResource(R.string.setup_enhanced_diagnostics_hint), s.enhancedDiagnosticsArmed,
+ stringResource(R.string.setup_enhanced_diagnostics_hint), s.enhancedDiagnosticsArmed, sideBySide = true,
) { a.onEnhancedDiagnostics() }
ToggleRow(
host, "game-debug-logs", stringResource(R.string.setup_game_debug_logs),
stringResource(if (s.gameDebugLogsNeedsRestart) R.string.setup_game_debug_logs_restart else R.string.setup_game_debug_logs_hint),
s.gameDebugLogsEnabled,
- enabled = s.logsEnabled,
+ enabled = s.logsEnabled, sideBySide = true,
) { a.onGameDebugLogs() }
- if (DeveloperTools.on) ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
- if (DeveloperTools.on) ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
- if (DeveloperTools.on && com.droiddeck.launcher.agent.AgentHost.available) {
- val agentContext = androidx.compose.ui.platform.LocalContext.current
- ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) {
- AgentPet.set(agentContext, it)
- }
- if (AgentPet.enabled && !AgentPet.allowed && AgentPet.usesOverlayWindows(com.droiddeck.launcher.session.QuestExperimental.isSupported())) ActionRow(
- stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint),
- stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) },
- )
- }
- if (DeveloperTools.on) ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() }
- if (DeveloperTools.on && !s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() }
+ if (DeveloperTools.on) ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics, sideBySide = true) { a.onVacDiagnostics() }
+ if (DeveloperTools.on) ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs, sideBySide = true) { a.onGraphicsLogs() }
+ if (DeveloperTools.on && !s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing, sideBySide = true) { a.onSteamGpuDrawing() }
+ }
+ SettingsGroup(stringResource(R.string.dev_group_log_files)) {
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
- progress = com.droiddeck.launcher.session.SessionLogShare.progress)
- androidx.compose.material3.HorizontalDivider()
- Text(stringResource(R.string.setup_log_sessions), fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
- color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
- Text(stringResource(R.string.setup_log_export_hint), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
- modifier = Modifier.padding(start = 14.dp, end = 14.dp, bottom = 8.dp))
- val sessionLogs = remember(ctx, logsRefresh) { com.droiddeck.launcher.session.SessionLogShare.sessions(ctx).asReversed() }
- if (sessionLogs.isEmpty()) {
- Text(stringResource(R.string.setup_log_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
- }
- sessionLogs.forEach { folder ->
- val active = folder == com.droiddeck.launcher.session.SessionPaths.current()
- var details by remember(folder) { mutableStateOf(null) }
- LaunchedEffect(folder, logsRefresh) {
- details = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
- com.droiddeck.launcher.session.SessionLogShare.details(folder)
- }
+ progress = com.droiddeck.launcher.session.SessionLogShare.progress, sideBySide = true)
+ ActionRow(
+ stringResource(R.string.setup_saved_logs), stringResource(R.string.dev_log_manage_hint),
+ stringResource(if (manageLogs) R.string.common_close else R.string.setup_manage),
+ onClick = { manageLogs = !manageLogs }, sideBySide = true,
+ )
+ if (manageLogs) {
+ Text(stringResource(R.string.setup_log_sessions), fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
+ color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
+ Text(stringResource(R.string.setup_log_export_hint), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(start = 14.dp, end = 14.dp, bottom = 8.dp))
+ val sessionLogs = remember(ctx, logsRefresh) { com.droiddeck.launcher.session.SessionLogShare.sessions(ctx).asReversed() }
+ if (sessionLogs.isEmpty()) {
+ Text(stringResource(R.string.setup_log_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
}
- Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp)) {
- Text(folder.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
- maxLines = 1, overflow = TextOverflow.Ellipsis)
- details?.let { detail ->
- Text(
- stringResource(R.string.setup_log_size_date,
- android.text.format.Formatter.formatShortFileSize(ctx, detail.sizeBytes),
- "${android.text.format.DateFormat.getDateFormat(ctx).format(java.util.Date(detail.modifiedAt))} ${android.text.format.DateFormat.getTimeFormat(ctx).format(java.util.Date(detail.modifiedAt))}"),
- fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
+ sessionLogs.forEach { folder ->
+ val active = folder == com.droiddeck.launcher.session.SessionPaths.current()
+ var details by remember(folder) { mutableStateOf(null) }
+ LaunchedEffect(folder, logsRefresh) {
+ details = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ com.droiddeck.launcher.session.SessionLogShare.details(folder)
+ }
}
- if (active) Text(stringResource(R.string.setup_log_current), fontSize = 12.sp, color = MaterialTheme.colorScheme.primary)
- Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- SecondaryButton(stringResource(R.string.setup_log_share), enabled = com.droiddeck.launcher.session.SessionLogShare.progress == null, compact = true, modifier = Modifier.weight(1f)) { a.onShareSessionLog(folder) }
- SecondaryButton(stringResource(R.string.setup_log_save), enabled = com.droiddeck.launcher.session.SessionLogShare.progress == null, compact = true, modifier = Modifier.weight(1f)) { a.onSaveSessionLog(folder) }
- SecondaryButton(stringResource(R.string.setup_log_delete), compact = true, enabled = !active, modifier = Modifier.weight(1f)) { deleteSessionLogs = folder }
+ Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp)) {
+ Text(folder.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
+ maxLines = 1, overflow = TextOverflow.Ellipsis)
+ details?.let { detail ->
+ Text(
+ stringResource(R.string.setup_log_size_date,
+ android.text.format.Formatter.formatShortFileSize(ctx, detail.sizeBytes),
+ "${android.text.format.DateFormat.getDateFormat(ctx).format(java.util.Date(detail.modifiedAt))} ${android.text.format.DateFormat.getTimeFormat(ctx).format(java.util.Date(detail.modifiedAt))}"),
+ fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ if (active) Text(stringResource(R.string.setup_log_current), fontSize = 12.sp, color = MaterialTheme.colorScheme.primary)
+ Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ SecondaryButton(stringResource(R.string.setup_log_share), enabled = com.droiddeck.launcher.session.SessionLogShare.progress == null, compact = true, modifier = Modifier.weight(1f)) { a.onShareSessionLog(folder) }
+ SecondaryButton(stringResource(R.string.setup_log_save), enabled = com.droiddeck.launcher.session.SessionLogShare.progress == null, compact = true, modifier = Modifier.weight(1f)) { a.onSaveSessionLog(folder) }
+ SecondaryButton(stringResource(R.string.setup_log_delete), compact = true, enabled = !active, modifier = Modifier.weight(1f)) { deleteSessionLogs = folder }
+ }
}
+ androidx.compose.material3.HorizontalDivider()
}
- androidx.compose.material3.HorizontalDivider()
+ ActionRow(stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS),
+ null, stringResource(R.string.setup_clear_logs),
+ onClick = { a.onClearLogs { logsRefresh++ } }, sideBySide = true)
}
- ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
+ }
+ SettingsGroup(stringResource(R.string.dev_group_reset)) {
ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint),
- stringResource(R.string.setup_reset_settings_button), a.onResetSettings)
+ stringResource(R.string.setup_reset_settings_button), a.onResetSettings, sideBySide = true)
}
}
GLASSES_TAB -> GlassesSetupPanel()
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
index f9bc7c1663..2bd881af35 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
@@ -131,7 +131,8 @@ internal object SettingsIndex {
s(SettingsSection.DEVELOPER, R.string.setup_game_debug_logs, "logs", "wine", "proton"),
SettingsEntry(SettingsPlace.SETTINGS, R.string.setup_enhanced_diagnostics, section = SettingsSection.DEVELOPER, words = listOf("logs"), developer = true),
s(SettingsSection.DEVELOPER, R.string.setup_reset_settings, "default"),
- s(SettingsSection.DEVELOPER, R.string.dev_tools_title, "agent", "ai", "claude", "codex"),
+ s(SettingsSection.DEVELOPER, R.string.dev_tools_show, "agent", "ai", "claude", "codex"),
+ SettingsEntry(SettingsPlace.SETTINGS, R.string.setup_agent_commands, section = SettingsSection.DEVELOPER, words = listOf("debugging tools", "cli"), developer = true),
SettingsEntry(SettingsPlace.SETTINGS, R.string.setup_graphics_logs, section = SettingsSection.DEVELOPER, words = listOf("logs", "gpu"), developer = true),
d(R.string.drawer_page_display, R.string.drawer_frame_limit, "fps", "cap", "limit", "non-steam", "desktop"),
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt
index 53a617b31b..b9ddae4311 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt
@@ -526,7 +526,7 @@ fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = nul
}
@Composable
-fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, tightControlSpacing: Boolean = false, control: @Composable () -> Unit) {
+fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, tightControlSpacing: Boolean = false, sideBySide: Boolean = false, control: @Composable () -> Unit) {
val compact = LocalCompactSettings.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -536,7 +536,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
lineHeight = if (compact) 14.sp else androidx.compose.ui.unit.TextUnit.Unspecified,
minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis)
}
- if (compact && !stacked) Column(
+ if (compact && !stacked && !sideBySide) Column(
modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -545,7 +545,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
control()
}
if (hint != null || hintLines != null) hintText(11.sp)
- } else if (stacked || LocalNarrowPane.current) Column(
+ } else if (stacked || (LocalNarrowPane.current && !sideBySide)) Column(
modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(
horizontal = if (compact) 10.dp else 14.dp,
vertical = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 12.dp),
@@ -613,8 +613,8 @@ fun UncertainMark(description: String) {
}
@Composable
-fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) =
- SettingsRow(label, hint) {
+fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, chipModifier: Modifier = Modifier, sideBySide: Boolean = false, onChange: (Boolean) -> Unit) =
+ SettingsRow(label, hint, sideBySide = sideBySide) {
ToggleSwitch(checked, enabled, label, chipModifier.testTag("setting-$key")) { host.open = null; onChange(it) }
}
@@ -774,8 +774,10 @@ fun MultiRow(
}
@Composable
-fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit, progress: Float? = null, modifier: Modifier = Modifier) {
- SettingsRow(label, hint) { SecondaryButton(button, modifier = modifier, progress = progress, onClick = onClick) }
+fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit, progress: Float? = null, modifier: Modifier = Modifier, sideBySide: Boolean = false) {
+ SettingsRow(label, hint, sideBySide = sideBySide) {
+ SecondaryButton(button, compact = sideBySide, modifier = modifier, progress = progress, onClick = onClick)
+ }
}
@Composable
diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml
index 482a0b7393..84fc3b2afd 100644
--- a/app/src/main/res/values-ar/strings.xml
+++ b/app/src/main/res/values-ar/strings.xml
@@ -891,7 +891,6 @@
تضمين بيانات تشخيص Proton وWine والرسومات عند تشغيل اللعبة التالية. قد يقلّل الأداء ويستهلك مساحة تخزين أكبر.
أعِد تشغيل هذه الجلسة لحفظ سجلات تصحيح الألعاب
تعذّر تحديث التسجيل. تحقّق من المفتاح وحاول مرة أخرى.
- أدوات تصحيح الأخطاء
سجلات رسوميات مفصلة
واجهة Steam: الرسم عبر GPU
مع زوج مشغّلات Xclipse، ترسم Steam صفحاتها برمجيًا (أظهر الرسم عبر GPU مربعات مشوهة). شغّله للحصول على واجهة Steam أسرع إذا بدت الصورة سليمة على هذا الهاتف.
diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml
index 9f443f72ef..eeae44f24d 100644
--- a/app/src/main/res/values-b+es+419/strings.xml
+++ b/app/src/main/res/values-b+es+419/strings.xml
@@ -909,7 +909,6 @@
Incluye diagnósticos de Proton, Wine y gráficos en el próximo inicio de un juego. Puede reducir el rendimiento y usar más almacenamiento.
Reinicia esta sesión para guardar los registros de depuración de juegos
No se pudo actualizar el registro. Revisa el interruptor e inténtalo de nuevo.
- Herramientas de depuración
Registros detallados de gráficos
Interfaz de Steam: dibujo con GPU
Con el par de controladores Xclipse, Steam dibuja sus páginas por software (el dibujo con GPU mostraba mosaicos con errores). Actívalo para una interfaz de Steam más rápida si se ve bien en este teléfono.
diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml
index 7e60a6b97b..c534d118b4 100644
--- a/app/src/main/res/values-bg/strings.xml
+++ b/app/src/main/res/values-bg/strings.xml
@@ -879,7 +879,6 @@
Включва диагностика на Proton, Wine и графиката при следващото стартиране на игра. Може да намали производителността и да заеме повече място.
Рестартирайте тази сесия, за да запазите дневниците за дебъгване на игри
Записването в дневник не можа да бъде променено. Проверете превключвателя и опитайте пак.
- Инструменти за отстраняване на грешки
Подробни дневници за графиката
Интерфейс на Steam: изрисуване чрез GPU
При двойката драйвери Xclipse Steam изрисува страниците си софтуерно (изрисуването чрез GPU даваше разбити плочки). Включи за по-бърз интерфейс на Steam, ако изглежда правилно на този телефон.
diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml
index 1ce3b8dc74..d6215c068f 100644
--- a/app/src/main/res/values-cs/strings.xml
+++ b/app/src/main/res/values-cs/strings.xml
@@ -885,7 +885,6 @@
Při dalším spuštění hry zahrnout diagnostiku Protonu, Wine a grafiky. Může snížit výkon a zabrat více úložiště.
Pro ukládání ladicích protokolů her restartujte tuto relaci
Protokolování se nepodařilo změnit. Zkontrolujte přepínač a zkuste to znovu.
- Nástroje pro ladění
Podrobné protokoly grafiky
Rozhraní Steam: vykreslování na GPU
S párem ovladačů Xclipse vykresluje Steam své stránky softwarově (vykreslování na GPU zobrazovalo poškozené dlaždice). Pokud na tomto telefonu vypadá správně, zapněte tuto možnost pro rychlejší rozhraní Steam.
diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml
index 5d6672677e..044fc5e95e 100644
--- a/app/src/main/res/values-da/strings.xml
+++ b/app/src/main/res/values-da/strings.xml
@@ -879,7 +879,6 @@
Medtag Proton-, Wine- og grafikdiagnostik ved næste spilstart. Kan reducere ydelsen og bruge mere lagerplads.
Genstart denne session for at gemme fejlfindingslogs for spil
Kunne ikke opdatere logning. Tjek kontakten, og prøv igen.
- Fejlfindingsværktøjer
Detaljerede grafiklogfiler
Steam-brugerflade: GPU-tegning
Med Xclipse-driverparret tegner Steam sine sider i software (GPU-tegning gav ødelagte fliser). Slå til for en hurtigere Steam-brugerflade, hvis det ser rigtigt ud på denne telefon.
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index d619b039fd..98c0f73cf9 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -879,7 +879,6 @@
Beim nächsten Spielstart Diagnosen von Proton, Wine und Grafik einschließen. Kann die Leistung mindern und mehr Speicher belegen.
Starte diese Sitzung neu, um Spiel-Debug-Logs zu speichern
Protokollierung konnte nicht aktualisiert werden. Prüfe den Schalter und versuch es erneut.
- Debugging-Tools
Detaillierte Grafik-Protokolle
Steam-Oberfläche: Zeichnen mit der GPU
Mit dem Xclipse-Treiberpaar zeichnet Steam seine Seiten per Software (Zeichnen mit der GPU zeigte fehlerhafte Kacheln). Für eine schnellere Steam-Oberfläche einschalten, wenn die Darstellung auf diesem Telefon stimmt.
diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml
index 6ce8a1b5c4..e4b272d302 100644
--- a/app/src/main/res/values-el/strings.xml
+++ b/app/src/main/res/values-el/strings.xml
@@ -879,7 +879,6 @@
Συμπερίληψη διαγνωστικών Proton, Wine και γραφικών στην επόμενη εκκίνηση παιχνιδιού. Μπορεί να μειώσει την απόδοση και να χρησιμοποιήσει περισσότερο χώρο.
Επανεκκινήστε αυτή τη συνεδρία για να αποθηκεύσετε αρχεία καταγραφής εντοπισμού σφαλμάτων παιχνιδιών
Δεν ήταν δυνατή η ενημέρωση της καταγραφής. Ελέγξτε τον διακόπτη και δοκιμάστε ξανά.
- Εργαλεία εντοπισμού σφαλμάτων
Λεπτομερή αρχεία καταγραφής γραφικών
Διεπαφή Steam: σχεδίαση με GPU
Με το ζεύγος προγραμμάτων οδήγησης Xclipse, το Steam σχεδιάζει τις σελίδες του μέσω λογισμικού (η σχεδίαση με GPU εμφάνιζε σπασμένα πλακίδια). Ενεργοποιήστε το για ταχύτερη διεπαφή Steam, αν φαίνεται σωστή σε αυτό το τηλέφωνο.
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index abe9f2a9b2..0e347c900f 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -882,7 +882,6 @@
Incluye diagnósticos de Proton, Wine y gráficos en el próximo inicio de un juego. Puede reducir el rendimiento y usar más almacenamiento.
Reinicia esta sesión para guardar los registros de depuración de juegos
No se ha podido actualizar el registro. Comprueba el interruptor y vuelve a intentarlo.
- Herramientas de depuración
Registros detallados de gráficos
Interfaz de Steam: dibujo con GPU
Con el par de controladores Xclipse, Steam dibuja sus páginas por software (el dibujo con GPU mostraba teselas corruptas). Activa esta opción para una interfaz de Steam más rápida si se ve bien en este teléfono.
diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml
index 113ef7fecb..d9b1fa8e29 100644
--- a/app/src/main/res/values-fi/strings.xml
+++ b/app/src/main/res/values-fi/strings.xml
@@ -879,7 +879,6 @@
Sisällytä Protonin, Winen ja grafiikan diagnostiikka seuraavaan pelin käynnistykseen. Voi heikentää suorituskykyä ja käyttää enemmän tallennustilaa.
Käynnistä tämä istunto uudelleen tallentaaksesi pelien vianmäärityslokit
Lokitusta ei voitu päivittää. Tarkista kytkin ja yritä uudelleen.
- Vianmääritystyökalut
Yksityiskohtaiset grafiikkalokit
Steam-käyttöliittymä: GPU-piirto
Xclipse-ajuriparin kanssa Steam piirtää sivunsa ohjelmistollisesti (GPU-piirto näytti rikkinäisiä laattoja). Ota käyttöön nopeampaa Steam-käyttöliittymää varten, jos käyttöliittymä näyttää tässä puhelimessa virheettömältä.
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 51b795bc84..2a57e4bbe0 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -882,7 +882,6 @@
Inclure les diagnostics Proton, Wine et graphiques au prochain lancement d\'un jeu. Peut réduire les performances et utiliser plus de stockage.
Redémarrez cette session pour enregistrer les journaux de débogage des jeux
Impossible de modifier la journalisation. Vérifiez l\'interrupteur et réessayez.
- Outils de débogage
Journaux graphiques détaillés
Interface Steam : rendu GPU
Avec la paire de pilotes Xclipse, Steam dessine ses pages en logiciel : le rendu GPU produisait des tuiles corrompues. Activez cette option pour accélérer l\'interface Steam si l\'affichage est correct sur ce téléphone.
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index d70b2892c8..6666715301 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -879,7 +879,6 @@
अगली बार गेम लॉन्च होने पर Proton, Wine और ग्राफ़िक्स डायग्नोस्टिक्स शामिल करें। परफ़ॉर्मेंस घटा सकता है और ज़्यादा स्टोरेज ले सकता है।
गेम डीबग लॉग सेव करने के लिए यह सेशन रीस्टार्ट करें
लॉगिंग अपडेट नहीं हो सकी। स्विच जांचें और फिर कोशिश करें।
- डिबगिंग टूल
विस्तृत ग्राफ़िक्स लॉग
Steam इंटरफ़ेस: GPU ड्रॉइंग
Xclipse ड्राइवर जोड़ी के साथ, Steam अपने पेज सॉफ़्टवेयर से ड्रॉ करता है (GPU ड्रॉइंग में टाइलें टूटी हुई दिखीं)। अगर इस फ़ोन पर ठीक दिखे, तो तेज़ Steam इंटरफ़ेस के लिए इसे चालू करें।
diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml
index f37bbe9b47..6187af98a0 100644
--- a/app/src/main/res/values-hu/strings.xml
+++ b/app/src/main/res/values-hu/strings.xml
@@ -879,7 +879,6 @@
Proton-, Wine- és grafikai diagnosztika a következő játékindításkor. Csökkentheti a teljesítményt, és több tárhelyet használ.
Indítsa újra ezt a munkamenetet a játék-hibakeresési naplók mentéséhez
Nem sikerült frissíteni a naplózást. Ellenőrizze a kapcsolót, és próbálja újra.
- Hibakeresési eszközök
Részletes grafikai naplók
Steam felület: GPU-rajzolás
Az Xclipse illesztőprogram-párral a Steam szoftveresen rajzolja az oldalait (a GPU-rajzolás hibás csempéket eredményezett). Kapcsolja be a gyorsabb Steam-felületért, ha ezen a telefonon jól néz ki.
diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml
index 16a387909e..dbde063407 100644
--- a/app/src/main/res/values-in/strings.xml
+++ b/app/src/main/res/values-in/strings.xml
@@ -876,7 +876,6 @@
Sertakan diagnostik Proton, Wine, dan grafis pada peluncuran gim berikutnya. Dapat mengurangi performa dan memakai lebih banyak penyimpanan.
Mulai ulang sesi ini untuk menyimpan log debug gim
Tidak dapat memperbarui pencatatan log. Periksa tombolnya lalu coba lagi.
- Alat debug
Log grafis rinci
Antarmuka Steam: rendering GPU
Dengan pasangan driver Xclipse, Steam menggambar halamannya secara perangkat lunak (rendering GPU menampilkan ubin yang rusak). Aktifkan untuk antarmuka Steam yang lebih cepat jika tampilannya terlihat benar di ponsel ini.
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 19391afb90..cc2e8cdb17 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -882,7 +882,6 @@
Includi la diagnostica di Proton, Wine e grafica al prossimo avvio di un gioco. Può ridurre le prestazioni e occupare più spazio.
Riavvia questa sessione per salvare i log di debug dei giochi
Impossibile aggiornare i log. Controlla l\'interruttore e riprova.
- Strumenti di debug
Log grafici dettagliati
Interfaccia Steam: rendering GPU
Con la coppia di driver Xclipse, Steam disegna le pagine via software (il rendering GPU mostrava riquadri danneggiati). Attivala per un\'interfaccia Steam più veloce, se su questo telefono appare corretta.
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index d59e899b39..522a0c3464 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -876,7 +876,6 @@
次回のゲーム起動時にProton、Wine、グラフィックスの診断情報を含めます。パフォーマンスが低下し、ストレージを多く使用する場合があります。
ゲームのデバッグログを保存するにはこのセッションを再起動してください
ログ設定を更新できませんでした。スイッチを確認して、もう一度お試しください。
- デバッグツール
詳細なグラフィックスログ
Steam インターフェース: GPU 描画
Xclipse ドライバーの組み合わせでは、Steam はソフトウェアでページを描画します (GPU 描画ではタイルが乱れました)。この端末で表示が正しければ、オンにすると Steam インターフェースが高速化します。
diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml
index ce421947f1..8d248636d1 100644
--- a/app/src/main/res/values-ko/strings.xml
+++ b/app/src/main/res/values-ko/strings.xml
@@ -876,7 +876,6 @@
다음 게임 실행 시 Proton, Wine 및 그래픽 진단 정보를 포함합니다. 성능이 저하되고 저장 공간을 더 사용할 수 있습니다.
게임 디버그 로그를 저장하려면 이 세션을 다시 시작하세요
로깅을 업데이트할 수 없습니다. 스위치를 확인하고 다시 시도하세요.
- 디버깅 도구
상세 그래픽 로그
Steam 인터페이스: GPU 렌더링
Xclipse 드라이버 조합에서는 Steam 페이지를 소프트웨어로 그립니다(GPU 렌더링에서는 타일이 깨져 보였습니다). 이 기기에서 정상적으로 보인다면 더 빠른 Steam 인터페이스를 위해 켜세요.
diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml
index 3f6880ad2f..26e9bf9a31 100644
--- a/app/src/main/res/values-ms/strings.xml
+++ b/app/src/main/res/values-ms/strings.xml
@@ -876,7 +876,6 @@
Sertakan diagnostik Proton, Wine dan grafik pada pelancaran permainan seterusnya. Boleh mengurangkan prestasi dan menggunakan lebih banyak storan.
Mulakan semula sesi ini untuk menyimpan log nyahpepijat permainan
Tidak dapat mengemas kini pengelogan. Semak suis dan cuba lagi.
- Alatan penyahpepijatan
Log grafik terperinci
Antara muka Steam: pelukisan GPU
Dengan pasangan pemacu Xclipse, Steam melukis halamannya melalui perisian (pelukisan GPU menghasilkan jubin yang cacat). Hidupkan untuk antara muka Steam yang lebih pantas jika hasilnya kelihatan betul pada telefon ini.
diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml
index da7973003d..2a368ae0fa 100644
--- a/app/src/main/res/values-nb/strings.xml
+++ b/app/src/main/res/values-nb/strings.xml
@@ -879,7 +879,6 @@
Ta med diagnostikk for Proton, Wine og grafikk ved neste spillstart. Kan redusere ytelsen og bruke mer lagringsplass.
Start denne sesjonen på nytt for å lagre feilsøkingslogger for spill
Kunne ikke oppdatere loggingen. Sjekk bryteren og prøv igjen.
- Feilsøkingsverktøy
Detaljerte grafikklogger
Steam-grensesnitt: GPU-tegning
Med Xclipse-driverparet tegner Steam sidene sine i programvare (GPU-tegning viste ødelagte fliser). Slå på for et raskere Steam-grensesnitt hvis det ser riktig ut på denne telefonen.
diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml
index 529163c725..12afedf888 100644
--- a/app/src/main/res/values-nl/strings.xml
+++ b/app/src/main/res/values-nl/strings.xml
@@ -879,7 +879,6 @@
Neem bij de volgende gamestart diagnostiek van Proton, Wine en graphics op. Kan de prestaties verlagen en meer opslag gebruiken.
Start deze sessie opnieuw om debuglogs van games op te slaan
Kan logging niet bijwerken. Controleer de schakelaar en probeer het opnieuw.
- Hulpmiddelen voor debuggen
Gedetailleerde grafische logboeken
Steam-interface: GPU-tekenen
Met het Xclipse-driverpaar tekent Steam zijn pagina\'s in software (GPU-tekenen liet gebroken tegels zien). Schakel dit in voor een snellere Steam-interface als het op deze telefoon goed uitziet.
diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml
index 594dd86aed..13d2fde1e0 100644
--- a/app/src/main/res/values-pl/strings.xml
+++ b/app/src/main/res/values-pl/strings.xml
@@ -885,7 +885,6 @@
Dołącz diagnostykę Proton, Wine i grafiki przy następnym uruchomieniu gry. Może obniżyć wydajność i zająć więcej miejsca.
Uruchom ponownie tę sesję, aby zapisywać logi debugowania gier
Nie udało się zmienić logowania. Sprawdź przełącznik i spróbuj ponownie.
- Narzędzia debugowania
Szczegółowe logi graficzne
Interfejs Steam: rysowanie przez GPU
Z parą sterowników Xclipse Steam rysuje swoje strony programowo (rysowanie przez GPU dawało uszkodzone kafelki). Włącz, aby przyspieszyć interfejs Steam, jeśli na tym telefonie wygląda poprawnie.
diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml
index 65c9cdbebf..fe41c32f18 100644
--- a/app/src/main/res/values-pt-rPT/strings.xml
+++ b/app/src/main/res/values-pt-rPT/strings.xml
@@ -882,7 +882,6 @@
Inclui diagnósticos do Proton, do Wine e de gráficos no próximo arranque de um jogo. Pode reduzir o desempenho e ocupar mais armazenamento.
Reinicie esta sessão para guardar os registos de depuração dos jogos
Não foi possível atualizar os registos. Verifique o interruptor e tente novamente.
- Ferramentas de depuração
Registos gráficos detalhados
Interface do Steam: desenho pela GPU
Com o par de controladores Xclipse, o Steam desenha as suas páginas por software (o desenho pela GPU mostrou mosaicos com falhas). Ative para uma interface do Steam mais rápida se esta parecer correta neste telemóvel.
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index c5a841b99d..15d61c10b9 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -889,7 +889,6 @@
Inclui diagnósticos do Proton, do Wine e de gráficos na próxima inicialização do jogo. Pode reduzir o desempenho e usar mais armazenamento.
Reinicie esta sessão para salvar os logs de depuração dos jogos
Não foi possível atualizar os logs. Verifique a chave e tente novamente.
- Ferramentas de depuração
Logs detalhados de gráficos
Interface do Steam: renderização pela GPU
Com o par de drivers Xclipse, o Steam renderiza suas páginas por software (a renderização pela GPU apresentou blocos quebrados). Ative para ter uma interface do Steam mais rápida se ela aparecer corretamente neste telefone.
diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml
index bb3ba2645a..33d0ad8ffe 100644
--- a/app/src/main/res/values-ro/strings.xml
+++ b/app/src/main/res/values-ro/strings.xml
@@ -882,7 +882,6 @@
Include diagnosticare Proton, Wine și grafică la următoarea lansare a unui joc. Poate reduce performanța și folosește mai mult spațiu.
Repornește această sesiune pentru a salva jurnalele de depanare
Jurnalizarea nu a putut fi actualizată. Verifică comutatorul și încearcă din nou.
- Instrumente de depanare
Jurnale detaliate de grafică
Interfața Steam: desenare GPU
Cu perechea de drivere Xclipse, Steam își desenează paginile în software (desenarea GPU a afișat dale stricate). Activează pentru o interfață Steam mai rapidă dacă arată corect pe acest telefon.
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index cb5131c8de..3b174cc427 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -885,7 +885,6 @@
Добавлять диагностику Proton, Wine и графики при следующем запуске игры. Может снизить производительность и занять больше места.
Перезапустите сессию, чтобы сохранять журналы отладки игр
Не удалось обновить журналирование. Проверьте переключатель и повторите попытку.
- Инструменты отладки
Подробные журналы графики
Интерфейс Steam: отрисовка на GPU
С парой драйверов Xclipse Steam отрисовывает страницы программно (при отрисовке на GPU появлялись битые тайлы). Включите, чтобы ускорить интерфейс Steam, если на этом телефоне он выглядит корректно.
diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml
index 5ffcf3e027..5253d6526f 100644
--- a/app/src/main/res/values-sv/strings.xml
+++ b/app/src/main/res/values-sv/strings.xml
@@ -879,7 +879,6 @@
Ta med diagnostik för Proton, Wine och grafik vid nästa spelstart. Kan sänka prestandan och använda mer lagringsutrymme.
Starta om sessionen för att spara felsökningsloggar för spel
Det gick inte att uppdatera loggningen. Kontrollera reglaget och försök igen.
- Felsökningsverktyg
Detaljerade grafikloggar
Steam-gränssnitt: GPU-ritning
Med Xclipse-drivrutinsparet ritar Steam sina sidor i mjukvara (GPU-ritning gav trasiga rutor). Slå på för ett snabbare Steam-gränssnitt om det ser rätt ut på den här telefonen.
diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml
index afc6037646..7d4e61d40a 100644
--- a/app/src/main/res/values-th/strings.xml
+++ b/app/src/main/res/values-th/strings.xml
@@ -876,7 +876,6 @@
รวมข้อมูลวินิจฉัยของ Proton, Wine และกราฟิกในการเปิดเกมครั้งถัดไป อาจลดประสิทธิภาพและใช้พื้นที่จัดเก็บมากขึ้น
รีสตาร์ทเซสชันนี้เพื่อบันทึกบันทึกดีบักของเกม
อัปเดตการบันทึกไม่ได้ ตรวจสอบสวิตช์แล้วลองใหม่
- เครื่องมือดีบัก
บันทึกกราฟิกโดยละเอียด
อินเทอร์เฟซ Steam: วาดด้วย GPU
ด้วยไดรเวอร์คู่ Xclipse Steam จะวาดหน้าเพจด้วยซอฟต์แวร์ (การวาดด้วย GPU ทำให้ภาพแตกเป็นชิ้น) เปิดตัวเลือกนี้เพื่อให้อินเทอร์เฟซ Steam เร็วขึ้นหากดูปกติบนเครื่องนี้
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 8986422061..03482cffa8 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -879,7 +879,6 @@
Sonraki oyun başlatmada Proton, Wine ve grafik tanılamalarını ekler. Performansı düşürebilir ve daha fazla depolama kullanabilir.
Oyun hata ayıklama günlüklerini kaydetmek için bu oturumu yeniden başlatın
Günlük kaydı güncellenemedi. Anahtarı kontrol edip tekrar deneyin.
- Hata ayıklama araçları
Ayrıntılı grafik günlükleri
Steam arayüzü: GPU ile çizim
Xclipse sürücü ikilisi kullanıldığında Steam, sayfalarını yazılımla çizer (GPU ile çizimde bozuk döşemeler görüldü). Bu telefonda düzgün görünüyorsa daha hızlı bir Steam arayüzü için açın.
diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml
index 1acda2257b..90c756ac29 100644
--- a/app/src/main/res/values-uk/strings.xml
+++ b/app/src/main/res/values-uk/strings.xml
@@ -885,7 +885,6 @@
Додавати діагностику Proton, Wine і графіки під час наступного запуску гри. Може знизити продуктивність і зайняти більше місця.
Перезапустіть цей сеанс, щоб зберігати журнали налагодження ігор
Не вдалося оновити журналювання. Перевірте перемикач і спробуйте ще раз.
- Засоби діагностики
Детальні журнали графіки
Інтерфейс Steam: малювання на GPU
Із парою драйверів Xclipse Steam малює свої сторінки програмно (малювання на GPU давало пошкоджені фрагменти). Увімкніть для швидшого інтерфейсу Steam, якщо на цьому телефоні все виглядає правильно.
diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml
index 62b8003f40..70300f0512 100644
--- a/app/src/main/res/values-vi/strings.xml
+++ b/app/src/main/res/values-vi/strings.xml
@@ -876,7 +876,6 @@
Thêm chẩn đoán Proton, Wine và đồ họa vào lần khởi chạy game tiếp theo. Có thể giảm hiệu năng và tốn thêm bộ nhớ.
Khởi động lại phiên này để lưu nhật ký gỡ lỗi game
Không thể cập nhật ghi nhật ký. Hãy kiểm tra công tắc rồi thử lại.
- Công cụ gỡ lỗi
Nhật ký đồ họa chi tiết
Giao diện Steam: vẽ bằng GPU
Với cặp driver Xclipse, Steam vẽ các trang bằng phần mềm (vẽ bằng GPU làm vỡ các ô hiển thị). Bật để có giao diện Steam nhanh hơn nếu hình hiển thị đúng trên máy này.
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index c92dd86eac..2e606c068a 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -876,7 +876,6 @@
在下次启动游戏时包含 Proton、Wine 和图形诊断信息。可能降低性能并占用更多存储空间。
重启此会话以保存游戏调试日志
无法更新日志设置。请检查开关后重试。
- 调试工具
详细图形日志
Steam 界面:GPU 绘制
使用 Xclipse 驱动组合时,Steam 以软件方式绘制页面(GPU 绘制会出现图块错乱)。若在这台手机上画面正常,开启即可获得更快的 Steam 界面。
diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml
index 84dc0fd288..51859bdb29 100644
--- a/app/src/main/res/values-zh-rHK/strings.xml
+++ b/app/src/main/res/values-zh-rHK/strings.xml
@@ -875,7 +875,6 @@
在下次啟動遊戲時加入 Proton、Wine 和圖形診斷資訊。可能降低效能並佔用更多儲存空間。
重新啟動此會話以儲存遊戲偵錯記錄
無法更新記錄設定。請檢查開關後再試一次。
- 偵錯工具
詳細圖形記錄
Steam 介面:GPU 繪製
使用 Xclipse 驅動程式組合時,Steam 會以軟件繪製頁面(GPU 繪製曾出現圖塊破損)。若在這部手機上顯示正常,可開啟以加快 Steam 介面。
diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml
index 2c71886340..6e7d316be3 100644
--- a/app/src/main/res/values-zh-rTW/strings.xml
+++ b/app/src/main/res/values-zh-rTW/strings.xml
@@ -875,7 +875,6 @@
在下次啟動遊戲時加入 Proton、Wine 和圖形診斷資訊。可能降低效能並佔用更多儲存空間。
重新啟動此工作階段以儲存遊戲偵錯日誌
無法更新日誌設定。請檢查開關後再試一次。
- 偵錯工具
詳細圖形記錄
Steam 介面:GPU 繪製
使用 Xclipse 驅動程式組合時,Steam 會改用軟體繪製頁面(GPU 繪製曾出現圖塊破損)。若這支手機上顯示正常,開啟此選項可加快 Steam 介面。
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 37832231c0..04749c6918 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -976,7 +976,8 @@
Include Proton, Wine and graphics diagnostics on the next game launch. Turns itself off when that session ends. Can reduce performance and use more storage.
Restart this session to save game debug logs
Couldn\'t update logging. Check the switch and try again.
- Debugging tools
+ droiddeckctl
+ Allow command-line control of DroidDeck sessions, input, and logs.
Detailed graphics logs
Steam interface: GPU drawing
With the Xclipse driver pair, Steam draws its pages in software (GPU drawing showed broken tiles). Turn on for a faster Steam interface if it looks right on this phone.
@@ -4460,7 +4461,12 @@
In-game menu
Steam or Desktop options (swipe up)
Steam quick menu (•••)
- Logs
+ Diagnostics
+ UI previews
+ Log files
+ Reset
+ Share, save, or delete individual session logs.
+ Show Dev Harness over the launcher and games.
UI zoo
Screens that are hard to reach, shown only when you pick one
Open
@@ -4509,7 +4515,8 @@
Syncthing
Download settings
Developer tools
- Agent, graphics logs and other tools for testing DroidDeck
+ Show developer tools
+ Show advanced testing and diagnostics controls.
Options
Steam defaults · used each time Steam starts
Desktop defaults · used each time Desktop starts
diff --git a/docs/agent-control.md b/docs/agent-control.md
index 6cce0e77df..f794b6d8c6 100644
--- a/docs/agent-control.md
+++ b/docs/agent-control.md
@@ -40,7 +40,7 @@ Player controls and observations work over authorized ADB on any build: `state`,
`resume`, `wait`, `launch`, `quit`, `focus`, `input`, `ui`, `logs`, `screenshot`, `record`, `pacing`,
`thermal`, `displays`, `wake`, `glasses` (except `glasses raw`), and `access`.
-**Setup > Developer > Debugging tools** is off by default in every build, including debug builds.
+**Setup > Developer > droiddeckctl** is off by default in every build, including debug builds.
It enables `run`, `guest`, `cdp`, all `env` operations, `override`, `prefs`, and `glasses raw`. The
toggle switches directly without a confirmation dialog. The bridge refuses to change it through `ui`
or preference writes. The existing preference key, `setting-agent-commands` test tag, JSON command
@@ -233,7 +233,7 @@ and returns its exit code with the last 160 KiB of stdout and stderr (`--timeout
`cloud down|up ` syncs one game's cloud saves now, without launching it, with the
`result`, `files`, `bytes`, `reason`, `conflicts` and `detail` the game page shows; `--force` takes
that side over conflicts. The store id is the one in the game's install record (`library` shows
-it). Both need Setup > Developer > Debugging tools.
+it). Both need Setup > Developer > droiddeckctl.
`input pad` writes to the session's virtual pad, the one the guest sees, and never reaches the app's
own key handling. To test how DroidDeck's own screens treat a controller (menu focus and outlines,
@@ -243,13 +243,13 @@ controller, and presses the buttons in order: `a b x y lb rb select start guide
d-pad `up down left right`. `--hold` (120 ms) is how long each stays down and `--gap` (400 ms) the
pause after it; a d-pad press always waits at least 20 ms, so Android sees each release before
the next press. The device exists only while the command runs, takes about a second to appear, and
-works without a session or Setup > Developer > Debugging tools. Its name does not start with
+works without a session or Setup > Developer > droiddeckctl. Its name does not start with
`uinput-`, which the app treats as a system virtual device. `UINPUT_UNAVAILABLE` and `UINPUT_FAILED`
mean the same as for `input pen`.
`input pen` does not go through the app. It registers a virtual pen with `adb shell uinput -`, so
Android's own input reader makes the stylus events, as for a built-in pen, and it works on whatever
-is on screen, without a session or Setup > Developer > Debugging tools. Positions are fractions of
+is on screen, without a session or Setup > Developer > droiddeckctl. Positions are fractions of
the screen as shown; `dumpsys input` gives the frame, rotation and size of the display Android maps
internal touchscreens to. `hover` comes near and glides to `--to`; `tap`, `stroke` and `button`
hover for `--hover-ms` (80) before and after the touch or the button press. Each takes
diff --git a/docs/development/boot-movies.md b/docs/development/boot-movies.md
index 7cb03ce5bb..e4fca523b2 100644
--- a/docs/development/boot-movies.md
+++ b/docs/development/boot-movies.md
@@ -35,6 +35,6 @@ plays without sound rather than louder, and plays nothing if that fails too. Cov
Selecting a movie here sets `bootMovieApplyNext`, so the next session stages the movie as `bigpicture_startup.webm` and
points both sections at it, over a movie Steam had picked; otherwise a movie picked in Steam is left alone and taken over as
the choice here without being staged over Steam's own setting. Settings > Boot movie > Installed has a report button that
-writes what Steam and DroidDeck know to `Download/DroidDeck/boot-movie-report.txt`; it only shows while Debugging tools is on.
+writes what Steam and DroidDeck know to `Download/DroidDeck/boot-movie-report.txt`; it only shows while droiddeckctl is on.
A movie larger than 1920x1080 (4K and the like) is never copied or remuxed as it is: import and staging always convert it
(the converter scales to at most 1280x720), because such movies have made Steam crash while it starts.
diff --git a/docs/development/proot-performance.md b/docs/development/proot-performance.md
index 254106016a..26da4c38de 100644
--- a/docs/development/proot-performance.md
+++ b/docs/development/proot-performance.md
@@ -325,7 +325,7 @@ or repeatedly hit a path the wrappers cannot resolve.
### Opt-in tracer profiling
-With **Setup > Developer > Debugging tools** enabled, queue profiling for one session:
+With **Setup > Developer > droiddeckctl** enabled, queue profiling for one session:
```sh
tools/droiddeckctl proot-profile enable --slow-us 1000
diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md
index b3bee82824..a0c81c0faf 100644
--- a/docs/phantom-processes.md
+++ b/docs/phantom-processes.md
@@ -499,7 +499,7 @@ handed-off daemons. With only the hook's handoffs off (`DD_SPAWN_DAEMONS=0`), RE
runs in workers (`GuestWorkers.enabled`: the native userland, Android 11+, and the
`childProcessHandoff` session preference, on by default). It does not block Steam. Turning the
preference off (`droiddeckctl prefs set session childProcessHandoff false --type bool`, with
-Setup > Developer > Debugging tools on; see `docs/agent-control.md`) brings back
+Setup > Developer > droiddeckctl on; see `docs/agent-control.md`) brings back
the old behavior and the old requirement.
### C. Plan
diff --git a/docs/settings-map.md b/docs/settings-map.md
index e3138eee65..b38a8fdf9f 100644
--- a/docs/settings-map.md
+++ b/docs/settings-map.md
@@ -59,7 +59,8 @@ Links of the form `droiddeck://settings/` open a Settings section direc
| Game debug logs | Settings › Developer (`droiddeck://settings/developer`) | logs, wine, proton |
| Enhanced diagnostics for next session | Settings › Developer (`droiddeck://settings/developer`) | logs |
| Reset all settings | Settings › Developer (`droiddeck://settings/developer`) | default |
-| Developer tools | Settings › Developer (`droiddeck://settings/developer`) | agent, ai, claude, codex |
+| Show developer tools | Settings › Developer (`droiddeck://settings/developer`) | agent, ai, claude, codex |
+| droiddeckctl | Settings › Developer (`droiddeck://settings/developer`) | debugging tools, cli |
| Detailed graphics logs | Settings › Developer (`droiddeck://settings/developer`) | logs, gpu |
## Tabs
diff --git a/tools/droiddeckctl b/tools/droiddeckctl
index fd9931a9cd..b5a09825a5 100755
--- a/tools/droiddeckctl
+++ b/tools/droiddeckctl
@@ -600,7 +600,7 @@ def unpack_logs(archive: Path, destination: Path, session_id: str) -> None:
def require_commands(adb: str, serial: str) -> dict:
access = checked(provider_call(adb, serial, "access"), "ACCESS_FAILED")
if access.get("commands") is not True:
- raise ControlError("Debugging tools are off: turn on Setup > Developer > Debugging tools on the device",
+ raise ControlError("droiddeckctl is off: turn on Setup > Developer > droiddeckctl on the device",
"AGENT_COMMANDS_DISABLED")
return access
diff --git a/tools/tests/test_droiddeckctl.py b/tools/tests/test_droiddeckctl.py
index 4873d13ce5..5ff6652ae2 100644
--- a/tools/tests/test_droiddeckctl.py
+++ b/tools/tests/test_droiddeckctl.py
@@ -373,7 +373,7 @@ class DroiddeckctlTest(FakeAdbTest):
code, out = self.run_ctl("run", "/usr/bin/sh", "--", "-c", "true")
self.assertEqual(7, code)
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
- self.assertIn("Setup > Developer > Debugging tools", out["error"]["message"])
+ self.assertIn("Setup > Developer > droiddeckctl", out["error"]["message"])
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
def test_override_checks_names_before_pushing_any_file(self):
From 73fac3723fd68114553c4b4f86fe9f1019e0d188 Mon Sep 17 00:00:00 2001
From: MaxsTechReview
Date: Sat, 5 Dec 2026 18:57:23 -0500
Subject: [PATCH 6/8] fix: Games start again in proot sessions (session preload
no longer needs spare static TLS) (#3765)
* Keep the session preload loadable when spare static TLS runs out
The syscall-dispatch selector pointer in the zram preload used the
initial-exec TLS model. That marks the whole libddsession TLS block
(about 1.8 KB) as static, so loading it at runtime needs that much spare
static TLS. Under proot there is not enough, and every guest program
failed with "cannot allocate memory in static TLS block". The default
model keeps the same per-thread behaviour without that requirement.
* Read the dispatch selector only once a thread has turned dispatch on
A thread's first read of the selector can allocate its TLS block when the
preload was loaded at runtime. The page-out handler and the prctl wrapper
now read it only after some thread in the process enabled syscall user
dispatch, so processes that never use it never touch the variable from a
signal handler.
* Keep the dispatch selector in a thread key so the signal handler never allocates
* Bind the selector lookup before the handler can run and refuse to arm dispatch without a selector slot
* fix(preload): retry selector key setup after key exhaustion
* fix(preload): publish the dispatch selector only after the kernel accepts it
---
tools/linuxfs/preload/zram.c | 55 ++++++++++++++--
tools/tests/test_zram_preload.py | 106 +++++++++++++++++++++++++++++++
2 files changed, 156 insertions(+), 5 deletions(-)
diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c
index 446996a06e..9bc0558ff0 100644
--- a/tools/linuxfs/preload/zram.c
+++ b/tools/linuxfs/preload/zram.c
@@ -542,7 +542,35 @@ static int zr_start(void) {
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, ...) {
va_list ap;
@@ -552,16 +580,32 @@ int prctl(int option, ...) {
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
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;
if (selector) *dispatch = 0;
+ if (arming && pthread_setspecific(zr_key, dispatch != NULL ? (void *)dispatch : (void *)&zr_idle) != 0) {
+ if (selector) *dispatch = selector;
+ errno = ENOMEM;
+ return -1;
+ }
long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5);
+ int failed = (unsigned long)result > -4096UL;
+ if (arming) pthread_setspecific(zr_key, failed ? (void *)dispatch : (void *)arg5);
if (selector) *dispatch = selector;
- if ((unsigned long)result > -4096UL) {
+ int ready = __atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE);
+ if (failed) {
errno = (int)-result;
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;
}
@@ -569,7 +613,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)context;
if (info == NULL || info->si_code != SI_USER) return;
- volatile unsigned char *dispatch = zr_dispatch;
+ volatile unsigned char *dispatch = zr_selector();
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
int saved = errno;
@@ -598,6 +642,7 @@ static void zr_paths(void) {
}
__attribute__((constructor)) static void zr_init(void) {
+ pthread_atfork(NULL, NULL, zr_key_child);
zr_paths();
int fd = zr_open(zr_ctl);
if (fd < 0) return;
diff --git a/tools/tests/test_zram_preload.py b/tools/tests/test_zram_preload.py
index 3d6b7d6126..cc798afaa5 100644
--- a/tools/tests/test_zram_preload.py
+++ b/tools/tests/test_zram_preload.py
@@ -555,6 +555,79 @@ def swap_total_kb():
return 0
+CROSS_THREAD = r"""
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#ifndef PR_SET_SYSCALL_USER_DISPATCH
+#define PR_SET_SYSCALL_USER_DISPATCH 59
+#endif
+
+extern void *__libc_malloc(size_t);
+extern void *__libc_calloc(size_t, size_t);
+extern void *__libc_realloc(void *, size_t);
+
+static int watching;
+static pid_t victim;
+static int allocations;
+
+static void count(void) {
+ if (__atomic_load_n(&watching, __ATOMIC_ACQUIRE) && gettid() == __atomic_load_n(&victim, __ATOMIC_RELAXED)) __atomic_add_fetch(&allocations, 1, __ATOMIC_RELAXED);
+}
+
+void *malloc(size_t n) { count(); return __libc_malloc(n); }
+void *calloc(size_t a, size_t b) { count(); return __libc_calloc(a, b); }
+void *realloc(void *p, size_t n) { count(); return __libc_realloc(p, n); }
+
+static void *idle(void *arg) {
+ (void)arg;
+ sigset_t none;
+ sigemptyset(&none);
+ __atomic_store_n(&victim, gettid(), __ATOMIC_RELAXED);
+ __atomic_store_n(&watching, 1, __ATOMIC_RELEASE);
+ sigsuspend(&none);
+ __atomic_store_n(&watching, 0, __ATOMIC_RELEASE);
+ return NULL;
+}
+
+int main(int argc, char **argv) {
+ sigset_t urg;
+ sigemptyset(&urg);
+ sigaddset(&urg, SIGURG);
+ pthread_sigmask(SIG_BLOCK, &urg, NULL);
+ void *lib = dlopen(argv[1], RTLD_LAZY);
+ if (lib == NULL) { puts(dlerror()); return 1; }
+ int (*control)(int, ...) = (int (*)(int, ...))dlsym(lib, "prctl");
+ volatile char selector = 0;
+ if (argc > 2) {
+ pthread_key_t key, last = 0;
+ while (pthread_key_create(&key, NULL) == 0) last = key;
+ int r = control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector);
+ printf("refused %d %s\n", r, r != 0 && errno == EAGAIN ? "again" : "other");
+ pthread_key_delete(last);
+ printf("retried %d\n", control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector));
+ return 0;
+ }
+ if (control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector) != 0) { puts("nodispatch"); return 0; }
+ pthread_t thread;
+ pthread_create(&thread, NULL, idle, NULL);
+ while (!__atomic_load_n(&watching, __ATOMIC_ACQUIRE)) usleep(1000);
+ if (write(2, "signal\n", 7) != 7) return 1;
+ kill(getpid(), SIGURG);
+ pthread_join(thread, NULL);
+ printf("allocations %d\n", allocations);
+ return 0;
+}
+"""
+
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
class ZramPreloadTest(unittest.TestCase):
@classmethod
@@ -773,6 +846,39 @@ class ZramPreloadTest(unittest.TestCase):
self.assertEqual([1], out["trimmed"], out)
self.assertEqual([1], out["named"], out)
+ def test_a_signal_on_another_thread_allocates_nothing_after_dispatch_was_armed(self):
+ source = self.dir / "crossthread.c"
+ program = self.dir / "crossthread"
+ source.write_text(CROSS_THREAD)
+ subprocess.run(["cc", "-O2", "-pthread", "-o", str(program), str(source), "-ldl"], check=True)
+ environment = dict(os.environ, GLIBC_TUNABLES="glibc.rtld.optional_static_tls=0", LD_DEBUG="bindings")
+ for name in ("LD_PRELOAD", "LD_BIND_NOW"):
+ environment.pop(name, None)
+ result = subprocess.run([str(program), str(self.lib)], env=environment, capture_output=True, text=True, timeout=60)
+ self.assertEqual(0, result.returncode, result.stdout + result.stderr)
+ if result.stdout.strip() == "nodispatch":
+ self.skipTest("kernel lacks syscall user dispatch")
+ self.assertEqual("allocations 0", result.stdout.strip())
+ after = result.stderr.split("signal\n", 1)[1]
+ self.assertNotIn("pthread_getspecific", after)
+ refused = subprocess.run([str(program), str(self.lib), "exhaust"], env=environment, capture_output=True,
+ text=True, timeout=60)
+ self.assertEqual("refused -1 again\nretried 0", refused.stdout.strip())
+
+ def test_loads_at_runtime_without_spare_static_tls(self):
+ loader = self.dir / "loader"
+ source = self.dir / "loader.c"
+ source.write_text("#include \n#include \n"
+ "int main(int c, char **v) { (void)c; void *h = dlopen(v[1], RTLD_NOW);"
+ " puts(h ? \"loaded\" : dlerror()); return h == NULL; }\n")
+ subprocess.run(["cc", "-O2", "-o", str(loader), str(source), "-ldl"], check=True)
+ environment = dict(os.environ, GLIBC_TUNABLES="glibc.rtld.optional_static_tls=0")
+ environment.pop("LD_PRELOAD", None)
+ result = subprocess.run([str(loader), str(self.lib)], env=environment, capture_output=True, text=True,
+ timeout=60)
+ self.assertEqual(0, result.returncode, result.stdout + result.stderr)
+ self.assertEqual("loaded", result.stdout.strip())
+
if __name__ == "__main__":
unittest.main()
From 88d44b0dc6a50fed4819206241ad0a5b9809b7bf Mon Sep 17 00:00:00 2001
From: LunaDL <91587464+EnzoDLofi@users.noreply.github.com>
Date: Sat, 5 Dec 2026 20:09:28 -0400
Subject: [PATCH 7/8] Feat: Improve ARMv8.0 Steam compatibility with LSE
emulation (#3720)
* feat: emulate LSE atomics so the Steam client starts on ARMv8.0 CPUs
* fix: keep NZCV across patched LSE min/max stubs and catch st* aliases
* fix: fail the LSE check when objdump fails
* fix: validate the CASP pair on a mismatch in the LSE emulator
* fix: sandboxes switch on the LSE emulator when it is preloaded
* fix: keep the MaliBridge pointer from main
* Handle LSE atomics before preload constructors
* Support early LSE handling in root guest processes
* Fix LSE-Emu signal and patching review findings
* Assert CASP and min/max sites use patched stubs
* Correct patch test statistics regexes
* Validate SIGILL syscall ABI and retain active state on restore failure
* Preserve the previous SIGILL disposition during early install
* Synchronize instruction fetch on generated LSE stubs
* Address LSE-Emu follow-up review findings
* Fix missing LSE signal handler state declarations
* Honor application signal mask when forwarding SIGILL
* Preserve SA_RESETHAND mask during handler forwarding
* Fix LSE opt-out after early handler install
* Avoid recursive SIGILL forwarding during LSE emulation
* Fix LSE SIGILL handler re-entry tracking
* Honor SA_NODEFER in forwarded SIGILL mask
* Preserve nested SIGILL delivery semantics
* Preserve explicit SIGILL mask with SA_NODEFER
* Reduce LSE patch contention across threads
* Guard nested faults before acquiring patch lock
* Fix early SIGILL restore and wake patch waiters
* Preserve libc restorer when restoring application SIGILL
* Wait for concurrent LSE patch instead of skipping
* Fix LSE patch lock release and fork recovery
* Avoid reinstalling the early SIGILL handler
* chore: retrigger CI
* Avoid proc maps reads in concurrent SIGILL patching
* Prevent late IFUNC handler install when emulation is disabled
* Clarify cached mapping lookup
* Move cached map declarations before find_gap
* Default LSE instruction patching to off
* Document conservative LSE emulation default
* Keep LSE instruction patching opt-in in sandbox preload
* Document default and opt-in LSE emulation checks
* Assert LSE patching remains opt-in in sandbox tests
* Align LSE device checks with SDK 34 patching behavior
* Check expected mprotect failures in opt-in device run
* Clarify LSE emulator device validation criteria
* Specify controlled SDK mprotect validation
* fix(lse-emu): publish SIGILL actions atomically
* fix(runtime): honor LSE_EMU=0 before preload
* test(runtime): keep LSE preload disabled when opted out
* fix(runtime): fully honor LSE_EMU=0 opt-out
* test(runtime): verify LSE opt-out removes inherited preload
* fix(runtime): filter inherited LSE preload without preload file
* fix(lse-emu): use bounded signal-safe action snapshots
* fix(runtime): split inherited preloads on spaces and colons
* test(runtime): cover both LSE preload entry orders
* fix(lse-emu): recycle displaced SIGILL snapshots
* fix(preload): preserve colliding path cache entries
* test(lse-emu): report patch failure details
* fix(lse-emu): serialize action snapshot publishers
* fix(lse-emu): fall back to reachable arena mapping
* fix(lse-emu): make signal action publication nonblocking
* refactor(lse-emu): remove obsolete publisher lock
* Fix SIGILL snapshot retirement and honor session LSE opt-out
* Preserve the Java staging API and isolate the SIGILL stress test
* fix(nativeguest): filter LSE preload when disabled
* fix(lse-emu): tighten seccomp and signal setup
* fix(session): preserve active LSE override while staging
* fix(lse-emu): return atomically displaced signal actions
* fix(lse-emu): stage raw signal masks safely
* fix(lse-emu): distinguish seccomp listener success
* fix(lse-emu): publish seccomp veto atomically
* fix(lse-emu): fail closed on RX restore errors
* fix(lse-emu): keep stack-using atomic stubs on trap path
* fix(lse-emu): allow patching with inherited seccomp
* test(lse-emu): cover LDAPR patch path
* test(lse-emu): assert LDAPR-only patching
* fix(nativeguest): filter disabled LSE from preload chains
* docs(lse-emu): define inherited seccomp patch policy
* fix(lse-emu): emulate LDAPR trap fallback
* refactor(lse-emu): remove unused seccomp query
* fix(nativeguest): release filtered preload chain in scope
* test(lse-emu): allow forwarded udf diagnostic
* fix(nativeguest): avoid unsafe preload fallback when disabled
* test(lse-emu): match full zero instruction field
* test(lse-emu): match complete instruction diagnostics
* Keep nested native preloads from duplicating host libraries
* fix(nativeguest): fail exec when disabled preload cannot map
* fix(nativeguest): stop exec when preload mapping fails
* fix(nativeguest): propagate preload filter allocation failures
* Consume only the selected one-shot SIGILL action
* Reclaim abandoned SIGILL action slots after fork
* Revalidate the live file mapping before optional LSE patching
---------
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
---
.github/workflows/build.yml | 3 +
.../droiddeck/launcher/core/CpuFeatures.kt | 17 +
.../launcher/runtime/BwrapSpawner.kt | 22 +-
.../droiddeck/launcher/runtime/NativeGuest.kt | 8 +-
.../launcher/session/BottomDesktop.kt | 3 +-
.../launcher/session/SessionFiles.kt | 26 +-
.../launcher/session/SessionService.kt | 5 +-
.../launcher/core/CpuFeaturesTest.kt | 48 +
.../launcher/runtime/BwrapSpawnerTest.kt | 46 +
.../launcher/runtime/NativeGuestTest.kt | 21 +
docs/arm-v8.0-steam-client.md | 147 ++
tools/build_local.sh | 1 +
tools/components/reuse.py | 4 +-
tools/linuxfs/check-preloads.sh | 4 +
tools/linuxfs/lse-emu/README.md | 23 +
tools/linuxfs/lse-emu/build.sh | 15 +
tools/linuxfs/lse-emu/lse_emu.c | 1184 +++++++++++++++++
.../overlay/usr/local/bin/droiddeck-session | 7 +
tools/linuxfs/preload/pathcache.c | 31 +-
tools/nativeguest/hook/env.c | 152 ++-
tools/nativeguest/hook/exec.c | 15 +
tools/release/runtime_inputs.py | 1 +
tools/tests/lse_emu_early_dependency.c | 17 +
tools/tests/lse_emu_early_main.c | 9 +
tools/tests/lse_emu_test.c | 300 +++++
tools/tests/test_lse_emu.py | 141 ++
tools/tests/test_native_hook_preload_list.py | 53 +
27 files changed, 2263 insertions(+), 40 deletions(-)
create mode 100644 app/src/main/java/com/droiddeck/launcher/core/CpuFeatures.kt
create mode 100644 app/src/test/java/com/droiddeck/launcher/core/CpuFeaturesTest.kt
create mode 100644 docs/arm-v8.0-steam-client.md
create mode 100644 tools/linuxfs/lse-emu/README.md
create mode 100644 tools/linuxfs/lse-emu/build.sh
create mode 100644 tools/linuxfs/lse-emu/lse_emu.c
mode change 100755 => 100644 tools/linuxfs/overlay/usr/local/bin/droiddeck-session
create mode 100644 tools/tests/lse_emu_early_dependency.c
create mode 100644 tools/tests/lse_emu_early_main.c
create mode 100644 tools/tests/lse_emu_test.c
create mode 100644 tools/tests/test_lse_emu.py
create mode 100644 tools/tests/test_native_hook_preload_list.py
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index e4229729de..40ae60df71 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -307,6 +307,9 @@ jobs:
aarch64-linux-gnu-gcc -O2 -Wall -o "$D/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-glprobe"
+ - name: Build the LSE atomics emulator for ARMv8.0 CPUs
+ run: bash tools/linuxfs/lse-emu/build.sh app/src/main/assets/linuxfs
+
- name: Check the preloads
run: |
set -euo pipefail
diff --git a/app/src/main/java/com/droiddeck/launcher/core/CpuFeatures.kt b/app/src/main/java/com/droiddeck/launcher/core/CpuFeatures.kt
new file mode 100644
index 0000000000..e8cd318bc2
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/core/CpuFeatures.kt
@@ -0,0 +1,17 @@
+package com.droiddeck.launcher.core
+
+import java.io.File
+
+object CpuFeatures {
+ internal fun lacksAtomics(cpuInfo: String): Boolean {
+ val cores = cpuInfo.lineSequence()
+ .filter { it.substringBefore(':').trim() == "Features" }
+ .map { it.substringAfter(':').trim().split(Regex("\\s+")) }
+ .toList()
+ return cores.isNotEmpty() && cores.any { "atomics" !in it }
+ }
+
+ val lacksAtomics: Boolean by lazy {
+ runCatching { lacksAtomics(File("/proc/cpuinfo").readText()) }.getOrDefault(false)
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
index 0e42e770e3..0577c2fece 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
@@ -288,12 +288,26 @@ object BwrapSpawner {
}
private fun preload(session: List, rootfs: String, env: MutableMap): List {
- val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
- ?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: return emptyList()
- if (libs.isEmpty()) return emptyList()
+ val configured = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines()
+ ?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: emptyList()
+ val lseDisabled = env["LSE_EMU"] == "0"
+ val libs = configured.filterNot { lseDisabled && it.endsWith("/liblse_emu.so") }
+ val inherited = env["LD_PRELOAD"]?.split(Regex("[\\s:]+"))
+ ?.filter { it.isNotEmpty() && !(lseDisabled && it.substringAfterLast('/') == "liblse_emu.so") }
+ ?: emptyList()
+ if (libs.isEmpty()) {
+ if (lseDisabled) {
+ if (inherited.isEmpty()) env.remove("LD_PRELOAD")
+ else env["LD_PRELOAD"] = inherited.joinToString(":")
+ }
+ return emptyList()
+ }
val binds = ArrayList()
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
- env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":")
+ env["LD_PRELOAD"] = (paths + inherited).joinToString(":")
+ if (libs.any { it.endsWith("/liblse_emu.so") }) {
+ env.putIfAbsent("LSE_EMU", "1")
+ }
File(rootfs, NET_LINK).takeIf { it.isFile }?.let { binds.add(Bind(it.path, "/$NET_LINK")) }
env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev ->
binds.addAll(bindsFor(session, rootfs, dev, dev))
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt
index 95a660eaf4..6ad6a321c4 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt
@@ -104,8 +104,11 @@ object NativeGuest {
private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/"))
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
- fun sessionEnvironment(root: File, binds: List, program: String, hostname: String? = null): Map {
- val preload = preloadList(root)
+ fun sessionEnvironment(
+ root: File, binds: List, program: String, hostname: String? = null, lseEmu: String? = null,
+ ): Map {
+ val preload = preloadList(root).filterNot { lseEmu == "0" && it.substringAfterLast('/') == "liblse_emu.so" }
+ val lse = lseEmu ?: "1".takeIf { preload.any { it.substringAfterLast('/') == "liblse_emu.so" } }
return linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
@@ -113,6 +116,7 @@ object NativeGuest {
"DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"),
+ "LSE_EMU" to lse.orEmpty(),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt
index ffccd3e237..b815d29fdd 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt
@@ -343,7 +343,8 @@ object BottomDesktop {
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
}
val environment = if (current.nativeUserland) {
- com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
+ val lseEmu = current.guest.lastOrNull { it.startsWith("LSE_EMU=") }?.substringAfter('=')
+ com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context), lseEmu)
.map { (k, v) -> "$k=$v" }.toTypedArray()
} else current.hostEnvironment
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
index d28ae192db..525844d880 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
@@ -5,6 +5,7 @@ import android.content.Context
import android.os.Environment
import android.util.Log
import com.droiddeck.launcher.R
+import com.droiddeck.launcher.core.CpuFeatures
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.runtime.DesktopCatalog
@@ -22,6 +23,10 @@ object SessionFiles {
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
+ internal const val LSE_EMU = "usr/local/lib/droiddeck-lse/liblse_emu.so"
+
+ internal fun lsePreload(lacksAtomics: Boolean, staged: Boolean, lseEmu: String? = null): String =
+ if (lacksAtomics && staged && lseEmu != "0") "/$LSE_EMU\n" else ""
private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json"
private const val IME_DEFAULT_MODE = 420
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
@@ -102,10 +107,23 @@ object SessionFiles {
}
private val STAGE_LOCK = Any()
+ @Volatile private var activeSessionLseEmu: String? = null
- fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
+ fun stage(context: Context, root: File, startsSession: Boolean = false) =
+ stage(context, root, startsSession, lseEmu = null)
- private fun stageNow(context: Context, root: File, startsSession: Boolean) {
+ fun stage(context: Context, root: File, startsSession: Boolean, lseEmu: String?) =
+ synchronized(STAGE_LOCK) {
+ val selection = if (startsSession) {
+ activeSessionLseEmu = lseEmu
+ lseEmu
+ } else {
+ lseEmu ?: activeSessionLseEmu
+ }
+ stageNow(context, root, startsSession, selection)
+ }
+
+ private fun stageNow(context: Context, root: File, startsSession: Boolean, lseEmu: String?) {
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
GameEnvironmentStore.publish(context)
@@ -281,6 +299,7 @@ object SessionFiles {
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
+ LSE_EMU to LSE_EMU,
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
@@ -343,7 +362,8 @@ object SessionFiles {
stageImeFiles(context, root, ledger)
ledger.save()
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
- val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
+ val preload = StringBuilder(lsePreload(CpuFeatures.lacksAtomics, File(root, LSE_EMU).isFile, lseEmu))
+ preload.append("/usr/local/lib/libddsession.so\n")
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
index 5ad8fe253e..3e53e37d75 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
@@ -566,6 +566,7 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "agent environment skipped", it) }
val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList())
val customEnvironment = extraEnv()
+ val lseEmu = (customEnvironment + agentEnvironment).lastOrNull { it.startsWith("LSE_EMU=") }?.substringAfter('=')
try {
if (systemVulkan) {
SystemVulkanDriver.prepare(this)
@@ -575,7 +576,7 @@ class SessionService : Service() {
}
pruneSystemVulkanRuntime()
}
- SessionFiles.stage(this, root, startsSession = true)
+ SessionFiles.stage(this, root, startsSession = true, lseEmu = lseEmu)
} catch (error: Exception) {
Log.e(TAG, "Could not prepare the session graphics runtime", error)
failSession(gen, "GRAPHICS_RUNTIME_FAILED", getString(R.string.session_graphics_runtime_failed), -1)
@@ -830,7 +831,7 @@ class SessionService : Service() {
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
- com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
+ com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this), lseEmu)
.forEach { (k, v) -> env[k] = v }
} else prootEnv
diff --git a/app/src/test/java/com/droiddeck/launcher/core/CpuFeaturesTest.kt b/app/src/test/java/com/droiddeck/launcher/core/CpuFeaturesTest.kt
new file mode 100644
index 0000000000..cbb7c374a0
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/core/CpuFeaturesTest.kt
@@ -0,0 +1,48 @@
+package com.droiddeck.launcher.core
+
+import com.droiddeck.launcher.session.SessionFiles
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class CpuFeaturesTest {
+ @Test fun anArmv80CpuLacksAtomics() {
+ val cpuInfo = """
+ processor : 0
+ Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid
+ processor : 1
+ Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid
+ """.trimIndent()
+ assertTrue(CpuFeatures.lacksAtomics(cpuInfo))
+ }
+
+ @Test fun oneCoreWithoutAtomicsIsEnough() {
+ val cpuInfo = """
+ processor : 0
+ Features : fp asimd atomics
+ processor : 4
+ Features : fp asimd
+ """.trimIndent()
+ assertTrue(CpuFeatures.lacksAtomics(cpuInfo))
+ }
+
+ @Test fun anArmv82CpuHasAtomics() {
+ val cpuInfo = """
+ processor : 0
+ Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
+ """.trimIndent()
+ assertFalse(CpuFeatures.lacksAtomics(cpuInfo))
+ }
+
+ @Test fun noFeatureLinesMeansNoEmulation() {
+ assertFalse(CpuFeatures.lacksAtomics("processor : 0\n"))
+ assertFalse(CpuFeatures.lacksAtomics(""))
+ }
+
+ @Test fun theEmulatorIsPreloadedFirstOnlyWhenNeededAndStaged() {
+ assertEquals("/usr/local/lib/droiddeck-lse/liblse_emu.so\n", SessionFiles.lsePreload(lacksAtomics = true, staged = true))
+ assertEquals("", SessionFiles.lsePreload(lacksAtomics = true, staged = false))
+ assertEquals("", SessionFiles.lsePreload(lacksAtomics = false, staged = true))
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt
index 5b5cef26b4..cfb40f5404 100644
--- a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt
@@ -251,6 +251,52 @@ class BwrapSpawnerPlanTest {
}
}
+ @Test fun sandboxesSwitchOnTheLseEmulatorWhenItIsPreloaded() {
+ val context = RuntimeEnvironment.getApplication()
+ val rootfs = LinuxRuntime.rootDir(context)
+ val emu = File(rootfs, "usr/local/lib/droiddeck-lse/liblse_emu.so").apply { parentFile?.mkdirs(); writeText("") }
+ val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/droiddeck-lse/liblse_emu.so\n") }
+ try {
+ val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
+ assertEquals("/run/droiddeck-preload/liblse_emu.so", plan.env["LD_PRELOAD"])
+ assertEquals("1", plan.env["LSE_EMU"])
+ assertFalse(plan.env.containsKey("LSE_EMU_PATCH"))
+ val chosen = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp"))
+ .apply { getJSONObject("env").put("LSE_EMU_PATCH", "0") }, dir)
+ assertEquals("0", chosen.env["LSE_EMU_PATCH"])
+ assertEquals("1", chosen.env["LSE_EMU"])
+ for (inherited in listOf(
+ "/run/droiddeck-preload/liblse_emu.so /custom.so",
+ "/custom.so:/run/droiddeck-preload/liblse_emu.so",
+ )) {
+ val disabled = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp"))
+ .apply {
+ getJSONObject("env").put("LSE_EMU", "0")
+ getJSONObject("env").put("LD_PRELOAD", inherited)
+ }, dir)
+ assertEquals("0", disabled.env["LSE_EMU"])
+ assertEquals("/custom.so", disabled.env["LD_PRELOAD"])
+ assertFalse(disabled.binds.any { it.guest == "/run/droiddeck-preload/liblse_emu.so" })
+ }
+ } finally {
+ listOf(emu, preload).forEach { it.delete() }
+ }
+ }
+
+ @Test fun sandboxesLeaveTheLseSwitchesAloneWithoutTheEmulator() {
+ val context = RuntimeEnvironment.getApplication()
+ val rootfs = LinuxRuntime.rootDir(context)
+ val lib = File(rootfs, "usr/local/lib/libddsession.so").apply { parentFile?.mkdirs(); writeText("") }
+ val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libddsession.so\n") }
+ try {
+ val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
+ assertFalse(plan.env.containsKey("LSE_EMU"))
+ assertFalse(plan.env.containsKey("LSE_EMU_PATCH"))
+ } finally {
+ listOf(lib, preload).forEach { it.delete() }
+ }
+ }
+
@Test fun zypakLaunchesTheBrowserWithoutItsSandbox() {
val context = RuntimeEnvironment.getApplication()
val app = File(runtime, "app").apply { File(this, "bin").mkdirs() }
diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt
index 563b09dd36..2375b8497d 100644
--- a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt
@@ -94,6 +94,27 @@ class NativeGuestTest {
assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so"))
}
+ @Test
+ fun disablingLseKeepsItOutOfTheLoaderAndItsDescendants() {
+ val root = rootWithLoader()
+ val emulator = "/usr/lib/liblse_emu.so"
+ val session = "/usr/lib/libddsession.so"
+ listOf(emulator, session).forEach { File(root, it.removePrefix("/")).writeText("") }
+ File(root, "etc/droiddeck").mkdirs()
+ File(root, "etc/droiddeck/native-preload").writeText("$emulator\n$session\n")
+
+ val enabled = NativeGuest.sessionEnvironment(root, emptyList(), "/usr/bin/env")
+ assertEquals("1", enabled["LSE_EMU"])
+ assertEquals("$emulator:$session", enabled["DDNATV_PRELOAD"])
+ assertTrue(enabled.getValue("LD_PRELOAD").startsWith(File(root, emulator.removePrefix("/")).path + ":"))
+
+ val disabled = NativeGuest.sessionEnvironment(root, emptyList(), "/usr/bin/env", lseEmu = "0")
+ assertEquals("0", disabled["LSE_EMU"])
+ assertEquals(session, disabled["DDNATV_PRELOAD"])
+ assertEquals(listOf(File(root, session.removePrefix("/")).path, NativeGuest.hook(root).path),
+ disabled.getValue("LD_PRELOAD").split(':'))
+ }
+
@Test
fun theProgramTheLoaderRunsIsNamedInItsEnvironment() {
val root = rootWithLoader()
diff --git a/docs/arm-v8.0-steam-client.md b/docs/arm-v8.0-steam-client.md
new file mode 100644
index 0000000000..5b6de79d32
--- /dev/null
+++ b/docs/arm-v8.0-steam-client.md
@@ -0,0 +1,147 @@
+# Steam client on ARMv8.0 CPUs
+
+## The crash
+
+Valve's native arm64 Steam client stopped starting on ARMv8.0 CPUs after the April 15 2026
+build (client version 1776387948). The process dies with SIGILL right away, the session log
+shows `"$steam_root/steamrtarm64/steam" ... Illegal instruction` and `steam exited rc=132`,
+and the screen stays black.
+
+The faulting instruction is an ARMv8.1 LSE atomic. The GDB trace in
+[ValveSoftware/steam-for-linux#13288](https://github.com/ValveSoftware/steam-for-linux/issues/13288)
+stops on `ldaddal x1, x0, [x0]`, with `swpa` and `casal` next to it. Earlier builds were most
+likely compiled with `-moutline-atomics`, which picks LL/SC or LSE at run time. Newer builds
+inline LSE. Valve has not replied on that issue, so the cause comes from the reporter's
+disassembly, not from Valve.
+
+Affected cores are the ARMv8.0 ones without LSE: Cortex-A35, A53, A57, A72 and A73. A55, A75
+and later have it. On Android that covers the Snapdragon 4xx/6xx parts built on A53/A73 (for example the
+Snapdragon 685 with Adreno 610 in
+[Droid-Deck/DroidDeck#380](https://github.com/Droid-Deck/DroidDeck/issues/380)), plus the
+Nintendo Switch, Raspberry Pi 4 and older, and the Jetson Nano outside Android.
+`/proc/cpuinfo` shows it: the `Features` line has no `atomics`.
+
+LSE is an ARMv8.1 feature. LSE-Emu users report the current client running on a Cortex-A57,
+so nothing later than LSE seems to be required yet.
+
+## What other projects do
+
+- [SildurFX/Switchdeck](https://github.com/SildurFX/Switchdeck) (Switch, L4T Linux) lets the
+ client update once, then overlays `linuxarm64`, `steamrtarm64`, `steamui` and a `steam.cfg`
+ from the April build. It works there because the install script controls the whole system.
+ For us a pinned client is replaced by the self updater on its next start, which is why #380
+ was closed.
+- [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) is a preload library by the same
+ author, written to run the current arm64 client on the Switch. A SIGILL handler performs
+ each LSE instruction with an LL/SC loop. With `LSE_EMU_PATCH=1` the first trap at a site
+ writes an LL/SC stub within branch range and replaces the instruction with a `b` to it, so
+ the site runs natively after that. It covers the full LSE set plus `LDAPR`. The author
+ reports Steam, FEX, Proton games and ARMSX2 running on a Cortex-A57, with ARMSX2 close to
+ native ARMv8.0 speed once patched. GPL-3.0, same as this repo.
+- [Azkali/proton-arm64-a57](https://github.com/Azkali/proton-arm64-a57) rebuilds Proton 11
+ arm64 (Wine, DXVK, vkd3d-proton, FEX's WoW64 and ARM64EC DLLs) with
+ `-march=armv8-a -mtune=cortex-a57`. Stock Proton 11 arm64 also SIGILLs on ARMv8.0
+ (`wineboot` rc=132), so the client is not the only problem for games.
+- Some installers fall back to Valve's x86-64 client under FEX on CPUs without LSE. We already
+ have that path (`DD_STEAM_CLIENT_ARCH=x86_64`, `droiddeck-steam-x64`), but it is slower and
+ FEX itself has to be built without LSE.
+- [FrankNat996/armor](https://github.com/FrankNat996/armor) notes a separate problem: the arm64
+ client's ELF segments are 4K aligned, so it SIGSEGVs at once on 16K page kernels.
+
+## This change
+
+The session vendors LSE-Emu (`tools/linuxfs/lse-emu`, upstream commit `8bc9548`). CI and
+`tools/build_local.sh` build it as `usr/local/lib/droiddeck-lse/liblse_emu.so` with
+`-march=armv8-a -mno-outline-atomics`. The build fails if the library contains LSE
+instructions itself.
+
+When `/proc/cpuinfo` reports any core without `atomics`, `SessionFiles` puts the library first
+in the rootfs `/etc/ld.so.preload`. `BwrapSpawner` already turns that file into `LD_PRELOAD`
+for sandboxed processes. On CPUs with LSE nothing changes: the file is staged but not
+preloaded, and the library would also stay idle on its own because it checks `HWCAP_ATOMICS`.
+
+`droiddeck-session` sees the library in `ld.so.preload` and exports `LSE_EMU=1`. Runtime
+instruction rewriting is disabled by default (`LSE_EMU_PATCH=0`): the emulator uses the slower
+SIGILL path rather than rewriting executable code while other threads may be running it. To
+opt in to patching for testing, set `LSE_EMU_PATCH=1` explicitly. With a session debug folder,
+the script also sets `LSE_EMU_LOG=$DD_DEBUG_DIR/lse_emu.log`, and `session.log` gets a line
+starting with `== cpu: no LSE atomics`.
+
+The test APK targets SDK 34. To verify the expected `mprotect` restriction, run a controlled
+test executable containing a known-patchable, file-backed LSE instruction with
+`LSE_EMU_PATCH=1` under this APK configuration, and confirm `mprotect-failed` for that site.
+A normal Steam run alone cannot establish the restriction.
+
+## Tests
+
+`tools/tests/test_lse_emu.py` builds the library and a program that uses every LSE family
+(`ldadd` in all four sizes, `ldclr`, `ldeor`, `ldset`, `swp`, `ldsmax`, `ldumin`, `casal`,
+`caspal`) from four threads, and runs it under `qemu-aarch64 -cpu cortex-a57`:
+
+- without the library the program dies with SIGILL
+- trapping alone runs every form and keeps the threaded counters exact
+- patching runs every form twice, so the second run goes through the generated stubs, both
+ single threaded and with four threads
+- condition flags survive a patched `ldumax`/`ldsmaxb`, and `caspal` returns the current pair
+ on a mismatch
+- without `LSE_EMU=1`, and on `-cpu neoverse-n1`, the library stays out of the way
+- a SIGILL handler the program installs itself still runs for an unrelated `udf`
+
+The patch tests cannot run on an Apple Silicon Mac in an amd64 Docker container: qemu-aarch64
+there segfaults whenever code is written to an executable page after code on it has run, even
+in a ten line program without the library. CI runs them on x86 hardware.
+
+## Fixes over upstream
+
+The vendored copy carries two fixes found in review, both in the patched stubs and the
+emulation path:
+
+- `LDSMAX`/`LDSMIN`/`LDUMAX`/`LDUMIN` stubs used `cmp`/`csel` and overwrote NZCV. They now
+ save and restore it.
+- `CASP` with a 64-bit pair returned the `ldxp` result on a mismatch without a store. A 128-bit
+ `ldxp` is only single-copy atomic once a `stxp` succeeds, so a concurrent update could give
+ one old and one new half. Both the trap path and the stub now store the loaded pair back on a
+ mismatch and retry if that store fails, as libatomic does.
+
+Patching replaces an LSE instruction with a `b` while other threads may be running it.
+The architecture does not guarantee safe concurrent replacement for every instruction (including
+`LDADD`), so patching is opt-in and defaults to `LSE_EMU_PATCH=0`. This avoids that specific
+self-modifying-code race by keeping sites on the SIGILL emulation path, at the cost of speed.
+It does not eliminate all signal-handler compatibility risks: direct raw `rt_sigaction` syscalls,
+complex signal masks/flags, and applications that depend on exact kernel signal semantics still
+need dedicated tests. The handler forwarding is not a complete substitute for kernel delivery.
+
+## Testing on a device
+
+On an ARMv8.0 phone or handheld (no `atomics` in `/proc/cpuinfo`):
+
+1. Install the test APK and start a Steam session.
+2. `session.log` should have `== cpu: no LSE atomics` and no `steam exited rc=132`.
+3. In the default-mode run, check that `lse_emu.log` contains a `start` record for the
+ affected PID and that the process remains on the trap path. While Steam is running, its
+ `exit` record may not exist yet: either confirm a `no-patch` record for that PID, or exit
+ Steam normally before checking that its `exit` record has a nonzero `traps=` value. Confirm
+ there are no `patched` records. Summarise events with
+ `cut -d' ' -f2 lse_emu.log | sort | uniq -c`.
+ Then repeat with `LSE_EMU_PATCH=1` explicitly set in the session environment. Do not require
+ `mprotect-failed` for a valid trap-path run: `no-arena` means arena allocation failed before
+ `mprotect` was attempted, so it is inconclusive about the SDK restriction. Check that
+ restriction separately using the controlled patchable site described above. `unhandled`
+ means an instruction the library does not cover.
+4. Compare UI responsiveness against an ARMv8.2 device, and note any `lse_emu: unhandled`
+ lines in `session.log`.
+
+## Still open
+
+- Games. Proton 11 arm64 and Valve's FEX build need the same treatment. The preload reaches
+ them when they inherit `LD_PRELOAD`, but pressure-vessel and static binaries can drop it,
+ and FEX installs its own signal handlers with raw syscalls. An ARMv8.0 Proton build like
+ Azkali's is the cleaner fix.
+- In #380 the session first died with SIGILL in the app's own `wl-compositor` thread, inside
+ `turnip-sdk36/vulkan.ad08XX.so`, which is the A8xx driver build loaded on an Adreno 610.
+ Picking the 6xx/7xx Turnip fixed it, and Auto picks that build once the driver release list
+ is loaded. Nobody has checked yet whether our bundled driver builds avoid LSE. The preload
+ cannot help there because the compositor is a bionic thread in the app process.
+- JIT code (anonymous memory) is never patched and always traps.
+- If Valve starts requiring something past LSE, the library prints
+ `lse_emu: unhandled pc=... insn=...` and the client crashes as before.
diff --git a/tools/build_local.sh b/tools/build_local.sh
index 3c4feff55f..4d05bc6b02 100755
--- a/tools/build_local.sh
+++ b/tools/build_local.sh
@@ -225,6 +225,7 @@ else
external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc
aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe"
+ bash tools/linuxfs/lse-emu/build.sh "$d"
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard"
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
diff --git a/tools/components/reuse.py b/tools/components/reuse.py
index 1eb02dca9d..2000396d6c 100644
--- a/tools/components/reuse.py
+++ b/tools/components/reuse.py
@@ -23,8 +23,8 @@ import prepare # noqa: E402
# CI records identities under its runner labels and pinned NDK, not this host's.
RUNNER_ARCHITECTURES = ('X64', 'ARM64')
# The components job builds these outside the recipe registry.
-UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c',
- 'tools/quest']
+UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/linuxfs/lse-emu',
+ 'tools/venus/glprobe.c', 'tools/quest']
def ci_environment(architecture, root):
diff --git a/tools/linuxfs/check-preloads.sh b/tools/linuxfs/check-preloads.sh
index 0f801f87a0..f329f3537c 100644
--- a/tools/linuxfs/check-preloads.sh
+++ b/tools/linuxfs/check-preloads.sh
@@ -31,5 +31,9 @@ for sym in vkNegotiateLoaderLayerInterfaceVersion vkGetInstanceProcAddr vkGetDev
grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; }
done
test -f "$D/usr/local/lib/droiddeck-xclipse/VkLayer_droiddeck_xclipse.json"
+LSE=$(syms "$D/usr/local/lib/droiddeck-lse/liblse_emu.so")
+for sym in sigaction signal sigprocmask pthread_sigmask prctl syscall; do
+ grep -qx "$sym" <<<"$LSE" || { echo "::error::liblse_emu.so does not export $sym"; exit 1; }
+done
test -f "$D/usr/local/bin/droiddeck-session"
test -f "$D/usr/local/bin/droiddeck-proton-extra"
diff --git a/tools/linuxfs/lse-emu/README.md b/tools/linuxfs/lse-emu/README.md
new file mode 100644
index 0000000000..df6dd93cfd
--- /dev/null
+++ b/tools/linuxfs/lse-emu/README.md
@@ -0,0 +1,23 @@
+# LSE-Emu
+
+`lse_emu.c` is a copy of [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) at commit
+`8bc9548ac6fd24a8d506b266b17ba8d0e71a9b01` (GPL-3.0-or-later) with two fixes, listed in
+`docs/arm-v8.0-steam-client.md` under "Fixes over upstream": NZCV kept across the min/max
+stubs, and a store-back on `CASP` mismatches so the returned pair is atomic. Carry them forward
+until upstream has them.
+
+It is an `LD_PRELOAD` library that emulates the ARMv8.1 LSE atomic instructions (and `LDAPR`)
+on ARMv8.0 CPUs. A SIGILL handler performs each trapped instruction with an LL/SC loop. A GNU
+IFUNC resolver installs a minimal early handler on CPUs without LSE before dependency
+constructors, covering LSE instructions executed before the preload constructor. The early handler
+is removed after initialization unless `LSE_EMU=1` is set. With `LSE_EMU_PATCH=1` the first trap at a site
+writes an LL/SC stub nearby and replaces the instruction with a branch to it, so later runs do not trap.
+Patching is off by default. It is restricted to private file-backed executable mappings whose
+live file and offset still match the original mapping. Leave patching off for programs that
+can remap executable pages concurrently: checking the mapping cannot lock it against a remap.
+
+The session stages it as `/usr/local/lib/droiddeck-lse/liblse_emu.so` and only lists it in
+`/etc/ld.so.preload` when `/proc/cpuinfo` has no `atomics` flag. See
+`docs/arm-v8.0-steam-client.md` for why.
+
+To update, copy `lse_emu.c` from a newer upstream commit and change the commit above.
diff --git a/tools/linuxfs/lse-emu/build.sh b/tools/linuxfs/lse-emu/build.sh
new file mode 100644
index 0000000000..76eaa50375
--- /dev/null
+++ b/tools/linuxfs/lse-emu/build.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+set -euo pipefail
+D=${1:?asset directory}
+CC=${CC:-aarch64-linux-gnu-gcc}
+STRIP=${STRIP:-aarch64-linux-gnu-strip}
+here=$(cd "$(dirname "$0")" && pwd)
+out="$D/usr/local/lib/droiddeck-lse/liblse_emu.so"
+mkdir -p "$(dirname "$out")"
+"$CC" -shared -fPIC -O2 -march=armv8-a -mno-outline-atomics -Wall -Wextra -Wno-unused-parameter \
+ -Wl,-z,now,-z,max-page-size=65536 -o "$out" "$here/lse_emu.c" -ldl
+"$STRIP" --strip-unneeded "$out"
+disassembly=$("${OBJDUMP:-aarch64-linux-gnu-objdump}" -d "$out")
+if grep -qE $'\t((ld|st)(add|clr|eor|set|smax|smin|umax|umin)|swp|cas)[a-z]*\t' <<<"$disassembly"; then
+ echo "::error::liblse_emu.so itself contains LSE instructions"; exit 1
+fi
diff --git a/tools/linuxfs/lse-emu/lse_emu.c b/tools/linuxfs/lse-emu/lse_emu.c
new file mode 100644
index 0000000000..1c07d32ada
--- /dev/null
+++ b/tools/linuxfs/lse-emu/lse_emu.c
@@ -0,0 +1,1184 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// https://github.com/SildurFX/LSE-Emu
+// Copyright (C) 2026 SildurFX
+
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#ifndef HWCAP_ATOMICS
+#define HWCAP_ATOMICS (1UL << 8)
+#endif
+#ifndef SA_RESTORER
+#define SA_RESTORER 0x04000000
+#endif
+#ifndef MAP_FIXED_NOREPLACE
+#define MAP_FIXED_NOREPLACE 0x100000
+#endif
+
+/* ======================= raw syscalls (no PLT in handler) ================= */
+
+static long sc(long n, long a, long b, long c, long d, long e, long f) {
+ register long x8 asm("x8") = n, x0 asm("x0") = a, x1 asm("x1") = b;
+ register long x2 asm("x2") = c, x3 asm("x3") = d, x4 asm("x4") = e, x5 asm("x5") = f;
+ asm volatile("svc 0" : "+r"(x0)
+ : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5)
+ : "memory", "cc");
+ return x0;
+}
+
+/* ======================= slow path: emulation ============================= */
+
+#define DEFINE_RMW(NAME, UT, ST) \
+static UT NAME(void *p, unsigned op, UT v) { \
+ UT *q = (UT *)p; \
+ switch (op) { \
+ case 0: return __atomic_fetch_add(q, v, __ATOMIC_SEQ_CST); \
+ case 1: return __atomic_fetch_and(q, (UT)~v, __ATOMIC_SEQ_CST); \
+ case 2: return __atomic_fetch_xor(q, v, __ATOMIC_SEQ_CST); \
+ case 3: return __atomic_fetch_or (q, v, __ATOMIC_SEQ_CST); \
+ case 8: return __atomic_exchange_n(q, v, __ATOMIC_SEQ_CST); \
+ } \
+ UT old = __atomic_load_n(q, __ATOMIC_RELAXED), nw; \
+ do { \
+ switch (op) { \
+ case 4: nw = ((ST)old > (ST)v) ? old : v; break; \
+ case 5: nw = ((ST)old < (ST)v) ? old : v; break; \
+ case 6: nw = (old > v) ? old : v; break; \
+ default: nw = (old < v) ? old : v; break; \
+ } \
+ } while (!__atomic_compare_exchange_n(q, &old, nw, 1, \
+ __ATOMIC_SEQ_CST, __ATOMIC_RELAXED));\
+ return old; \
+}
+DEFINE_RMW(rmw8, uint8_t, int8_t)
+DEFINE_RMW(rmw16, uint16_t, int16_t)
+DEFINE_RMW(rmw32, uint32_t, int32_t)
+DEFINE_RMW(rmw64, uint64_t, int64_t)
+
+#define DEFINE_CAS(NAME, UT) \
+static UT NAME(void *p, UT exp, UT des) { \
+ UT e = exp; \
+ __atomic_compare_exchange_n((UT *)p, &e, des, 0, \
+ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); \
+ return e; \
+}
+DEFINE_CAS(cas8, uint8_t)
+DEFINE_CAS(cas16, uint16_t)
+DEFINE_CAS(cas32, uint32_t)
+DEFINE_CAS(cas64, uint64_t)
+
+static void casp128(void *p, uint64_t *o0, uint64_t *o1,
+ uint64_t e0, uint64_t e1, uint64_t d0, uint64_t d1) {
+ uint64_t a, b, t, s;
+ asm volatile(
+ "1: ldaxp %0, %1, [%6]\n"
+ " eor %2, %0, %7\n"
+ " eor %3, %1, %8\n"
+ " orr %2, %2, %3\n"
+ " cbnz %2, 2f\n"
+ " stlxp %w2, %9, %10, [%6]\n"
+ " cbnz %w2, 1b\n"
+ " b 3f\n"
+ "2: stlxp %w2, %0, %1, [%6]\n" // a 128-bit ldxp is only single-copy atomic once a stxp succeeds
+ " cbnz %w2, 1b\n"
+ "3:\n"
+ : "=&r"(a), "=&r"(b), "=&r"(t), "=&r"(s)
+ : "0"(0), "1"(0), "r"(p), "r"(e0), "r"(e1), "r"(d0), "r"(d1)
+ : "memory", "cc");
+ *o0 = a; *o1 = b;
+}
+
+static int emulate(ucontext_t *uc, uint32_t i) {
+ uint64_t *x = (uint64_t *)uc->uc_mcontext.regs;
+ unsigned rt = i & 31, rn = (i >> 5) & 31, rs = (i >> 16) & 31;
+ unsigned size = i >> 30;
+ void *p = (void *)(rn == 31 ? uc->uc_mcontext.sp : x[rn]);
+#define RD(r) ((r) >= 31 ? 0 : x[r])
+#define WR(r, v) do { if ((r) < 31) x[r] = (v); } while (0)
+
+ /* LDAPR is not covered by the LD/SWP encoding mask below. Emulate it
+ as an acquire load so patch mode can safely fall back if stub allocation
+ or code modification is unavailable. */
+ if ((i & 0x3FFFFC00u) == 0x38BFC000u) {
+ uint64_t v;
+ switch (size) {
+ case 0: v = __atomic_load_n((uint8_t *)p, __ATOMIC_ACQUIRE); break;
+ case 1: v = __atomic_load_n((uint16_t *)p, __ATOMIC_ACQUIRE); break;
+ case 2: v = __atomic_load_n((uint32_t *)p, __ATOMIC_ACQUIRE); break;
+ default: v = __atomic_load_n((uint64_t *)p, __ATOMIC_ACQUIRE); break;
+ }
+ WR(rt, v);
+ return 1;
+ }
+
+ if ((i & 0x3f200c00) == 0x38200000) { // LD, SWP
+ unsigned o3 = (i >> 15) & 1, opc = (i >> 12) & 7, op;
+ uint64_t v, old;
+ if (!o3) op = opc;
+ else if (opc == 0) op = 8;
+ else if (opc == 4 && rs == 31 &&
+ (i & (1u << 23)) && !(i & (1u << 22))) {
+ switch (size) {
+ case 0: v = __atomic_load_n((uint8_t *)p, __ATOMIC_ACQUIRE); break;
+ case 1: v = __atomic_load_n((uint16_t *)p, __ATOMIC_ACQUIRE); break;
+ case 2: v = __atomic_load_n((uint32_t *)p, __ATOMIC_ACQUIRE); break;
+ default: v = __atomic_load_n((uint64_t *)p, __ATOMIC_ACQUIRE); break;
+ }
+ WR(rt, v);
+ return 1;
+ } else return 0;
+ v = RD(rs);
+ switch (size) {
+ case 0: old = rmw8 (p, op, (uint8_t)v); break;
+ case 1: old = rmw16(p, op, (uint16_t)v); break;
+ case 2: old = rmw32(p, op, (uint32_t)v); break;
+ default: old = rmw64(p, op, v); break;
+ }
+ WR(rt, old);
+ return 1;
+ }
+ if ((i & 0x3fa07c00) == 0x08a07c00) { // CAS
+ uint64_t e = RD(rs), d = RD(rt), old;
+ switch (size) {
+ case 0: old = cas8 (p, (uint8_t)e, (uint8_t)d); break;
+ case 1: old = cas16(p, (uint16_t)e, (uint16_t)d); break;
+ case 2: old = cas32(p, (uint32_t)e, (uint32_t)d); break;
+ default: old = cas64(p, e, d); break;
+ }
+ WR(rs, old);
+ return 1;
+ }
+ if ((i & 0xbfa07c00) == 0x08207c00) { // CASP
+ if ((rs & 1) || (rt & 1)) return 0;
+ uint64_t e0 = RD(rs), e1 = RD(rs + 1), d0 = RD(rt), d1 = RD(rt + 1);
+ if (size == 0) {
+ uint64_t e = (uint32_t)e0 | ((uint64_t)(uint32_t)e1 << 32);
+ uint64_t d = (uint32_t)d0 | ((uint64_t)(uint32_t)d1 << 32);
+ uint64_t o = cas64(p, e, d);
+ WR(rs, (uint32_t)o); WR(rs + 1, o >> 32);
+ } else {
+ uint64_t o0, o1;
+ casp128(p, &o0, &o1, e0, e1, d0, d1);
+ WR(rs, o0); WR(rs + 1, o1);
+ }
+ return 1;
+ }
+ return 0;
+}
+
+/* ======================= fast path: stub generator ======================== */
+
+#define STP2(a,b) (0xA9BE0000u | ((b) << 10) | (31u << 5) | (a)) // stp a,b,[sp,#-32]!
+#define LDP2(a,b) (0xA8C20000u | ((b) << 10) | (31u << 5) | (a)) // ldp a,b,[sp],#32
+#define STR16(c) (0xF9000800u | (31u << 5) | (c)) // str c,[sp,#16]
+#define LDR16(c) (0xF9400800u | (31u << 5) | (c)) // ldr c,[sp,#16]
+#define MOVX(d,m) (0xAA0003E0u | ((m) << 16) | (d)) // mov xd,xm
+#define W(x) do { uint32_t _v = (x); w[n++] = _v; } while (0)
+
+static uint32_t ldx(unsigned sz, unsigned acq, unsigned rt, unsigned rn) {
+ return (sz << 30) | 0x085F7C00u | (acq << 15) | (rn << 5) | rt;
+}
+static uint32_t stx(unsigned sz, unsigned rel, unsigned rs, unsigned rt, unsigned rn) {
+ return (sz << 30) | 0x08007C00u | (rs << 16) | (rel << 15) | (rn << 5) | rt;
+}
+static uint32_t alu(unsigned op, unsigned d, unsigned n, unsigned m) {
+ static const uint32_t base[4] = { 0x8B000000u, 0x8A200000u, 0xCA000000u, 0xAA000000u };
+ return base[op] | (m << 16) | (n << 5) | d; // add, bic, eor, orr
+}
+
+// CASP{A}{L} Xs,Xs+1,Xt,Xt+1,[Xn] (64-bit pair): ldxp/ldaxp + compare + stxp/stlxp. Four scratch registers, no flag changes, 17 words.
+static int gen_casp(uint32_t *w, uintptr_t stub, uintptr_t ret, unsigned sz,
+ unsigned rs, unsigned rt, unsigned rn, unsigned acq, unsigned rel) {
+ // sz 1: 64-bit pair (LDXP x), sz 0: 32-bit pair (LDXP w, 8-byte aligned)
+ const uint32_t LDXP = sz ? 0xC87F0000u : 0x887F0000u, STXP = sz ? 0xC8200000u : 0x88200000u;
+ const uint32_t EOR = sz ? 0xCA000000u : 0x4A000000u, ORR = sz ? 0xAA000000u : 0x2A000000u;
+ unsigned t[4], k = 0; int n = 0;
+ for (unsigned r = 9; r <= 17 && k < 4; r++)
+ if (r != rs && r != rs + 1 && r != rt && r != rt + 1 && r != rn) t[k++] = r;
+ if (k < 4) return 0;
+ unsigned t0 = t[0], t1 = t[1], t2 = t[2], t3 = t[3];
+ W(0xD5033FDFu); // isb: synchronize instruction fetch on every entry
+ W(STP2(t0, t1));
+ W(0xA9010000u | (t3 << 10) | (31u << 5) | t2); // stp t2,t3,[sp,#16]
+ int loop = n;
+ W(LDXP | (acq << 15) | (t1 << 10) | (rn << 5) | t0); // ldxp/ldaxp t0,t1,[rn]
+ W(EOR | (rs << 16) | (t0 << 5) | t2); // eor t2,t0,rs
+ W(EOR | ((rs + 1) << 16) | (t1 << 5) | t3); // eor t3,t1,rs+1
+ W(ORR | (t3 << 16) | (t2 << 5) | t2); // orr t2,t2,t3
+ W(0xB4000000u | (3u << 5) | t2); // cbz t2, match (+3)
+ W(STXP | (t2 << 16) | (rel << 15) | (t1 << 10) | (rn << 5) | t0); // mismatch: store the loaded pair back, which validates it
+ W(0x14000002u); // b check (+2)
+ W(STXP | (t2 << 16) | (rel << 15) | ((rt + 1) << 10) | (rn << 5) | rt); // match: stxp/stlxp w(t2),rt,rt+1,[rn]
+ W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2); // check: cbnz w(t2), loop
+ W(MOVX(rs, t0));
+ W(MOVX(rs + 1, t1));
+ W(0xA9410000u | (t3 << 10) | (31u << 5) | t2); // ldp t2,t3,[sp,#16]
+ W(LDP2(t0, t1));
+ { int64_t off = (int64_t)ret - (int64_t)(stub + 4 * (uintptr_t)n);
+ W(0x14000000u | (((uint32_t)(off >> 2)) & 0x03FFFFFFu)); }
+ return n;
+}
+
+// Builds the stub for one instruction. Returns word count, 0 if unsupported.
+static int gen(uint32_t *w, uintptr_t stub, uintptr_t ret, uint32_t i) {
+ unsigned size = i >> 30, rt = i & 31, rn = (i >> 5) & 31, rs = (i >> 16) & 31;
+ unsigned kind, op = 0, acq, rel; // kind: 0 ldop, 1 swp, 2 cas, 3 casp, 4 min/max
+ int n = 0;
+
+ if ((i & 0x3FFFFC00u) == 0x38BFC000u) { // LDAPR[B|H]: stub = LDAR[B|H] (same operands, stronger ordering) ; b ret
+ W(0xD5033FDFu); // isb before executing the generated sequence
+ W((i & 0xC0000000u) | 0x08DFFC00u | (i & 0x3FFu));
+ { int64_t off = (int64_t)ret - (int64_t)(stub + 4 * (uintptr_t)n);
+ W(0x14000000u | (((uint32_t)(off >> 2)) & 0x03FFFFFFu)); }
+ return n;
+ }
+ if ((i & 0x3f200c00) == 0x38200000) {
+ unsigned o3 = (i >> 15) & 1, opc = (i >> 12) & 7;
+ if (!o3 && opc <= 3) { kind = 0; op = opc; }
+ else if (!o3) { kind = 4; op = opc; } // LDSMAX LDSMIN LDUMAX LDUMIN (opc 4..7)
+ else if (o3 && opc == 0) kind = 1;
+ else return 0;
+ acq = (i >> 23) & 1; rel = (i >> 22) & 1;
+ } else if ((i & 0x3fa07c00) == 0x08a07c00) {
+ kind = 2; acq = (i >> 22) & 1; rel = (i >> 15) & 1;
+ } else if ((i & 0xbfa07c00) == 0x08207c00) { // CASP, 32-bit (size 0) and 64-bit (size 1) pairs
+ if (size > 1 || (rs & 1) || (rt & 1) || rs >= 30 || rt >= 30) return 0;
+ kind = 3; acq = (i >> 22) & 1; rel = (i >> 15) & 1;
+ } else return 0;
+ if (rn == 31) return 0; // sp-based: leave to trap path
+ if (kind == 3) return gen_casp(w, stub, ret, size, rs, rt, rn, acq, rel);
+
+ W(0xD5033FDFu); // isb after the atomic branch redirects execution here
+ unsigned t[3], k = 0; // three scratch regs from x9..x17
+ for (unsigned r = 9; r <= 17 && k < 3; r++)
+ if (r != rs && r != rt && r != rn) t[k++] = r;
+ unsigned t0 = t[0], t1 = t[1], t2 = t[2];
+
+ W(STP2(t0, t1));
+ W(STR16(t2));
+ if (kind == 4) { // cmp/csel below clobber NZCV, the real instruction does not
+ W(0xD53B4200u | t2); // mrs t2, nzcv
+ W(0xF9000C00u | (31u << 5) | t2); // str t2,[sp,#24]
+ }
+ int loop = n;
+ W(ldx(size, acq, t0, rn)); // t0 = old
+ if (kind == 1) {
+ W(stx(size, rel, t2, rs, rn));
+ W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2);
+ } else if (kind == 4) { // LDSMAX/LDSMIN/LDUMAX/LDUMIN
+ static const unsigned cc[4] = { 0xC /*gt*/, 0xB /*lt*/, 0x8 /*hi*/, 0x3 /*lo*/ };
+ unsigned sgn = !(op & 2), sf = (size == 3), cmpn = t0;
+ if (size < 2 && sgn) { // sign-extend the loaded value: sxtb/sxth wt1,wt0
+ W((size == 1 ? 0x13003C00u : 0x13001C00u) | (t0 << 5) | t1);
+ cmpn = t1;
+ }
+ if (size < 2) // cmp wcmpn, wrs, {u,s}xt{b,h}
+ W(0x6B20001Fu | (rs << 16) | ((sgn ? (size == 1 ? 5u : 4u) : (size == 1 ? 1u : 0u)) << 13) | (cmpn << 5));
+ else // cmp t0, rs
+ W((sf ? 0xEB00001Fu : 0x6B00001Fu) | (rs << 16) | (t0 << 5));
+ W((sf ? 0x9A800000u : 0x1A800000u) | (rs << 16) | (cc[op - 4] << 12) | (t0 << 5) | t1); // csel t1,t0,rs,cond
+ W(stx(size, rel, t2, t1, rn));
+ W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2);
+ } else if (kind == 0) {
+ W(alu(op, t1, t0, rs)); // t1 = new
+ W(stx(size, rel, t2, t1, rn));
+ W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2);
+ } else {
+ if (size == 3) W(0xCA000000u | (rs << 16) | (t0 << 5) | t1);
+ else if (size == 2) W(0x4A000000u | (rs << 16) | (t0 << 5) | t1); // 32-bit eor
+ else {
+ W((size == 1 ? 0x53003C00u : 0x53001C00u) | (rs << 5) | t1); // uxth/uxtb
+ W(0xCA000000u | (t1 << 16) | (t0 << 5) | t1);
+ }
+ W(0xB5000000u | (3u << 5) | t1); // cbnz t1, fail (+3)
+ W(stx(size, rel, t2, rt, rn));
+ W(0x35000000u | (((unsigned)(loop - n) & 0x7FFFF) << 5) | t2);
+ W(0xD5033F5Fu); // fail: clrex
+ }
+ if (kind == 2) { if (rs != 31) W(MOVX(rs, t0)); }
+ else if (rt != 31) W(MOVX(rt, t0));
+ if (kind == 4) {
+ W(0xF9400C00u | (31u << 5) | t2); // ldr t2,[sp,#24]
+ W(0xD51B4200u | t2); // msr nzcv, t2
+ }
+ W(LDR16(t2));
+ W(LDP2(t0, t1));
+ { int64_t off = (int64_t)ret - (int64_t)(stub + 4 * (uintptr_t)n);
+ W(0x14000000u | (((uint32_t)(off >> 2)) & 0x03FFFFFFu)); }
+ return n;
+}
+
+/* ---- stub arenas (must sit within +-128 MiB of the patched code) ---- */
+
+#define ARENA_SZ 0x10000
+#define SLOT 68
+#define MAX_ARENAS 256
+#define REACH 0x7000000 // 112 MiB, safely inside the 128 MiB branch range
+#define MAX_MAPS 4096
+static struct { uintptr_t lo, hi; } maprng[MAX_MAPS];
+static volatile int nmap;
+static struct { uintptr_t base, used; } arena[MAX_ARENAS];
+static volatile int narena;
+
+static int near_(uintptr_t b, uintptr_t pc) {
+ intptr_t d = (intptr_t)b - (intptr_t)pc;
+ return d > -(intptr_t)REACH && d < (intptr_t)REACH;
+}
+static int in_arena(uintptr_t a) {
+ int n = __atomic_load_n(&narena, __ATOMIC_ACQUIRE); // pairs with the release store in alloc_slot
+ for (int k = 0; k < n; k++)
+ if (a >= arena[k].base && a < arena[k].base + ARENA_SZ) return 1;
+ return 0;
+}
+static unsigned long hexv(const char **p);
+
+// Find a free 64 KiB-aligned hole within REACH using the cached map snapshot.
+// Use the constructor-time mapping snapshot in the SIGILL path. mmap with
+// MAP_FIXED_NOREPLACE remains the authority if another thread changes mappings.
+static uintptr_t find_gap(uintptr_t pc, const uintptr_t *tr, int ntr) {
+ uintptr_t lo = pc > (uintptr_t)REACH + 0x100000 ? pc - REACH : 0x100000;
+ uintptr_t hi = pc + REACH;
+ uintptr_t prev = 0, best = 0, bestd = ~(uintptr_t)0;
+ int count = __atomic_load_n(&nmap, __ATOMIC_ACQUIRE);
+ for (int i = 0; i <= count; i++) {
+ uintptr_t s0 = i < count ? maprng[i].lo : hi;
+ uintptr_t e0 = i < count ? maprng[i].hi : hi;
+ uintptr_t g0 = prev > lo ? prev : lo;
+ g0 = (g0 + 0xFFFF) & ~(uintptr_t)0xFFFF;
+ uintptr_t g1 = (s0 < hi ? s0 : hi) & ~(uintptr_t)0xFFFF;
+ if (g1 > g0 && g1 - g0 >= ARENA_SZ) {
+ uintptr_t rlo = g0, rhi = g1 - ARENA_SZ;
+ uintptr_t cand = pc & ~(uintptr_t)0xFFFF;
+ if (cand < rlo) cand = rlo;
+ if (cand > rhi) cand = rhi;
+ for (int st = 0; st < 16; st++) {
+ uintptr_t pick = 0; int found = 0;
+ for (int w = 0; w < 2 && !found; w++) {
+ if (w == 1 && st == 0) continue;
+ uintptr_t c;
+ if (w == 0) {
+ if (cand + (uintptr_t)st * ARENA_SZ > rhi) continue;
+ c = cand + (uintptr_t)st * ARENA_SZ;
+ } else {
+ if (cand < rlo + (uintptr_t)st * ARENA_SZ) continue;
+ c = cand - (uintptr_t)st * ARENA_SZ;
+ }
+ int is_bad = 0;
+ for (int t = 0; t < ntr; t++) if (tr[t] == c) is_bad = 1;
+ if (!is_bad) { pick = c; found = 1; }
+ }
+ if (found) {
+ uintptr_t d = pick > pc ? pick - pc : pc - pick;
+ if (d < bestd) { bestd = d; best = pick; }
+ break;
+ }
+ }
+ }
+ if (e0 > prev) prev = e0;
+ if (i == count || prev >= hi) break;
+ }
+ return best;
+}
+
+static uintptr_t alloc_slot(uintptr_t pc) {
+ for (int k = 0; k < narena; k++)
+ if (arena[k].used + SLOT <= ARENA_SZ && near_(arena[k].base, pc)) {
+ uintptr_t s = arena[k].base + arena[k].used;
+ arena[k].used += SLOT;
+ return s;
+ }
+ if (narena >= MAX_ARENAS) return 0;
+ // free hole nearest to the site, found by walking /proc/self/maps
+ uintptr_t tried[16]; int ntried = 0; // blocks mmap refused, don't offer them again
+ for (int attempt = 0; attempt < 12; attempt++) {
+ uintptr_t hint = find_gap(pc, tried, ntried);
+ if (!hint) break;
+ long r = sc(SYS_mmap, hint, ARENA_SZ, PROT_READ | PROT_WRITE | PROT_EXEC,
+ MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
+ if ((unsigned long)r > (unsigned long)-4096) { tried[ntried++] = hint; continue; }
+ if ((uintptr_t)r != hint) { //kernel without MAP_FIXED_NOREPLACE moved it
+ sc(SYS_munmap, r, ARENA_SZ, 0, 0, 0, 0);
+ tried[ntried++] = hint; continue;
+ }
+ arena[narena].base = (uintptr_t)r;
+ arena[narena].used = SLOT;
+ int idx = narena;
+ __atomic_store_n(&narena, idx + 1, __ATOMIC_RELEASE); // publish the slot only after base/used are written
+ return arena[idx].base;
+ }
+
+ /* The cached map snapshot may not expose a usable gap (e.g. under QEMU).
+ An advisory mapping is safe: the kernel chooses a free address, and we
+ keep it only if the generated branch can reach it. */
+ uintptr_t hint = pc & ~(uintptr_t)0xFFFF;
+ long r = sc(SYS_mmap, hint, ARENA_SZ, PROT_READ | PROT_WRITE | PROT_EXEC,
+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ if ((unsigned long)r > (unsigned long)-4096) return 0;
+ if (!near_((uintptr_t)r, pc)) {
+ sc(SYS_munmap, r, ARENA_SZ, 0, 0, 0, 0);
+ return 0;
+ }
+ arena[narena].base = (uintptr_t)r;
+ arena[narena].used = SLOT;
+ int idx = narena;
+ __atomic_store_n(&narena, idx + 1, __ATOMIC_RELEASE);
+ return arena[idx].base;
+}
+
+/* ---- known executable file-backed ranges (parsed from /proc/self/maps) ---- */
+
+#define MAX_RANGES 512
+struct file_range {
+ uintptr_t lo, hi;
+ unsigned long offset, major, minor, inode;
+};
+static struct file_range rng[MAX_RANGES];
+static int nrng;
+
+static const struct file_range *recorded_range(uintptr_t pc) {
+ for (int k = 0; k < nrng; k++)
+ if (pc >= rng[k].lo && pc < rng[k].hi) return &rng[k];
+ return NULL;
+}
+static unsigned long hexv(const char **p) {
+ unsigned long v = 0;
+ for (;; (*p)++) {
+ char c = **p; int d;
+ if (c >= '0' && c <= '9') d = c - '0';
+ else if (c >= 'a' && c <= 'f') d = c - 'a' + 10;
+ else break;
+ v = (v << 4) | d;
+ }
+ return v;
+}
+static const char *skip_spaces(const char *p) {
+ while (*p == ' ') p++;
+ return p;
+}
+
+static int file_range_at(const char *p, struct file_range *out, int remember_gap) {
+ struct file_range map = {0};
+ map.lo = hexv(&p);
+ if (*p != '-') return 0;
+ p++;
+ map.hi = hexv(&p);
+ if (*p != ' ' || map.hi <= map.lo) return 0;
+ if (remember_gap && nmap < MAX_MAPS) {
+ maprng[nmap].lo = map.lo; maprng[nmap].hi = map.hi;
+ nmap = nmap + 1;
+ }
+ p = skip_spaces(p);
+ if (p[0] != 'r' || p[1] != '-' || p[2] != 'x' || p[3] != 'p' || p[4] != ' ') return 0;
+ p = skip_spaces(p + 4);
+ map.offset = hexv(&p);
+ if (*p != ' ') return 0;
+ p = skip_spaces(p);
+ map.major = hexv(&p);
+ if (*p != ':') return 0;
+ p++;
+ map.minor = hexv(&p);
+ if (*p != ' ') return 0;
+ p = skip_spaces(p);
+ while (*p >= '0' && *p <= '9') map.inode = map.inode * 10 + (unsigned)(*p++ - '0');
+ if (map.inode == 0 || *p != ' ' || *skip_spaces(p) != '/') return 0;
+ *out = map;
+ return 1;
+}
+
+static int same_file_at(const struct file_range *first, const struct file_range *now, uintptr_t pc) {
+ return pc >= now->lo && pc < now->hi && first->major == now->major &&
+ first->minor == now->minor && first->inode == now->inode &&
+ first->offset + (pc - first->lo) == now->offset + (pc - now->lo);
+}
+
+/* The constructor records candidates. The patch lock serializes live reads
+ in the signal handler. Never treat a failed live read as a match. */
+static int read_ranges(const struct file_range *wanted, uintptr_t pc) {
+ static char buf[4096], line[512];
+ long fd = sc(SYS_openat, -100, (long)"/proc/self/maps", O_RDONLY | O_CLOEXEC, 0, 0, 0);
+ if (fd < 0) return 0;
+ int ll = 0, found = 0; long n;
+ while (!found && (n = sc(SYS_read, fd, (long)buf, sizeof buf, 0, 0, 0)) > 0)
+ for (long k = 0; k < n; k++) {
+ char c = buf[k];
+ if (c == '\n') {
+ struct file_range map;
+ line[ll] = 0;
+ ll = 0;
+ if (!file_range_at(line, &map, wanted == NULL)) continue;
+ if (wanted) {
+ if (same_file_at(wanted, &map, pc)) { found = 1; break; }
+ } else if (nrng < MAX_RANGES) {
+ rng[nrng++] = map;
+ }
+ } else if (ll < (int)sizeof line - 1) line[ll++] = c;
+ }
+ sc(SYS_close, fd, 0, 0, 0, 0, 0);
+ return found;
+}
+
+static void refresh_ranges(void) {
+ nrng = 0; nmap = 0;
+ (void)read_ranges(NULL, 0);
+}
+
+/* ---- debug log (LSE_EMU_LOG=1) ---- */
+
+static int add_str(char *b, int n, const char *s);
+static int add_dec(char *b, int n, unsigned long v);
+
+static volatile int logon;
+static char logpath[200] = "/tmp/lse_emu.log";
+static unsigned long st_traps, st_patched, st_failed;
+
+static void logwrite(const char *b, int n) { // raw syscalls, O_APPEND: safe from the handler
+ long fd = sc(SYS_openat, -100, (long)logpath, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0666, 0, 0);
+ if (fd < 0) return;
+ sc(SYS_write, fd, (long)b, n, 0, 0, 0);
+ sc(SYS_close, fd, 0, 0, 0, 0, 0);
+}
+static int add_hex(char *b, int n, uint64_t v, int digits) {
+ for (int k = (digits - 1) * 4; k >= 0; k -= 4) b[n++] = "0123456789abcdef"[(v >> k) & 15];
+ return n;
+}
+// One line per site, patched is logged as it happens, failures are de-duplicated.
+static void logsite(const char *why, uintptr_t pc, uint32_t insn) {
+ if (!logon) return;
+ static uintptr_t seen[256];
+ if (why[0] != 'p') {
+ for (int k = 0; k < 256; k++)
+ if (__atomic_load_n(&seen[k], __ATOMIC_ACQUIRE) == pc) return;
+ int claimed = 0;
+ for (int k = 0; k < 256; k++) {
+ uintptr_t empty = 0;
+ if (__atomic_compare_exchange_n(&seen[k], &empty, pc, 0,
+ __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
+ claimed = 1; break;
+ }
+ }
+ if (!claimed) return;
+ }
+ char b[160]; int n = 0;
+ n = add_str(b, n, "pid="); n = add_dec(b, n, (unsigned long)sc(SYS_getpid, 0, 0, 0, 0, 0, 0));
+ n = add_str(b, n, " "); n = add_str(b, n, why);
+ n = add_str(b, n, " pc=0x"); n = add_hex(b, n, pc, 16);
+ n = add_str(b, n, " insn=0x"); n = add_hex(b, n, insn, 8);
+ b[n++] = '\n';
+ logwrite(b, n);
+}
+static void logstats(const char *tag) {
+ if (!logon) return;
+ char b[160]; int n = 0;
+ n = add_str(b, n, "pid="); n = add_dec(b, n, (unsigned long)sc(SYS_getpid, 0, 0, 0, 0, 0, 0));
+ n = add_str(b, n, " "); n = add_str(b, n, tag);
+ n = add_str(b, n, " traps="); n = add_dec(b, n, st_traps);
+ n = add_str(b, n, " patched="); n = add_dec(b, n, st_patched);
+ n = add_str(b, n, " failed="); n = add_dec(b, n, st_failed);
+ n = add_str(b, n, " arenas="); n = add_dec(b, n, (unsigned long)narena);
+ b[n++] = '\n';
+ logwrite(b, n);
+}
+
+/* ---- patching ---- */
+
+static volatile int plock, patch_enabled, stats;
+static volatile int seccomp_filter_installed;
+/* A per-thread guard prevents recursive acquisition from a nested SIGILL. */
+static __thread volatile sig_atomic_t patching;
+
+#define FUTEX_WAIT_PRIVATE 128
+#define FUTEX_WAKE_PRIVATE 129
+static size_t kernel_page_size = 4096;
+static uintptr_t bad[256];
+
+// Try-lock, a handler that interrupts try_patch on the same thread and traps again must never spin on a lock it already owns. A skipped site is simply retried on its next trap.
+static int trylock(void) { return !__atomic_exchange_n(&plock, 1, __ATOMIC_ACQUIRE); }
+static void unlock(void) { __atomic_store_n(&plock, 0, __ATOMIC_RELEASE); }
+
+// Overwrite one instruction word with a branch (single aligned release store), then flush the icache.
+static int patch_word(uintptr_t pc, uint32_t v) {
+ size_t page_size = kernel_page_size ? kernel_page_size : 4096;
+ uintptr_t page = pc & ~((uintptr_t)page_size - 1);
+ if (sc(SYS_mprotect, page, page_size, PROT_READ | PROT_WRITE | PROT_EXEC, 0, 0, 0)) return -1;
+ __atomic_store_n((uint32_t *)pc, v, __ATOMIC_RELEASE);
+ __builtin___clear_cache((char *)pc, (char *)pc + 4);
+ if (sc(SYS_mprotect, page, page_size, PROT_READ | PROT_EXEC, 0, 0, 0)) {
+ if (!sc(SYS_mprotect, page, page_size, PROT_READ | PROT_EXEC, 0, 0, 0))
+ return 0;
+ if (sc(SYS_mprotect, page, page_size, PROT_READ, 0, 0, 0))
+ (void)sc(SYS_mprotect, page, page_size, PROT_NONE, 0, 0, 0);
+ return -2; // instruction was written, but execution permission could not be restored
+ }
+ return 0;
+}
+
+static void try_patch(uintptr_t pc, uint32_t insn) {
+ uint32_t w[17];
+ if (__atomic_load_n(&seccomp_filter_installed, __ATOMIC_ACQUIRE) ||
+ !__atomic_load_n(&patch_enabled, __ATOMIC_ACQUIRE)) return;
+ if (bad[(pc >> 2) & 255] == pc) return;
+ if (!gen(w, 0, 0, insn)) { logsite("unsupported-form", pc, insn); return; } // not a patchable form
+ // The remaining generated atomic stubs save scratch registers on the guest
+ // stack. Keep them on the trap path: a later caller may have no stack headroom.
+ if ((insn & 0x3FFFFC00u) != 0x38BFC000u) return;
+
+ if (patching) return;
+ /* Mark this thread before touching the lock: the lock operation itself
+ can fault and re-enter this handler on CPUs without native LSE. */
+ patching = 1;
+ if (!trylock()) {
+ /* Nested faults return at the function entry while this thread
+ owns or waits for the patch operation. */
+ for (;;) {
+ (void)sc(SYS_futex, (long)&plock, FUTEX_WAIT_PRIVATE, 1, 0, 0, 0);
+ if (trylock()) break;
+ }
+ }
+ const struct file_range *recorded = recorded_range(pc);
+ if (!recorded || !read_ranges(recorded, pc)) {
+ logsite("not-current-file-mapping", pc, insn);
+ bad[(pc >> 2) & 255] = pc;
+ goto out;
+ }
+ if (*(volatile uint32_t *)pc != insn) goto out;
+ uintptr_t slot = alloc_slot(pc);
+ if (!slot) { logsite("no-arena", pc, insn); bad[(pc >> 2) & 255] = pc; st_failed++; goto out; }
+ int n = gen(w, slot, pc + 4, insn);
+
+ for (int k = 0; k < n; k++) ((volatile uint32_t *)slot)[k] = w[k];
+ __builtin___clear_cache((char *)slot, (char *)slot + 4 * n);
+
+ long off = (long)slot - (long)pc;
+ uint32_t b = 0x14000000u | (((uint32_t)(off >> 2)) & 0x03FFFFFFu);
+ if (!read_ranges(recorded, pc) || *(volatile uint32_t *)pc != insn) {
+ bad[(pc >> 2) & 255] = pc;
+ goto out;
+ }
+ int patch_result = patch_word(pc, b);
+ if (patch_result) {
+ logsite(patch_result == -2 ? "rx-restore-failed" : "mprotect-failed", pc, insn);
+ bad[(pc >> 2) & 255] = pc; st_failed++;
+ if (patch_result == -2)
+ (void)sc(SYS_exit_group, 128 + SIGSEGV, 0, 0, 0, 0, 0);
+ goto out;
+ }
+ st_patched++;
+ logsite("patched", pc, insn);
+out:
+ unlock();
+ (void)sc(SYS_futex, (long)&plock, FUTEX_WAKE_PRIVATE, INT32_MAX, 0, 0, 0);
+ patching = 0;
+}
+
+/* ======================= libc hooks (unchanged logic) ===================== */
+
+static int (*real_sigaction)(int, const struct sigaction *, struct sigaction *);
+static int (*real_sigprocmask)(int, const sigset_t *, sigset_t *);
+static int (*real_pthread_sigmask)(int, const sigset_t *, sigset_t *);
+static long (*real_syscall)(long, ...);
+
+static void resolve(void) {
+ if (!real_sigaction) real_sigaction = dlsym(RTLD_NEXT, "sigaction");
+ if (!real_sigprocmask) real_sigprocmask = dlsym(RTLD_NEXT, "sigprocmask");
+ if (!real_pthread_sigmask) real_pthread_sigmask = dlsym(RTLD_NEXT, "pthread_sigmask");
+ if (!real_syscall) real_syscall = dlsym(RTLD_NEXT, "syscall");
+}
+
+static volatile int active, app_replaced;
+struct app_action { void *h; unsigned long f; sigset_t mask; int valid; };
+/* Retire a slot only after taking it out of current_app_action. A reader
+ that still holds it must have entered before that exchange. After claiming
+ the retired slot, a zero reader count therefore permits reuse. */
+#define APP_ACTION_SLOTS 256
+enum { ACTION_FREE, ACTION_IN_USE, ACTION_RETIRED };
+static struct app_action default_app_action;
+static struct app_action early_app_action;
+static struct app_action app_action_slots[APP_ACTION_SLOTS];
+static unsigned char app_action_state[APP_ACTION_SLOTS];
+static unsigned int app_action_readers;
+static struct app_action *current_app_action = &default_app_action;
+struct ksa { void *h; unsigned long f; void *restorer; uint64_t mask; };
+static struct ksa early_previous;
+static volatile int early_saved_valid, early_disabled;
+
+/* fork() can be called from an unrelated signal handler. Prevent that handler
+ from interrupting this thread inside a snapshot or slot publication. This
+ does not run on the ordinary LSE emulation path. */
+static long block_action_signals(uint64_t *previous) {
+ uint64_t all = UINT64_MAX;
+ return sc(SYS_rt_sigprocmask, SIG_BLOCK, (long)&all, (long)previous, 8, 0, 0);
+}
+static void restore_action_signals(long blocked, const uint64_t *previous) {
+ if (blocked == 0)
+ (void)sc(SYS_rt_sigprocmask, SIG_SETMASK, (long)previous, 0, 8, 0, 0);
+}
+
+/* Only the forking thread survives. Its live action is the last published
+ complete slot, not an unpublished write or the old process's reader count. */
+static void reset_after_fork(void) {
+ uint64_t previous = 0;
+ long blocked = block_action_signals(&previous);
+ struct app_action *current = __atomic_load_n(¤t_app_action, __ATOMIC_SEQ_CST);
+ __atomic_store_n(&app_action_readers, 0, __ATOMIC_SEQ_CST);
+ for (int i = 0; i < APP_ACTION_SLOTS; i++)
+ __atomic_store_n(&app_action_state[i], current == &app_action_slots[i] ? ACTION_IN_USE : ACTION_FREE,
+ __ATOMIC_RELEASE);
+ __atomic_store_n(&plock, 0, __ATOMIC_RELEASE);
+ patching = 0;
+ restore_action_signals(blocked, &previous);
+}
+
+static void load_app_action(struct app_action *out) {
+ uint64_t previous = 0;
+ long blocked = block_action_signals(&previous);
+ __atomic_add_fetch(&app_action_readers, 1, __ATOMIC_SEQ_CST);
+ struct app_action *snapshot = __atomic_load_n(¤t_app_action, __ATOMIC_SEQ_CST);
+ *out = *snapshot;
+ __atomic_sub_fetch(&app_action_readers, 1, __ATOMIC_SEQ_CST);
+ restore_action_signals(blocked, &previous);
+}
+static void retire_app_action(struct app_action *old) {
+ if (old != &default_app_action && old != &early_app_action) {
+ __atomic_store_n(&app_action_state[old - app_action_slots], ACTION_RETIRED, __ATOMIC_RELEASE);
+ }
+}
+
+static void replace_app_action(struct app_action *next, struct app_action *old_out) {
+ struct app_action *old = __atomic_exchange_n(¤t_app_action, next, __ATOMIC_SEQ_CST);
+ if (old_out) *old_out = *old;
+ retire_app_action(old);
+}
+static int publish_app_action(void *h, unsigned long flags, const sigset_t *mask, int valid,
+ struct app_action *old_out) {
+ uint64_t previous = 0;
+ long blocked = block_action_signals(&previous);
+ /* Never wait for a suspended publisher or reader in a nested handler. */
+ for (int reclaim = 0; reclaim <= 1; reclaim++) {
+ unsigned char state = reclaim ? ACTION_RETIRED : ACTION_FREE;
+ for (int i = 0; i < APP_ACTION_SLOTS; i++) {
+ unsigned char expected = state;
+ if (__atomic_load_n(&app_action_state[i], __ATOMIC_RELAXED) != state ||
+ !__atomic_compare_exchange_n(&app_action_state[i], &expected, ACTION_IN_USE, 0,
+ __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) continue;
+ if (state == ACTION_RETIRED && __atomic_load_n(&app_action_readers, __ATOMIC_SEQ_CST) != 0) {
+ __atomic_store_n(&app_action_state[i], ACTION_RETIRED, __ATOMIC_RELEASE);
+ continue;
+ }
+ struct app_action *next = &app_action_slots[i];
+ next->h = h; next->f = flags; next->mask = *mask; next->valid = valid;
+ replace_app_action(next, old_out);
+ restore_action_signals(blocked, &previous);
+ return 0;
+ }
+ }
+ restore_action_signals(blocked, &previous);
+ errno = ENOMEM;
+ return -1;
+}
+/* Keep the publication pinned across snapshot and conditional consumption.
+ Slot reclamation cannot reuse that address while our reader is live. */
+static void select_app_action(struct app_action *out) {
+ uint64_t previous = 0;
+ long blocked = block_action_signals(&previous);
+ __atomic_add_fetch(&app_action_readers, 1, __ATOMIC_SEQ_CST);
+ for (;;) {
+ struct app_action *selected = __atomic_load_n(¤t_app_action, __ATOMIC_SEQ_CST);
+ *out = *selected;
+ if (!out->valid || out->h == (void *)SIG_IGN || out->h == (void *)SIG_DFL ||
+ !(out->f & SA_RESETHAND)) break;
+ if (__atomic_compare_exchange_n(¤t_app_action, &selected, &default_app_action, 0,
+ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
+ retire_app_action(selected);
+ break;
+ }
+ }
+ __atomic_sub_fetch(&app_action_readers, 1, __ATOMIC_SEQ_CST);
+ restore_action_signals(blocked, &previous);
+}
+
+int sigaction(int sig, const struct sigaction *act, struct sigaction *old) {
+ resolve();
+ if (!active || sig != SIGILL) return real_sigaction(sig, act, old);
+ struct sigaction requested;
+ if (act) requested = *act;
+ struct app_action snapshot;
+ if (act) {
+ if (publish_app_action((void *)requested.sa_sigaction, (unsigned long)requested.sa_flags,
+ &requested.sa_mask, 1, &snapshot) < 0) return -1;
+ app_replaced = 1;
+ } else {
+ load_app_action(&snapshot);
+ }
+ if (old) {
+ memset(old, 0, sizeof *old);
+ if (snapshot.valid) {
+ old->sa_sigaction = snapshot.h;
+ old->sa_flags = (int)(snapshot.f & ~(unsigned long)SA_RESTORER);
+ old->sa_mask = snapshot.mask;
+ } else old->sa_handler = SIG_DFL;
+ }
+ return 0;
+}
+
+sighandler_t signal(int sig, sighandler_t h) {
+ struct sigaction sa, o;
+ memset(&sa, 0, sizeof sa);
+ sa.sa_handler = h; sa.sa_flags = SA_RESTART;
+ sigemptyset(&sa.sa_mask);
+ if (sigaction(sig, &sa, &o) < 0) return SIG_ERR;
+ return o.sa_handler;
+}
+
+int sigprocmask(int how, const sigset_t *set, sigset_t *old) {
+ resolve();
+ if (active && set && how != SIG_UNBLOCK) {
+ sigset_t t = *set; sigdelset(&t, SIGILL);
+ return real_sigprocmask(how, &t, old);
+ }
+ return real_sigprocmask(how, set, old);
+}
+int pthread_sigmask(int how, const sigset_t *set, sigset_t *old) {
+ resolve();
+ if (active && set && how != SIG_UNBLOCK) {
+ sigset_t t = *set; sigdelset(&t, SIGILL);
+ return real_pthread_sigmask(how, &t, old);
+ }
+ return real_pthread_sigmask(how, set, old);
+}
+
+// a process that turns on seccomp must not be patched afterwards
+int prctl(int opt, ...) {
+ va_list ap; va_start(ap, opt);
+ unsigned long a1 = va_arg(ap, unsigned long), a2 = va_arg(ap, unsigned long);
+ unsigned long a3 = va_arg(ap, unsigned long), a4 = va_arg(ap, unsigned long);
+ va_end(ap);
+ resolve();
+ int result = (int)real_syscall(SYS_prctl, (long)opt, a1, a2, a3, a4);
+ if (opt == PR_SET_SECCOMP && result == 0) {
+ __atomic_store_n(&seccomp_filter_installed, 1, __ATOMIC_RELEASE);
+ __atomic_store_n(&patch_enabled, 0, __ATOMIC_RELEASE);
+ }
+ return result;
+}
+
+long syscall(long n, ...) {
+ unsigned long a[6];
+ va_list ap; va_start(ap, n);
+ for (int k = 0; k < 6; k++) a[k] = va_arg(ap, unsigned long);
+ va_end(ap);
+ resolve();
+ if (active) {
+#ifdef SYS_seccomp
+#endif
+ if (n == SYS_rt_sigaction && a[0] == SIGILL) {
+ if (a[3] != 8) { errno = EINVAL; return -1; }
+ struct ksa *act = (struct ksa *)a[1], *old = (struct ksa *)a[2];
+ struct ksa requested;
+ if (act) requested = *act;
+ sigset_t requested_mask;
+ memset(&requested_mask, 0, sizeof requested_mask);
+ if (act) memcpy(&requested_mask, &requested.mask, sizeof requested.mask);
+ struct app_action snapshot;
+ if (act) {
+ if (publish_app_action(requested.h, requested.f, &requested_mask, 1, &snapshot) < 0) return -1;
+ app_replaced = 1;
+ } else {
+ load_app_action(&snapshot);
+ }
+ if (old) {
+ memset(old, 0, sizeof *old);
+ if (snapshot.valid) {
+ old->h = snapshot.h; old->f = snapshot.f;
+ memcpy(&old->mask, &snapshot.mask, sizeof old->mask);
+ }
+ }
+ /* act was staged before old was written, so aliased buffers are safe. */
+ return 0;
+ }
+ if (n == SYS_rt_sigprocmask && a[1] && a[3] == 8 && a[0] != SIG_UNBLOCK) {
+ uint64_t m = *(uint64_t *)a[1];
+ m &= ~(1ULL << (SIGILL - 1));
+ return real_syscall(n, a[0], &m, a[2], a[3], a[4], a[5]);
+ }
+ }
+ long result = real_syscall(n, a[0], a[1], a[2], a[3], a[4], a[5]);
+#ifdef SYS_seccomp
+ if (active && n == SYS_seccomp &&
+ (result == 0 || (result >= 0 && (a[1] & 8UL) != 0))) {
+ __atomic_store_n(&seccomp_filter_installed, 1, __ATOMIC_RELEASE);
+ __atomic_store_n(&patch_enabled, 0, __ATOMIC_RELEASE);
+ }
+#endif
+ if (active && n == SYS_prctl && a[0] == PR_SET_SECCOMP && result == 0) {
+ __atomic_store_n(&seccomp_filter_installed, 1, __ATOMIC_RELEASE);
+ __atomic_store_n(&patch_enabled, 0, __ATOMIC_RELEASE);
+ }
+ return result;
+}
+
+/* TLS keeps re-entry state isolated between threads and signal-safe. */
+static __thread volatile sig_atomic_t forwarding_app_handler;
+static __thread uintptr_t forwarding_app_stack;
+
+static void forward_app_sigill(void *h, unsigned long flags, const sigset_t *mask_set,
+ int sig, siginfo_t *si, void *ctx) {
+ uint64_t mask = 0, oldmask = 0;
+ memcpy(&mask, mask_set, sizeof mask);
+ if (!(flags & SA_NODEFER)) mask |= 1ULL << (SIGILL - 1);
+ long blocked = sc(SYS_rt_sigprocmask, SIG_BLOCK, (long)&mask,
+ (long)&oldmask, 8, 0, 0);
+ uintptr_t marker = (uintptr_t)&mask;
+ sig_atomic_t was_forwarding = forwarding_app_handler;
+ uintptr_t was_stack = forwarding_app_stack;
+ forwarding_app_handler = 1;
+ forwarding_app_stack = marker;
+ if (flags & SA_SIGINFO)
+ ((void (*)(int, siginfo_t *, void *))h)(sig, si, ctx);
+ else
+ ((void (*)(int))h)(sig);
+ forwarding_app_handler = was_forwarding;
+ forwarding_app_stack = was_stack;
+ if (blocked == 0)
+ (void)sc(SYS_rt_sigprocmask, SIG_SETMASK, (long)&oldmask, 0, 8, 0, 0);
+}
+
+/* ======================= handler ========================================== */
+
+static void put_hex(uint64_t v) {
+ char b[18]; b[0] = '0'; b[1] = 'x';
+ for (int k = 0; k < 16; k++) b[2 + k] = "0123456789abcdef"[(v >> (60 - 4 * k)) & 15];
+ (void)!write(2, b, 18);
+}
+
+static void on_sigill(int sig, siginfo_t *si, void *ctx) {
+ if (!si || si->si_code <= 0) {
+ uintptr_t marker = (uintptr_t)▮
+ /* A siglongjmp can abandon the forwarding frame; detect the stale TLS
+ state when execution later resumes at a shallower stack address. */
+ if (forwarding_app_handler && marker >= forwarding_app_stack) {
+ forwarding_app_handler = 0;
+ forwarding_app_stack = 0;
+ }
+ /* With SA_NODEFER, a nested application-generated SIGILL may be
+ delivered recursively; otherwise the forwarded mask keeps it pending. */
+ struct app_action snapshot; select_app_action(&snapshot);
+ void *h = snapshot.h; unsigned long flags = snapshot.f;
+ if (snapshot.valid && h == (void *)SIG_IGN) return;
+ if (snapshot.valid && h != (void *)SIG_DFL && h != (void *)SIG_IGN) {
+ forward_app_sigill(h, flags, &snapshot.mask, sig, si, ctx);
+ return;
+ }
+ struct ksa dfl = { (void *)SIG_DFL, 0, 0, 0 };
+ (void)sc(SYS_rt_sigaction, SIGILL, (long)&dfl, 0, 8, 0, 0);
+ (void)sc(SYS_tgkill, sc(SYS_getpid, 0, 0, 0, 0, 0, 0),
+ sc(SYS_gettid, 0, 0, 0, 0, 0, 0), SIGILL, 0, 0, 0);
+ return;
+ }
+ ucontext_t *uc = (ucontext_t *)ctx;
+ uintptr_t pc = uc->uc_mcontext.pc;
+ uint32_t insn = __atomic_load_n((uint32_t *)pc, __ATOMIC_ACQUIRE); // pairs with the release store in patch_word
+
+ if ((insn & 0xFC000000u) == 0x14000000u) { // another thread patched it first
+ intptr_t off = ((int32_t)(insn << 6)) >> 4;
+ if (in_arena(pc + off)) return; // just re-execute the new branch
+ }
+
+ if (emulate(uc, insn)) {
+ uc->uc_mcontext.pc = pc + 4;
+ st_traps++;
+ if (__atomic_load_n(&patch_enabled, __ATOMIC_ACQUIRE)) try_patch(pc, insn);
+ else if (logon) logsite("no-patch", pc, insn);
+ if (logon && !(st_traps & 0x3FFF)) logstats("stats"); // every 16384 traps
+ return;
+ }
+
+ logsite("unhandled", pc, insn);
+ (void)!write(2, "lse_emu: unhandled pc=", 22);
+ put_hex(pc);
+ (void)!write(2, " insn=", 6);
+ put_hex(insn);
+ (void)!write(2, "\n", 1);
+
+ /* A nested synchronous fault gets one emulation attempt, never re-forwarding. */
+ if (forwarding_app_handler) {
+ (void)sc(SYS_exit_group, 128 + SIGILL, 0, 0, 0, 0, 0);
+ return;
+ }
+
+ struct app_action snapshot; select_app_action(&snapshot);
+ void *h = snapshot.h; unsigned long flags = snapshot.f;
+ if (snapshot.valid && h != (void *)SIG_DFL && h != (void *)SIG_IGN) {
+ forward_app_sigill(h, flags, &snapshot.mask, sig, si, ctx);
+ return;
+ }
+ struct ksa dfl = { (void *)SIG_DFL, 0, 0, 0 };
+ sc(SYS_rt_sigaction, SIGILL, (long)&dfl, 0, 8, 0, 0);
+}
+
+/* ======================= early install ==================================== */
+
+// A dependency may execute LSE in its constructor before this preload's constructor.
+static void early_target(void) {}
+static void (*early_install(uint64_t hwcap))(void) {
+ /* IFUNC resolution may happen more than once; never save our own handler
+ as the original action or re-enable emulation after init disables it. */
+ if (!(hwcap & HWCAP_ATOMICS) && !early_saved_valid && !early_disabled) {
+ unsigned long restart = early_saved_valid ? (early_previous.f & SA_RESTART) : 0;
+ struct ksa k = { (void *)on_sigill, SA_SIGINFO | SA_ONSTACK | SA_NODEFER | restart, 0, 0 };
+ if (sc(SYS_rt_sigaction, SIGILL, (long)&k, (long)&early_previous, 8, 0, 0) == 0) {
+ early_saved_valid = 1;
+ early_app_action.h = early_previous.h; early_app_action.f = early_previous.f;
+ memset(&early_app_action.mask, 0, sizeof early_app_action.mask);
+ memcpy(&early_app_action.mask, &early_previous.mask, sizeof early_previous.mask);
+ early_app_action.valid = early_previous.h != (void *)SIG_DFL;
+ __atomic_store_n(¤t_app_action, &early_app_action, __ATOMIC_RELEASE);
+ active = 1;
+ }
+ }
+ return early_target;
+}
+__attribute__((visibility("hidden"))) void lse_emu_early(void) __attribute__((ifunc("early_install")));
+void (*volatile lse_emu_early_ref)(void) = lse_emu_early;
+
+/* ======================= init / fini ====================================== */
+
+static int add_str(char *b, int n, const char *s) { while (*s) b[n++] = *s++; return n; }
+static int add_dec(char *b, int n, unsigned long v) {
+ char t[21]; int k = 0;
+ if (!v) t[k++] = '0';
+ while (v) { t[k++] = '0' + v % 10; v /= 10; }
+ while (k) b[n++] = t[--k];
+ return n;
+}
+
+static int skipped(void) { // LSE_EMU_SKIP=name:name
+ const char *s = getenv("LSE_EMU_SKIP");
+ if (!s || !*s) return 0;
+ char exe[512]; ssize_t r = readlink("/proc/self/exe", exe, sizeof exe - 1);
+ if (r <= 0) return 0;
+ exe[r] = 0;
+ char tok[128];
+ while (*s) {
+ int k = 0;
+ while (*s && *s != ':' && k < 127) tok[k++] = *s++;
+ tok[k] = 0;
+ if (*s == ':') s++;
+ if (k && strstr(exe, tok)) return 1;
+ }
+ return 0;
+}
+
+static void disable_early(void) {
+ if (!active) return;
+ struct sigaction sa;
+ memset(&sa, 0, sizeof sa);
+ struct app_action snapshot; load_app_action(&snapshot);
+ if (app_replaced) {
+ if (snapshot.valid) {
+ if (snapshot.f & SA_SIGINFO) sa.sa_sigaction = snapshot.h;
+ else sa.sa_handler = snapshot.h;
+ sa.sa_flags = (int)(snapshot.f & ~(unsigned long)SA_RESTORER);
+ sa.sa_mask = snapshot.mask;
+ } else sa.sa_handler = SIG_DFL;
+ } else if (early_saved_valid) {
+ if (early_previous.f & SA_SIGINFO) sa.sa_sigaction = early_previous.h;
+ else sa.sa_handler = early_previous.h;
+ sa.sa_flags = (int)(early_previous.f & ~(unsigned long)SA_RESTORER);
+ memcpy(&sa.sa_mask, &early_previous.mask, sizeof early_previous.mask);
+ } else sa.sa_handler = SIG_DFL;
+ int restored = -1;
+ if (app_replaced) {
+ restored = real_sigaction(SIGILL, &sa, NULL);
+ } else {
+ struct ksa kernel_sa = { (void *)SIG_DFL, 0, 0, 0 };
+ if (early_saved_valid) kernel_sa = early_previous;
+ restored = (int)sc(SYS_rt_sigaction, SIGILL, (long)&kernel_sa, 0, 8, 0, 0);
+ }
+ if (restored == 0) active = 0;
+}
+
+__attribute__((constructor)) static void init(void) {
+ (void)pthread_atfork(NULL, NULL, reset_after_fork);
+ resolve();
+ long page_size = sysconf(_SC_PAGESIZE);
+ if (page_size > 0 && (((unsigned long)page_size & ((unsigned long)page_size - 1)) == 0))
+ kernel_page_size = (size_t)page_size;
+ // The early IFUNC resolver can install the handler before this constructor.
+ // Always remove it when emulation is disabled, even if HWCAP disagrees with
+ // the resolver's view of the CPU features.
+ const char *emu_env = getenv("LSE_EMU");
+ if (!emu_env || emu_env[0] != '1') {
+ early_disabled = 1;
+ disable_early();
+ return;
+ }
+
+ if (getauxval(AT_HWCAP) & HWCAP_ATOMICS) {
+ early_disabled = 1;
+ disable_early();
+ return; // CPU has real LSE
+ }
+
+ struct sigaction sa; memset(&sa, 0, sizeof sa);
+ sa.sa_sigaction = on_sigill;
+ sa.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_NODEFER |
+ (early_saved_valid ? (int)(early_previous.f & SA_RESTART) : 0);
+ sigemptyset(&sa.sa_mask);
+ if (real_sigaction(SIGILL, &sa, NULL) == 0) active = 1;
+ else if (!active) return;
+
+ const char *p = getenv("LSE_EMU_PATCH");
+ stats = getenv("LSE_EMU_STATS") != NULL;
+ /* LSE_EMU_PATCH=1 is an explicit opt-in to code modification. If a
+ restrictive seccomp filter was inherited, patching may fail or the
+ process may be terminated when mmap/mprotect is denied. Trap-only mode
+ remains the default; hooks veto patching when this process installs a
+ filter later. */
+ if (p && p[0] == '1' && !skipped() &&
+ !__atomic_load_n(&seccomp_filter_installed, __ATOMIC_ACQUIRE)) {
+ refresh_ranges();
+ if (!__atomic_load_n(&seccomp_filter_installed, __ATOMIC_ACQUIRE))
+ __atomic_store_n(&patch_enabled, 1, __ATOMIC_RELEASE);
+ }
+
+ const char *lg = getenv("LSE_EMU_LOG"); // =1 -> /tmp/lse_emu.log, =/path -> that file
+ if (lg && lg[0] && lg[0] != '0') {
+ if (lg[0] == '/') { size_t l = strlen(lg); if (l < sizeof logpath) memcpy(logpath, lg, l + 1); }
+ logon = 1;
+ char b[700], exe[480]; int n = 0;
+ ssize_t r = readlink("/proc/self/exe", exe, sizeof exe - 1);
+ exe[r > 0 ? r : 0] = 0;
+ n = add_str(b, n, "pid="); n = add_dec(b, n, (unsigned long)getpid());
+ n = add_str(b, n, " start patch="); n = add_dec(b, n, (unsigned long)patch_enabled);
+ n = add_str(b, n, " exe="); n = add_str(b, n, exe);
+ b[n++] = '\n';
+ logwrite(b, n);
+ }
+}
+
+__attribute__((destructor)) static void fini(void) {
+ if (!active) return;
+ logstats("exit");
+ if (!stats) return;
+ char b[160]; int n = 0;
+ n = add_str(b, n, "lse_emu: pid="); n = add_dec(b, n, (unsigned long)getpid());
+ n = add_str(b, n, " traps="); n = add_dec(b, n, st_traps);
+ n = add_str(b, n, " patched="); n = add_dec(b, n, st_patched);
+ n = add_str(b, n, " failed="); n = add_dec(b, n, st_failed);
+ b[n++] = '\n';
+ (void)!write(2, b, n);
+}
\ No newline at end of file
diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
old mode 100755
new mode 100644
index d82fb99350..10d522084d
--- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
+++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session
@@ -11,6 +11,12 @@ if [ "${DD_RAISE_NOFILE:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ]; then
unset dd_nofile_was
fi
export HOME=${HOME:-/root}
+if grep -qs '/liblse_emu\.so$' /etc/ld.so.preload; then
+ if [ "${LSE_EMU+x}" != x ]; then export LSE_EMU=1; fi
+ # Runtime instruction rewriting is opt-in; the SIGILL emulation path remains available.
+ export LSE_EMU_PATCH=${LSE_EMU_PATCH:-0}
+ [ -n "${DD_DEBUG_DIR:-}" ] && export LSE_EMU_LOG=${LSE_EMU_LOG:-$DD_DEBUG_DIR/lse_emu.log}
+fi
mode=${1:-desktop}
shift || true
@@ -100,6 +106,7 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then
echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
+ [ "${LSE_EMU:-}" = 1 ] && echo "== cpu: no LSE atomics (ARMv8.0); liblse_emu.so emulates them (log: ${LSE_EMU_LOG:-off})"
fi
start_diagnostic_inventory() {
diff --git a/tools/linuxfs/preload/pathcache.c b/tools/linuxfs/preload/pathcache.c
index beefbfbe24..6d6a7146fb 100644
--- a/tools/linuxfs/preload/pathcache.c
+++ b/tools/linuxfs/preload/pathcache.c
@@ -56,27 +56,38 @@ static unsigned hash_of(const char *s, int kind, int mode, int flags) {
return h;
}
-static struct entry *slot(unsigned h) {
- return &table[(h ^ (h >> 16)) % PATH_CACHE_SLOTS];
-}
-
static int cacheable(const char *path) {
return path != NULL && path[0] == '/' && strlen(path) < PATH_CACHE_KEY_MAX && enabled();
}
static struct entry *find(const char *path, int kind, int mode, int flags, unsigned h) {
- struct entry *e = slot(h);
+ long long now = now_ns();
- if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) return NULL;
- if (now_ns() - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) return NULL;
- return e;
+ for (int i = 0; i < PATH_CACHE_SLOTS; i++) {
+ struct entry *e = &table[i];
+ if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) continue;
+ if (now - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) continue;
+ return e;
+ }
+ return NULL;
}
static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) {
- struct entry *e = slot(h);
+ struct entry *e = find(path, kind, mode, flags, h);
+ long long now = now_ns();
char *copy = value != NULL ? strdup(value) : NULL;
if (value != NULL && copy == NULL) return;
+ if (e == NULL) {
+ e = &table[0];
+ for (int i = 0; i < PATH_CACHE_SLOTS; i++) {
+ if (table[i].stamp == 0 || now - table[i].stamp > PATH_CACHE_TTL_NS) {
+ e = &table[i];
+ break;
+ }
+ if (table[i].stamp < e->stamp) e = &table[i];
+ }
+ }
free(e->value);
e->value = copy;
e->hash = h;
@@ -84,7 +95,7 @@ static void store(const char *path, int kind, int mode, int flags, unsigned h, c
e->mode = mode;
e->flags = flags;
memcpy(e->key, path, strlen(path) + 1);
- e->stamp = now_ns();
+ e->stamp = now;
}
__attribute__((visibility("hidden")))
diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c
index d83ad87492..53f1da0f8b 100644
--- a/tools/nativeguest/hook/env.c
+++ b/tools/nativeguest/hook/env.c
@@ -41,9 +41,73 @@ static char **clean_env_for_system(char *const envp[]) {
return new_env;
}
+static int preload_has_entry(const char *chain, const char *entry, size_t entry_len) {
+ if (!chain || !entry_len) return 0;
+ const char *p = chain;
+ while (*p) {
+ size_t len = strcspn(p, ": ");
+ if (len == entry_len && memcmp(p, entry, len) == 0) return 1;
+ p += len;
+ if (*p) p++;
+ }
+ return 0;
+}
+
+static char *merge_preload_env(const char *host, const char *mapped) {
+ size_t host_len = host ? strlen(host) : 0;
+ char *out = malloc(11 + host_len + 1 + strlen(mapped) + 1);
+ if (!out) return NULL;
+ memcpy(out, "LD_PRELOAD=", 11);
+ size_t used = 11;
+ if (host_len) {
+ memcpy(out + used, host, host_len);
+ used += host_len;
+ }
+ for (const char *p = mapped; *p; ) {
+ size_t n = strcspn(p, ": ");
+ if (n && !preload_has_entry(host, p, n)) {
+ if (used > 11) out[used++] = ':';
+ memcpy(out + used, p, n);
+ used += n;
+ }
+ p += n;
+ if (*p) p++;
+ }
+ out[used] = '\0';
+ return out;
+}
+
+// Filter the LSE emulator from colon/space-separated preload chains when explicitly disabled.
+static char *filter_lse_emu_preloads(const char *value, int lse_emu_disabled) {
+ if (!value) return NULL;
+ size_t len = strlen(value);
+ char *out = malloc(len + 1);
+ if (!out) return NULL;
+ size_t used = 0;
+ const char *p = value;
+ while (*p) {
+ size_t n = strcspn(p, ": ");
+ if (n) {
+ const char *base = p + n;
+ while (base > p && base[-1] != '/' && base[-1] != ':' && base[-1] != ' ') base--;
+ int is_lse_emu = n - (size_t)(base - p) == strlen("liblse_emu.so") &&
+ memcmp(base, "liblse_emu.so", strlen("liblse_emu.so")) == 0;
+ if (!(lse_emu_disabled && is_lse_emu)) {
+ if (used) out[used++] = ':';
+ memcpy(out + used, p, n);
+ used += n;
+ }
+ }
+ p += n;
+ if (*p) p++;
+ }
+ out[used] = '\0';
+ return out;
+}
+
// LD_PRELOAD with every absolute path that is not in the rootfs yet mapped into it. Entries are
// separated by ':' or ' '. free() the result.
-static char *map_preload_paths(const char *value) {
+static char *map_preload_paths(const char *value, int lse_emu_disabled) {
if (!value) return NULL;
size_t cap = strlen(value) + (g_ddnatv_root_len + 1) * 16 + 16;
char *out = malloc(cap);
@@ -57,6 +121,13 @@ static char *map_preload_paths(const char *value) {
char entry[PATH_MAX];
memcpy(entry, p, len);
entry[len] = '\0';
+ const char *base = strrchr(entry, '/');
+ base = base ? base + 1 : entry;
+ if (lse_emu_disabled && strcmp(base, "liblse_emu.so") == 0) {
+ p += len;
+ if (*p) p++;
+ continue;
+ }
char buf[PATH_MAX];
const char *mapped = entry[0] == '/' ? rewrite_path_in_root(entry, buf, sizeof(buf)) : entry;
size_t mlen = strlen(mapped);
@@ -72,10 +143,13 @@ static char *map_preload_paths(const char *value) {
return out;
}
+static void free_modified_env(char **modified_env, char *const orig_env[]);
+
static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) {
init_ddnatv_hook();
int count = 0;
int has_preload = 0;
+ int lse_emu_disabled = 0;
int has_root = 0;
int has_tunables = 0;
int has_path = 0;
@@ -105,6 +179,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
switch (e[0]) {
case 'L':
if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; }
+ else if (strncmp(e, "LSE_EMU=0", 9) == 0 && e[9] == '\0') lse_emu_disabled = 1;
break;
case 'G':
if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1;
@@ -140,6 +215,12 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
count++;
}
+ char *filtered_host_chain = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_host, 1) : NULL;
+ if (lse_emu_disabled && g_preload_host && !filtered_host_chain) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ const char *host_preload = lse_emu_disabled ? (filtered_host_chain ? filtered_host_chain : "") : g_preload_host;
char **new_env = calloc(count + 26, sizeof(char *));
int dst = 0;
// The user the program runs as (hardlinks.c): this process's, whatever the environment it passes
@@ -157,23 +238,45 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) {
continue;
}
+ if (lse_emu_disabled && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_PRELOAD=", 15) == 0) {
+ char *filtered = filter_lse_emu_preloads(envp[i] + 15, 1);
+ if (!filtered) {
+ free_modified_env(new_env, envp);
+ free(filtered_host_chain);
+ errno = ENOMEM;
+ return NULL;
+ }
+ size_t len = 15 + strlen(filtered) + 1;
+ char *str = malloc(len);
+ if (!str) {
+ free(filtered);
+ free_modified_env(new_env, envp);
+ free(filtered_host_chain);
+ errno = ENOMEM;
+ return NULL;
+ }
+ snprintf(str, len, "DDNATV_PRELOAD=%s", filtered);
+ new_env[dst++] = str;
+ free(filtered);
+ continue;
+ }
if (has_preload && envp[i][0] == 'L' && strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
// ld.so opens these itself: the guest's paths are mapped to the rootfs, and the libraries every
// program loads (DDNATV_PRELOAD) come first
- char *mapped = map_preload_paths(preload_value);
+ char *mapped = map_preload_paths(preload_value, lse_emu_disabled);
if (mapped) {
- size_t chain = g_preload_host ? strlen(g_preload_host) : 0;
- int has_chain = chain > 0 && strstr(mapped, g_preload_host) != NULL;
- size_t len = 11 + chain + 1 + strlen(mapped) + 1;
- char *str = malloc(len);
+ char *str = merge_preload_env(host_preload, mapped);
+ free(mapped);
if (str) {
- if (chain > 0 && !has_chain) snprintf(str, len, "LD_PRELOAD=%s:%s", g_preload_host, mapped);
- else snprintf(str, len, "LD_PRELOAD=%s", mapped);
new_env[dst++] = str;
- free(mapped);
continue;
}
- free(mapped);
+ }
+ if (lse_emu_disabled) {
+ free_modified_env(new_env, envp);
+ free(filtered_host_chain);
+ errno = ENOMEM;
+ return NULL;
}
}
// If we have an explicit real executable, drop the inherited entry to replace with the fresh target
@@ -211,13 +314,13 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL;
if (hook) {
size_t hook_len = strlen(hook);
- size_t host_len = g_preload_host ? strlen(g_preload_host) + 1 : 0;
+ size_t host_len = host_preload ? strlen(host_preload) + 1 : 0;
size_t size = 11 + host_len + hook_len + 1;
char *str = malloc(size);
if (str) {
size_t n = ddnatv_append(str, size, 0, "LD_PRELOAD=", 11);
if (host_len) {
- n = ddnatv_append(str, size, n, g_preload_host, host_len - 1);
+ n = ddnatv_append(str, size, n, host_preload, host_len - 1);
n = ddnatv_append(str, size, n, ":", 1);
}
ddnatv_append(str, size, n, hook, hook_len);
@@ -225,13 +328,29 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
}
}
if (!has_preload_list && g_preload_guest) {
- size_t len = strlen(g_preload_guest);
- char *str = malloc(15 + len + 1);
- if (str) {
+ char *filtered = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_guest, 1) : NULL;
+ if (lse_emu_disabled && !filtered) {
+ free_modified_env(new_env, envp);
+ free(filtered_host_chain);
+ errno = ENOMEM;
+ return NULL;
+ }
+ const char *guest_preload = lse_emu_disabled ? filtered : g_preload_guest;
+ if (guest_preload) {
+ size_t len = strlen(guest_preload);
+ char *str = malloc(15 + len + 1);
+ if (!str) {
+ free(filtered);
+ free_modified_env(new_env, envp);
+ free(filtered_host_chain);
+ errno = ENOMEM;
+ return NULL;
+ }
memcpy(str, "DDNATV_PRELOAD=", 15);
- memcpy(str + 15, g_preload_guest, len + 1);
+ memcpy(str + 15, guest_preload, len + 1);
new_env[dst++] = str;
}
+ free(filtered);
}
if (!has_root && g_ddnatv_root[0] != '\0') {
char *str = malloc(PATH_MAX + 16);
@@ -319,6 +438,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
new_env[dst++] = strdup("DEBCONF_NONINTERACTIVE_SEEN=true");
}
new_env[dst] = NULL;
+ free(filtered_host_chain);
return new_env;
}
diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c
index ede8c4354d..8ffbe4eeca 100644
--- a/tools/nativeguest/hook/exec.c
+++ b/tools/nativeguest/hook/exec.c
@@ -483,6 +483,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
return -1;
}
char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path);
+ if (!new_env) {
+ free(new_argv);
+ errno = ENOMEM;
+ return -1;
+ }
int ret = run_execve(orig_execve, ld_so, new_argv, new_env);
if (errno == EACCES && chmod(ld_so, 0755) == 0) {
// ld.so without its exec bit (an unusual restore): fix it once and retry
@@ -507,6 +512,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
if (new_argv) {
prepare_static_program(static_elf); // ld.so is a static program itself
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
+ if (!ddnatv_env) {
+ free(new_argv);
+ errno = ENOMEM;
+ return -1;
+ }
int ret = run_execve(orig_execve, target, new_argv, ddnatv_env);
int saved_errno = errno;
free_modified_env(ddnatv_env, envp);
@@ -559,6 +569,10 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
if (static_elf) prepare_static_program(static_elf);
char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL);
+ if (!ddnatv_env) {
+ errno = ENOMEM;
+ return -1;
+ }
int ret = run_execve(orig_execve, target, argv, ddnatv_env);
int saved_errno = errno;
free_modified_env(ddnatv_env, envp);
@@ -1021,6 +1035,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path));
char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL)
: clean_env_for_system(orig_ep);
+ if (in_root && !new_envp) return ENOMEM;
int ret = -1;
if (via_ld_so) {
diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py
index ed71ffa93c..01cd38c996 100644
--- a/tools/release/runtime_inputs.py
+++ b/tools/release/runtime_inputs.py
@@ -110,6 +110,7 @@ def required():
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-xclipse/' + name for name in
['libVkLayer_droiddeck_xclipse.so', 'VkLayer_droiddeck_xclipse.json']]
+ paths += ['assets/linuxfs/usr/local/lib/droiddeck-lse/liblse_emu.so']
paths += ['assets/linuxfs/usr/local/lib/droiddeck-vr/' + name for name in
['droiddeck/bin/linuxarm64/driver_droiddeck.so', 'droiddeck/bin/linuxarm64/xr-display-mode',
'droiddeck/driver.vrdrivermanifest',
diff --git a/tools/tests/lse_emu_early_dependency.c b/tools/tests/lse_emu_early_dependency.c
new file mode 100644
index 0000000000..4c16a0d3ba
--- /dev/null
+++ b/tools/tests/lse_emu_early_dependency.c
@@ -0,0 +1,17 @@
+#include
+#include
+
+static volatile uint64_t value;
+
+__attribute__((constructor))
+static void use_lse_before_preload_init(void) {
+ uint64_t old;
+ uint64_t increment = 1;
+ __asm__ volatile("ldaddal %x1, %x0, [%2]"
+ : "=r"(old)
+ : "r"(increment), "r"(&value)
+ : "memory");
+ if (old != 0 || value != 1) _exit(91);
+}
+
+void lse_emu_early_dependency_anchor(void) {}
diff --git a/tools/tests/lse_emu_early_main.c b/tools/tests/lse_emu_early_main.c
new file mode 100644
index 0000000000..5eaba99f0a
--- /dev/null
+++ b/tools/tests/lse_emu_early_main.c
@@ -0,0 +1,9 @@
+#include
+
+void lse_emu_early_dependency_anchor(void);
+
+int main(void) {
+ lse_emu_early_dependency_anchor();
+ puts("early lse ok");
+ return 0;
+}
diff --git a/tools/tests/lse_emu_test.c b/tools/tests/lse_emu_test.c
new file mode 100644
index 0000000000..b63fb92462
--- /dev/null
+++ b/tools/tests/lse_emu_test.c
@@ -0,0 +1,300 @@
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define MAX_THREADS 8
+#define ROUNDS 20000
+
+static uint64_t counter64;
+static uint32_t counter32;
+static uint16_t counter16;
+static uint8_t counter8;
+static uint64_t spin;
+
+static void check(int ok, const char *what) {
+ if (!ok) {
+ printf("FAIL %s\n", what);
+ exit(1);
+ }
+}
+
+static uint64_t ldaddal64(uint64_t *p, uint64_t v) {
+ uint64_t old;
+ __asm__ volatile("ldaddal %x1, %x0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
+ return old;
+}
+
+static uint32_t ldadd32(uint32_t *p, uint32_t v) {
+ uint32_t old;
+ __asm__ volatile("ldadd %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
+ return old;
+}
+
+static uint16_t ldaddlh(uint16_t *p, uint16_t v) {
+ uint16_t old;
+ __asm__ volatile("ldaddlh %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
+ return old;
+}
+
+static uint8_t ldaddab(uint8_t *p, uint8_t v) {
+ uint8_t old;
+ __asm__ volatile("ldaddab %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
+ return old;
+}
+
+static uint64_t casal64(uint64_t *p, uint64_t expected, uint64_t desired) {
+ __asm__ volatile("casal %x0, %x2, [%1]" : "+r"(expected) : "r"(p), "r"(desired) : "memory");
+ return expected;
+}
+
+static void *worker(void *arg) {
+ (void)arg;
+ for (int i = 0; i < ROUNDS; i++) {
+ ldaddal64(&counter64, 1);
+ ldadd32(&counter32, 1);
+ ldaddlh(&counter16, 1);
+ ldaddab(&counter8, 1);
+ uint64_t seen = __atomic_load_n(&spin, __ATOMIC_RELAXED);
+ while (casal64(&spin, seen, seen + 1) != seen) seen = __atomic_load_n(&spin, __ATOMIC_RELAXED);
+ }
+ return NULL;
+}
+
+static volatile sig_atomic_t app_handler_ran;
+
+static void app_sigill(int sig, siginfo_t *info, void *context) {
+ (void)sig;
+ (void)info;
+ app_handler_ran = 1;
+ ((ucontext_t *)context)->uc_mcontext.pc += 4;
+}
+
+static void simple_sigill(int sig) { (void)sig; }
+
+static volatile sig_atomic_t once_calls, persistent_calls, once_saw_default;
+static void persistent_sigill(int sig) { (void)sig; persistent_calls++; }
+
+static void once_sigill(int sig) {
+ struct sigaction previous, next = {0};
+ once_calls++;
+ if (sigaction(sig, NULL, &previous) == 0 && previous.sa_handler == SIG_DFL)
+ once_saw_default = 1;
+ next.sa_handler = persistent_sigill;
+ sigemptyset(&next.sa_mask);
+ if (sigaction(sig, &next, NULL) != 0) _Exit(2);
+}
+
+static void check_one_shot_action(void) {
+ struct sigaction action = {0};
+ action.sa_handler = once_sigill;
+ action.sa_flags = SA_RESETHAND;
+ sigemptyset(&action.sa_mask);
+ check(sigaction(SIGILL, &action, NULL) == 0, "install one-shot SIGILL");
+ check(raise(SIGILL) == 0, "deliver one-shot SIGILL");
+ check(once_calls == 1 && once_saw_default, "one-shot consumed before calling handler");
+ check(raise(SIGILL) == 0, "deliver replacement SIGILL");
+ check(once_calls == 1 && persistent_calls == 1, "replacement survives one-shot consumption");
+}
+
+
+static void set_test_action(int variant) {
+ struct sigaction sa = {0};
+ sigemptyset(&sa.sa_mask);
+ if (variant == 0) {
+ sa.sa_handler = simple_sigill;
+ sigaddset(&sa.sa_mask, SIGUSR1);
+ } else {
+ sa.sa_sigaction = app_sigill;
+ sa.sa_flags = SA_SIGINFO;
+ sigaddset(&sa.sa_mask, SIGUSR2);
+ }
+ int attempt;
+ for (attempt = 0; attempt < 10000; attempt++) {
+ if (sigaction(SIGILL, &sa, NULL) == 0) return;
+ check(errno == ENOMEM, "unexpected action publication failure");
+ sched_yield();
+ }
+ check(0, "action slots stayed exhausted");
+}
+
+static void *replace_test_action(void *unused) {
+ (void)unused;
+ for (int i = 0; i < 4096; i++) set_test_action(i & 1);
+ return NULL;
+}
+
+static void *query_test_action(void *unused) {
+ (void)unused;
+ for (int i = 0; i < 4096; i++) {
+ struct sigaction sa;
+ check(sigaction(SIGILL, NULL, &sa) == 0, "query SIGILL action");
+ int a = sigismember(&sa.sa_mask, SIGUSR1);
+ int b = sigismember(&sa.sa_mask, SIGUSR2);
+ if (sa.sa_flags & SA_SIGINFO)
+ check(sa.sa_sigaction == app_sigill && !a && b, "coherent siginfo snapshot");
+ else
+ check(sa.sa_handler == simple_sigill && a && !b, "coherent simple snapshot");
+ }
+ return NULL;
+}
+
+static unsigned int fork_readers_stop;
+
+static void *read_during_fork(void *unused) {
+ (void)unused;
+ while (!__atomic_load_n(&fork_readers_stop, __ATOMIC_RELAXED)) {
+ struct sigaction out;
+ if (sigaction(SIGILL, NULL, &out) != 0) _Exit(4);
+ }
+ return NULL;
+}
+
+static void check_forked_actions(void) {
+ struct sigaction install = {0};
+ install.sa_handler = simple_sigill;
+ sigemptyset(&install.sa_mask);
+ check(sigaction(SIGILL, &install, NULL) == 0, "install SIGILL before fork");
+ pthread_t readers[4];
+ for (int i = 0; i < 4; i++)
+ check(pthread_create(&readers[i], NULL, read_during_fork, NULL) == 0, "start fork reader");
+ for (int child = 0; child < 8; child++) {
+ pid_t pid = fork();
+ check(pid >= 0, "fork SIGILL snapshot child");
+ if (pid == 0) {
+ struct sigaction inherited;
+ if (sigaction(SIGILL, NULL, &inherited) != 0 || inherited.sa_handler != simple_sigill) _Exit(2);
+ for (int i = 0; i < 1024; i++)
+ if (sigaction(SIGILL, &install, NULL) != 0) _Exit(3);
+ _Exit(0);
+ }
+ int status = 0;
+ check(waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0,
+ "child keeps action and can recycle more than 256 slots");
+ }
+ __atomic_store_n(&fork_readers_stop, 1, __ATOMIC_RELAXED);
+ for (int i = 0; i < 4; i++) check(pthread_join(readers[i], NULL) == 0, "join fork reader");
+}
+
+static void check_reused_actions(void) {
+ set_test_action(0);
+ pthread_t threads[4];
+ for (int i = 0; i < 4; i++)
+ check(pthread_create(&threads[i], NULL, i < 2 ? replace_test_action : query_test_action, NULL) == 0,
+ "start action worker");
+ for (int i = 0; i < 4; i++) check(pthread_join(threads[i], NULL) == 0, "join action worker");
+}
+
+static __attribute__((noinline)) void single_forms(void) {
+ uint64_t v = 0xF0;
+ uint64_t old;
+ register uint64_t ldap_result __asm__("x0");
+ register uintptr_t ldap_address __asm__("x1") = (uintptr_t)&v;
+ __asm__ volatile(".inst 0xf8bfc020" : "=r"(ldap_result) : "r"(ldap_address) : "memory");
+ check(ldap_result == v, "ldapr");
+ __asm__ volatile("ldclral %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0x30), "r"(&v) : "memory");
+ check(old == 0xF0 && v == 0xC0, "ldclral");
+ __asm__ volatile("ldeora %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0xFF), "r"(&v) : "memory");
+ check(old == 0xC0 && v == 0x3F, "ldeora");
+ __asm__ volatile("ldsetl %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)0x100), "r"(&v) : "memory");
+ check(old == 0x3F && v == 0x13F, "ldsetl");
+ __asm__ volatile("swpal %x1, %x0, [%2]" : "=r"(old) : "r"((uint64_t)7), "r"(&v) : "memory");
+ check(old == 0x13F && v == 7, "swpal");
+
+ int64_t s = -5;
+ int64_t sold;
+ __asm__ volatile("ldsmax %x1, %x0, [%2]" : "=r"(sold) : "r"((int64_t)-9), "r"(&s) : "memory");
+ check(sold == -5 && s == -5, "ldsmax keeps the larger value");
+ uint32_t u = 10;
+ uint32_t uold;
+ __asm__ volatile("ldumin %w1, %w0, [%2]" : "=r"(uold) : "r"((uint32_t)3), "r"(&u) : "memory");
+ check(uold == 10 && u == 3, "ldumin");
+
+ uint64_t pair[2] __attribute__((aligned(16))) = {1, 2};
+ register uint64_t e0 __asm__("x4") = 1, e1 __asm__("x5") = 2, d0 __asm__("x6") = 3, d1 __asm__("x7") = 4;
+ __asm__ volatile("caspal x4, x5, x6, x7, [%4]" : "+r"(e0), "+r"(e1) : "r"(d0), "r"(d1), "r"(pair) : "memory");
+ check(e0 == 1 && e1 == 2 && pair[0] == 3 && pair[1] == 4, "caspal");
+ register uint64_t m0 __asm__("x4") = 8, m1 __asm__("x5") = 9, n0 __asm__("x6") = 5, n1 __asm__("x7") = 6;
+ __asm__ volatile("caspal x4, x5, x6, x7, [%4]" : "+r"(m0), "+r"(m1) : "r"(n0), "r"(n1), "r"(pair) : "memory");
+ check(m0 == 3 && m1 == 4 && pair[0] == 3 && pair[1] == 4, "caspal returns the current pair on a mismatch");
+
+ uint64_t missed = casal64(&v, 99, 1);
+ check(missed == 7 && v == 7, "casal leaves memory alone on a mismatch");
+
+ uint32_t m = 1;
+ uint32_t mold;
+ uint64_t eq;
+ __asm__ volatile("cmp %w3, %w3\n\tldumax %w2, %w0, [%4]\n\tcset %1, eq"
+ : "=&r"(mold), "=&r"(eq) : "r"((uint32_t)5), "r"((uint32_t)0), "r"(&m) : "memory", "cc");
+ check(mold == 1 && m == 5 && eq == 1, "ldumax leaves the condition flags alone");
+ int8_t b = -3;
+ int8_t bold;
+ __asm__ volatile("cmp %w3, %w3\n\tldsmaxb %w2, %w0, [%4]\n\tcset %1, eq"
+ : "=&r"(bold), "=&r"(eq) : "r"((int32_t)-7), "r"((uint32_t)0), "r"(&b) : "memory", "cc");
+ check(bold == -3 && b == -3 && eq == 1, "ldsmaxb leaves the condition flags alone");
+}
+
+int main(int argc, char **argv) {
+ if (argc == 2 && strcmp(argv[1], "sigill-fork") == 0) {
+ check_forked_actions();
+ puts("sigill fork ok");
+ return 0;
+ }
+ if (argc == 2 && strcmp(argv[1], "sigill-oneshot") == 0) {
+ check_one_shot_action();
+ puts("sigill one-shot ok");
+ return 0;
+ }
+ if (argc == 2 && strcmp(argv[1], "sigill-actions") == 0) {
+ check_reused_actions();
+ puts("sigill actions ok");
+ return 0;
+ }
+ int threads_wanted = argc > 1 ? atoi(argv[1]) : 4;
+ check(threads_wanted >= 1 && threads_wanted <= MAX_THREADS, "thread count");
+ single_forms();
+ single_forms();
+
+ pthread_t threads[MAX_THREADS];
+ int started = 0;
+ for (; started < threads_wanted; started++) {
+ int err = pthread_create(&threads[started], NULL, worker, NULL);
+ if (err != 0) {
+ for (int i = 0; i < started; i++) pthread_join(threads[i], NULL);
+ fprintf(stderr, "pthread_create failed: %s\n", strerror(err));
+ return err;
+ }
+ }
+ for (int i = 0; i < started; i++) {
+ int err = pthread_join(threads[i], NULL);
+ if (err != 0) {
+ fprintf(stderr, "pthread_join failed: %s\n", strerror(err));
+ return err;
+ }
+ }
+ uint64_t total = (uint64_t)threads_wanted * ROUNDS;
+ check(counter64 == total, "64-bit counter");
+ check(counter32 == (uint32_t)total, "32-bit counter");
+ check(counter16 == (uint16_t)total, "16-bit counter");
+ check(counter8 == (uint8_t)total, "8-bit counter");
+ check(spin == total, "casal loop");
+
+ struct sigaction sa;
+ memset(&sa, 0, sizeof sa);
+ sa.sa_sigaction = app_sigill;
+ sa.sa_flags = SA_SIGINFO;
+ sigaction(SIGILL, &sa, NULL);
+ __asm__ volatile("udf #0");
+ check(app_handler_ran, "the program's own SIGILL handler still runs");
+
+ printf("lse ok\n");
+ return 0;
+}
diff --git a/tools/tests/test_lse_emu.py b/tools/tests/test_lse_emu.py
new file mode 100644
index 0000000000..539fb18326
--- /dev/null
+++ b/tools/tests/test_lse_emu.py
@@ -0,0 +1,141 @@
+import os
+import re
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+
+TOOLS = Path(__file__).resolve().parents[1]
+SYSROOT = Path("/usr/aarch64-linux-gnu")
+
+
+def toolchain():
+ if not (shutil.which("aarch64-linux-gnu-gcc") and shutil.which("qemu-aarch64") and SYSROOT.is_dir()):
+ if os.environ.get("CI"):
+ raise AssertionError("CI must install gcc-aarch64-linux-gnu, libc6-dev-arm64-cross and qemu-user")
+ raise unittest.SkipTest("needs aarch64-linux-gnu-gcc, libc6-dev-arm64-cross and qemu-user")
+
+
+class LseEmuTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ toolchain()
+ cls.tmp = tempfile.TemporaryDirectory(prefix="droiddeck-lse-")
+ out = Path(cls.tmp.name)
+ subprocess.run(["bash", str(TOOLS / "linuxfs/lse-emu/build.sh"), str(out)], check=True)
+ cls.library = out / "usr/local/lib/droiddeck-lse/liblse_emu.so"
+ cls.program = out / "lse-test"
+ subprocess.run(["aarch64-linux-gnu-gcc", "-O1", "-march=armv8.1-a", "-Wall", "-Wextra", "-Werror", "-pthread",
+ str(Path(__file__).with_name("lse_emu_test.c")), "-o", str(cls.program)], check=True)
+ cls.early_library = out / "liblse_emu_early.so"
+ subprocess.run(["aarch64-linux-gnu-gcc", "-shared", "-fPIC", "-O1", "-march=armv8.1-a", "-Wall", "-Wextra", "-Werror",
+ str(Path(__file__).with_name("lse_emu_early_dependency.c")), "-o", str(cls.early_library)], check=True)
+ cls.early_program = out / "lse-early-test"
+ subprocess.run(["aarch64-linux-gnu-gcc", "-O1", "-Wall", "-Wextra", "-Werror",
+ str(Path(__file__).with_name("lse_emu_early_main.c")), "-L", str(out),
+ "-Wl,--no-as-needed", "-llse_emu_early", "-Wl,-rpath,$ORIGIN", "-o", str(cls.early_program)], check=True)
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.tmp.cleanup()
+
+ def run_on(self, cpu, *env, threads=4, program=None, program_args=None):
+ command = ["qemu-aarch64",
+ "-U", "LSE_EMU", "-U", "LSE_EMU_PATCH",
+ "-U", "LSE_EMU_STATS", "-U", "LSE_EMU_LOG", "-U", "LSE_EMU_SKIP",
+ "-cpu", cpu, "-L", str(SYSROOT)]
+ for item in env:
+ command += ["-E", item]
+ args = [str(program or self.program)]
+ if program_args is not None:
+ args.extend(program_args)
+ elif program is None:
+ args.append(str(threads))
+ return subprocess.run(command + args, capture_output=True, text=True, timeout=120)
+
+ def test_an_armv8_0_cpu_faults_without_the_emulator(self):
+ result = self.run_on("cortex-a57")
+ self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
+
+ def test_dependency_constructor_can_execute_lse_before_preload_init(self):
+ result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", program=self.early_program)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("early lse ok", result.stdout)
+
+ def test_trapping_alone_runs_every_form_on_an_armv8_0_cpu(self):
+ result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("lse ok", result.stdout)
+ self.assertRegex(result.stderr, r"traps=[1-9]\d* patched=0 ")
+
+ def test_concurrent_sigill_registrations_keep_recycled_snapshots_coherent(self):
+ result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
+ program_args=["sigill-actions"])
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("sigill actions ok", result.stdout)
+
+ def test_child_inherits_the_sigill_handler_but_not_other_threads_action_slots(self):
+ result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
+ program_args=["sigill-fork"])
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("sigill fork ok", result.stdout)
+
+ def test_oneshot_sigill_is_consumed_before_dispatch_and_replacement_survives(self):
+ result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1",
+ program_args=["sigill-oneshot"])
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("sigill one-shot ok", result.stdout)
+
+ def patched(self, threads):
+ log = Path(self.tmp.name) / f"patched-{threads}.log"
+ log.unlink(missing_ok=True)
+ result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_PATCH=1",
+ "LSE_EMU_STATS=1", f"LSE_EMU_LOG={log}", threads=threads)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("lse ok", result.stdout)
+ self.assertRegex(result.stderr, r"patched=[1-9]\d* failed=0",
+ f"{result.stderr}\nLSE log:\n{log.read_text() if log.is_file() else ''}")
+ self.assertTrue(log.is_file(), "patch log was not created")
+ instructions = [
+ int(match, 16)
+ for match in re.findall(r"patched pc=0x[0-9a-f]+ insn=0x([0-9a-f]+)", log.read_text())
+ ]
+ self.assertTrue(
+ any((insn & 0x3FFFFC00) == 0x38BFC000 for insn in instructions),
+ "LDAPR did not use a generated stub",
+ )
+ self.assertFalse(
+ any((insn & 0xBFA07C00) == 0x08207C00 for insn in instructions),
+ "CASP must remain on the stack-safe trap path",
+ )
+ self.assertFalse(
+ any(
+ (insn & 0x3F200C00) == 0x38200000
+ and ((insn >> 15) & 1) == 0
+ and ((insn >> 12) & 7) >= 4
+ for insn in instructions
+ ),
+ "min/max must remain on the stack-safe trap path",
+ )
+ self.assertNotRegex(result.stderr, r"unhandled pc=.*insn=0x(?!0000000000000000(?:\n|$))[0-9a-f]{16}")
+
+ def test_patching_runs_every_form_on_an_armv8_0_cpu(self):
+ self.patched(threads=1)
+
+ def test_patching_stays_atomic_across_threads(self):
+ self.patched(threads=4)
+
+ def test_it_stays_off_without_the_switch(self):
+ result = self.run_on("cortex-a57", f"LD_PRELOAD={self.library}", "LSE_EMU=0", "LSE_EMU_PATCH=0")
+ self.assertEqual(result.returncode, -4, result.stdout + result.stderr)
+
+ def test_it_stays_off_on_a_cpu_with_lse(self):
+ result = self.run_on("neoverse-n1", f"LD_PRELOAD={self.library}", "LSE_EMU=1", "LSE_EMU_STATS=1")
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertNotIn("traps=", result.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/tests/test_native_hook_preload_list.py b/tools/tests/test_native_hook_preload_list.py
new file mode 100644
index 0000000000..71911a8d0b
--- /dev/null
+++ b/tools/tests/test_native_hook_preload_list.py
@@ -0,0 +1,53 @@
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+
+
+ENV = Path(__file__).resolve().parents[1] / "nativeguest/hook/env.c"
+
+
+class NativeHookPreloadListTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.tmp = tempfile.TemporaryDirectory()
+ cls.addClassCleanup(cls.tmp.cleanup)
+ p = Path(cls.tmp.name)
+ env = ENV.read_text()
+ helpers = env[env.index("static int preload_has_entry("):env.index("// Filter the LSE")]
+ (p / "probe.c").write_text("""
+#include
+#include
+#include
+""" + helpers + """
+int main(int argc, char **argv) {
+ (void)argc;
+ char *out = merge_preload_env(argv[1], argv[2]);
+ if (!out) return 2;
+ puts(out);
+ free(out);
+ return 0;
+}
+""")
+ cls.probe = p / "probe"
+ subprocess.run([os.environ.get("CC", "cc"), "-Wall", "-Wextra", "-Werror",
+ str(p / "probe.c"), "-o", str(cls.probe)], check=True)
+
+ def merge(self, host, inherited):
+ return subprocess.check_output([self.probe, host, inherited], text=True).strip()
+
+ def test_nested_exec_keeps_the_same_multi_entry_chain(self):
+ host = "/root/session.so:/root/hook.so"
+ original = host + ":user.so"
+ for _ in range(3):
+ original = self.merge(host, original).removeprefix("LD_PRELOAD=")
+ self.assertEqual(host + ":user.so", original)
+
+ def test_partial_chain_keeps_host_order_and_exact_matches(self):
+ self.assertEqual("LD_PRELOAD=/root/session.so:/root/hook.so:/root/hook.so.extra:custom.so",
+ self.merge("/root/session.so:/root/hook.so",
+ "/root/hook.so.extra /root/session.so:custom.so"))
+
+ def test_empty_custom_chain_keeps_only_the_host_chain(self):
+ self.assertEqual("LD_PRELOAD=host.so", self.merge("host.so", ""))
From c85e82683bd75fe8cdf5ace89e317f982ca71672 Mon Sep 17 00:00:00 2001
From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Date: Sat, 5 Dec 2026 19:51:23 -0500
Subject: [PATCH 8/8] Standardize native runtime defaults (#3779)
fix: standardize guest runtime defaults
---
.../droiddeck/launcher/FrontEndActivity.kt | 11 +-----
.../com/droiddeck/launcher/SessionActivity.kt | 5 ---
.../com/droiddeck/launcher/agent/AgentHost.kt | 1 -
.../droiddeck/launcher/agent/AgentNative.kt | 2 -
.../droiddeck/launcher/core/DeviceReport.kt | 9 +++--
.../launcher/runtime/BwrapSpawner.kt | 6 ++-
.../launcher/runtime/GuestCommand.kt | 2 -
.../droiddeck/launcher/runtime/NativeGuest.kt | 8 ++--
.../launcher/runtime/ProotFastPath.kt | 16 +++-----
.../droiddeck/launcher/runtime/RootSpawner.kt | 2 -
.../launcher/session/SessionFiles.kt | 9 +++--
.../launcher/session/SessionPrefs.kt | 18 ---------
.../launcher/session/SessionService.kt | 25 ++++++------
.../droiddeck/launcher/stores/gog/GogComet.kt | 2 -
.../droiddeck/launcher/stores/xbox/Xodus.kt | 2 -
.../launcher/ui/PerformanceDialog.kt | 31 ++-------------
.../droiddeck/launcher/ui/SettingsIndex.kt | 3 --
.../runtime/NativeGuestDefaultsTest.kt | 38 +++++++++++++++++++
.../launcher/runtime/ProotFastPathTest.kt | 10 ++---
docs/settings-map.md | 3 --
20 files changed, 84 insertions(+), 119 deletions(-)
create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestDefaultsTest.kt
diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
index 08b966e98b..900823e0f4 100644
--- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
@@ -191,9 +191,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var gpuClockPin by mutableStateOf(false)
- private var prootNoSeccomp by mutableStateOf(false)
- private var prootFastPath by mutableStateOf(true)
- private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
@@ -3125,7 +3122,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
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,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = 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 },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
- onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
- onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
- onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
@@ -3464,9 +3458,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
- prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
- prootFastPath = SessionPrefs.prootFastPath(this)
- nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index 371d200f47..3b5166bf5a 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -3862,7 +3862,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
presentationFaultHint()?.let { return it }
if (log == null || !log.isFile) return null
return try {
- var enosys = 0
var fexMissing = false
val size = log.length()
val text = java.io.RandomAccessFile(log, "r").use { f ->
@@ -3873,7 +3872,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
String(bytes, Charsets.ISO_8859_1)
}
text.lineSequence().forEach { line ->
- if (line.contains("Function not implemented")) enosys++
if (line.contains(FEX_MISSING)) fexMissing = true
}
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
@@ -3895,9 +3893,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
- } else if (enosys >= 8) {
- EndHint(resources.getQuantityString(R.plurals.session_hint_enosys, enosys, enosys,
- getString(R.string.perf_title), getString(R.string.perf_seccomp), getString(R.string.perf_xalia)))
} else null
} catch (e: Exception) {
null
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt
index 87188e34d7..22c30a994e 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt
@@ -571,7 +571,6 @@ object AgentHost {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
- if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentNative.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentNative.kt
index 613cbe2c39..0d2fffc73e 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentNative.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentNative.kt
@@ -14,8 +14,6 @@ object AgentNative {
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
val root = LinuxRuntime.rootDir(context)
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
- // with the setting off, staging leaves the rootfs as proot wants it
- if (!com.droiddeck.launcher.session.SessionPrefs.nativeUserland(context)) NativeGuest.prepare(context, root)
if (!NativeGuest.available(root)) throw AgentException("NATIVE_UNAVAILABLE", "The rootfs has no native hook or glibc loader yet; start a session once")
val argvJson = request.optJSONArray("argv") ?: throw AgentException("INVALID_REQUEST", "argv is required")
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
index 4beeec8d45..46b74fbafa 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
@@ -291,9 +291,12 @@ object DeviceReport {
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context))
- k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
- k("native userland (no proot)", SessionPrefs.nativeUserland(context))
- k("proot fast path", SessionPrefs.prootFastPath(context))
+ k("guest runtime policy", "native preferred with PRoot fallback")
+ k("guest runtime", when (com.droiddeck.launcher.runtime.NativeGuest.sessionMode) {
+ true -> "native"
+ false -> "PRoot"
+ null -> if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) "native available" else "native unavailable"
+ })
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
k("Guest host name", SessionPrefs.guestHostname(context))
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
index 0577c2fece..d72274443b 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
@@ -577,12 +577,15 @@ object BwrapSpawner {
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
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) {
ProcessBuilder(native.first).redirectErrorStream(true)
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
} else {
+ val reason = if (nativeSession) "sandbox native launch unavailable" else "parent guest uses PRoot"
+ Log.i(TAG, "Flatpak: using PRoot ($reason)")
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
@@ -599,7 +602,6 @@ object BwrapSpawner {
putAll(prootEnvironment(plan, envTool))
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
- if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
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 6c0936e679..50a190c1ba 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt
@@ -6,7 +6,6 @@ import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionFiles
import com.droiddeck.launcher.session.SessionPaths
-import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
@@ -67,7 +66,6 @@ object GuestCommand {
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
- if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt
index 6ad6a321c4..6e69ffe376 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt
@@ -22,15 +22,15 @@ object NativeGuest {
}
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
- * 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.
*/
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
@@ -39,7 +39,7 @@ object NativeGuest {
/**
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
- * session's own mode while one runs, as the 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.
*/
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt
index 27ef86f086..33fa897237 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.Build
import android.util.Log
-import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.MessageDigest
@@ -12,17 +11,14 @@ object ProotFastPath {
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
const val MAX_BINDS = 256
- fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
- preference && !noSeccomp && !nativeUserland && source == LinuxRuntime.PROOT_PACK
+ internal fun allows(source: String, native: Boolean): Boolean =
+ !native && source == LinuxRuntime.PROOT_PACK
- fun enabled(context: Context): Boolean {
- val preference = SessionPrefs.prootFastPath(context)
- val noSeccomp = SessionPrefs.prootNoSeccomp(context)
- val nativeUserland = SessionPrefs.nativeUserland(context)
+ fun enabled(context: Context, native: Boolean = NativeGuest.forSession(context)): Boolean {
+ if (native) return false
val source = LinuxRuntime.prootSource(context)
- val on = allows(preference, noSeccomp, source, nativeUserland)
- if (preference && !noSeccomp && !nativeUserland && !on)
- Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
+ val on = allows(source, native)
+ if (!on) Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
return on
}
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RootSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/RootSpawner.kt
index 16228be728..1791df54b0 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/RootSpawner.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/RootSpawner.kt
@@ -8,7 +8,6 @@ import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
-import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.DataInputStream
import java.io.DataOutputStream
@@ -128,7 +127,6 @@ object RootSpawner {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
- if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
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 525844d880..dc708cb51d 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
@@ -367,16 +367,17 @@ object SessionFiles {
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
- val nativeUserland = SessionPrefs.nativeUserland(context)
- if (nativeUserland) com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
- if (ProotFastPath.enabled(context)) {
+ com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
+ val native = com.droiddeck.launcher.runtime.NativeGuest.available(root)
+ val nativePreload = preload.toString()
+ if (ProotFastPath.enabled(context, native)) {
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
preload.append(library + "\n")
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
}
val etc = File(root, "etc").apply { mkdirs() }
File(etc, "droiddeck").mkdirs()
- FileUtils.writeString(File(etc, "droiddeck/native-preload"), preload.toString())
+ FileUtils.writeString(File(etc, "droiddeck/native-preload"), nativePreload)
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
index e42c8f48a5..523857654a 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
@@ -1181,21 +1181,9 @@ object SessionPrefs {
prefs(context).edit().putBoolean("mountSharedStorage", on).apply()
}
- fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
-
- fun setProotNoSeccomp(context: Context, on: Boolean) {
- prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
- }
-
- fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
-
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
- fun setNativeUserland(context: Context, on: Boolean) {
- prefs(context).edit().putBoolean("nativeUserland", on).apply()
- }
-
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
@@ -1203,12 +1191,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
- fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
-
- fun setProotFastPath(context: Context, on: Boolean) {
- prefs(context).edit().putBoolean("prootFastPath", on).apply()
- }
-
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
fun setCursorComposite(context: Context, on: Boolean) {
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
index 3e53e37d75..fb6d3503f8 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
@@ -47,6 +47,7 @@ import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
+import com.droiddeck.launcher.runtime.NativeGuest
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -784,12 +785,13 @@ class SessionService : Service() {
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
val sharedStorage = LinuxRuntime.sharedStorage(this)
- val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage)
- val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
+ val nativeUserland = NativeGuest.enabled(this)
+ val fastPath = ProotFastPath.enabled(this, nativeUserland)
+ val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage, fastPath)
synchronized(stopLock) {
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(
this, sessionRoot, runtimeDir, sharedStorage, binds,
)
@@ -810,16 +812,14 @@ class SessionService : Service() {
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
} else {
+ val reason = if (NativeGuest.loader(root) == null) "missing glibc loader" else "missing native hook"
+ Log.i(TAG, "guest runtime: using PRoot ($reason)")
LinuxRuntime.command(this, sessionRoot, runtimeDir, sharedStorage, binds, guest)
}
val prootEnv = HostEnvironment()
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
prootEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
- if (SessionPrefs.prootNoSeccomp(this)) {
- prootEnv["PROOT_NO_SECCOMP"] = "1"
- if (!nativeUserland) Log.i(TAG, "proot: seccomp acceleration off by request")
- }
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> prootEnv[k] = v } }
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
@@ -1313,6 +1313,7 @@ class SessionService : Service() {
sessionRoot: File,
runtimeDir: File,
sharedStorage: File?,
+ fastPath: Boolean,
): ArrayList {
val binds = ArrayList()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
@@ -1446,7 +1447,7 @@ class SessionService : Service() {
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
if (gamesLibraries.isNotEmpty()) {
- var room = if (ProotFastPath.enabled(this)) {
+ var room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
for (games in gamesLibraries) {
@@ -1488,7 +1489,7 @@ class SessionService : Service() {
continue
}
try {
- val room = if (ProotFastPath.enabled(this)) {
+ val room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val content = SecondaryLibrary.contentPath(entry.host)
@@ -1517,7 +1518,7 @@ class SessionService : Service() {
if (problem != null) {
Log.w(TAG, "x86-64 steam library: $problem")
} else try {
- val room = if (ProotFastPath.enabled(this)) {
+ val room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, x64, listOf(GameStorage.X64_CARD_GUEST)).drop(1)
@@ -1539,7 +1540,7 @@ class SessionService : Service() {
continue
}
try {
- val room = if (ProotFastPath.enabled(this)) {
+ val room = if (fastPath) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
@@ -1575,7 +1576,7 @@ class SessionService : Service() {
try {
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
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
} else Int.MAX_VALUE
for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) {
diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogComet.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogComet.kt
index 6f77df7990..56e8d6e128 100644
--- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogComet.kt
+++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogComet.kt
@@ -8,7 +8,6 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionEvents
-import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.AchievementNotifications
@@ -149,7 +148,6 @@ object GogComet {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
- if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/Xodus.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/Xodus.kt
index 07d47c78cd..6be4ddb14e 100644
--- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/Xodus.kt
+++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/Xodus.kt
@@ -5,7 +5,6 @@ import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
-import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONObject
import java.io.Closeable
@@ -107,7 +106,6 @@ internal object Xodus {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
- if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt
index 69aa3c6f97..45edd262af 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt
@@ -46,9 +46,7 @@ fun PerformancePage(
fsyncFirst: Boolean,
gamescopeRealtime: Boolean,
gpuClockPin: Boolean,
- prootNoSeccomp: Boolean,
- prootFastPath: Boolean,
- nativeUserland: Boolean,
+ nativeDesktopAvailable: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
@@ -65,9 +63,6 @@ fun PerformancePage(
onFsyncFirst: (Boolean) -> Unit,
onGamescopeRealtime: (Boolean) -> Unit,
onGpuClockPin: (Boolean) -> Unit,
- onProotNoSeccomp: (Boolean) -> Unit,
- onProotFastPath: (Boolean) -> Unit,
- onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
@@ -152,26 +147,6 @@ fun PerformancePage(
stringResource(R.string.perf_fastsync_hint),
fastSync, onChange = onFastSync,
)
- ToggleRow(
- host, "seccomp", stringResource(R.string.perf_seccomp),
- stringResource(R.string.perf_seccomp_hint),
- prootNoSeccomp, onChange = onProotNoSeccomp,
- )
- ToggleRow(
- host, "fastpath", stringResource(R.string.perf_fastpath),
- when {
- nativeUserland -> stringResource(R.string.perf_fastpath_needs_proot)
- prootNoSeccomp -> stringResource(R.string.perf_fastpath_needs_seccomp)
- else -> stringResource(R.string.perf_fastpath_hint)
- },
- prootFastPath && !prootNoSeccomp && !nativeUserland, enabled = !prootNoSeccomp && !nativeUserland,
- onChange = onProotFastPath,
- )
- ToggleRow(
- host, "nativeuserland", stringResource(R.string.perf_native_userland),
- stringResource(R.string.perf_native_userland_hint),
- nativeUserland, onChange = onNativeUserland,
- )
ToggleRow(
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
stringResource(R.string.perf_cursor_composite_hint),
@@ -198,8 +173,8 @@ fun PerformancePage(
}
ToggleRow(
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),
- desktopAsUser && nativeUserland, enabled = nativeUserland,
+ stringResource(R.string.perf_desktop_as_user_hint),
+ desktopAsUser && nativeDesktopAvailable, enabled = nativeDesktopAvailable,
onChange = onDesktopAsUser,
)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
index 2bd881af35..4359813c07 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt
@@ -85,9 +85,6 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_esync, "esync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_fsync, "fsync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_fastsync, "ntsync", "sync", "wine"),
- s(SettingsSection.PERFORMANCE, R.string.perf_seccomp, "proot"),
- s(SettingsSection.PERFORMANCE, R.string.perf_fastpath, "proot"),
- s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestDefaultsTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestDefaultsTest.kt
new file mode 100644
index 0000000000..fd4b629e7a
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestDefaultsTest.kt
@@ -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()
+ }
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/ProotFastPathTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/ProotFastPathTest.kt
index f413618942..24da684e49 100644
--- a/app/src/test/java/com/droiddeck/launcher/runtime/ProotFastPathTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/runtime/ProotFastPathTest.kt
@@ -27,14 +27,12 @@ class ProotFastPathTest {
}
@Test fun fastPathStaysOffForTheRootfsProot() {
- assertTrue(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
- assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_ROOTFS))
- assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_MISSING))
- assertFalse(ProotFastPath.allows(preference = false, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
- assertFalse(ProotFastPath.allows(preference = true, noSeccomp = true, source = LinuxRuntime.PROOT_PACK))
+ assertTrue(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = false))
+ assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_ROOTFS, native = false))
+ assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_MISSING, native = false))
}
@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))
}
}
diff --git a/docs/settings-map.md b/docs/settings-map.md
index b38a8fdf9f..66ad66d802 100644
--- a/docs/settings-map.md
+++ b/docs/settings-map.md
@@ -27,9 +27,6 @@ Links of the form `droiddeck://settings/` open a Settings section direc
| droiddeck-esync | Settings › Performance (`droiddeck://settings/performance`) | esync, sync, wine |
| droiddeck-fsync first | Settings › Performance (`droiddeck://settings/performance`) | fsync, sync, wine |
| droiddeck-ntsync | Settings › Performance (`droiddeck://settings/performance`) | ntsync, sync, wine |
-| Run proot without seccomp | Settings › Performance (`droiddeck://settings/performance`) | proot |
-| proot fast path | Settings › Performance (`droiddeck://settings/performance`) | proot |
-| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |