Compare commits

..
113 changed files with 630 additions and 5006 deletions

No files matched your search

-36
View File
@@ -164,9 +164,6 @@ jobs:
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Clear scratch earlier runs left behind
if: runner.environment == 'self-hosted'
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
- name: Merge the pinned APK base
if: github.event_name == 'pull_request'
env:
@@ -304,9 +301,6 @@ jobs:
aarch64-linux-gnu-gcc -O2 -Wall -o "$D/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-glprobe"
- name: Build the LSE atomics emulator for ARMv8.0 CPUs
run: bash tools/linuxfs/lse-emu/build.sh app/src/main/assets/linuxfs
- name: Check the preloads
run: |
set -euo pipefail
@@ -373,10 +367,6 @@ jobs:
persist-credentials: false
submodules: recursive
- name: Clear scratch earlier runs left behind
if: runner.environment == 'self-hosted'
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
- name: Check human authorship
env:
EVENT_NAME: ${{ github.event_name }}
@@ -695,32 +685,6 @@ jobs:
if-no-files-found: ignore
overwrite: true
- name: Resolve the Robolectric version
id: robolectric
run: |
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
# The cache path sits beside the workspace because runner homes are at different depths from it, and
# actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache.
- name: Place Robolectric's Android jars beside the workspace
id: robolectric-jars
run: |
set -euo pipefail
jars="$GITHUB_WORKSPACE/../robolectric-jars"
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
echo "cache=false" >> "$GITHUB_OUTPUT"
else
mkdir -p "$jars" "$(dirname "$m2")"
ln -sfn "$(cd "$jars" && pwd)" "$m2"
echo "cache=true" >> "$GITHUB_OUTPUT"
fi
- name: Cache Robolectric's Android jars
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache@v4
with:
path: ../robolectric-jars
key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }}
- name: Unit tests
id: unit-tests
env:
+1 -35
View File
@@ -2,41 +2,7 @@
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
# Building and testing
- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step.
- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`.
- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout.
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally.
- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI.
- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape.
- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`.
- Compile errors in code you didn't touch, after switching branches, are usually stale incremental state. Rebuild once before you change anything.
# Worktrees and shared machines
- After `git worktree add`, run `git submodule update --init --recursive`. Without it, `buildVkBridgeServer` fails on missing `external/MaliBridge`. Do not commit the `tools/syncthing/syncthing-android` pointer the build dirties.
- Other agents may be building on the same machine. Never run `./gradlew --stop` or kill Gradle/Kotlin daemons you did not start. If you need isolation, use `GRADLE_USER_HOME=<own dir> GRADLE_RO_DEP_CACHE=$HOME/.gradle/caches`.
# Driving the app and device
- Do it yourself with `tools/droiddeckctl` (see `docs/agent-control.md`) instead of asking the user: `cdp eval` for Steam's UI (`SteamClient.Apps.TerminateApp('<appid>', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display <id>`.
- A stream has started only when the session state reads `Streaming`. `SteamClient.Apps.StreamGame` alone can leave Steam on its menu, so open the game page and press Stream.
- Test controller navigation with `tools/droiddeckctl input gamepad ...`, a real uinput pad. `adb shell input keyevent DPAD_*` does not arrive as a joystick event and hides d-pad/stick bugs.
- A release-signed build installs over a release-signed install with `adb install -r`. Don't back up, uninstall or clear data to update. Scope `pm` and permission resets to `com.droiddeck.launcher`, never the whole device.
# CI
- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge.
- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors.
- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them.
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results`. Don't call a failure a runner problem until you have read it.
- Only these are known flakes worth a `gh run rerun <run> --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real.
- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`.
# Agents running on the device (DroidDeck's in-app agent)
These apply only where `dd-lab-build` exists. Agents on a dev host use `tools/quick_deploy.sh` instead.
# Working on the device
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
+6 -8
View File
@@ -125,8 +125,7 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
android {
namespace 'com.droiddeck.launcher'
compileSdk 34
ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env'))
.asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim()
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
defaultConfig {
applicationId "com.droiddeck.launcher"
@@ -233,9 +232,6 @@ android {
}
maxHeapSize = '2g'
maxParallelForks = 2
def jvmTemp = new File(temporaryDir, 'jvm')
systemProperty 'java.io.tmpdir', jvmTemp.absolutePath
doFirst { jvmTemp.mkdirs() }
def logTarget = providers.systemProperty('robolectric.logging').orNull
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
}
@@ -265,9 +261,11 @@ if (vitureSdkDir) {
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
}
def stageSessionScripts = tasks.register('stageSessionScripts', Exec) {
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage'
def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
from(rootProject.file('tools/linuxfs/overlay')) {
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
}
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
}
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
@@ -21,7 +21,6 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
checkAgain = null
checkComponentUpdates(again)
}
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; "))
if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
refreshComponents()
}
}, "component-updates").start()
@@ -254,12 +254,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
refreshWifiDiscovery()
}
private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (!granted && !shouldShowRequestPermissionRationale(android.Manifest.permission.BLUETOOTH_CONNECT)) {
integrationSettings(SteamIntegration.appInfo(this))
}
integrationState = readIntegration()
}
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this)
}
@@ -381,10 +375,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SteamIntegration.Feature.SHORTCUTS -> {
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
}
SteamIntegration.Feature.BLUETOOTH -> {
if (SteamIntegration.bluetoothAllowed(this)) integrationSettings(SteamIntegration.appInfo(this))
else bluetoothPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT)
}
}
}
@@ -2176,7 +2166,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!OfflineMode.enabled(this)) {
val updated = runCatching { ComponentUpdater.ensure(this, force = false) }
.onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList())
if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; "))
if (updated.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
}
}
ui.post {
componentsQueueBusy = false
@@ -3217,7 +3209,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
ui.post { autoUpdateRuntime() }
Thread({ com.droiddeck.launcher.session.Onboarding.recheck(this) }, "onboarding-recheck").start()
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
@@ -3439,24 +3430,18 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun install(release: LinuxRuntimeInstaller.Release) {
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
}
private fun followRuntimeOperation(onboarding: Boolean = false, run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
busy = true
failed = false
stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
percent = -1
Thread({
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
if (onboarding) com.droiddeck.launcher.session.Onboarding.report(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, s, p)
ui.post { stage = s; percent = p }
})
if (onboarding) {
if (ok == false) com.droiddeck.launcher.session.Onboarding.fail(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, LinuxRuntimeInstaller.removalError() ?: "")
else com.droiddeck.launcher.session.Onboarding.finish(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME)
}
com.droiddeck.launcher.session.Onboarding.recheck(this)
ui.post {
busy = false
if (ok != null) failed = !ok
@@ -3465,7 +3450,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
refresh()
com.droiddeck.launcher.agent.AgentHost.refresh(this)
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() }
if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
}
}, "runtime-operation").start()
}
@@ -3476,10 +3461,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
if (release.version == installed) return
if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) ||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(this))) return
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself")
if (installed == null) protons.prefetchOwn()
install(release)
}
}
@@ -8,9 +8,7 @@ import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.Onboarding
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.SteamClientPrefetch
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionPhase
@@ -62,15 +60,10 @@ internal class ProtonMenu(
Thread({
val problem = runCatching {
installer(tool) { label, value ->
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
ui.post { protonStage = label; protonPercent = value }
}
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
if (tool.id == ProtonExtras.OWN) {
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
}
ui.post {
protonProblem = problem
protonBusyId = null
@@ -177,46 +170,16 @@ internal class ProtonMenu(
Operation.checking.set(false)
}
ensureAutoUpdates()
ensureSteamClient()
}
if (!published) Operation.checking.set(false)
}, "proton-updates").start()
}
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
fun prefetchOwn() {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
Thread({
val problem = runCatching {
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
ui.post { ensureAutoUpdates() }
}, "proton-prefetch").start()
}
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
fun ensureSteamClient() {
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
SteamClientPrefetch.start(
activity,
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
activity.getString(R.string.onboarding_steam_failed),
)
}
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN
protonProblem = null
@@ -154,8 +154,6 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.LatestRequestCoordinator
import com.droiddeck.launcher.ui.SessionDrawerPage
import com.droiddeck.launcher.ui.sessionDrawerPages
import com.droiddeck.launcher.ui.strip
import com.droiddeck.launcher.ui.tabFor
import com.droiddeck.launcher.ui.step
import kotlin.math.abs
@@ -596,7 +594,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var backHold by mutableStateOf(true)
private var dockedMenuController by mutableStateOf(false)
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)
private var backDoubleTapMs by mutableStateOf(500)
private var lowLatency by mutableStateOf(true)
@@ -936,6 +933,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
!SessionPrefs.bluetoothAsked(this)) {
SessionPrefs.setBluetoothAsked(this)
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
}
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
@Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
@@ -1533,8 +1535,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
secondScreenNone = !bottomOutputActive && !dockDrawer(),
dualScreenMode = dualScreenSessionMode,
onDualScreenMode = ::chooseDualScreenSessionMode,
gameOnBottom = bottomOutputActive,
gameSwapAvailable = bottomSwapAvailable,
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
@@ -2659,7 +2659,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this)
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
@@ -3665,9 +3664,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
val pages = sessionDrawerPages(glasses.present)
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
drawerPage = sessionDrawerPages(glasses.present)
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection()
}
return true
@@ -4398,27 +4396,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
}
private fun chooseDualScreenSessionMode(mode: String) {
if (mode !in com.droiddeck.launcher.input.DualScreen.modes || mode == dualScreenSessionMode) return
SessionPrefs.setDualScreenSessionMode(this, mode)
dualScreenSessionMode = mode
SessionState.secondScreenAutoOpened = false
val menuOnBottom = drawerDocked
val menuOnTop = drawerOpenState && !drawerDocked
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
if (gameOnBottom) putGameOnBottom(false)
if (secondScreenMode != SecondScreenMode.NONE || menuOnBottom) closeSecondScreen(reset = true)
if (menuOnBottom) drawerOpen = true
} else if (menuOnTop) {
// The menu moves to the second screen as the menu itself, not as one of the control panels.
SessionState.secondScreenAutoOpened = true
refreshSecondScreenDisplays()
pinDockedMenu()
return
}
refreshSecondScreenDisplays()
}
private fun selectSecondScreenDisplay(displayId: Int) {
if (secondScreenDisplays.none { it.id == displayId }) return
selectedSecondScreenDisplay = displayId
@@ -5981,11 +5958,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (secondScreenPresentation == null) showSecondScreen(secondScreenMode)
if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu()
SessionState.bottomMenu = false
} else {
if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu()
SessionState.bottomMenu = false
if (!menuShownOnBottom()) openDualScreenControls()
}
} else openDualScreenControls()
startedScreens++
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
Glasses.rescan()
@@ -1,17 +0,0 @@
package com.droiddeck.launcher.core
import java.io.File
object CpuFeatures {
internal fun lacksAtomics(cpuInfo: String): Boolean {
val cores = cpuInfo.lineSequence()
.filter { it.substringBefore(':').trim() == "Features" }
.map { it.substringAfter(':').trim().split(Regex("\\s+")) }
.toList()
return cores.isNotEmpty() && cores.any { "atomics" !in it }
}
val lacksAtomics: Boolean by lazy {
runCatching { lacksAtomics(File("/proc/cpuinfo").readText()) }.getOrDefault(false)
}
}
@@ -16,7 +16,7 @@ object SteamIntegration {
const val EXTRA_FEATURE = "integration_feature"
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
private const val SHORTCUTS_ASSET = "shortcuts.apk"
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH }
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
data class State(
val wifi: Boolean = false,
@@ -28,7 +28,6 @@ object SteamIntegration {
val shortcuts: Boolean = false,
val shortcutsRestricted: Boolean = false,
val shortcutsTried: Boolean = false,
val bluetooth: Boolean = false,
val suggested: Boolean = true,
)
@@ -40,16 +39,9 @@ object SteamIntegration {
home = HomeApp.isDefault(context),
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
shortcutsRestricted = restrictedSettings(context),
bluetooth = bluetoothAllowed(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
)
fun bluetoothAllowed(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching {
@@ -47,7 +47,6 @@ object AutoComponents {
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
@VisibleForTesting @Volatile internal var runNow = false
@@ -534,10 +533,6 @@ object AutoComponents {
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
fun powerSaveOrMetered(context: Context): Boolean =
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
fun constrained(context: Context): Boolean {
val power = context.getSystemService(PowerManager::class.java)
if (power?.isPowerSaveMode == true) return true
@@ -274,10 +274,6 @@ object BwrapSpawner {
val binds = ArrayList<Bind>()
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":")
if (libs.any { it.endsWith("/liblse_emu.so") }) {
env.putIfAbsent("LSE_EMU", "1")
env.putIfAbsent("LSE_EMU_PATCH", "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))
@@ -72,8 +72,6 @@ object CurseForgeApp {
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
.put("installLatestFile", true).put("installSource", 4)
private const val CACHE = "__droiddeckServices"
private const val SERVICES = """(() => {
const seen = new Set(), out = {};
const walk = (o, d) => {
@@ -93,8 +91,7 @@ object CurseForgeApp {
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
val name = JSONObject.quote(method)
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
val key = JSONObject.quote(service)
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
val inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " +
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
"return { value: $run }; })()"
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
@@ -173,7 +170,6 @@ object CurseForgeApp {
}
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
private val connected = ConcurrentHashMap.newKeySet<String>()
private fun lines(context: Context, argv: List<String>): List<String> {
val out = ArrayList<String>()
@@ -236,25 +232,19 @@ object CurseForgeApp {
}
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
hold.set(true)
inspector?.let(connected::remove)
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
}
private fun connect(context: Context, inspector: String) {
if (inspector in connected) return
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
connected += inspector
}
private fun instances(context: Context, inspector: String): Any? =
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
connect(context, inspector)
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
}
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
@@ -270,34 +260,34 @@ object CurseForgeApp {
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? {
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): Boolean {
val deadline = System.currentTimeMillis() + INSTALL_MS
while (System.currentTimeMillis() < deadline) {
val listed = runCatching { projects(context, inspector, guid) }
val error = listed.exceptionOrNull()
if (error is Failure && error.gone) throw error
listed.getOrNull()?.let { if (done(it)) return it }
listed.getOrNull()?.let { if (done(it)) return true }
Thread.sleep(1_000)
}
return null
return false
}
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
}
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
}
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean {
connect(context, inspector)
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
if (failed == null || failed.length() > 0) return null
if (failed == null || failed.length() > 0) return false
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
}
}
@@ -275,15 +275,12 @@ class LinuxNetworkLinkComponent(
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
*/
private fun replace(file: File, text: String) {
synchronized(WRITES) {
if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return
val staged = File(file.path + ".staged")
java.io.FileOutputStream(staged).use { out ->
out.write(text.toByteArray())
out.fd.sync()
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
val staged = File(file.path + ".staged")
java.io.FileOutputStream(staged).use { out ->
out.write(text.toByteArray())
out.fd.sync()
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
}
private fun writeResolver(properties: LinkProperties?) {
@@ -336,8 +333,6 @@ class LinuxNetworkLinkComponent(
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
companion object {
private val WRITES = Any()
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
properties?.routes.orEmpty()
@@ -1,102 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.runtime.RuntimeInstallService
import kotlinx.coroutines.flow.MutableStateFlow
/** What first run installs by itself, in the order it is needed, and how far each part has got. */
object Onboarding {
enum class Step { RUNTIME, PROTON, STEAM }
data class Progress(val label: String, val percent: Int)
data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true)
enum class State { DONE, ACTIVE, WAITING, FAILED }
data class Row(val step: Step, val state: State, val label: String?, val percent: Int)
val active = MutableStateFlow<Map<Step, Progress>>(emptyMap())
val failed = MutableStateFlow<Map<Step, String>>(emptyMap())
val facts = MutableStateFlow(Facts())
@Volatile private var appContext: Context? = null
private var hold: (() -> Unit)? = null
fun attach(context: Context) {
appContext = context.applicationContext
}
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
@Synchronized private fun keepAlive() {
val context = appContext ?: return
val running = active.value
if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) {
if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title))
val rows = rows(running, failed.value, facts.value)
RuntimeInstallService.packageProgress(running.values.first().label, overall(rows))
} else {
hold?.invoke()
hold = null
}
}
@Synchronized fun recheck(context: Context) {
val runtime = LinuxRuntime.isInstalled(context)
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
facts.value = Facts(
runtime = runtime,
proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(),
steam = runtime && !SteamClientPrefetch.pending(context),
)
}
fun report(step: Step, label: String, percent: Int) {
failed.value = failed.value - step
active.value = active.value + (step to Progress(label, percent))
keepAlive()
}
fun finish(step: Step) {
active.value = active.value - step
failed.value = failed.value - step
keepAlive()
}
fun fail(step: Step, message: String) {
active.value = active.value - step
failed.value = failed.value + (step to message)
keepAlive()
}
fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step ->
val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam }
val progress = active[step]
when {
progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent)
failed[step] != null -> Row(step, State.FAILED, failed[step], -1)
ready -> Row(step, State.DONE, null, 100)
else -> Row(step, State.WAITING, null, -1)
}
}
fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE }
/** The aggregate fraction of the whole first-run work, weighting each step by what it downloads. */
fun overall(rows: List<Row>): Int {
val weights = mapOf(Step.RUNTIME to 60, Step.PROTON to 15, Step.STEAM to 25)
val total = weights.values.sum()
val got = rows.sumOf { row ->
val w = weights.getValue(row.step)
when (row.state) {
State.DONE -> w
State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0
else -> 0
}
}
return got * 100 / total
}
}
@@ -23,7 +23,6 @@ object ProtonExtras {
const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile
var installInProgress = false
@Volatile var prefetching = false
private set
@Volatile
private var replacing = false
@@ -218,12 +217,24 @@ object ProtonExtras {
@Synchronized
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
if (installInProgress) return context.getString(R.string.pextra_busy)
installInProgress = true
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
}
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
return context.getString(R.string.pextra_no_space, tool.name)
}
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
onProgress(downloading, 0)
var downloaded = false
@@ -241,41 +252,6 @@ object ProtonExtras {
}
}
if (!downloaded) return context.getString(R.string.pextra_download_failed)
return null
}
/** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */
@Synchronized
fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress) return context.getString(R.string.pextra_busy)
prefetching = true
try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false }
}
private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name)
return fetchArchive(context, tool, asset, archive, onProgress)
}
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
return context.getString(R.string.pextra_no_space, tool.name)
}
fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
if (asset.size > 0 && archive.length() != asset.size) {
if (archive.length() > asset.size) {
archive.delete()
@@ -5,7 +5,6 @@ import android.content.Context
import android.os.Environment
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.CpuFeatures
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.runtime.DesktopCatalog
@@ -22,10 +21,6 @@ object SessionFiles {
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
internal const val LSE_EMU = "usr/local/lib/droiddeck-lse/liblse_emu.so"
internal fun lsePreload(lacksAtomics: Boolean, staged: Boolean): String =
if (lacksAtomics && staged) "/$LSE_EMU\n" else ""
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
internal val DESKTOP_FILES = arrayOf(
@@ -100,11 +95,7 @@ object SessionFiles {
return all
}
private val STAGE_LOCK = Any()
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
fun stage(context: Context, root: File, startsSession: Boolean = false) {
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)
@@ -269,7 +260,6 @@ object SessionFiles {
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"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)
@@ -331,8 +321,7 @@ object SessionFiles {
for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger)
ledger.save()
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
val preload = StringBuilder(lsePreload(CpuFeatures.lacksAtomics, File(root, LSE_EMU).isFile))
preload.append("/usr/local/lib/libddsession.so\n")
val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
@@ -671,7 +660,6 @@ object SessionFiles {
private const val UI_STATE = "UIStoreLocalSteamUIState"
private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false"
private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true"
private const val LIBRARY_BIG_ART = "LibraryHomeBigArt"
private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}"
/**
@@ -721,12 +709,7 @@ object SessionFiles {
val block = out.substring(web.keyStart, web.close + 1)
out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline))
}
out = seedRecentSort(out, newline)
val last = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out
if (!hasKey(out.substring(last.open + 1, last.close), LIBRARY_BIG_ART)) {
out = insertInto(out, last, listOf("\"$LIBRARY_BIG_ART\"\t\t\"1\""), newline)
}
return out
return seedRecentSort(out, newline)
}
// The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort,
@@ -746,11 +729,9 @@ object SessionFiles {
private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String {
val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 }
val before = text.substring(lineStart, parent.close)
val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t"
val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val section = lines.joinToString(newline) { indent + it } + newline
if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart)
return text.substring(0, parent.close) + newline + section + text.substring(parent.close)
return text.substring(0, lineStart) + section + text.substring(lineStart)
}
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
@@ -63,13 +63,6 @@ object SessionPrefs {
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
/** The session menu's width in dp the user dragged it to; null keeps the default. */
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
fun setDrawerWidthDp(context: Context, dp: Int) {
prefs(context).edit().putInt("drawerWidthDp", dp).apply()
}
fun setOrientation(context: Context, orientation: Int) {
require(orientationOptions.any { it.first == orientation })
prefs(context).edit().putInt("orientation", orientation).apply()
@@ -2705,7 +2705,6 @@ class SessionService : Service() {
gameId: String? = null,
displayId: Int = Display.DEFAULT_DISPLAY,
) {
SteamClientPrefetch.cancel()
SessionState.activityDisplayId = displayId
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
.putExtra(EXTRA_DISPLAY_ID, displayId)
@@ -13,7 +13,7 @@ object SettingsReset {
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
@@ -1,104 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import kotlinx.coroutines.flow.update
/**
* Downloads Valve's Steam client while the session is stopped, so the first Play does not wait on it.
* It runs the same droiddeck-steam-install the session runs, which keeps what arrived when it is cut
* short and resumes from there.
*/
object SteamClientPrefetch {
private const val TAG = "SteamClientPrefetch"
private val DOWNLOADING = Regex("""downloading Steam: .*, (\d+) of (\d+) MB""")
private const val CANCELLED = "cancelled"
private val lock = Any()
private var process: Process? = null
private var cancelled = false
@Volatile private var thread: Thread? = null
internal fun parse(line: String): Pair<Int, Int>? {
val match = DOWNLOADING.find(line) ?: return null
val done = match.groupValues[1].toLongOrNull() ?: return null
val total = match.groupValues[2].toLongOrNull()?.takeIf { it > 0 } ?: return null
return (done * 100 / total).toInt().coerceIn(0, 100) to total.toInt()
}
fun running(): Boolean = thread?.isAlive == true
private const val CACHED = "root/.local/share/Steam/package/droiddeck-cached"
fun installPending(context: Context): Boolean = SteamDownloadMonitor.clientInstallPending(LinuxRuntime.rootDir(context))
fun pending(context: Context): Boolean =
installPending(context) || !File(LinuxRuntime.rootDir(context), CACHED).isFile
/** Stops a running download so a session can take over; the script resumes the partial files. */
fun cancel() {
synchronized(lock) {
cancelled = true
process?.destroy()
}
}
private fun isCancelled() = synchronized(lock) { cancelled }
@Synchronized
fun start(context: Context, label: (Int) -> String, failedLabel: String) {
if (running() || SessionState.running || !LinuxRuntime.isInstalled(context) || !pending(context)) return
val app = context.applicationContext
synchronized(lock) { cancelled = false }
thread = Thread({
Onboarding.report(Onboarding.Step.STEAM, label(-1), -1)
val problem = runCatching { run(app, label) }.getOrElse { it.message ?: it.javaClass.simpleName }
synchronized(lock) { process = null }
if (problem == null && !pending(app)) Onboarding.finish(Onboarding.Step.STEAM)
else if (SessionState.running || problem == CANCELLED || isCancelled()) Onboarding.finish(Onboarding.Step.STEAM)
else Onboarding.fail(Onboarding.Step.STEAM, problem ?: failedLabel)
val steamReady = !pending(app)
Onboarding.facts.update { it.copy(steam = steamReady) }
}, "steam-client-prefetch").also { it.start() }
}
private fun run(context: Context, label: (Int) -> String): String? {
if (isCancelled()) return CANCELLED
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, root)
val install = installPending(context)
if (install) {
val problem = script(context, emptyList(), label, 0, 35)
if (problem != null) return problem
}
return script(context, listOf("--cache"), label, if (install) 35 else 0, 100)
}
private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? {
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share", "/usr/local/bin/droiddeck-steam-install",
) + args
if (isCancelled()) return CANCELLED
val child = ProtonExtras.guestProcess(context, guest).start()
synchronized(lock) {
if (cancelled) {
child.destroy()
return CANCELLED
}
process = child
}
child.inputStream.bufferedReader().useLines { lines ->
lines.forEach { line ->
Log.i(TAG, line)
val progress = parse(line)
if (progress != null) Onboarding.report(Onboarding.Step.STEAM, label(progress.second), from + progress.first * (to - from) / 100)
}
}
val status = child.waitFor()
return if (status == 0) null else "droiddeck-steam-install exited $status"
}
}
@@ -103,9 +103,7 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
XboxContent.complete(app, item, folder)
return folder.path
}
val exe = runCatching { executable(folder) }.onFailure {
StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}")
}.getOrThrow()
val exe = executable(folder)
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
extra = item.extra + mapOf("contentId" to selected, "market" to market)))
@@ -21,9 +21,8 @@ internal object XboxManifest {
val files = folder.listFiles().orEmpty()
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
val manifests = config.ifEmpty { legacy }
require(manifests.size == 1) { "Missing or ambiguous game manifest." }
val manifest = manifests.single()
require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
val manifest = (config + legacy).single()
val rootTag = if (config.isEmpty()) "Package" else "Game"
require(manifest.length() <= 1_048_576)
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
@@ -110,9 +110,6 @@ internal class CurseLink(val app: UserApps.App) {
private val guids = HashMap<String, String>()
private val scanLock = Object()
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
private val settleLock = Object()
private val settled = HashMap<String, Pair<Int, List<CurseForgeApp.Project>>>()
private val turns = HashMap<String, Int>()
var generation by mutableIntStateOf(0)
private set
@@ -123,7 +120,7 @@ internal class CurseLink(val app: UserApps.App) {
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
synchronized(scanLock) {
scans[target.addOns.path]?.takeIf { it.first == key }?.second
?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also {
?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also {
scans[target.addOns.path] = key to it
report(target, it)
}
@@ -134,26 +131,6 @@ internal class CurseLink(val app: UserApps.App) {
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
private fun settledFor(target: WowAddons.Target): List<CurseForgeApp.Project>? = synchronized(settleLock) {
settled.remove(target.addOns.path)?.takeIf { it.first == generation }?.second
}
fun change(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> List<CurseForgeApp.Project>?): Boolean {
val path = target.addOns.path
val turn = synchronized(settleLock) {
settled.remove(path)
((turns[path] ?: 0) + 1).also { turns[path] = it }
}
val projects = call(context, target, launch, block) ?: return false
synchronized(settleLock) {
if (turns[path] == turn) {
settled[path] = generation to projects
report(target, projects)
}
}
return true
}
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
val linked = synchronized(lock) { link(context, target, launch) }
try {
@@ -197,9 +174,11 @@ internal class CurseLink(val app: UserApps.App) {
return Linked(url, guid)
}
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked ->
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked ->
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() }
val project = CurseForgeApp.owner(projects, folder) ?: return@call false
if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState()
true
}
internal val stopped: Job get() = work
@@ -343,7 +322,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
scope.launch {
val done = withContext(Dispatchers.IO) {
runCatching {
via.change(context, into) {
via.call(context, into) {
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
}
@@ -175,7 +175,7 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
val code = e.nativeKeyEvent.keyCode
if (code != android.view.KeyEvent.KEYCODE_BUTTON_L1 && code != android.view.KeyEvent.KEYCODE_BUTTON_R1) return@onPreviewKeyEvent false
if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) {
page = sessionDrawerPages().let { it.strip().step(it.tabFor(page), if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) }
page = sessionDrawerPages().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
}
true
}
@@ -33,8 +33,6 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
@@ -111,21 +109,13 @@ internal fun VeilRing() {
}
}
private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray =
private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float =
when (val o = shape.createOutline(size, dir, density)) {
is Outline.Rounded -> o.roundRect.run {
floatArrayOf(topLeftCornerRadius.x, topRightCornerRadius.x, bottomRightCornerRadius.x, bottomLeftCornerRadius.x)
}
is Outline.Rectangle -> FloatArray(4)
is Outline.Generic -> FloatArray(4) { minOf(size.width, size.height) / 2f }
is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x
is Outline.Rectangle -> 0f
is Outline.Generic -> minOf(size.width, size.height) / 2f
}
private fun ringRect(l: Float, t: Float, w: Float, h: Float, radii: FloatArray, inset: Float): Path {
// Radii are not capped one by one: the path scales corners whose neighbours overlap, as the outline does.
fun r(i: Int) = CornerRadius((radii[i] - inset).coerceAtLeast(0f))
return Path().apply { addRoundRect(RoundRect(Rect(l, t, l + w, t + h), r(0), r(1), r(2), r(3))) }
}
@Composable
internal fun Modifier.glideBorder(
hot: Boolean,
@@ -200,7 +190,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
val density = LocalDensity.current
val dir = LocalLayoutDirection.current
val edges = remember { List(4) { Animatable(0f) } }
val corners = remember { List(4) { Animatable(0f) } }
val corner = remember { Animatable(0f) }
val solid = remember { Animatable(0f) }
val alpha = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
@@ -269,14 +259,14 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
fun droplet(s: GlideSource, b: Rect) {
jobs.forEach { it?.cancel() }
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
val endCorners = cornersOf(s.shape, size, dir, density)
val endCorner = cornerOf(s.shape, size, dir, density)
jobs[5] = scope.launch {
val r = with(density) { 6.dp.toPx() }
fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r)
val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f)
coroutineScope {
launch { solid.animateTo(1f, Motion.tw(80)) }
corners.forEach { c -> launch { c.animateTo(r, Motion.tw(90)) } }
launch { corner.animateTo(r, Motion.tw(90)) }
dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } }
}
val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density
@@ -291,9 +281,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
flight.cancel()
val at = glide.boundsOf(s) ?: b
launch { solid.animateTo(0f, Motion.tw(150)) }
// The droplet job is cancelled by the next move, so the shape settles on the corner job instead.
jobs[4]?.cancel()
jobs[4] = scope.launch { corners.forEachIndexed { i, c -> launch { c.animateTo(endCorners[i], Motion.sp(0.8f, 600f)) } } }
launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) }
listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v ->
jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) }
}
@@ -301,11 +289,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
}
fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) {
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
val r = cornersOf(s.shape, size, dir, density)
val r = cornerOf(s.shape, size, dir, density)
jobs[4]?.cancel()
jobs[4] = scope.launch {
corners.forEachIndexed { i, c -> launch { if (snap) c.snapTo(r[i]) else c.animateTo(r[i], Motion.sp(0.8f, 500f)) } }
}
jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) }
}
snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) ->
if (Motion.scale == 0f) {
@@ -316,7 +302,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
else {
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> edges[i].snapTo(v) }
val size = src.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) }
corner.snapTo(cornerOf(src.shape, size, dir, density))
alpha.snapTo(1f)
}
shown = src
@@ -357,11 +343,10 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
val out = with(density) { 3.dp.toPx() }
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
jobs.forEach { it?.cancel() }
// Set before the join: a move of the target restarts this block there, after shown is already set.
cornerTo(src, b, snap = true)
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
dirSpecs = List(4) { Edge(0.6f, 700f) }
delays = LongArray(4)
cornerTo(src, b, snap = true)
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
} else {
val dx = b.center.x - (edges[0].value + edges[2].value) / 2f
@@ -409,13 +394,21 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value
val sw = (r - l - w).coerceAtLeast(0f)
val sh = (b - t - w).coerceAtLeast(0f)
val radii = FloatArray(4) { corners[it].value }
val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f)
val f = solid.value
if (f > 0.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f)
if (f > 0.01f) drawRoundRect(
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
cornerRadius = CornerRadius(corner.value), alpha = a * f,
)
if (f < 0.99f) {
val inner = ringRect(l + w / 2f, t + w / 2f, sw, sh, radii, w / 2f)
drawPath(inner, color, alpha = a * (1f - f) * fillAlpha)
drawPath(inner, color, style = Stroke(w), alpha = a)
drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha,
)
drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
)
}
}
}
@@ -51,7 +51,6 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -249,7 +248,6 @@ internal fun SetupPanel(
if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) }
else when (tab) {
OVERVIEW_TAB -> {
OnboardingCard(limitBlocks, a.onShowPhantomGate)
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
@@ -1275,65 +1273,3 @@ private fun CustomColorRows() {
}
}
}
@Composable
internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Unit = {}) {
val active by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
val failed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
val facts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
val rows = com.droiddeck.launcher.session.Onboarding.rows(active, failed, facts)
val settling = com.droiddeck.launcher.session.Onboarding.pending(rows)
if (!settling) return
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val overall = com.droiddeck.launcher.session.Onboarding.overall(rows)
Column(Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 12.dp)) {
Text(stringResource(R.string.onboarding_title), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(stringResource(R.string.onboarding_summary, overall), fontSize = 13.sp, color = colors.onSurfaceVariant)
LinearProgressIndicator(progress = { overall / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(4.dp))
}
rows.forEach { row ->
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(
stringResource(when (row.step) {
com.droiddeck.launcher.session.Onboarding.Step.RUNTIME -> R.string.onboarding_step_runtime
com.droiddeck.launcher.session.Onboarding.Step.PROTON -> R.string.onboarding_step_proton
com.droiddeck.launcher.session.Onboarding.Step.STEAM -> R.string.onboarding_step_steam
}),
fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
)
val detail = when (row.state) {
com.droiddeck.launcher.session.Onboarding.State.ACTIVE -> row.label.orEmpty()
com.droiddeck.launcher.session.Onboarding.State.FAILED -> stringResource(R.string.onboarding_failed)
com.droiddeck.launcher.session.Onboarding.State.WAITING -> stringResource(R.string.onboarding_waiting)
com.droiddeck.launcher.session.Onboarding.State.DONE -> stringResource(R.string.onboarding_done)
}
Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (row.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE) {
if (row.percent >= 0) LinearProgressIndicator(progress = { row.percent / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
}
}
}
}
if (limitBlocks) {
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.setup_limit), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(stringResource(R.string.onboarding_limit_reason), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
PrimaryButton(stringResource(R.string.onboarding_limit_action), compact = true, onClick = onSetUpLimit)
}
}
}
}
@@ -1157,7 +1157,7 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
val message = withContext(Dispatchers.IO) {
if (curse != null) {
val (project, link) = curse
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
WowAddons.changed()
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
@@ -57,7 +57,7 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
SortableRows(
rows = { current.map { it.name } },
commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) },
movable = { it != SessionDrawerPage.MORE.name },
movable = { true },
rowHeight = STORE_ROW, handleWidth = STORE_HANDLE,
releaseSignal = releaseSignal,
onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } },
@@ -66,8 +66,6 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
},
) { name, held, offset, hint, rowModifier, onFocus ->
val page = current.first { it.name == name }
// The same divider the launcher's Edit tabs uses: pages above it are tabs, pages below it are kept in More.
if (page == SessionDrawerPage.MORE) { MoreLine(STORE_ROW); return@SortableRows }
val shown = page !in DrawerPages.hidden
val pal = LocalPalette.current
val label = stringResource(page.title)
@@ -202,7 +202,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
if (!pad) return@LaunchedEffect
repeat(60) {
androidx.compose.runtime.withFrameNanos { }
if (holds || !open || Steps.open) return@LaunchedEffect
if (holds || !open) return@LaunchedEffect
runCatching { inside.requestFocus() }
}
}
@@ -210,7 +210,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
Modifier.width(width).fillMaxHeight()
.onFocusChanged { holds = it.hasFocus }
.focusRequester(inside)
.focusProperties { exit = { if (open && !Steps.open) FocusRequester.Cancel else FocusRequester.Default } }
.focusProperties { exit = { if (open) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup()
.background(MaterialTheme.colorScheme.background)
.border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag(tag),
@@ -27,7 +27,7 @@ internal object DeveloperTools {
internal object NavTabs {
const val MORE = "more"
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
@@ -12,11 +12,10 @@ internal enum class SessionDrawerPage(val firstControl: String) {
DISPLAY("fg"),
HUD("hud"),
EFFECTS("look"),
VR("steamvr"),
GAMES("anisotropy"),
AGENT("agent-input"),
SESSION("suspend"),
MORE("more-edit"),
VR("steamvr"),
}
internal object DrawerPages {
@@ -28,7 +27,7 @@ internal object DrawerPages {
/** The order captured when a page row was grabbed in Arrange pages; Back restores it. */
var heldFrom: List<SessionDrawerPage>? = null
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION && page != SessionDrawerPage.MORE
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION
fun load(context: Context) {
order = arrange(SessionPrefs.drawerPageOrder(context))
@@ -82,22 +81,6 @@ internal fun sessionDrawerPages(
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
/** The pages shown as tabs: everything up to and including the More tab. */
internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> {
val more = indexOf(SessionDrawerPage.MORE)
return if (more < 0) this else subList(0, more + 1)
}
/** The pages kept inside More: those after the More tab. */
internal fun List<SessionDrawerPage>.inMore(): List<SessionDrawerPage> {
val more = indexOf(SessionDrawerPage.MORE)
return if (more < 0) emptyList() else subList(more + 1, size)
}
/** The tab that stands for [page]: the More tab for a page kept inside More. */
internal fun List<SessionDrawerPage>.tabFor(page: SessionDrawerPage): SessionDrawerPage =
if (page in inMore()) SessionDrawerPage.MORE else page
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
val index = indexOf(current).coerceAtLeast(0)
return this[Math.floorMod(index + direction, size)]
@@ -39,7 +39,6 @@ import androidx.compose.material.icons.outlined.AutoFixHigh
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.PowerSettingsNew
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.material.icons.outlined.DesktopWindows
@@ -96,14 +95,6 @@ import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.unit.Dp
import androidx.compose.runtime.rememberUpdatedState
import android.view.KeyEvent
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.HomeApp
@@ -183,7 +174,6 @@ internal val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.GAMES -> R.string.game_settings_title
SessionDrawerPage.AGENT -> R.string.rail_agent
SessionDrawerPage.SESSION -> R.string.mode_session
SessionDrawerPage.MORE -> R.string.drawer_page_more
}
internal val SessionDrawerPage.icon get() = when (this) {
@@ -196,7 +186,6 @@ internal val SessionDrawerPage.icon get() = when (this) {
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
SessionDrawerPage.AGENT -> Icons.Outlined.Terminal
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
SessionDrawerPage.MORE -> Icons.Outlined.MoreHoriz
}
private class DrawerFocus {
@@ -272,8 +261,6 @@ class DrawerActions(
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
val secondScreenMode: SecondScreenMode,
val secondScreenNone: Boolean = true,
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
val onDualScreenMode: (String) -> Unit = {},
val gameOnBottom: Boolean = false,
val gameSwapAvailable: Boolean = false,
val gameSwapBuiltIn: Boolean = true,
@@ -431,8 +418,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
var confirmStop by remember { mutableStateOf(false) }
var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
val widthContext = LocalContext.current
var savedWidth by remember { mutableStateOf(SessionPrefs.drawerWidthDp(widthContext)) }
var stopCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
val pageScroll = remember { SessionDrawerPage.entries.associateWith { ScrollState(0) } }
LaunchedEffect(glassesTab) {
@@ -443,17 +428,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
val focus = remember { DrawerFocus() }
val inputModeManager = LocalInputModeManager.current
val focusManager = LocalFocusManager.current
// A page kept inside More is one step deeper than the strip: back returns to More before it closes the menu.
val insideMore = page in pages.inMore()
BackHandler(enabled = open) {
when {
host.open != null -> host.open = null
insideMore -> onPageChange(SessionDrawerPage.MORE)
else -> a.onClose()
}
if (host.open != null) host.open = null else a.onClose()
}
BackHandler(enabled = open && confirmStop) { confirmStop = false }
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore)
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop)
LaunchedEffect(layerOpen) { onLayerChange(layerOpen) }
var seenBackRequest by remember { mutableStateOf(backRequest) }
LaunchedEffect(backRequest) {
@@ -463,10 +442,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
confirmStop -> confirmStop = false
appToChooseDisplay != null -> appToChooseDisplay = null
host.open != null -> host.open = null
insideMore -> onPageChange(SessionDrawerPage.MORE)
}
}
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false }
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
LaunchedEffect(a.selectedGameProfileId) {
if (host.open == "fex") host.open = null
}
@@ -528,22 +506,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
val short = maxHeight < 440.dp
// The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back.
val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp)
val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet)
val defaultSheet = minOf(420.dp, maxWidth * 0.92f)
val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet)
val sheetWidth = if (docked) maxWidth else minOf(420.dp, maxWidth * 0.92f)
val narrow = sheetWidth < 320.dp
AnimatedVisibility(
open,
enter = if (docked) fadeIn(Motion.tw(160)) else slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)),
exit = if (docked) fadeOut(Motion.tw(140)) else slideOutHorizontally(Motion.tw(240)) { it } + fadeOut(Motion.tw(200)),
) {
FocusGlideHost(Modifier.fillMaxHeight().width(if (docked) sheetWidth else sheetWidth + DRAWER_HANDLE_STRIP)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) {
FocusGlideHost(Modifier.fillMaxHeight().width(sheetWidth)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(start = if (docked) 0.dp else DRAWER_HANDLE_STRIP)
.background(if (docked) pal.background else pal.background.copy(alpha = 0.97f))
.blockTouches()
.focusGroup()
@@ -554,7 +527,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
DrawerPages.rearrange(drawerContext, held)
releaseSignal++
} ?: run { managing = false }
insideMore -> onPageChange(SessionDrawerPage.MORE)
else -> a.onClose()
}
}
@@ -632,14 +604,16 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
) {
DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) {
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), -1))
host.open = null; onPageChange(pages.step(page, -1))
}
DrawerPageTabs(page = pages.tabFor(page), pages = pages.strip(), compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
DrawerPageTabs(page = page, pages = pages, compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) {
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), 1))
host.open = null; onPageChange(pages.step(page, 1))
}
SmallIconButton(
Icons.Outlined.Tune, stringResource(R.string.drawer_manage_pages), colors.onSurfaceVariant,
) { host.open = null; managing = !managing }
}
if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) }
if (managing) ManageDrawerPages(
offeredDrawerPages(a.glassesPresent),
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
@@ -914,7 +888,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
)
}
SessionDrawerPage.AGENT -> Unit
SessionDrawerPage.MORE -> DrawerMorePage(host, pages.inMore(), { host.open = null; onPageChange(it) }, { host.open = null; managing = true }) { key -> focus.track(page, key) }
SessionDrawerPage.SESSION -> {
SettingsGroup(stringResource(R.string.drawer_support)) {
SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) {
@@ -992,12 +965,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
} }
}
}
if (!docked) DrawerResizeHandle(
width = sheetWidth, min = minSheet, max = maxSheet,
onWidth = { savedWidth = it.value.roundToInt() },
onCommit = { savedWidth?.let { SessionPrefs.setDrawerWidthDp(widthContext, it) } },
modifier = Modifier.align(Alignment.CenterStart).then(focus.track(page, "resize")),
)
StopConfirm(
open = confirmStop,
pill = sheetCoords?.let { sc -> stopCoords?.takeIf { it.isAttached && sc.isAttached }?.let { sc.localBoundingBoxOf(it, clipBounds = false) } },
@@ -1185,70 +1152,6 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
private const val LOOK_CUSTOM = "custom"
/** The row above a page kept inside More that goes back to the More list. */
@Composable
private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(12.dp)
val label = stringResource(R.string.drawer_more_back, stringResource(R.string.drawer_page_more))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier.padding(top = 8.dp, start = 14.dp, end = 14.dp).fillMaxWidth().heightIn(min = 44.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal)
.testTag("drawer-more-back")
.hoverable(source)
.clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = onBack)
.controllerConfirm(onClick = onBack)
.semantics { contentDescription = label }
.padding(horizontal = 8.dp),
) {
Icon(Icons.AutoMirrored.Outlined.ArrowBack, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
Text(stringResource(R.string.drawer_page_more), fontSize = 13.sp, color = colors.onSurfaceVariant)
Text("·", fontSize = 13.sp, color = colors.onSurfaceVariant)
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
}
}
/** The pages kept inside More, and the way into arranging which pages sit on the strip and which here. */
@Composable
private fun DrawerMorePage(host: MenuHost, pages: List<SessionDrawerPage>, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
SettingsGroup(stringResource(R.string.drawer_page_more)) {
if (pages.isEmpty()) Text(
stringResource(R.string.drawer_more_empty), fontSize = 13.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
)
for (item in pages) {
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(12.dp)
val open = { onOpen(item) }
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal)
.then(track("more-${item.name.lowercase()}"))
.testTag("drawer-more-${item.name.lowercase()}")
.hoverable(source)
.clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = open)
.controllerConfirm(onClick = open)
.padding(horizontal = 14.dp),
) {
Icon(item.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
Text(stringResource(item.title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f))
}
}
}
Spacer(Modifier.height(10.dp))
DrawerOutlineButton(stringResource(R.string.drawer_manage_pages), modifier = track("more-edit").testTag("drawer-more-edit"), onClick = onEdit)
}
@Composable
private fun ScreenEffectsGroup(
host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit,
@@ -1435,92 +1338,12 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole
(if (dashboard) listOf(SecondScreenMode.DASHBOARD) else emptyList()) +
(if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList())
private val DRAWER_MIN_WIDTH = 300.dp
private val DRAWER_HANDLE_STRIP = 24.dp
private val DRAWER_EDGE_GAP = 80.dp
/** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */
@Composable
private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Unit, onCommit: () -> Unit, modifier: Modifier) {
val pal = LocalPalette.current
val density = LocalDensity.current
val source = remember { MutableInteractionSource() }
val focused by source.collectIsFocusedAsState()
var dragging by remember { mutableStateOf(false) }
var coords by remember { mutableStateOf<LayoutCoordinates?>(null) }
val current by rememberUpdatedState(width)
val lower by rememberUpdatedState(min)
val upper by rememberUpdatedState(max)
val change by rememberUpdatedState(onWidth)
val commit by rememberUpdatedState(onCommit)
val hot = focused || dragging
val label = stringResource(R.string.drawer_resize)
Box(
contentAlignment = Alignment.Center,
modifier = modifier.width(24.dp).height(96.dp)
.onGloballyPositioned { coords = it }
.focusable(true, source)
.onPreviewKeyEvent { event ->
val key = event.nativeKeyEvent
val wider = key.keyCode == KeyEvent.KEYCODE_DPAD_LEFT
if (!wider && key.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) false
else {
if (key.action == KeyEvent.ACTION_DOWN) {
change((current + if (wider) 24.dp else (-24).dp).coerceIn(lower, upper))
commit()
}
true
}
}
// The handle moves with the finger as the sheet resizes, so the drag is measured on the screen.
.pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
var last = (coords?.positionInRoot()?.x ?: 0f) + down.position.x
// Several moves can arrive before the sheet recomposes, so the width is accumulated here.
var live = current
dragging = true
do {
val event = awaitPointerEvent()
val pointer = event.changes.firstOrNull() ?: break
val x = (coords?.positionInRoot()?.x ?: 0f) + pointer.position.x
val delta = with(density) { (x - last).toDp() }
last = x
if (delta != 0.dp) {
live = (live - delta).coerceIn(lower, upper)
change(live)
}
pointer.consume()
} while (event.changes.any { it.pressed })
dragging = false
commit()
}
}
.semantics {
contentDescription = label
stateDescription = "${width.value.roundToInt()} dp"
},
) {
Box(
Modifier.width(if (hot) 6.dp else 4.dp).height(56.dp).clip(CircleShape)
.background(if (hot) pal.signal else pal.onSurfaceVariant.copy(alpha = 0.55f)),
)
}
}
@Composable
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val choosesDisplay = a.secondScreenDisplays.size > 1
val swapsGame = a.gameSwapAvailable || a.gameOnBottom
val hasSecondScreen = a.secondScreenDisplays.isNotEmpty()
if (!hasSecondScreen && !choosesDisplay && !swapsGame) return
if (!choosesDisplay && !swapsGame) return
SettingsGroup(stringResource(R.string.drawer_second_screen)) {
if (hasSecondScreen) ChoiceRow(host, "dual-screen-mode", stringResource(R.string.setup_dual_screen_sessions), null,
listOf(
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
), a.dualScreenMode, chipModifier = track("dual-screen-mode"), onPick = a.onDualScreenMode)
if (swapsGame) ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom))
else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)),
@@ -31,7 +31,6 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
@@ -155,24 +154,8 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
words = {
val runtimeStatus: @Composable () -> Unit = {
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
val onboardingFacts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
val onboardingRows = com.droiddeck.launcher.session.Onboarding.rows(onboardingActive, onboardingFailed, onboardingFacts)
val settling = onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows)
if (settling || s.busy || (s.available != null && s.available != s.installed)) {
if (settling) {
val overall = com.droiddeck.launcher.session.Onboarding.overall(onboardingRows)
Chip(
stringResource(R.string.onboarding_chip, overall, onboardingRows.firstOrNull { it.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE }?.label.orEmpty()),
ok = false, fraction = overall / 100f,
)
} else RuntimeChip(s)
if (com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) {
SecondaryButton(stringResource(R.string.onboarding_limit_while_waiting), compact = true,
modifier = Modifier.testTag("setup-while-waiting"), onClick = a.onShowPhantomGate)
}
} else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s)
else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true,
modifier = Modifier.testTag("play-needs-you")) { SetupTabs.openSection = SettingsSection.OVERVIEW }
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
@@ -23,7 +23,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Bluetooth
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.KeyboardCommandKey
import androidx.compose.material.icons.outlined.LightMode
@@ -62,7 +61,6 @@ internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) {
Feature.BRIGHTNESS -> brightness
Feature.HOME -> home
Feature.SHORTCUTS -> shortcuts
Feature.BLUETOOTH -> bluetooth
}
internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) }
@@ -118,7 +116,6 @@ private fun IntegrationRow(
feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint
feature == Feature.BRIGHTNESS -> R.string.integration_brightness_hint
feature == Feature.HOME -> R.string.integration_home_hint
feature == Feature.BLUETOOTH -> R.string.integration_bluetooth_hint
else -> R.string.integration_shortcuts_hint
})
Row(
@@ -167,7 +164,6 @@ private fun featureIcon(feature: Feature) = when (feature) {
Feature.BRIGHTNESS -> Icons.Outlined.LightMode
Feature.HOME -> Icons.Outlined.Home
Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey
Feature.BLUETOOTH -> Icons.Outlined.Bluetooth
}
private fun featureTitle(feature: Feature) = when (feature) {
@@ -175,7 +171,6 @@ private fun featureTitle(feature: Feature) = when (feature) {
Feature.BRIGHTNESS -> R.string.integration_brightness
Feature.HOME -> R.string.integration_home
Feature.SHORTCUTS -> R.string.integration_shortcuts
Feature.BLUETOOTH -> R.string.integration_bluetooth
}
@Composable
@@ -45,7 +45,6 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Matrix
@@ -175,7 +174,6 @@ internal fun StepOut(
var grown by remember { mutableStateOf(false) }
var measured by remember { mutableStateOf<IntSize?>(null) }
val first = remember { FocusRequester() }
var holdsFocus by remember { mutableStateOf(false) }
val glide = LocalFocusGlide.current
val opener = remember { arrayOfNulls<GlideSource>(1) }
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
@@ -243,12 +241,8 @@ internal fun StepOut(
LaunchedEffect(open, measured) {
if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
delay(Motion.ms(300).toLong())
// Another focus group can hold on to focus for a few frames, so the request is repeated until it lands.
repeat(30) {
withFrameNanos { }
if (holdsFocus) return@LaunchedEffect
runCatching { first.requestFocus() }
}
withFrameNanos { }
runCatching { first.requestFocus() }
}
LaunchedEffect(open, grown, inputMode.inputMode) {
@@ -295,7 +289,6 @@ internal fun StepOut(
.heightIn(max = availableHeight)
.onSizeChanged { if (measured != it) measured = it }
.controllerBack(onDismiss)
.onFocusChanged { holdsFocus = it.hasFocus }
.focusProperties { exit = { if (openNow.value) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup()
.verticalScroll(rememberScrollState())
@@ -213,10 +213,10 @@ internal fun SortableRows(
}
@Composable
internal fun MoreLine(height: androidx.compose.ui.unit.Dp = TAB_ROW) {
private fun MoreLine() {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth().height(height).testTag("tab-more-line")) {
Column(Modifier.fillMaxWidth().height(TAB_ROW).testTag("tab-more-line")) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
+1 -22
View File
@@ -36,7 +36,7 @@
<string name="wall_settings_match" translatable="false">Match screen</string>
<string name="wall_settings_speed" translatable="false">Scroll speed</string>
<string-array name="loading_hints">
<item>DroidDeck downloads Steam in the background while you set up, so your first launch is quicker.</item>
<item>First run downloads Steam. This may take a few minutes.</item>
<item>Your controller shows up to Steam as a Steam Deck controller. Switch it to a Steam Controller, DualShock 4, DualSense or Xbox 360 pad in the session settings; it applies next session.</item>
<item>Hold Back on your controller to open Steam\'s Quick Access menu. Hold Back for Steam shortcuts must be on in the session settings.</item>
<item>Background behavior decides what happens when you leave the app: Native readies Steam for sleep, Auto pauses it, Manual waits for Resume, Never keeps it running.</item>
@@ -704,9 +704,6 @@
<string name="drawer_prev_page">Previous page</string>
<string name="drawer_next_page">Next page</string>
<string name="drawer_manage_pages">Arrange pages</string>
<string name="drawer_page_more">More</string>
<string name="drawer_more_back">Back to %1$s</string>
<string name="drawer_more_empty">Nothing is kept here. Arrange pages and move one below the More row.</string>
<string name="drawer_pages_reset">Reset</string>
<string name="drawer_pages_done">Done</string>
<string name="drawer_hud">Performance HUD</string>
@@ -867,7 +864,6 @@
<string name="drawer_pc_keyboard">PC keyboard</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Second screen</string>
<string name="drawer_resize">Resize the menu</string>
<string name="drawer_second_screen_shows">Shows</string>
<string name="drawer_android_apps">Android apps</string>
<string name="drawer_launch_app">Launch an app</string>
@@ -4152,8 +4148,6 @@
<string name="integration_wifi_denied">Location denied · allow it in App info</string>
<string name="integration_brightness_hint">Steam’s slider sets screen brightness</string>
<string name="integration_home_hint">Home opens the Steam menu in a session</string>
<string name="integration_bluetooth">Bluetooth controllers</string>
<string name="integration_bluetooth_hint">Lets DroidDeck connect to Steam Controllers and other Bluetooth pads</string>
<string name="integration_shortcuts_hint">Alt+Tab, Win key and Home button stay in the session</string>
<string name="integration_shortcuts_maybe_restricted">Greyed out in Android? App info → ⋮ → Allow restricted settings</string>
<string name="integration_shortcuts_install_failed">System keys didn\'t install</string>
@@ -4401,19 +4395,4 @@
<string name="tabs_reset_title">Reset tabs</string>
<string name="tabs_reset_hint">Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More.</string>
<string name="tabs_reset_body">Your tab order and what sits under More or is hidden go back to the defaults.</string>
<string name="onboarding_title">Getting DroidDeck ready</string>
<string name="onboarding_summary">%1$d%% · you can keep using the app</string>
<string name="onboarding_step_runtime">Linux runtime</string>
<string name="onboarding_step_proton">DroidDeck Proton</string>
<string name="onboarding_step_steam">Steam client</string>
<string name="onboarding_waiting">Waiting</string>
<string name="onboarding_done">Ready</string>
<string name="onboarding_failed">Will retry</string>
<string name="onboarding_steam_downloading">Downloading the Steam client</string>
<string name="onboarding_steam_downloading_mb">Downloading the Steam client (%1$d MB)</string>
<string name="onboarding_steam_failed">The Steam client download will retry</string>
<string name="onboarding_limit_reason">Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish.</string>
<string name="onboarding_limit_action">Do it for me</string>
<string name="onboarding_limit_while_waiting">Set up while you wait</string>
<string name="onboarding_chip">Getting ready · %1$d%% · %2$s</string>
</resources>
@@ -35,7 +35,6 @@ import java.util.concurrent.atomic.AtomicInteger
class ProtonMenuAutoTest {
private val online = AutoComponents.online
private val constrained = AutoComponents.unfavourable
private val firstRunHeldBack = AutoComponents.firstRunHeldBack
private lateinit var activity: Activity
private lateinit var menu: ProtonMenu
private lateinit var root: File
@@ -50,7 +49,6 @@ class ProtonMenuAutoTest {
}
AutoComponents.online = { true }
AutoComponents.unfavourable = { false }
AutoComponents.firstRunHeldBack = { false }
SessionState.running = false
SessionState.phase = SessionPhase.IDLE
SessionState.stopRequested = false
@@ -65,7 +63,6 @@ class ProtonMenuAutoTest {
menu.protonProblem = null
menu.protonStage = null
menu.protonPercent = -1
menu.experimentalRefresh = { emptyList() }
menu.installer = { tool, progress ->
progress("Installing ${tool.name}", 50)
install("${tool.prefix}-11-12")
@@ -80,7 +77,6 @@ class ProtonMenuAutoTest {
menu.protonPercent = -1
AutoComponents.online = online
AutoComponents.unfavourable = constrained
AutoComponents.firstRunHeldBack = firstRunHeldBack
SessionState.running = false
SessionState.phase = SessionPhase.IDLE
SessionState.stopRequested = false
@@ -11,13 +11,13 @@ class AgentStorageTest {
@Test fun removingAFolderKeepsWhatItsLinksPointAt() {
val base = Files.createTempDirectory("agent-storage")
val outside = Files.createDirectories(base.resolve("sdcard"))
Files.write(outside.resolve("save.dat"), ByteArray(1 shl 20))
Files.write(outside.resolve("save.dat"), ByteArray(100))
val item = Files.createDirectories(base.resolve("rootfs/android-sdk"))
Files.write(item.resolve("a.jar"), ByteArray(10))
val linked = runCatching { Files.createSymbolicLink(item.resolve("saves"), outside) }.isSuccess
assumeTrue("symbolic links need privileges on this OS", linked)
assertTrue(AgentStorage.size(item) < 1 shl 20)
assertTrue(AgentStorage.size(item) < 100)
AgentStorage.delete(item)
assertFalse(Files.exists(item))
assertTrue(Files.exists(outside.resolve("save.dat")))
@@ -1,48 +0,0 @@
package com.droiddeck.launcher.core
import com.droiddeck.launcher.session.SessionFiles
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class CpuFeaturesTest {
@Test fun anArmv80CpuLacksAtomics() {
val cpuInfo = """
processor : 0
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid
processor : 1
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid
""".trimIndent()
assertTrue(CpuFeatures.lacksAtomics(cpuInfo))
}
@Test fun oneCoreWithoutAtomicsIsEnough() {
val cpuInfo = """
processor : 0
Features : fp asimd atomics
processor : 4
Features : fp asimd
""".trimIndent()
assertTrue(CpuFeatures.lacksAtomics(cpuInfo))
}
@Test fun anArmv82CpuHasAtomics() {
val cpuInfo = """
processor : 0
Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp
""".trimIndent()
assertFalse(CpuFeatures.lacksAtomics(cpuInfo))
}
@Test fun noFeatureLinesMeansNoEmulation() {
assertFalse(CpuFeatures.lacksAtomics("processor : 0\n"))
assertFalse(CpuFeatures.lacksAtomics(""))
}
@Test fun theEmulatorIsPreloadedFirstOnlyWhenNeededAndStaged() {
assertEquals("/usr/local/lib/droiddeck-lse/liblse_emu.so\n", SessionFiles.lsePreload(lacksAtomics = true, staged = true))
assertEquals("", SessionFiles.lsePreload(lacksAtomics = true, staged = false))
assertEquals("", SessionFiles.lsePreload(lacksAtomics = false, staged = true))
}
}
@@ -209,39 +209,6 @@ class BwrapSpawnerPlanTest {
}
}
@Test fun sandboxesSwitchOnTheLseEmulatorWhenItIsPreloaded() {
val context = RuntimeEnvironment.getApplication()
val rootfs = LinuxRuntime.rootDir(context)
val emu = File(rootfs, "usr/local/lib/droiddeck-lse/liblse_emu.so").apply { parentFile?.mkdirs(); writeText("") }
val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/droiddeck-lse/liblse_emu.so\n") }
try {
val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir)
assertEquals("/run/droiddeck-preload/liblse_emu.so", plan.env["LD_PRELOAD"])
assertEquals("1", plan.env["LSE_EMU"])
assertEquals("1", plan.env["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"])
} 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() }
@@ -5,7 +5,6 @@ import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
@@ -159,7 +158,6 @@ class CurseForgeAppTest {
assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()"))
assertTrue(text.contains("desktop.html"))
assertTrue(text.contains("executeJavaScript("))
assertTrue(text.contains("let m = globalThis.__droiddeckServices; if (!m || !m[\\\"ProjectAppService\\\"]) m = globalThis.__droiddeckServices = "))
assertFalse(text.contains("show()"))
val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null)
assertFalse(probe.contains("await s["))
@@ -294,37 +292,6 @@ class CurseForgeAppTest {
assertTrue(calls.isEmpty())
}
@Test
fun aGameFolderCurseForgeAlreadyKnowsSkipsTheFolderDetection() {
val flavor = "/root/Games/World of Warcraft/_retail_"
val curse = fakeCurse(flavor = flavor)
val context = org.robolectric.RuntimeEnvironment.getApplication()
assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor))
assertFalse("detectGameFromPath" in curse.methods)
}
@Test
fun aGameFolderCurseForgeDoesNotKnowIsDetectedOnce() {
val flavor = "/root/Games/World of Warcraft/_retail_"
val curse = fakeCurse(flavor = flavor)
curse.known = false
val context = org.robolectric.RuntimeEnvironment.getApplication()
assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor))
assertEquals(1, curse.methods.count { it == "detectGameFromPath" })
assertEquals(listOf("getGameInstances", "detectGameFromPath", "getGameInstances"), curse.methods.filter { it != "connect" })
}
@Test
fun curseForgeConnectsOncePerLaunch() {
val curse = fakeCurse()
val context = org.robolectric.RuntimeEnvironment.getApplication()
val launched = "ws://127.0.0.1:43118/${java.util.UUID.randomUUID()}"
CurseForgeApp.projects(context, launched, "g")
CurseForgeApp.projects(context, launched, "g")
CurseForgeApp.instance(context, launched, "/root", "")
assertEquals(1, curse.methods.count { it == "connect" })
}
@Test
fun theInspectorUrlIsRedactedFromCommandLogs() {
val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ")
@@ -338,7 +305,6 @@ class CurseForgeAppTest {
val methods = java.util.Collections.synchronizedList(mutableListOf<String>())
@Volatile var unreachableAfterDelete = false
@Volatile var unreachable = false
@Volatile var known = true
fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status)
@@ -362,11 +328,8 @@ class CurseForgeAppTest {
projects.forEach { it.put("status", 1) }
true
}
"detectGameFromPath" -> {
known = true
JSONObject().put("gameInstanceGuid", "g")
}
"getGameInstances" -> if (known) JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) else JSONArray()
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor))
"deleteMods" -> {
projects.removeAll { p ->
(p.getString("installedModId") in expression).also { gone ->
@@ -504,7 +467,7 @@ class CurseForgeAppTest {
curse.add("18808", "TomTom", 1)
val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update }
assertEquals(mapOf("298842" to true, "18808" to false), before)
assertNotNull(CurseForgeApp.update(context, url, "g", "298842"))
assertTrue(CurseForgeApp.update(context, url, "g", "298842"))
assertTrue("updateMod" in curse.methods)
assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update })
}
@@ -516,7 +479,7 @@ class CurseForgeAppTest {
curse.add("298842", "Leatrix_Maps", 1)
curse.add("18808", "TomTom", 1)
val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!!
assertNotNull(CurseForgeApp.uninstall(context, url, "g", project))
assertTrue(CurseForgeApp.uninstall(context, url, "g", project))
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
assertFalse(File(curse.addOns, "Leatrix_Maps").exists())
assertTrue(File(curse.addOns, "TomTom").isDirectory)
@@ -155,37 +155,4 @@ class LinuxNetworkLinkComponentTest {
})
assertEquals(before, link)
}
@Test fun parallelPublishersFromSeparateComponentsAllLandAndLeaveNoStagedCopy() {
val context = ApplicationProvider.getApplicationContext<Context>()
val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1)
val failures = java.util.concurrent.atomic.AtomicInteger()
val threads = (0 until 8).map {
Thread {
val component = LinuxNetworkLinkComponent(context, temporary.root)
repeat(25) {
runCatching {
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace",
from(java.io.File::class.java, temporary.root.resolve("etc/droiddeck-net").apply { parentFile!!.mkdirs() }),
from(String::class.java, "if tun0 $it\n"))
}.onFailure { failures.incrementAndGet() }
}
}.apply { start() }
}
threads.forEach { it.join() }
assertEquals(0, failures.get())
assertFalse(temporary.root.resolve("etc/droiddeck-net.staged").exists())
assertEquals("if tun0 24\n", temporary.root.resolve("etc/droiddeck-net").readText())
}
@Test fun anUnchangedFileIsNotRewritten() {
val context = ApplicationProvider.getApplicationContext<Context>()
val component = LinuxNetworkLinkComponent(context, temporary.root)
val file = temporary.root.resolve("etc/resolv.conf").apply { parentFile!!.mkdirs(); writeText("nameserver 1.1.1.1\n") }
assertTrue(file.setLastModified(1_000_000L))
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 1.1.1.1\n"))
assertEquals(1_000_000L, file.lastModified())
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 8.8.8.8\n"))
assertEquals("nameserver 8.8.8.8\n", file.readText())
}
}
@@ -1,44 +0,0 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.session.Onboarding.Facts
import com.droiddeck.launcher.session.Onboarding.Progress
import com.droiddeck.launcher.session.Onboarding.State
import com.droiddeck.launcher.session.Onboarding.Step
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class OnboardingTest {
private val none = Facts(runtime = false, proton = false, steam = false)
@Test fun everythingReadyShowsNothing() {
val rows = Onboarding.rows(emptyMap(), emptyMap(), Facts())
assertFalse(Onboarding.pending(rows))
assertEquals(100, Onboarding.overall(rows))
}
@Test fun stepsAreActiveFailedOrWaiting() {
val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), mapOf(Step.PROTON to "no"), none)
assertEquals(listOf(State.ACTIVE, State.FAILED, State.WAITING), rows.map { it.state })
assertTrue(Onboarding.pending(rows))
}
@Test fun anActiveStepStaysActiveWhenItsFactIsAlreadyTrue() {
val rows = Onboarding.rows(mapOf(Step.STEAM to Progress("x", -1)), emptyMap(), Facts())
assertEquals(State.ACTIVE, rows.first { it.step == Step.STEAM }.state)
}
@Test fun overallWeighsDownloadsBySize() {
val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), emptyMap(), Facts(runtime = false))
assertEquals(30 + 15 + 25, Onboarding.overall(rows))
}
@Test fun reportingClearsAPriorFailure() {
Onboarding.fail(Step.STEAM, "boom")
Onboarding.report(Step.STEAM, "again", 3)
assertTrue(Onboarding.failed.value[Step.STEAM] == null)
Onboarding.finish(Step.STEAM)
assertTrue(Onboarding.active.value[Step.STEAM] == null)
}
}
@@ -1,22 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SteamClientPrefetchTest {
@Test fun readsPercentAndTotalFromTheInstallersStepLine() {
val line = "== STEP 14:21:07 downloading Steam: bins_linuxarm64.zip (2/5), 120 of 480 MB"
assertEquals(25 to 480, SteamClientPrefetch.parse(line))
}
@Test fun aRetryNoteDoesNotChangeTheReading() {
val line = "== STEP 14:21:07 downloading Steam: x.zip (1/3), 10 of 40 MB - retrying in 5s"
assertEquals(25 to 40, SteamClientPrefetch.parse(line))
}
@Test fun otherLinesAreIgnored() {
assertNull(SteamClientPrefetch.parse("== STEP 14:21:07 the Steam client now follows steamdeck_stable"))
assertNull(SteamClientPrefetch.parse("downloading Steam: x (1/1), 5 of 0 MB"))
}
}
@@ -59,27 +59,6 @@ class SteamUserDefaultsTest {
assertFalse(File(home, "userdata/123/config/droiddeck-user-defaults-initialized").exists())
}
@Test fun libraryHomeUsesBigArtUnlessChosenOtherwise() {
val fresh = home("")
SessionFiles.seedUserDefaults(fresh)
assertTrue(text(fresh).contains("\"LibraryHomeBigArt\"\t\t\"1\""))
val chosen = home("\t\"LibraryHomeBigArt\"\t\t\"0\"\n")
SessionFiles.seedUserDefaults(chosen)
assertTrue(text(chosen).contains("\"LibraryHomeBigArt\"\t\t\"0\""))
assertEquals(1, Regex("LibraryHomeBigArt").findAll(text(chosen)).count())
}
@Test fun bigArtLandsInTheRootWhenNestedStoresCloseOnItsLastLine() {
val home = home("")
File(home, "userdata/123/config/localconfig.vdf").writeText(
"\"UserLocalConfigStore\"\n{\n\t\"WebStorage\"\n\t{\n\t\t\"Other\"\t\t\"x\"\n\t}}\n")
SessionFiles.seedUserDefaults(home)
val t = text(home)
val beforeBigArt = t.substring(0, t.indexOf("\"LibraryHomeBigArt\""))
assertEquals(beforeBigArt.count { it == '{' }, beforeBigArt.count { it == '}' } + 1)
assertTrue(t.indexOf("\"CachedBatteryPreferences\"") < t.indexOf("\"LibraryHomeBigArt\""))
}
@Test fun librarySortsByRecentlyPlayed() {
val fresh = home("")
SessionFiles.seedUserDefaults(fresh)
@@ -1,16 +0,0 @@
package com.droiddeck.launcher.session
import org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin
/**
* A plain JVM has no default uncaught-exception handler, so CrashHandler's fallback halts the test JVM (exit 2)
* on any background-thread error. Each test starts from a handler that only prints, like the JVM's own.
*/
class TestJvmUncaughtHandler : TestEnvironmentLifecyclePlugin {
override fun onSetupApplicationState() {
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
System.err.print("Exception in thread \"${thread.name}\" ")
error.printStackTrace(System.err)
}
}
}
@@ -1,21 +0,0 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.App
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class UncaughtBackgroundErrorTest {
@Test fun anUncaughtErrorOnABackgroundThreadDoesNotEndTheTestRun() {
assertTrue(RuntimeEnvironment.getApplication() is App)
Thread({ throw IllegalStateException("expected by the test") }, "uncaught-background-error").apply {
start()
join()
}
}
}
@@ -87,34 +87,6 @@ class XboxManifestTest {
assertEquals(listOf("Retail.exe"), info.executables)
assertEquals("Retail.exe", XboxManifest.executable(root))
}
@Test fun aGameCorePackageIsReadFromItsConfigBesideTheGeneratedAppxManifest() {
val root = temporary.newFolder()
java.io.File(root, "Game.exe").writeText("encrypted")
java.io.File(root, "Other.exe").writeText("encrypted")
java.io.File(root, "MicrosoftGame.config").writeText("""<Game configVersion="1"><Identity Name="Test.Game" Publisher="CN=Test" Version="1.2.3.0"/>
<ExecutableList><Executable Name="Game.exe" TargetDeviceFamily="PC"/></ExecutableList><StoreId>9AAAAAAAAAAA</StoreId></Game>""")
java.io.File(root, "appxmanifest.xml").writeText("""<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10">
<Identity Name="Generated.Game" Publisher="CN=Generated" Version="9.9.9.0"/>
<Applications><Application Id="Game" Executable="Other.exe" EntryPoint="Game.App"/></Applications></Package>""")
val info = XboxManifest.read(root)
assertEquals("Test.Game", info.name)
assertEquals("1.2.3.0", info.version)
assertEquals("9AAAAAAAAAAA", info.storeId)
assertEquals("Game.exe", XboxInstaller.executable(root))
assertFalse(XboxManifest.needsAppModel(root))
}
@Test fun aFolderWithoutOneManifestIsStillRefused() {
val empty = temporary.newFolder()
java.io.File(empty, "Game.exe").writeText("encrypted")
assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(empty) }
val twice = temporary.newFolder()
java.io.File(twice, "Game.exe").writeText("encrypted")
java.io.File(twice, "MicrosoftGame.config").writeText("<Game><Executable Name=\"Game.exe\"/></Game>")
java.io.File(twice, "microsoftgame.CONFIG").writeText("<Game><Executable Name=\"Game.exe\"/></Game>")
org.junit.Assume.assumeTrue(twice.list().orEmpty().size == 3)
assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(twice) }
}
@Test fun legacyPackageManifestNamesItsExecutableTheSameWay() {
// A legacy EAppx package carries AppxManifest.xml and has no config; the
// launcher must still find the identity and the launch path, or an install
@@ -133,88 +133,6 @@ class CurseLinkTabTest {
}
}
@Test
fun anInstallHandsCurseForgesSettledListToTheNextReadWithoutARescan() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
assertEquals(listOf("298842"), link.installed(context, target, 1).map { it.id })
assertEquals(1, methods.count { it == "scanGameInstance" })
link.installed(context, target, 2)
assertEquals(2, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun aFailedInstallLeavesTheNextReadToRescan() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertFalse(link.change(context, target) { null })
link.installed(context, target, 1)
assertEquals(2, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun aRefreshAfterAnInstallStillRescans() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
link.refresh()
link.installed(context, target, 1)
assertEquals(2, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun aFailedChangeDropsAnEarlierSettledList() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
assertFalse(link.change(context, target) { null })
link.installed(context, target, 1)
assertEquals(2, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun anOlderChangeFinishingLastDoesNotReplaceTheNewerList() {
val target = wow()
tocFolder(target.addOns, "Older", "1")
tocFolder(target.addOns, "Newer", "2")
val older = CurseForgeApp.Project("1", "11", listOf("Older"), false)
val newer = CurseForgeApp.Project("2", "22", listOf("Newer"), false)
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertTrue(link.change(context, target) {
assertTrue(link.change(context, target) { listOf(older, newer) })
listOf(older)
})
assertEquals(setOf("1", "2"), CurseLink.lastReported(target).keys)
assertEquals(listOf("1", "2"), link.installed(context, target, 1).map { it.id })
assertEquals(1, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() {
val target = wow()
@@ -40,8 +40,8 @@ class NavTabsTest {
}
@Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() {
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent"))
assertFalse(com.droiddeck.launcher.agent.AgentTab.shown)
@@ -51,13 +51,13 @@ class NavTabsTest {
@Test fun showingMusicOnceKeepsItShownAfterReload() {
place("soundtracks", TabPlace.BAR)
NavTabs.load(ctx)
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "soundtracks", NavTabs.MORE), navigationKeys(state()))
}
@Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() {
place("desktop", TabPlace.MORE)
val s = state()
assertEquals(listOf("desktop", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
assertEquals(NavTabs.MORE, navigationKeys(s).last())
assertFalse("desktop" in navigationKeys(s))
}
@@ -70,14 +70,14 @@ class NavTabsTest {
}
@Test fun resettingPutsBackTheDefaultLayout() {
place("stores", TabPlace.MORE)
place("stores", TabPlace.BAR)
place("updates", TabPlace.HIDDEN)
moveTab("downloads", -1)
assertFalse(NavTabs.isDefault())
NavTabs.reset(ctx)
NavTabs.load(ctx)
assertTrue(NavTabs.isDefault())
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state()))
}
@Test fun anOldLayoutKeepsWhatItsSwitchesShowed() {
@@ -8,45 +8,15 @@ class SessionDrawerPageTest {
val pages = sessionDrawerPages(hasAgent = false)
assertEquals(SessionDrawerPage.CONTROLLER, pages.first())
assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1))
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1))
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1))
assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1))
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1))
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1))
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1))
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
}
@Test fun moreKeepsSteamVrByDefaultAndStandsInForThePagesInsideIt() {
val pages = sessionDrawerPages(hasAgent = false)
assertEquals(listOf(SessionDrawerPage.VR), pages.inMore())
assertEquals(SessionDrawerPage.MORE, pages.strip().last())
assertFalse(SessionDrawerPage.VR in pages.strip())
assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR))
assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES))
val strip = pages.strip()
assertEquals(SessionDrawerPage.MORE, strip.step(SessionDrawerPage.SESSION, 1))
assertEquals(SessionDrawerPage.CONTROLLER, strip.step(SessionDrawerPage.MORE, 1))
assertEquals(SessionDrawerPage.SESSION, strip.step(pages.tabFor(SessionDrawerPage.VR), -1))
}
@Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() {
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION")
val out = DrawerPages.arrange(saved)
assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1])
assertTrue(out.indexOf(SessionDrawerPage.VR) < out.indexOf(SessionDrawerPage.EFFECTS) + 2)
assertTrue(out.inMore().isEmpty())
}
@Test fun sessionCanBeKeptInsideMore() {
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "GAMES", "AGENT", "MORE", "SESSION", "VR")
val out = DrawerPages.arrange(saved)
assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore())
assertFalse(SessionDrawerPage.SESSION in out.strip())
}
@Test fun moreAndSessionCannotBeHidden() {
assertFalse(DrawerPages.hideable(SessionDrawerPage.MORE))
}
@Test fun glassesAddTheirPageAfterController() {
val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false)
assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1))
@@ -41,8 +41,7 @@ class SteamIntegrationGroupTest {
compose.onNodeWithTag("integration-action-brightness").performClick()
compose.onNodeWithTag("integration-action-home").performClick()
compose.onNodeWithTag("integration-action-shortcuts").performClick()
compose.onNodeWithTag("integration-action-bluetooth").performClick()
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS, Feature.BLUETOOTH), requests)
assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests)
}
@Test fun switchesReflectAndroidGrants() {
@@ -51,8 +50,7 @@ class SteamIntegrationGroupTest {
compose.onNodeWithTag("integration-action-brightness").assert(stateIs("On"))
compose.onNodeWithTag("integration-action-shortcuts").assert(stateIs("On"))
compose.onNodeWithTag("integration-action-wifi").assert(stateIs("Off"))
compose.onNodeWithTag("integration-action-bluetooth").assert(stateIs("Off"))
compose.onNodeWithText("3 of 5 on").assertExists()
compose.onNodeWithText("3 of 4 on").assertExists()
}
@Test fun shortcutsDoNotNeedHome() {
@@ -1 +0,0 @@
com.droiddeck.launcher.session.TestJvmUncaughtHandler
-135
View File
@@ -1,135 +0,0 @@
# Steam client on ARMv8.0 CPUs
## The crash
Valve's native arm64 Steam client stopped starting on ARMv8.0 CPUs after the April 15 2026
build (client version 1776387948). The process dies with SIGILL right away, the session log
shows `"$steam_root/steamrtarm64/steam" ... Illegal instruction` and `steam exited rc=132`,
and the screen stays black.
The faulting instruction is an ARMv8.1 LSE atomic. The GDB trace in
[ValveSoftware/steam-for-linux#13288](https://github.com/ValveSoftware/steam-for-linux/issues/13288)
stops on `ldaddal x1, x0, [x0]`, with `swpa` and `casal` next to it. Earlier builds were most
likely compiled with `-moutline-atomics`, which picks LL/SC or LSE at run time. Newer builds
inline LSE. Valve has not replied on that issue, so the cause comes from the reporter's
disassembly, not from Valve.
Affected cores are the ARMv8.0 ones without LSE: Cortex-A35, A53, A57, A72 and A73. A55, A75
and later have it. On Android that covers the Snapdragon 4xx/6xx parts built on A53/A73 (for example the
Snapdragon 685 with Adreno 610 in
[Droid-Deck/DroidDeck#380](https://github.com/Droid-Deck/DroidDeck/issues/380)), plus the
Nintendo Switch, Raspberry Pi 4 and older, and the Jetson Nano outside Android.
`/proc/cpuinfo` shows it: the `Features` line has no `atomics`.
LSE is an ARMv8.1 feature. LSE-Emu users report the current client running on a Cortex-A57,
so nothing later than LSE seems to be required yet.
## What other projects do
- [SildurFX/Switchdeck](https://github.com/SildurFX/Switchdeck) (Switch, L4T Linux) lets the
client update once, then overlays `linuxarm64`, `steamrtarm64`, `steamui` and a `steam.cfg`
from the April build. It works there because the install script controls the whole system.
For us a pinned client is replaced by the self updater on its next start, which is why #380
was closed.
- [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) is a preload library by the same
author, written to run the current arm64 client on the Switch. A SIGILL handler performs
each LSE instruction with an LL/SC loop. With `LSE_EMU_PATCH=1` the first trap at a site
writes an LL/SC stub within branch range and replaces the instruction with a `b` to it, so
the site runs natively after that. It covers the full LSE set plus `LDAPR`. The author
reports Steam, FEX, Proton games and ARMSX2 running on a Cortex-A57, with ARMSX2 close to
native ARMv8.0 speed once patched. GPL-3.0, same as this repo.
- [Azkali/proton-arm64-a57](https://github.com/Azkali/proton-arm64-a57) rebuilds Proton 11
arm64 (Wine, DXVK, vkd3d-proton, FEX's WoW64 and ARM64EC DLLs) with
`-march=armv8-a -mtune=cortex-a57`. Stock Proton 11 arm64 also SIGILLs on ARMv8.0
(`wineboot` rc=132), so the client is not the only problem for games.
- Some installers fall back to Valve's x86-64 client under FEX on CPUs without LSE. We already
have that path (`DD_STEAM_CLIENT_ARCH=x86_64`, `droiddeck-steam-x64`), but it is slower and
FEX itself has to be built without LSE.
- [FrankNat996/armor](https://github.com/FrankNat996/armor) notes a separate problem: the arm64
client's ELF segments are 4K aligned, so it SIGSEGVs at once on 16K page kernels.
## This change
The session vendors LSE-Emu (`tools/linuxfs/lse-emu`, upstream commit `8bc9548`). CI and
`tools/build_local.sh` build it as `usr/local/lib/droiddeck-lse/liblse_emu.so` with
`-march=armv8-a -mno-outline-atomics`. The build fails if the library contains LSE
instructions itself.
When `/proc/cpuinfo` reports any core without `atomics`, `SessionFiles` puts the library first
in the rootfs `/etc/ld.so.preload`. `BwrapSpawner` already turns that file into `LD_PRELOAD`
for sandboxed processes. On CPUs with LSE nothing changes: the file is staged but not
preloaded, and the library would also stay idle on its own because it checks `HWCAP_ATOMICS`.
`droiddeck-session` sees the library in `ld.so.preload` and exports `LSE_EMU=1` and
`LSE_EMU_PATCH=1`, so the Steam client and everything it starts get the emulation. With a
session debug folder it also sets `LSE_EMU_LOG=$DD_DEBUG_DIR/lse_emu.log`, and `session.log`
gets a line starting with `== cpu: no LSE atomics`.
The app targets SDK 28, so the app domain still has `execmod` and the in-place patching can
make file-backed code pages writable. If the target SDK goes up, `mprotect` on those pages is
refused, every site logs `mprotect-failed`, and execution stays on the slower trap path.
## 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 also replaces an LSE instruction with a `b` while other threads may be running it.
The architecture only promises old-or-new behavior for such changes between a few instruction
types, and `LDADD` is not one of them. Upstream accepts that and reports it working on a
Cortex-A57. If it ever shows up as random crashes on a device, running with `LSE_EMU_PATCH=0`
keeps every site on the trap path at the cost of speed.
## 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 session debug folder, `lse_emu.log` should show `start`, `patched` and `exit` lines.
`cut -d' ' -f2 lse_emu.log | sort | uniq -c` summarises it. `unhandled` means an
instruction the library does not cover, and `mprotect-failed` or `no-arena` mean sites left
on the trap path.
4. Compare UI responsiveness against an ARMv8.2 device, and note any `lse_emu: unhandled`
lines in `session.log`.
## Still open
- Games. Proton 11 arm64 and Valve's FEX build need the same treatment. The preload reaches
them when they inherit `LD_PRELOAD`, but pressure-vessel and static binaries can drop it,
and FEX installs its own signal handlers with raw syscalls. An ARMv8.0 Proton build like
Azkali's is the cleaner fix.
- In #380 the session first died with SIGILL in the app's own `wl-compositor` thread, inside
`turnip-sdk36/vulkan.ad08XX.so`, which is the A8xx driver build loaded on an Adreno 610.
Picking the 6xx/7xx Turnip fixed it, and Auto picks that build once the driver release list
is loaded. Nobody has checked yet whether our bundled driver builds avoid LSE. The preload
cannot help there because the compositor is a bionic thread in the app process.
- JIT code (anonymous memory) is never patched and always traps.
- If Valve starts requiring something past LSE, the library prints
`lse_emu: unhandled pc=... insn=...` and the client crashes as before.
+1
View File
@@ -4,5 +4,6 @@ org.gradle.configuration-cache=true
org.gradle.parallel=true
android.useAndroidX=true
android.nonTransitiveRClass=true
ndkVersion=27.3.13750724
org.gradle.tooling.parallel=true
+236 -309
View File
@@ -24,7 +24,6 @@ java_dir="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents
[[ -x "$java_dir/bin/java" ]] || java_dir="${HOME}/.local/share/mise/installs/java/temurin-17"
[[ "$java_dir" == */homebrew/* ]] && echo "using homebrew java path: $java_dir"
[[ "$java_dir" == */mise/* ]] && echo "using mise java path: $java_dir"
requested_image=${DROIDDECK_BUILD_IMAGE:-}
. "${repo_root}/tools/docker_platform.sh"
image_name=${DROIDDECK_BUILD_IMAGE}
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
@@ -64,11 +63,6 @@ fi
ndk_version=${DROIDDECK_NDK_VERSION:-}
if [[ -z "${ndk_version}" ]]; then
. "${repo_root}/tools/ci/toolchains.env"
[[ -d "${sdk_dir}/ndk/${CI_ANDROID_NDK_VERSION}" ]] && ndk_version=${CI_ANDROID_NDK_VERSION}
fi
if [[ -z "${ndk_version}" ]]; then
echo "NDK ${CI_ANDROID_NDK_VERSION} (tools/ci/toolchains.env) is not installed; using the newest NDK instead, so native caches will not match CI." >&2
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 2 -maxdepth 2 -name source.properties -print | xargs -n1 dirname | sort -V | tail -1)
ndk_version=${ndk_path##*/}
fi
@@ -118,6 +112,101 @@ save_step() {
python3 "${repo_root}/tools/docker_preflight.py" "${image_name}"
image_id=$(docker image inspect --format '{{.Id}}' "${image_name}")
rm -rf -- "${linuxfs_dir}"
mkdir -p "${linuxfs_dir}"
git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir)
docker run --rm --platform "${docker_platform}" \
--user "$(id -u):$(id -g)" \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc '
set -euo pipefail
d=app/src/main/assets/linuxfs
mkdir -p "$d"
put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; }
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
-o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so"
bash tools/nativeguest/build.sh "$d/libddnatv-hook.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
-fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c
aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
-o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
mkdir -p "$d/usr/local/bin"
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"
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
put "$script" "$d/usr/local/bin/$(basename "$script")"
done
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
[ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}"
done
put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper"
put tools/linuxfs/desktop/firefox-droiddeck.js \
"$d/usr/lib/firefox/defaults/pref/droiddeck.js"
READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d"
'
x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \
app/src/main/cpp/fakeinput_steam.cpp)
x86_stage="${staging_dir}/x86-preloads"
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
x86_platform=linux/amd64
x86_packages="gcc g++ gcc-multilib g++-multilib binutils"
x86_cross=0
if [[ "${docker_platform}" == linux/arm64 ]]; then
x86_platform=linux/arm64
x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu"
x86_cross=1
fi
docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
set -euo pipefail
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
apt-get -o Acquire::Check-Valid-Until=false update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
'
mkdir -p "${x86_stage}"
cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/"
save_step x86-preloads "${x86_key}" "${x86_stage}"
fi
vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr"
vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c)
if ! restore_step vr "${vr_key}" "${vr_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}"
save_step vr "${vr_key}" "${vr_out}"
fi
gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload"
gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload)
if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}"
save_step gpuload "${gpuload_key}" "${gpuload_out}"
fi
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
if [[ -z "${github_repo}" ]]; then
origin_url=$(git -C "${repo_root}" remote get-url origin)
@@ -134,290 +223,46 @@ if [[ -z "${github_repo}" ]]; then
github_repo=${github_repo%.git}
fi
ci_components=0
ci_run=
ci_cache="${cache_dir}/ci-components"
reuse_ci_components() {
[[ "${DROIDDECK_CI_COMPONENTS:-1}" == 1 ]] && command -v gh >/dev/null 2>&1 || return 1
# CI prepares with the pinned NDK, its own build image and PulseAudio source, and the system Vulkan headers.
. "${repo_root}/tools/ci/toolchains.env"
[[ "${ndk_version}" == "${CI_ANDROID_NDK_VERSION}" && -z "${DROIDDECK_PA13_SOURCE_DIR:-}" && -z "${VK_INCLUDE:-}" \
&& -z "${requested_image}" ]] || return 1
local base candidates run artifact archive part
base=$(git -C "${repo_root}" merge-base HEAD origin/main 2>/dev/null || true)
# Only runs of this repository's own main: a fork's pull request can also name its branch main.
candidates=$(gh api "repos/${github_repo}/actions/artifacts?name=prepared-components&per_page=100" \
-q "[.artifacts[] | select(.expired | not) | select(.workflow_run.head_branch == \"main\")
| select(.workflow_run.head_repository_id == .workflow_run.repository_id)]
| sort_by(.workflow_run.head_sha != \"${base}\") | .[:3][] | \"\(.workflow_run.id):\(.id)\"" 2>/dev/null) || return 1
mkdir -p "${ci_cache}"
# CI keeps these artifacts for 14 days.
find "${ci_cache}" -mindepth 1 -maxdepth 1 -mtime +14 -exec rm -rf {} +
for candidate in ${candidates}; do
run=${candidate%%:*}
artifact=${candidate#*:}
archive="${ci_cache}/${artifact}.tar.gz"
if [[ ! -f "${archive}" ]]; then
part=$(mktemp -d "${ci_cache}/${run}.part.XXXXXX")
if gh run download "${run}" -R "${github_repo}" -n prepared-components -D "${part}" >/dev/null 2>&1; then
mv "${part}/prepared-components.tar.gz" "${archive}"
fi
rm -rf "${part}"
[[ -f "${archive}" ]] || continue
fi
if python3 "${repo_root}/tools/components/reuse.py" "${archive}"; then
ci_run=${run}
return 0
fi
done
return 1
}
fetch_ci_xbox() {
local stored="${ci_cache}/${ci_run}-xbox" part
if [[ ! -d "${stored}" ]]; then
part=$(mktemp -d "${ci_cache}/${ci_run}-xbox.part.XXXXXX")
gh run download "${ci_run}" -R "${github_repo}" -n xbox-arm64 -D "${part}" >/dev/null 2>&1 || { rm -rf "${part}"; return 1; }
# rename(2) refuses a non-empty destination, so a copy another build published first wins.
python3 -c 'import os, sys; os.rename(sys.argv[1], sys.argv[2])' "${part}" "${stored}" 2>/dev/null || rm -rf "${part}"
fi
rm -rf "${xbox_out}" && mkdir -p "${xbox_out}" && cp -R "${stored}/." "${xbox_out}/"
}
git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir)
proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a"
if reuse_ci_components; then
ci_components=1
echo "components: every recipe identity matches main CI run ${ci_run}; reusing its prepared components (DROIDDECK_CI_COMPONENTS=0 builds them here)"
else
rm -rf -- "${linuxfs_dir}"
mkdir -p "${linuxfs_dir}"
docker run --rm --platform "${docker_platform}" \
--user "$(id -u):$(id -g)" \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc '
set -euo pipefail
d=app/src/main/assets/linuxfs
mkdir -p "$d"
put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; }
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
-pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
-o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so"
bash tools/nativeguest/build.sh "$d/libddnatv-hook.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
-fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c
aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so"
mkdir -p "$d/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
-o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/"
mkdir -p "$d/usr/local/bin"
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
put "$script" "$d/usr/local/bin/$(basename "$script")"
done
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
[ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}"
done
put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper"
put tools/linuxfs/desktop/firefox-droiddeck.js \
"$d/usr/lib/firefox/defaults/pref/droiddeck.js"
READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d"
'
x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \
app/src/main/cpp/fakeinput_steam.cpp)
x86_stage="${staging_dir}/x86-preloads"
if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else
x86_platform=linux/amd64
x86_packages="gcc g++ gcc-multilib g++-multilib binutils"
x86_cross=0
if [[ "${docker_platform}" == linux/arm64 ]]; then
x86_platform=linux/arm64
x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu"
x86_cross=1
fi
docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \
-v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
set -euo pipefail
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
apt-get -o Acquire::Check-Valid-Until=false update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
'
mkdir -p "${x86_stage}"
cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/"
save_step x86-preloads "${x86_key}" "${x86_stage}"
fi
vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr"
vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c)
if ! restore_step vr "${vr_key}" "${vr_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}"
save_step vr "${vr_key}" "${vr_out}"
fi
gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload"
gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload)
if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}"
save_step gpuload "${gpuload_key}" "${gpuload_out}"
fi
cached() {
local sha=$1 name=$2 out
shift 2
out="${cache_dir}/${sha}-${name}"
if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then
echo "${out}"
return 0
fi
rm -f "${out}.part"
out="${out}.part" "$@" >&2
printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2
mv "${out}.part" "${out}"
cached() {
local sha=$1 name=$2 out
shift 2
out="${cache_dir}/${sha}-${name}"
if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then
echo "${out}"
}
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
. "${repo_root}/tools/gamescope/release.env"
gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \
bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}")
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
return 0
fi
rm -f "${out}.part"
out="${out}.part" "$@" >&2
printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2
mv "${out}.part" "${out}"
echo "${out}"
}
. "${repo_root}/tools/linuxfs/uruntime.env"
uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync"
if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
. "${repo_root}/tools/droiddeck-esync/release.env"
sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \
bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}")
rm -rf "${sync_assets}"
mkdir -p "${sync_assets}"
zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}"
test -f "${sync_assets}/index.json"
test -f "${sync_assets}/index.json.sig"
elif [[ -d "${sync_assets}" ]]; then
echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2
fi
msi_pkgs="${staging_dir}/msi-pkgs"
msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools"
mkdir -p "${msi_pkgs}" "${msi_dir}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
tar -xJf "${package_archive}" -C "${msi_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt")
for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done
for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done
for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}"
done
mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools"
for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
install -m644 "${repo_root}/tools/msitools/licenses/${license}" \
"${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}"
done
mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp"
mango_pkgs="${staging_dir}/mango-pkgs"
mkdir -p "${mango_dir}" "${mango_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
done
docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
mkdir -p "${linuxfs_dir}/usr/local/bin"
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
pw_pkgs="${staging_dir}/pw-pkgs"
mkdir -p "${pw_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \
https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
mv "${pa_tarball}.part" "${pa_tarball}"
fi
mkdir -p "${pa_source}"
tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1
fi
if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2
exit 1
fi
sink_output="${staging_dir}/sink-out"
"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}"
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1)
proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1)
if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \
&& "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \
&& (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then
echo "proot: sources unchanged, keeping ${proot_out}/libproot.so"
else
proot_stage="${staging_dir}/proot"
if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then
"${repo_root}/tools/proot/build.sh" "${proot_stage}"
save_step proot "${proot_inputs}" "${proot_stage}"
fi
install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/"
echo "${proot_inputs}" > "${proot_out}/.proot-inputs"
(cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs)
fi
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
. "${repo_root}/tools/gamescope/release.env"
gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \
bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}")
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
fi
. "${repo_root}/tools/linuxfs/uruntime.env"
uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}")
mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime"
install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime"
install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE"
sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync"
if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
# Packs revoked after a bundle was published are dropped from local and CI-prepared bundles alike.
. "${repo_root}/tools/droiddeck-esync/release.env"
sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \
bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}")
rm -rf "${sync_assets}"
mkdir -p "${sync_assets}"
zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}"
test -f "${sync_assets}/index.json"
test -f "${sync_assets}/index.json.sig"
sync_index=$(mktemp)
gh release download "${SYNC_BUNDLE_TAG}" -R "${SYNC_BUNDLE_REPO}" -p index.json -O "${sync_index}" --clobber
revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' "${sync_index}")
@@ -428,6 +273,94 @@ if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then
fi
done
rm -f "${sync_index}"
elif [[ -d "${sync_assets}" ]]; then
echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2
fi
msi_pkgs="${staging_dir}/msi-pkgs"
msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools"
mkdir -p "${msi_pkgs}" "${msi_dir}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
tar -xJf "${package_archive}" -C "${msi_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt")
for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done
for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done
for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}"
done
mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools"
for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
install -m644 "${repo_root}/tools/msitools/licenses/${license}" \
"${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}"
done
mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp"
mango_pkgs="${staging_dir}/mango-pkgs"
mkdir -p "${mango_dir}" "${mango_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
done
docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
mkdir -p "${linuxfs_dir}/usr/local/bin"
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
pw_pkgs="${staging_dir}/pw-pkgs"
mkdir -p "${pw_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \
https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
mv "${pa_tarball}.part" "${pa_tarball}"
fi
mkdir -p "${pa_source}"
tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1
fi
if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2
exit 1
fi
sink_output="${staging_dir}/sink-out"
"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}"
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a"
proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1)
proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1)
if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \
&& "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \
&& (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then
echo "proot: sources unchanged, keeping ${proot_out}/libproot.so"
else
proot_stage="${staging_dir}/proot"
if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then
"${repo_root}/tools/proot/build.sh" "${proot_stage}"
save_step proot "${proot_inputs}" "${proot_stage}"
fi
install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/"
echo "${proot_inputs}" > "${proot_out}/.proot-inputs"
(cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs)
fi
syncthing_src="${repo_root}/tools/syncthing/syncthing-android/syncthing/src/github.com/syncthing/syncthing"
@@ -451,23 +384,21 @@ else
echo "${syncthing_inputs}" > "${proot_out}/.syncthing-inputs"
fi
if [[ "${ci_components}" != 1 ]]; then
bundle_dir="${staging_dir}/pulseaudio-bundle"
mkdir -p "${bundle_dir}"
zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}"
if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \
|| -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then
echo "The committed audio bundle already contains a built ARM64 sink." >&2
exit 1
fi
install -m755 "${sink_output}/module-aaudio-sink.so" \
"${bundle_dir}/modules/arm64/module-aaudio-sink.so"
install -m755 "${sink_output}/module-directaudio-native-sink.so" \
"${bundle_dir}/modules/arm64/module-directaudio-native-sink.so"
tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst"
mkdir -p "${repo_root}/app/build/prepared-assets"
mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst"
bundle_dir="${staging_dir}/pulseaudio-bundle"
mkdir -p "${bundle_dir}"
zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}"
if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \
|| -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then
echo "The committed audio bundle already contains a built ARM64 sink." >&2
exit 1
fi
install -m755 "${sink_output}/module-aaudio-sink.so" \
"${bundle_dir}/modules/arm64/module-aaudio-sink.so"
install -m755 "${sink_output}/module-directaudio-native-sink.so" \
"${bundle_dir}/modules/arm64/module-directaudio-native-sink.so"
tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst"
mkdir -p "${repo_root}/app/build/prepared-assets"
mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst"
gradle_rust_arg=""
if [[ "${DROIDDECK_SKIP_RUST:-0}" == 1 ]]; then
@@ -488,23 +419,19 @@ else
fi
cd "${repo_root}"
[[ "${ci_components}" == 1 ]] || python3 tools/quest/build-driver.py "${NDK}"
python3 tools/quest/build-driver.py "${NDK}"
xbox_out="${linuxfs_dir}/usr/local/lib/droiddeck-xbox"
xbox_key=$(inputs_hash "native-arm64-ubuntu24.04" tools/xbox)
if [[ "${ci_components}" == 1 ]] && fetch_ci_xbox; then
echo "xbox: reused main CI run ${ci_run}"
elif ! restore_step xbox "${xbox_key}" "${xbox_out}"; then
if ! restore_step xbox "${xbox_key}" "${xbox_out}"; then
bash tools/xbox/build-local.sh
save_step xbox "${xbox_key}" "${xbox_out}"
fi
if [[ "${ci_components}" != 1 ]]; then
comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet"
comet_key=$(inputs_hash "${image_id}" tools/comet)
if ! restore_step comet "${comet_key}" "${comet_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
save_step comet "${comet_key}" "${comet_out}"
fi
comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet"
comet_key=$(inputs_hash "${image_id}" tools/comet)
if ! restore_step comet "${comet_key}" "${comet_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
save_step comet "${comet_key}" "${comet_out}"
fi
if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then
upc_out="${linuxfs_dir}/usr/local/lib/droiddeck-ubisoft"
-14
View File
@@ -1,14 +0,0 @@
#!/usr/bin/env bash
set -uo pipefail
workspace="${1:?}"
find /tmp -maxdepth 1 -user "$(id -u)" \( -name 'robolectric-*' -o -name 'junit*' -o -name 'gradle-*' -o -name 'kotlin-*' \) -mmin +180 -print0 |
while IFS= read -r -d '' entry; do
recent=$(find "$entry" -xdev -mmin -180 -print -quit 2>/dev/null) && [ -z "$recent" ] && rm -rf --one-file-system --preserve-root=all -- "$entry"
done
free=$(df --output=avail -k "$workspace" | tail -1)
if [ "$free" -lt 20971520 ]; then
rm -rf --one-file-system --preserve-root=all -- "${HOME:?}/.gradle/caches/build-cache-1" "${HOME:?}/.gradle/.tmp"
fi
df -h /tmp "$workspace"
du -xsh /tmp "${HOME:?}/.gradle" "${HOME:?}/.cargo" "${HOME:?}/.m2" "$(dirname "$workspace")" 2>/dev/null | sort -h
exit 0
-150
View File
@@ -1,150 +0,0 @@
"""Install the components a main CI run prepared when they match this tree.
The run's prepared-components archive is used only when every recipe identity it records equals
the identity of the local tree, the inputs CI builds outside the recipes are unchanged from the
run's source tree, and no recipe submodule has local edits. Files are verified in a staging
directory before any local output is replaced.
"""
import argparse
from contextlib import contextmanager
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import subprocess
import sys
import tarfile
import tempfile
sys.path.insert(0, str(Path(__file__).resolve().parent))
import prepare # noqa: E402
# CI records identities under its runner labels and pinned NDK, not this host's.
RUNNER_ARCHITECTURES = ('X64', 'ARM64')
# The components job builds these outside the recipe registry.
UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/linuxfs/lse-emu',
'tools/venus/glprobe.c', 'tools/quest']
def ci_environment(architecture, root):
ndk = next(line.split('=', 1)[1].strip()
for line in (root / 'tools/ci/toolchains.env').read_text().splitlines()
if line.startswith('CI_ANDROID_NDK_VERSION='))
return dict(RUNNER_OS='Linux', RUNNER_ARCH=architecture, NDK_VERSION=ndk)
@contextmanager
def environ(values):
saved = {key: os.environ.get(key) for key in values}
os.environ.update(values)
try:
yield
finally:
for key, value in saved.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def identities(environment, root):
with environ(environment):
return {name: prepare.identity(name, root) for name in prepare.registry(root)}
def git(root, *args):
return subprocess.run(['git', *args], cwd=root, capture_output=True, text=True)
def unregistered_changes(source_tree, root):
if git(root, 'cat-file', '-e', source_tree + '^{tree}').returncode:
return ['source tree ' + source_tree + ' (fetch origin main)']
changed = git(root, 'diff', '--name-only', source_tree, '--', *UNREGISTERED_INPUTS).stdout.split()
changed += git(root, 'ls-files', '--others', '--exclude-standard', '--', *UNREGISTERED_INPUTS).stdout.split()
return sorted(set(changed))
def edited_submodules(root):
inputs = [path for spec in prepare.registry(root).values()
for path in spec.get('inputs', []) + spec.get('source_inputs', [])]
staged = git(root, 'ls-files', '--stage', '--', *inputs).stdout.splitlines()
links = [line.split('\t', 1)[1] for line in staged if line.startswith('160000 ')]
return [link for link in links
if git(root, 'diff', '--quiet', '--ignore-submodules=none', '--', link).returncode]
def extract(archive_path, stage):
allowed = set(prepare.LIBRARIES + [prepare.MANIFEST])
total = 0
with tarfile.open(archive_path, mode='r:gz') as archive:
for entry in archive:
name = PurePosixPath(entry.name)
total += entry.size
if (not entry.isfile() or name.is_absolute() or '..' in name.parts or '\\' in entry.name
or name.as_posix() != entry.name or total > 2 * 1024**3
or not (entry.name in allowed or any(entry.name.startswith(t + '/') for t in prepare.TREES))):
raise ValueError('Unsafe prepared component archive: ' + entry.name)
path = stage / entry.name
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('xb') as output:
shutil.copyfileobj(archive.extractfile(entry), output)
path.chmod(entry.mode & 0o777)
def digest(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def install(stage, root):
for name in prepare.TREES:
shutil.rmtree(root / name, ignore_errors=True)
(root / name).parent.mkdir(parents=True, exist_ok=True)
os.replace(stage / name, root / name)
for name in prepare.LIBRARIES + [prepare.MANIFEST]:
(root / name).parent.mkdir(parents=True, exist_ok=True)
os.replace(stage / name, root / name)
def reuse(archive_path, root=prepare.ROOT):
with tarfile.open(archive_path, mode='r:gz') as archive:
data = json.load(archive.extractfile(prepare.MANIFEST))
if data.get('version') != 1:
raise ValueError('Unknown prepared component archive version')
recorded = data.get('recipes') or {}
environment = next((ci_environment(a, root) for a in RUNNER_ARCHITECTURES
if identities(ci_environment(a, root), root) == recorded), None)
if environment is None:
local = identities(ci_environment(RUNNER_ARCHITECTURES[0], root), root)
changed = sorted(name for name in local.keys() | recorded.keys() if local.get(name) != recorded.get(name))
print('CI run ' + str(data.get('run')) + ' prepared different components: ' + ', '.join(changed))
return False
differences = unregistered_changes(data['source_tree'], root) + edited_submodules(root)
if differences:
print('CI run ' + str(data.get('run')) + ' built from other sources: ' + ', '.join(differences))
return False
(root / 'app/build').mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=root / 'app/build', prefix='.reuse-') as stage:
stage = Path(stage)
extract(archive_path, stage)
files = sorted(path.relative_to(stage).as_posix() for path in stage.rglob('*')
if path.is_file() and path.relative_to(stage).as_posix() != prepare.MANIFEST)
if data.get('files') != {name: digest(stage / name) for name in files}:
raise ValueError('Prepared components do not match their recorded file hashes')
missing = [name for name in prepare.TREES if not (stage / name).is_dir()]
missing += [name for name in prepare.LIBRARIES + [prepare.MANIFEST] if not (stage / name).is_file()]
if missing:
raise ValueError('Prepared component archive is missing ' + ', '.join(missing))
install(stage, root)
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('archive', type=Path)
args = parser.parse_args()
try:
sys.exit(0 if reuse(args.archive) else 3)
except (ValueError, OSError, KeyError, tarfile.TarError) as error:
sys.exit('Cannot reuse CI components: ' + str(error))
@@ -1,5 +1,5 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
index 11ff163..4c3be85 100644
index 11ff163..085a621 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
@@ -209,6 +209,41 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1,
@@ -44,20 +44,6 @@ index 11ff163..4c3be85 100644
static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3<SYSCALL_DEF(read)>);
REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3<SYSCALL_DEF(write)>);
@@ -220,11 +255,11 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(shmctl, SyscallPassthrough3<SYSCALL_DEF(shmctl)>);
REGISTER_SYSCALL_IMPL(getpid, SyscallPassthrough0<SYSCALL_DEF(getpid)>);
REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3<SYSCALL_DEF(socket)>);
- REGISTER_SYSCALL_IMPL(connect, SyscallPassthrough3<SYSCALL_DEF(connect)>);
+ REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3<SYSCALL_DEF(connect)>);
REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6<SYSCALL_DEF(sendto)>);
REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6<SYSCALL_DEF(recvfrom)>);
REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2<SYSCALL_DEF(shutdown)>);
- REGISTER_SYSCALL_IMPL(bind, SyscallPassthrough3<SYSCALL_DEF(bind)>);
+ REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3<SYSCALL_DEF(bind)>);
REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2<SYSCALL_DEF(listen)>);
REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3<SYSCALL_DEF(getsockname)>);
REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3<SYSCALL_DEF(getpeername)>);
@@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2<SYSCALL_DEF(flock)>);
REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1<SYSCALL_DEF(fsync)>);
@@ -1,51 +0,0 @@
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
index e1f601b..cebf1f5 100644
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
@@ -222,6 +222,32 @@ class ELFCodeLoader final : public FEX::CodeLoader {
public:
+ static fextl::string GuestPreload(const char* List, const fextl::string& RootFS) {
+ fextl::string Result;
+ for (const char* Start = List; *Start; Start += *Start ? 1 : 0) {
+ size_t Length = strcspn(Start, ": ");
+ fextl::string Entry(Start, Length);
+ Start += Length;
+ if (Entry.empty()) {
+ continue;
+ }
+ if (Entry[0] == '/') {
+ auto Type = ::ELFLoader::ELFContainer::GetELFType(ResolveRootfsFile(Entry, RootFS));
+ if (Type == ::ELFLoader::ELFContainer::TYPE_NONE) {
+ Type = ::ELFLoader::ELFContainer::GetELFType(Entry);
+ }
+ if (Type == ::ELFLoader::ELFContainer::TYPE_OTHER_ELF) {
+ continue;
+ }
+ }
+ if (!Result.empty()) {
+ Result += ':';
+ }
+ Result += Entry;
+ }
+ return Result;
+ }
+
static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) {
// If the path is relative then just run that
if (File[0] != '/') {
@@ -330,6 +356,13 @@ public:
if (envp[i] == nullptr) {
break;
}
+ if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
+ auto Preload = GuestPreload(envp[i] + 11, RootFS);
+ if (!Preload.empty()) {
+ EnvironmentVariables.emplace_back("LD_PRELOAD=" + Preload);
+ }
+ continue;
+ }
EnvironmentVariables.emplace_back(envp[i]);
}
}
@@ -1,15 +0,0 @@
diff --git a/Data/ThunksDB.json b/Data/ThunksDB.json
index d52ff04..886379a 100644
--- a/Data/ThunksDB.json
+++ b/Data/ThunksDB.json
@@ -6,7 +6,9 @@
"@PREFIX_LIB@/libGL.so",
"@PREFIX_LIB@/libGL.so.1",
"@PREFIX_LIB@/libGL.so.1.2.0",
- "@PREFIX_LIB@/libGL.so.1.7.0"
+ "@PREFIX_LIB@/libGL.so.1.7.0",
+ "@PREFIX_LIB@/libOpenGL.so.0",
+ "@PREFIX_LIB@/libOpenGL.so.0.0.0"
]
},
"Vulkan": {
@@ -1,106 +0,0 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
index 4c3be85..e287cd2 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
@@ -209,6 +209,13 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1,
}
#endif
+template<int syscall_num>
+requires (syscall_num != -1)
+uint64_t SyscallPathPassthrough0(FEXCore::Core::CpuStateFrame* Frame) {
+ uint64_t Result = ::syscall(syscall_num);
+ SYSCALL_ERRNO();
+}
+
template<int syscall_num>
requires (syscall_num != -1)
uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) {
@@ -278,29 +285,29 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) {
REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1<SYSCALL_DEF(chdir)>);
REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1<SYSCALL_DEF(fchdir)>);
REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2<SYSCALL_DEF(fchmod)>);
- REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3<SYSCALL_DEF(fchown)>);
+ REGISTER_SYSCALL_IMPL(fchown, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>);
REGISTER_SYSCALL_IMPL(umask, SyscallPassthrough1<SYSCALL_DEF(umask)>);
- REGISTER_SYSCALL_IMPL(getuid, SyscallPassthrough0<SYSCALL_DEF(getuid)>);
+ REGISTER_SYSCALL_IMPL(getuid, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>);
REGISTER_SYSCALL_IMPL(syslog, SyscallPassthrough3<SYSCALL_DEF(syslog)>);
- REGISTER_SYSCALL_IMPL(getgid, SyscallPassthrough0<SYSCALL_DEF(getgid)>);
- REGISTER_SYSCALL_IMPL(setuid, SyscallPassthrough1<SYSCALL_DEF(setuid)>);
- REGISTER_SYSCALL_IMPL(setgid, SyscallPassthrough1<SYSCALL_DEF(setgid)>);
- REGISTER_SYSCALL_IMPL(geteuid, SyscallPassthrough0<SYSCALL_DEF(geteuid)>);
- REGISTER_SYSCALL_IMPL(getegid, SyscallPassthrough0<SYSCALL_DEF(getegid)>);
+ REGISTER_SYSCALL_IMPL(getgid, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>);
+ REGISTER_SYSCALL_IMPL(setuid, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>);
+ REGISTER_SYSCALL_IMPL(setgid, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>);
+ REGISTER_SYSCALL_IMPL(geteuid, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>);
+ REGISTER_SYSCALL_IMPL(getegid, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>);
REGISTER_SYSCALL_IMPL(setpgid, SyscallPassthrough2<SYSCALL_DEF(setpgid)>);
REGISTER_SYSCALL_IMPL(getppid, SyscallPassthrough0<SYSCALL_DEF(getppid)>);
REGISTER_SYSCALL_IMPL(setsid, SyscallPassthrough0<SYSCALL_DEF(setsid)>);
- REGISTER_SYSCALL_IMPL(setreuid, SyscallPassthrough2<SYSCALL_DEF(setreuid)>);
- REGISTER_SYSCALL_IMPL(setregid, SyscallPassthrough2<SYSCALL_DEF(setregid)>);
- REGISTER_SYSCALL_IMPL(getgroups, SyscallPassthrough2<SYSCALL_DEF(getgroups)>);
- REGISTER_SYSCALL_IMPL(setgroups, SyscallPassthrough2<SYSCALL_DEF(setgroups)>);
- REGISTER_SYSCALL_IMPL(setresuid, SyscallPassthrough3<SYSCALL_DEF(setresuid)>);
- REGISTER_SYSCALL_IMPL(getresuid, SyscallPassthrough3<SYSCALL_DEF(getresuid)>);
- REGISTER_SYSCALL_IMPL(setresgid, SyscallPassthrough3<SYSCALL_DEF(setresgid)>);
- REGISTER_SYSCALL_IMPL(getresgid, SyscallPassthrough3<SYSCALL_DEF(getresgid)>);
+ REGISTER_SYSCALL_IMPL(setreuid, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>);
+ REGISTER_SYSCALL_IMPL(setregid, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>);
+ REGISTER_SYSCALL_IMPL(getgroups, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>);
+ REGISTER_SYSCALL_IMPL(setgroups, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>);
+ REGISTER_SYSCALL_IMPL(setresuid, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>);
+ REGISTER_SYSCALL_IMPL(getresuid, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>);
+ REGISTER_SYSCALL_IMPL(setresgid, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>);
+ REGISTER_SYSCALL_IMPL(getresgid, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>);
REGISTER_SYSCALL_IMPL(getpgid, SyscallPassthrough1<SYSCALL_DEF(getpgid)>);
- REGISTER_SYSCALL_IMPL(setfsuid, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>);
- REGISTER_SYSCALL_IMPL(setfsgid, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>);
+ REGISTER_SYSCALL_IMPL(setfsuid, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>);
+ REGISTER_SYSCALL_IMPL(setfsgid, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>);
REGISTER_SYSCALL_IMPL(getsid, SyscallPassthrough1<SYSCALL_DEF(getsid)>);
REGISTER_SYSCALL_IMPL(capget, SyscallPassthrough2<SYSCALL_DEF(capget)>);
REGISTER_SYSCALL_IMPL(capset, SyscallPassthrough2<SYSCALL_DEF(capset)>);
@@ -537,23 +544,23 @@ namespace x64 {
namespace x32 {
void RegisterPassthrough(FEX::HLE::SyscallHandler* Handler) {
RegisterCommon(Handler);
- REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPassthrough0<SYSCALL_DEF(getuid)>);
- REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPassthrough0<SYSCALL_DEF(getgid)>);
- REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPassthrough0<SYSCALL_DEF(geteuid)>);
- REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPassthrough0<SYSCALL_DEF(getegid)>);
- REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPassthrough2<SYSCALL_DEF(setreuid)>);
- REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPassthrough2<SYSCALL_DEF(setregid)>);
- REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPassthrough2<SYSCALL_DEF(getgroups)>);
- REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPassthrough2<SYSCALL_DEF(setgroups)>);
- REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPassthrough3<SYSCALL_DEF(fchown)>);
- REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPassthrough3<SYSCALL_DEF(setresuid)>);
- REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPassthrough3<SYSCALL_DEF(getresuid)>);
- REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPassthrough3<SYSCALL_DEF(setresgid)>);
- REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPassthrough3<SYSCALL_DEF(getresgid)>);
- REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPassthrough1<SYSCALL_DEF(setuid)>);
- REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPassthrough1<SYSCALL_DEF(setgid)>);
- REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>);
- REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>);
+ REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>);
+ REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>);
+ REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>);
+ REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>);
+ REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>);
+ REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>);
+ REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>);
+ REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>);
+ REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>);
+ REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>);
+ REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>);
+ REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>);
+ REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>);
+ REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>);
+ REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>);
+ REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>);
+ REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>);
REGISTER_SYSCALL_IMPL_X32(sendfile64, SyscallPassthrough4<SYSCALL_DEF(sendfile)>);
REGISTER_SYSCALL_IMPL_X32(clock_gettime64, SyscallPassthrough2<SYSCALL_DEF(clock_gettime)>);
REGISTER_SYSCALL_IMPL_X32(clock_settime64, SyscallPassthrough2<SYSCALL_DEF(clock_settime)>);
-4
View File
@@ -31,9 +31,5 @@ for sym in vkNegotiateLoaderLayerInterfaceVersion vkGetInstanceProcAddr vkGetDev
grep -qx "$sym" <<<"$XCLIPSE" || { echo "::error::the Xclipse layer does not export $sym"; exit 1; }
done
test -f "$D/usr/local/lib/droiddeck-xclipse/VkLayer_droiddeck_xclipse.json"
LSE=$(syms "$D/usr/local/lib/droiddeck-lse/liblse_emu.so")
for sym in sigaction signal sigprocmask pthread_sigmask prctl syscall; do
grep -qx "$sym" <<<"$LSE" || { echo "::error::liblse_emu.so does not export $sym"; exit 1; }
done
test -f "$D/usr/local/bin/droiddeck-session"
test -f "$D/usr/local/bin/droiddeck-proton-extra"
+49 -2
View File
@@ -1,6 +1,7 @@
#!/usr/bin/python3
import os
import re
import shutil
HOME = os.environ.get("HOME", "/root")
SYSTEM_DIR = "/usr/share/applications"
@@ -9,6 +10,8 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application
USER_DIR = os.path.join(HOME, ".local/share/applications")
MARK = "X-DroidDeck-GPU=1"
SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I)
CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11"
def enabled():
@@ -24,6 +27,33 @@ def main_group(text):
return lines[:start + 1], lines[start + 1:end], lines[end:]
def split_program(exec_line):
if exec_line.startswith('"'):
end = exec_line.find('"', 1)
if end < 0:
return None, None
return exec_line[:end + 1], exec_line[end + 1:]
program, _, rest = exec_line.partition(" ")
return program, (" " + rest) if rest else ""
def chromium(exec_line):
program, _ = split_program(exec_line)
if not program:
return False
program = program.strip('"')
path = program if os.path.isabs(program) else shutil.which(program)
if not path:
return False
here = os.path.dirname(os.path.realpath(path))
return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here)))
def chromium_exec(exec_line):
program, rest = split_program(exec_line)
return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest
def gpu_exec(exec_line):
if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "):
exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1]
@@ -45,8 +75,24 @@ def wrap(text, gpu_on=True):
if not exec_line or exec_line.startswith("droiddeck-gpu "):
return None
cats = set(filter(None, keys.get("Categories", "").split(";")))
if not (gpu_on and cats & {"Game", "Emulator"}):
gpu = gpu_on and bool(cats & {"Game", "Emulator"})
browser = chromium(exec_line)
if not gpu and not browser:
return None
if browser:
exec_line = chromium_exec(exec_line)
if not gpu:
def fix(lines):
return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l
for l in lines]
out_group = fix(group)
while out_group and not out_group[-1].strip():
out_group.pop()
out_group.append(MARK)
out_rest = fix(rest)
if out_rest and out_rest[0].strip():
out_rest.insert(0, "")
return "\n".join(head + out_group + out_rest) + "\n"
out_group = []
actions = keys.get("Actions", "")
for l in group:
@@ -65,7 +111,8 @@ def wrap(text, gpu_on=True):
wrapped_rest = []
for l in rest:
if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "):
l = "Exec=" + gpu_exec(l[5:].strip())
action = l[5:].strip()
l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action)
wrapped_rest.append(l)
if wrapped_rest and wrapped_rest[0].strip():
wrapped_rest.insert(0, "")
-18
View File
@@ -1,18 +0,0 @@
# LSE-Emu
`lse_emu.c` is a copy of [SildurFX/LSE-Emu](https://github.com/SildurFX/LSE-Emu) at commit
`8bc9548ac6fd24a8d506b266b17ba8d0e71a9b01` (GPL-3.0-or-later) with two fixes, listed in
`docs/arm-v8.0-steam-client.md` under "Fixes over upstream": NZCV kept across the min/max
stubs, and a store-back on `CASP` mismatches so the returned pair is atomic. Carry them forward
until upstream has them.
It is an `LD_PRELOAD` library that emulates the ARMv8.1 LSE atomic instructions (and `LDAPR`)
on ARMv8.0 CPUs. A SIGILL handler performs each trapped instruction with an LL/SC loop. 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.
The session stages it as `/usr/local/lib/droiddeck-lse/liblse_emu.so` and only lists it in
`/etc/ld.so.preload` when `/proc/cpuinfo` has no `atomics` flag. See
`docs/arm-v8.0-steam-client.md` for why.
To update, copy `lse_emu.c` from a newer upstream commit and change the commit above.
-15
View File
@@ -1,15 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
D=${1:?asset directory}
CC=${CC:-aarch64-linux-gnu-gcc}
STRIP=${STRIP:-aarch64-linux-gnu-strip}
here=$(cd "$(dirname "$0")" && pwd)
out="$D/usr/local/lib/droiddeck-lse/liblse_emu.so"
mkdir -p "$(dirname "$out")"
"$CC" -shared -fPIC -O2 -march=armv8-a -mno-outline-atomics -Wall -Wextra -Wno-unused-parameter \
-Wl,-z,now,-z,max-page-size=65536 -o "$out" "$here/lse_emu.c" -ldl
"$STRIP" --strip-unneeded "$out"
disassembly=$("${OBJDUMP:-aarch64-linux-gnu-objdump}" -d "$out")
if grep -qE $'\t((ld|st)(add|clr|eor|set|smax|smin|umax|umin)|swp|cas)[a-z]*\t' <<<"$disassembly"; then
echo "::error::liblse_emu.so itself contains LSE instructions"; exit 1
fi
-768
View File
@@ -1,768 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// https://github.com/SildurFX/LSE-Emu
// Copyright (C) 2026 SildurFX
#define _GNU_SOURCE
#include <signal.h>
#include <ucontext.h>
#include <stdint.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/auxv.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#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)
if ((i & 0x3f200c00) == 0x38200000) { // LD<op>, SWP, LDAPR
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, 16 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(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((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);
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 64
#define MAX_ARENAS 256
#define REACH 0x7000000 // 112 MiB, safely inside the 128 MiB branch range
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 of pc by walking /proc/self/maps called with the patch lock held, so the static buffers are safe
static uintptr_t find_gap(uintptr_t pc, const uintptr_t *tr, int ntr) {
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;
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 ll = 0; long n;
while ((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') { if (ll < 511) line[ll++] = c; continue; }
line[ll] = 0; ll = 0;
const char *p = line;
uintptr_t s0 = hexv(&p); if (*p != '-') continue; p++;
uintptr_t e0 = hexv(&p);
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; // valid block start range
uintptr_t cand = pc & ~(uintptr_t)0xFFFF;
if (cand < rlo) cand = rlo;
if (cand > rhi) cand = rhi;
// skip blocks a previous mmap refused, walking outwards inside this hole
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;
}
sc(SYS_close, fd, 0, 0, 0, 0, 0);
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) return 0;
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;
}
return 0;
}
/* ---- known executable file-backed ranges (parsed from /proc/self/maps) ---- */
#define MAX_RANGES 512
static struct { uintptr_t lo, hi; } rng[MAX_RANGES];
static volatile int nrng;
static int misses;
static int in_ranges(uintptr_t pc) {
for (int k = 0; k < nrng; k++) if (pc >= rng[k].lo && pc < rng[k].hi) return 1;
return 0;
}
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 void parse_line(const char *p) {
unsigned long lo = hexv(&p); if (*p != '-') return; p++;
unsigned long hi = hexv(&p); if (*p != ' ') return; p++;
if (!(p[0] == 'r' && p[1] == '-' && p[2] == 'x' && p[3] == 'p')) return;
for (int f = 0; f < 4 && *p; f++) { while (*p && *p != ' ') p++; while (*p == ' ') p++; }
if (*p != '/') return;
if (nrng < MAX_RANGES) { rng[nrng].lo = lo; rng[nrng].hi = hi; nrng = nrng + 1; }
}
static void refresh_ranges(void) {
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;
nrng = 0;
int ll = 0; long n;
while ((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') { line[ll] = 0; parse_line(line); ll = 0; }
else if (ll < 511) line[ll++] = c;
}
sc(SYS_close, fd, 0, 0, 0, 0, 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]; static volatile int ns;
if (why[0] != 'p') { // only "patched" is logged every time
for (int k = 0; k < ns; k++) if (seen[k] == pc) return;
if (ns >= 256) return;
seen[ns] = pc; ns = ns + 1;
}
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 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) {
uintptr_t page = pc & ~(uintptr_t)4095;
if (sc(SYS_mprotect, page, 4096, 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);
sc(SYS_mprotect, page, 4096, PROT_READ | PROT_EXEC, 0, 0, 0);
return 0;
}
static void try_patch(uintptr_t pc, uint32_t insn) {
uint32_t w[16];
if (bad[(pc >> 2) & 255] == pc) return;
if (!gen(w, 0, 0, insn)) { logsite("unsupported-form", pc, insn); return; } // not a patchable form
if (!trylock()) return;
if (*(volatile uint32_t *)pc != insn) goto out; // already patched by another thread
if (!in_ranges(pc)) {
if (misses++ < 16) refresh_ranges();
if (!in_ranges(pc)) { logsite("not-file-backed", pc, insn); bad[(pc >> 2) & 255] = pc; 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 (patch_word(pc, b)) {
logsite("mprotect-failed", pc, insn);
bad[(pc >> 2) & 255] = pc; st_failed++; goto out;
}
st_patched++;
logsite("patched", pc, insn);
out:
unlock();
}
/* ======================= 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_valid;
static void * volatile app_h;
static volatile unsigned long app_f;
struct ksa { void *h; unsigned long f; void *restorer; uint64_t mask; };
int sigaction(int sig, const struct sigaction *act, struct sigaction *old) {
resolve();
if (!active || sig != SIGILL) return real_sigaction(sig, act, old);
if (old) {
memset(old, 0, sizeof *old);
if (app_valid) { old->sa_sigaction = app_h; old->sa_flags = (int)(app_f & ~(unsigned long)SA_RESTORER); }
else old->sa_handler = SIG_DFL;
}
if (act) { app_h = (void *)act->sa_sigaction; app_f = (unsigned long)act->sa_flags; app_valid = 1; }
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();
if (opt == PR_SET_SECCOMP) patch_enabled = 0;
return (int)real_syscall(SYS_prctl, (long)opt, a1, a2, a3, a4);
}
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
if (n == SYS_seccomp) patch_enabled = 0;
#endif
if (n == SYS_prctl && a[0] == PR_SET_SECCOMP) patch_enabled = 0;
if (n == SYS_rt_sigaction && a[0] == SIGILL) {
struct ksa *act = (struct ksa *)a[1], *old = (struct ksa *)a[2];
if (old) {
memset(old, 0, sizeof *old);
if (app_valid) { old->h = app_h; old->f = app_f; }
}
if (act) { app_h = act->h; app_f = act->f; app_valid = 1; }
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]);
}
}
return real_syscall(n, a[0], a[1], a[2], a[3], a[4], a[5]);
}
/* ======================= 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) {
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 (patch_enabled) 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);
void *h = app_h;
if (app_valid && h != (void *)SIG_DFL && h != (void *)SIG_IGN) {
if (app_f & SA_SIGINFO) ((void (*)(int, siginfo_t *, void *))h)(sig, si, ctx);
else ((void (*)(int))h)(sig);
return;
}
struct sigaction dfl; memset(&dfl, 0, sizeof dfl);
dfl.sa_handler = SIG_DFL;
real_sigaction(SIGILL, &dfl, NULL);
}
/* ======================= 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;
}
__attribute__((constructor)) static void init(void) {
resolve();
if (getauxval(AT_HWCAP) & HWCAP_ATOMICS) return; // CPU has real LSE
// Exit silently if LSE_EMU is missing or not set to "1"
const char *emu_env = getenv("LSE_EMU");
if (!emu_env || emu_env[0] != '1') {
return;
}
struct sigaction sa; memset(&sa, 0, sizeof sa);
sa.sa_sigaction = on_sigill;
sa.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_NODEFER;
sigemptyset(&sa.sa_mask);
real_sigaction(SIGILL, &sa, NULL);
active = 1;
const char *p = getenv("LSE_EMU_PATCH");
stats = getenv("LSE_EMU_STATS") != NULL;
if (p && p[0] == '1' && !skipped()) {
refresh_ranges();
patch_enabled = 1;
}
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);
}
@@ -45,20 +45,11 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
export QT_QPA_PLATFORM=xcb
fi
arch=$(cat "$dir/arch" 2>/dev/null)
if [ "$arch" = arm64 ]; then
find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \
-o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null |
while IFS= read -r lib; do
kept=$dir/bundled-gl/${lib#"$APPDIR"/}
mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one"
done
fi
fex=$(cat "$dir/fex" 2>/dev/null)
case $fex in on|off) ;; *) fex=auto ;; esac
run=("$APPDIR/AppRun")
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $fex:$arch in
case $fex:$(cat "$dir/arch" 2>/dev/null) in
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
auto:arm64) ;;
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
@@ -51,7 +51,7 @@ PROVIDED = frozenset((
"libssl.so.3", "libcrypto.so.3",
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
))
PROVIDED_NEEDS = {
"libwayland-client.so.0": ("libffi.so.8",),
@@ -670,8 +670,6 @@ def guest_environment(fex, env):
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
result.pop("GLIBC_TUNABLES", None)
if "aarch64" in result.get("GCONV_PATH", ""):
result["GCONV_PATH"] = ""
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
@@ -11,10 +11,6 @@ if [ "${DD_RAISE_NOFILE:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ]; then
unset dd_nofile_was
fi
export HOME=${HOME:-/root}
if grep -qs '/liblse_emu\.so$' /etc/ld.so.preload; then
export LSE_EMU=1 LSE_EMU_PATCH=${LSE_EMU_PATCH:-1}
[ -n "${DD_DEBUG_DIR:-}" ] && export LSE_EMU_LOG=${LSE_EMU_LOG:-$DD_DEBUG_DIR/lse_emu.log}
fi
mode=${1:-desktop}
shift || true
step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; }
@@ -34,7 +30,6 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then
echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
[ "${LSE_EMU:-}" = 1 ] && echo "== cpu: no LSE atomics (ARMv8.0); liblse_emu.so emulates them (log: ${LSE_EMU_LOG:-off})"
fi
start_diagnostic_inventory() {
@@ -65,14 +65,12 @@ if [ -n "$repair" ]; then
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
cache_only=
[ "${1:-}" = --cache ] && cache_only=1
sync=
if [ "${1:-}" = --sync ]; then
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
manifest=steam_client_${sync}_linuxarm64
fi
[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
@@ -169,46 +167,6 @@ if ! fetch_manifest; then
fallback=1
fetch_manifest || exit 1
fi
if [ -n "$cache_only" ]; then
cache=$steam_root/package
cached=$cache/droiddeck-cached
[ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0
awk -F'"' '
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
$2 == "size" { size[block] = $4 }
$2 == "zipvz" { vz[block] = $4 }
$2 == "sha2vz" { vzsha[block] = $4 }
END {
for (b in file) {
f = file[b]; h = sha[b]; n = size[b] + 0
if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 }
print b, f, h, n
}
}
' "$work/manifest" | sort > "$work/cache"
mkdir -p "$cache"
total=$(grep -c . "$work/cache" 2>/dev/null || echo 0)
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache")
done_bytes=0
i=0
while read -r block file sum size; do
i=$((i + 1))
progress "$cache/$file" "$block"
fetched=""
for host in "${cdn_order[@]}"; do
if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then
fetched=$host
break
fi
done
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
done_bytes=$((done_bytes + size))
done < "$work/cache"
echo "$version" > "$cached"
exit 0
fi
if [ -n "$sync" ]; then
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
@@ -10,7 +10,6 @@ import tempfile
DISPLAY = "External: gamescope|||Windowed"
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver")
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
@@ -138,10 +137,6 @@ def seed_no_screensaver_in_game(text):
return seed_value(text, SCREENSAVER_IN_GAME, '0')
def seed_bouncing_logo(text):
return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo')
def atomic_write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
@@ -184,11 +179,6 @@ def initialize_screensaver(steam_root):
'== steam: no screensaver over a running game')
def initialize_screensaver_choice(steam_root):
return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo,
'== steam: bouncing logo screensaver')
if __name__ == '__main__':
status = 0
try:
@@ -196,7 +186,7 @@ if __name__ == '__main__':
except (OSError, ValueError, RecursionError) as error:
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
status = 1
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)):
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
try:
step(sys.argv[1])
except (OSError, ValueError, RecursionError) as error:
+21 -38
View File
@@ -21,29 +21,6 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size) {
if (!file || !*file) return 0;
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
const char *paths = getenv("PATH");
if (!paths) paths = "/bin:/usr/bin";
char candidate[PATH_MAX];
int found = 0;
for (const char *p = paths;; ) {
const char *end = strchrnul(p, ':');
int n = end > p ? snprintf(candidate, sizeof candidate, "%.*s/%s", (int)(end - p), p, file)
: snprintf(candidate, sizeof candidate, "%s", file);
struct stat st;
if (n > 0 && n < (int)sizeof candidate && n < (int)size && stat(candidate, &st) == 0 && S_ISREG(st.st_mode)) {
int runs = access(candidate, X_OK) == 0;
if (runs || !found) memcpy(out, candidate, (size_t)n + 1);
found = 1;
if (runs) return 1;
}
if (!*end) return found;
p = end + 1;
}
}
#if defined(__aarch64__) || defined(BINFMT_TEST)
static int flag(const char *name) {
@@ -55,26 +32,17 @@ static int handing_off(void) {
return flag("DD_DESKTOP") || flag("DD_BINFMT");
}
static int appimage(int fd, const unsigned char *head, ssize_t n) {
Elf64_Ehdr eh;
if (n < (ssize_t)sizeof eh || head[EI_CLASS] != ELFCLASS64 || memcmp(head + EI_ABIVERSION, "AI\x02", 3)) return 0;
memcpy(&eh, head, sizeof eh);
char magic[6];
off_t at = (off_t)eh.e_shoff + (off_t)eh.e_shentsize * eh.e_shnum;
return pread(fd, magic, sizeof magic, at) == (ssize_t)sizeof magic && (!memcmp(magic, "hsqs", 4) || !memcmp(magic, "DWARFS", 6));
}
static int foreign(const char *path, int error) {
if (!path || !strcmp(path, BINFMT_HANDLER)) return 0;
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
struct stat st;
unsigned char head[sizeof(Elf64_Ehdr)];
unsigned char head[20];
ssize_t n = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) ? read(fd, head, sizeof head) : -1;
int kind = 0;
if (n >= 20 && !memcmp(head, ELFMAG, SELFMAG)) {
unsigned machine = head[EI_DATA] == ELFDATA2MSB ? (unsigned)head[18] << 8 | head[19] : head[18] | (unsigned)head[19] << 8;
kind = machine == EM_X86_64 || machine == EM_386 || appimage(fd, head, n) || error == EACCES ? 1 : 0;
kind = machine == EM_X86_64 || machine == EM_386 || error == EACCES ? 1 : 0;
} else if (n >= 2 && head[0] == 'M' && head[1] == 'Z') {
kind = 2;
} else if (n >= 2 && head[0] == '#' && head[1] == '!' && error == EACCES) {
@@ -90,6 +58,21 @@ static int wanted(const char *path, int error) {
return (error == ENOEXEC || error == ENOENT || error == EACCES) && handing_off() && foreign(path, error);
}
static int lookup(const char *file, char *out, size_t size) {
if (!file || !*file) return 0;
if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size;
const char *paths = getenv("PATH");
if (!paths) paths = "/bin:/usr/bin";
for (const char *p = paths;; ) {
const char *end = strchrnul(p, ':');
int n = end > p ? snprintf(out, size, "%.*s/%s", (int)(end - p), p, file) : snprintf(out, size, "%s", file);
struct stat st;
if (n > 0 && n < (int)size && stat(out, &st) == 0 && S_ISREG(st.st_mode)) return 1;
if (!*end) return 0;
p = end + 1;
}
}
static int count(char *const argv[]) {
int n = 0;
while (argv && argv[n]) n++;
@@ -134,12 +117,12 @@ __attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char
__attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) {
char path[PATH_MAX];
if (handing_off() && dd_program_lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
if (handing_off() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp);
}
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) {
char path[PATH_MAX];
if (handing_off() && dd_program_lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
if (handing_off() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error);
errno = error;
return -1;
}
@@ -161,7 +144,7 @@ __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char
int execvpe(const char *file, char *const argv[], char *const envp[]) {
char resolved[PATH_MAX];
const char *path = dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file;
const char *path = lookup(file, resolved, sizeof resolved) ? resolved : file;
char *const *adjusted = dd_webhelper_argv(path, argv, envp);
static int (*real)(const char *, char *const[], char *const[]);
if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execvpe");
@@ -173,7 +156,7 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) {
int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr,
char *const argv[], char *const envp[]) {
char path[PATH_MAX];
int found = dd_program_lookup(file, path, sizeof path);
int found = lookup(file, path, sizeof path);
char *const *adjusted = dd_webhelper_argv(found ? path : file, argv, envp);
static spawn_fn real, spawn;
if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp");
+1 -3
View File
@@ -277,7 +277,6 @@ __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *f
__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error);
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]);
__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size);
__attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[],
spawn_fn real);
@@ -378,8 +377,7 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi
}
int execvp(const char *file, char *const argv_in[]) {
char resolved[PATH_MAX];
char *const *argv = dd_webhelper_argv(dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file, argv_in, environ);
char *const *argv = dd_webhelper_argv(file, argv_in, environ);
static int (*real)(const char *, char *const[]);
if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp");
maybe_answer_lsof(file, argv);
+5 -192
View File
@@ -29,8 +29,6 @@
#define VDEC_BITSTREAM_SIZE (4u << 20)
#define VDEC_PADDING 64
#define VDEC_DUMB 64
#define VDEC_CAP_MIN_WIDTH 4096u
#define VDEC_CAP_MIN_HEIGHT 2304u
struct vd_dma_heap_alloc {
uint64_t len;
@@ -137,8 +135,6 @@ struct vdec {
uint32_t n_cap_done;
int out_on, cap_on;
int sock, hw, hw_failed;
int resizing;
uint32_t stream_w, stream_h;
int64_t pts;
void *ctx, *packet, *frame;
uint8_t *packet_data;
@@ -322,8 +318,7 @@ static int vd_open_hardware(struct vdec *v) {
if (sock < 0) return -1;
struct vdec_config c = {
.type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
.width = v->stream_w ? v->stream_w : v->width ? v->width : v->cap_width,
.height = v->stream_h ? v->stream_h : v->height ? v->height : v->cap_height,
.width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height,
.stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE,
};
struct vdec_result r;
@@ -568,12 +563,8 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
t.fourcc = p->pixelformat;
t.width = p->width;
t.height = p->height;
t.stream_w = p->width;
t.stream_h = p->height;
} else {
uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height;
if (w < VDEC_CAP_MIN_WIDTH) w = VDEC_CAP_MIN_WIDTH;
if (h < VDEC_CAP_MIN_HEIGHT) h = VDEC_CAP_MIN_HEIGHT;
if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL;
t.cap_width = (w + 15) & ~15u;
t.cap_height = (h + 15) & ~15u;
@@ -583,7 +574,6 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
if (apply) {
if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t);
*v = t;
if (v->cap_width >= v->width && v->cap_height >= v->height) v->resizing = 0;
}
vd_fill_format(&t, f);
return 0;
@@ -625,184 +615,13 @@ static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) {
return 0;
}
struct vd_bits {
const uint8_t *data;
size_t size, pos;
};
static uint32_t vd_get_bits(struct vd_bits *b, unsigned count) {
uint32_t value = 0;
while (count--) {
size_t byte = b->pos >> 3;
value = value << 1 | (byte < b->size ? (b->data[byte] >> (7 - (b->pos & 7))) & 1u : 0u);
b->pos++;
}
return value;
}
static uint32_t vd_get_ue(struct vd_bits *b) {
unsigned zeros = 0;
while (zeros < 32 && vd_get_bits(b, 1) == 0 && (b->pos >> 3) < b->size) zeros++;
if (zeros >= 32) return 0;
return ((1u << zeros) - 1) + (zeros ? vd_get_bits(b, zeros) : 0);
}
static int32_t vd_get_se(struct vd_bits *b) {
uint32_t k = vd_get_ue(b);
return (k & 1) ? (int32_t)((k + 1) / 2) : -(int32_t)(k / 2);
}
static int vd_skip_scaling_list(struct vd_bits *b, unsigned size) {
int32_t last = 8, next = 8;
for (unsigned i = 0; i < size; i++) {
if (next != 0) {
int32_t delta = vd_get_se(b);
if (delta < -128 || delta > 127) return -1;
next = (last + delta + 256) % 256;
}
last = next == 0 ? last : next;
}
return 0;
}
/* The coded size an H.264 SPS announces, rounded up to whole macroblocks, as a V4L2 decoder reports it. */
static int vd_parse_sps_h264(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
uint8_t buf[512];
size_t n = 0;
for (size_t i = 0; i < size && n < sizeof buf; i++) {
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
buf[n++] = rbsp[i];
}
struct vd_bits b = { buf, n, 0 };
uint32_t profile = vd_get_bits(&b, 8);
vd_get_bits(&b, 16);
vd_get_ue(&b);
uint32_t chroma = 1;
if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 ||
profile == 86 || profile == 118 || profile == 128 || profile == 138 || profile == 139 || profile == 134 || profile == 135) {
chroma = vd_get_ue(&b);
if (chroma == 3) vd_get_bits(&b, 1);
vd_get_ue(&b);
vd_get_ue(&b);
vd_get_bits(&b, 1);
if (vd_get_bits(&b, 1)) {
for (unsigned i = 0; i < (chroma != 3 ? 8u : 12u); i++)
if (vd_get_bits(&b, 1) && vd_skip_scaling_list(&b, i < 6 ? 16 : 64) != 0) return -1;
}
}
vd_get_ue(&b);
uint32_t poc = vd_get_ue(&b);
if (poc == 0) {
vd_get_ue(&b);
} else if (poc == 1) {
vd_get_bits(&b, 1);
vd_get_se(&b);
vd_get_se(&b);
uint32_t cycle = vd_get_ue(&b);
for (uint32_t i = 0; i < cycle && i < 256; i++) vd_get_se(&b);
}
vd_get_ue(&b);
vd_get_bits(&b, 1);
uint32_t mbs_wide = vd_get_ue(&b) + 1, map_units_high = vd_get_ue(&b) + 1;
if (b.pos > b.size * 8 || mbs_wide > 1024 || map_units_high > 1024) return -1;
uint32_t frame_mbs_only = vd_get_bits(&b, 1);
if (b.pos > b.size * 8) return -1;
*width = mbs_wide * 16;
*height = map_units_high * 16 * (2 - frame_mbs_only);
return 0;
}
/* Finds the first SPS in an Annex B access unit; returns its size in the stream through the out parameters. */
static int vd_stream_size_h264(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
for (size_t i = 0; i + 4 < size; i++) {
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || (data[i + 3] & 0x1f) != 7) continue;
size_t start = i + 4, end = start;
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
if (end + 2 >= size) end = size;
return vd_parse_sps_h264(data + start, end - start, width, height);
}
return -1;
}
/* The same for an H.265 SPS: the luma size in samples, rounded up to 16 as the client asks for it. */
static int vd_parse_sps_h265(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
uint8_t buf[512];
size_t n = 0;
for (size_t i = 0; i < size && n < sizeof buf; i++) {
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
buf[n++] = rbsp[i];
}
struct vd_bits b = { buf, n, 0 };
vd_get_bits(&b, 4);
uint32_t sub_layers = vd_get_bits(&b, 3);
vd_get_bits(&b, 1);
for (unsigned i = 0; i < 88; i += 8) vd_get_bits(&b, 8);
vd_get_bits(&b, 8);
uint32_t profile_present = 0, level_present = 0;
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
profile_present |= vd_get_bits(&b, 1) << i;
level_present |= vd_get_bits(&b, 1) << i;
}
if (sub_layers > 0) for (uint32_t i = sub_layers; i < 8; i++) vd_get_bits(&b, 2);
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
if (profile_present >> i & 1) for (unsigned k = 0; k < 88; k += 8) vd_get_bits(&b, 8);
if (level_present >> i & 1) vd_get_bits(&b, 8);
}
vd_get_ue(&b);
if (vd_get_ue(&b) == 3) vd_get_bits(&b, 1);
uint32_t w = vd_get_ue(&b), h = vd_get_ue(&b);
if (b.pos > b.size * 8 || w < 16 || h < 16 || w > 16384 || h > 16384) return -1;
*width = (w + 15) & ~15u;
*height = (h + 15) & ~15u;
return 0;
}
static int vd_stream_size_h265(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
for (size_t i = 0; i + 5 < size; i++) {
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || ((data[i + 3] >> 1) & 0x3f) != 33) continue;
size_t start = i + 5, end = start;
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
if (end + 2 >= size) end = size;
return vd_parse_sps_h265(data + start, end - start, width, height);
}
return -1;
}
/*
* A stream can change its picture size without telling the client: the host switches games or the window
* becomes fullscreen. A V4L2 decoder reports the new size through the format of its bitstream queue, which
* the client polls; the capture buffers it already allocated stay at the old size until it reconfigures.
*/
static int vd_follow_stream_size(struct vdec *v, const uint8_t *data, size_t size) {
uint32_t width, height;
int found = v->fourcc == V4L2_PIX_FMT_HEVC ? vd_stream_size_h265(data, size, &width, &height)
: vd_stream_size_h264(data, size, &width, &height);
if (found != 0) return 0;
uint32_t known_w = v->stream_w ? v->stream_w : v->width, known_h = v->stream_h ? v->stream_h : v->height;
if (width == known_w && height == known_h) return 0;
vd_log("the stream is now %ux%u, was %ux%u", width, height, known_w, known_h);
if (width <= v->cap_width && height <= v->cap_height) {
/* The client's capture buffers already hold the new size, so only the app decoder is reopened for it. */
v->stream_w = width;
v->stream_h = height;
if (v->hw) vd_close_decoder(v);
return 1;
}
v->width = v->stream_w = width;
v->height = v->stream_h = height;
v->resizing = 1;
v->n_cap_done = 0;
return 1;
}
static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL;
uint32_t bytes = b->m.planes[0].bytesused;
if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE;
if (v->out_on && v->bitstream && bytes) vd_follow_stream_size(v, v->bitstream + (size_t)b->index * VDEC_BITSTREAM_SIZE, bytes);
if (v->out_on && bytes && !v->resizing) vd_decode(v, b->index, bytes, b->timestamp);
if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp);
v->out_done[v->n_out_done++] = b->index;
} else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL;
@@ -833,15 +652,9 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) {
return 0;
}
if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
struct vd_done d;
for (;;) {
if (v->n_cap_done == 0) return -EAGAIN;
d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
struct stat st;
struct vd_capture *c = &v->cap[d.index];
if (c->map && c->fd >= 0 && fstat(c->fd, &st) == 0 && st.st_ino == c->ino) break;
}
if (v->n_cap_done == 0) return -EAGAIN;
struct vd_done d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
b->index = d.index;
b->memory = V4L2_MEMORY_DMABUF;
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY;
+24 -67
View File
@@ -26,83 +26,40 @@ static char *join_features(const char *have, const char *add) {
return strcat(out, add);
}
static const char *env_value(char *const envp[], const char *variable) {
size_t n = strlen(variable);
for (int i = 0; envp && envp[i]; i++)
if (!strncmp(envp[i], variable, n) && envp[i][n] == '=') return envp[i] + n + 1;
return NULL;
}
static int electron_node_mode(char *const envp[]) {
const char *mode = env_value(envp, "ELECTRON_RUN_AS_NODE");
return mode && *mode;
static const char variable[] = "ELECTRON_RUN_AS_NODE=";
for (int i = 0; envp && envp[i]; i++)
if (!strncmp(envp[i], variable, sizeof variable - 1))
return envp[i][sizeof variable - 1] != 0;
return 0;
}
static int beside_chrome_sandbox(const char *path) {
char *real = realpath(path, NULL);
if (!real) return 0;
int found = 0;
for (int up = 0; up < 2 && !found; up++) {
char *slash = strrchr(real, '/');
if (!slash) break;
*slash = 0;
size_t dir = strlen(real);
char *sandbox = malloc(dir + sizeof "/chrome-sandbox");
if (!sandbox) break;
memcpy(sandbox, real, dir);
strcpy(sandbox + dir, "/chrome-sandbox");
found = access(sandbox, F_OK) == 0;
free(sandbox);
}
free(real);
return found;
}
static char *folder_of(const char *path) {
char *real = realpath(path, NULL);
char *slash = real ? strrchr(real, '/') : NULL;
if (slash) *slash = 0;
return real;
}
static int started_by_its_own_app(const char *path) {
char self[4096];
ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
if (n <= 0) return 0;
self[n] = 0;
char *mine = folder_of(self), *theirs = folder_of(path);
int same = mine && theirs && !strcmp(mine, theirs) && beside_chrome_sandbox(self);
free(mine);
free(theirs);
return same;
}
static char *const *chromium_argv(const char *path, char *const argv[], char *const envp[]) {
if (!path || !argv || !argv[0]) return argv;
int argc = 0, sandbox = 1, ozone = 0;
for (; argv[argc]; argc++) {
if (!argc) continue;
if (!strncmp(argv[argc], "--type=", 7)) return argv;
if (!strcmp(argv[argc], "--no-sandbox")) sandbox = 0;
if (!strncmp(argv[argc], "--ozone-platform=", 17)) ozone = 1;
}
const char *display = env_value(envp, "DISPLAY");
int x11 = !ozone && display && *display;
if ((!sandbox && !x11) || !beside_chrome_sandbox(path) || started_by_its_own_app(path)) return argv;
char **out = calloc((size_t)argc + 3, sizeof *out);
static char *const *chromium_argv(const char *path, char *const argv[]) {
const char *slash = path ? strrchr(path, '/') : NULL;
if (!slash || !argv || !argv[0]) return argv;
int argc = 0;
for (; argv[argc]; argc++)
if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv;
size_t dir = (size_t)(slash - path) + 1;
char *sandbox = malloc(dir + sizeof "chrome-sandbox");
if (!sandbox) return argv;
memcpy(sandbox, path, dir);
strcpy(sandbox + dir, "chrome-sandbox");
int chromium = access(sandbox, F_OK) == 0;
free(sandbox);
if (!chromium) return argv;
char **out = calloc((size_t)argc + 2, sizeof *out);
if (!out) return argv;
int n = 0;
out[n++] = argv[0];
if (sandbox) out[n++] = (char *)"--no-sandbox";
if (x11) out[n++] = (char *)"--ozone-platform=x11";
for (int i = 1; i < argc; i++) out[n++] = argv[i];
out[0] = argv[0];
out[1] = (char *)"--no-sandbox";
for (int i = 1; i < argc; i++) out[i + 1] = argv[i];
return out;
}
__attribute__((visibility("hidden")))
char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]) {
if (electron_node_mode(envp)) return argv;
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv, envp);
if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv);
const char *spec = getenv("DD_WEBHELPER_ARGS");
if (!spec || !*spec) spec = WEBHELPER_DEFAULT;
if (!strcmp(spec, "stock")) return argv;
-1
View File
@@ -41,7 +41,6 @@
#include <elf.h>
#include <sys/sendfile.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sched.h>
#include <time.h>
#include <sys/xattr.h>
+2 -2
View File
@@ -476,7 +476,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
return -1;
}
int ret;
if (is_host_interpreter(interp, rewritten_interp)) {
if (is_host_interpreter(rewritten_interp)) {
char **sys_env = clean_env_for_system(envp);
ret = run_execve(orig_execve, rewritten_interp, new_argv, sys_env);
int saved_errno = errno;
@@ -829,7 +829,7 @@ static int spawn_script(pid_t *pid, const char *script, struct exec_probe *probe
char **new_argv = build_script_argv(rewritten_interp, interp_arg, script, argv);
if (!new_argv) return ENOMEM;
int ret;
if (is_host_interpreter(interp, rewritten_interp)) {
if (is_host_interpreter(rewritten_interp)) {
orig_posix_spawn_f_type orig_posix_spawn = real_posix_spawn();
char **sys_env = clean_env_for_system(envp);
ret = orig_posix_spawn ? orig_posix_spawn(pid, rewritten_interp, file_actions, attrp, new_argv, sys_env) : ENOSYS;
+4 -15
View File
@@ -10,13 +10,6 @@
// PT_INTERP) literally and failed with "bad interpreter: No such file or directory".
// getcwd() is not virtualised, so cwd + path is a real path that starts with DDNATV_ROOT.
static const char *absolutize_exec_path(const char *path, char *buffer, size_t bufsize) {
if (is_proc_self_exe(path)) {
ssize_t n = handle_proc_self_exe(buffer, bufsize - 1);
if (n > 0 && buffer[0] == '/') {
buffer[n] = '\0';
return buffer;
}
}
if (!path || path[0] == '\0' || path[0] == '/') return path;
char cwd[PATH_MAX];
static char *(*real_getcwd)(char *, size_t) = NULL;
@@ -973,14 +966,10 @@ static void parse_shebang(char *hdr, char **interp, char **interp_arg) {
*interp_arg = arg;
}
// Interpreters outside the rootfs and its binds (Android's /system/bin/sh) run with Android's environment.
static int is_host_interpreter(const char *interp, const char *rewritten) {
if (strncmp(rewritten, "/system", 7) == 0) return 1;
if (g_ddnatv_root[0] == '\0' || get_rootfs_subpath(rewritten)) return 0;
if (!is_mapped_guest_path(interp)) return 1;
struct exec_probe probe;
probe_exec_file(rewritten, &probe);
return probe.android_interp;
// Interpreters outside the rootfs (Android's /system/bin/sh) run with Android's environment.
static int is_host_interpreter(const char *interp) {
return strncmp(interp, "/system", 7) == 0 ||
(g_ddnatv_root[0] != '\0' && strncmp(interp, g_ddnatv_root, g_ddnatv_root_len) != 0);
}
// argv for running `script` with its interpreter: interp [arg] script args... (the script's own
+1 -1
View File
@@ -21,7 +21,7 @@ int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (voi
int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; }
int getgroups(int size, gid_t list[]) {
if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1;
if (size > 0 && list != NULL) list[0] = 0;
return 1;
}
// What programs built with _FORTIFY_SOURCE call when the buffer's size is known (the check is
+21 -61
View File
@@ -82,7 +82,7 @@ static void ddnatv_load_binds(const char *spec) {
char kernel_src[PATH_MAX];
if (strcmp(src, dst) != 0) {
ddnatv_kernel_path(src, strlen(src), kernel_src, sizeof(kernel_src));
if (strncmp(kernel_src, "/proc/", 6) != 0 || kernel_src[6] < '0' || kernel_src[6] > '9') src = kernel_src;
src = kernel_src;
}
b->src = strdup(src);
b->dst = strdup(dst);
@@ -188,25 +188,6 @@ static __thread int t_bind_link_depth = 0;
static void normalize_path(char *path);
static int climbs_past_root(const char *dir, const char *target) {
long depth = 0;
for (const char *p = dir; *p; p++)
if (*p != '/' && (p == dir || p[-1] == '/')) depth++;
for (const char *p = target; *p;) {
while (*p == '/') p++;
const char *end = p;
while (*end && *end != '/') end++;
size_t len = (size_t)(end - p);
if (len == 2 && p[0] == '.' && p[1] == '.') {
if (--depth < 0) return 1;
} else if (len > 0 && !(len == 1 && p[0] == '.')) {
depth++;
}
p = end;
}
return 0;
}
#if defined(__aarch64__)
static long raw_link_dir(const char *link, char *out, size_t size) {
const char *slash = strrchr(link, '/');
@@ -234,6 +215,25 @@ static long raw_link_dir(const char *link, char *out, size_t size) {
return n;
}
static int climbs_past_root(const char *dir, const char *target) {
long depth = 0;
for (const char *p = dir; *p; p++)
if (*p != '/' && (p == dir || p[-1] == '/')) depth++;
for (const char *p = target; *p;) {
while (*p == '/') p++;
const char *end = p;
while (*end && *end != '/') end++;
size_t len = (size_t)(end - p);
if (len == 2 && p[0] == '.' && p[1] == '.') {
if (--depth < 0) return 1;
} else if (len > 0 && !(len == 1 && p[0] == '.')) {
depth++;
}
p = end;
}
return 0;
}
static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int *converted);
static const char *guest_path_of_host_dir(const char *dir, char *out, size_t size) {
@@ -335,15 +335,6 @@ static const char *resolve_drive_links(const char *host, char *buffer, size_t bu
// Maps an absolute Ubuntu path into the rootfs. Returns `path` (possibly advanced past
// redundant leading "/" and "/." components) when it needs no change, else `buffer`.
static const char *rewrite_normalized_in_root(const char *path, char *buffer, size_t bufsize) {
char normalized[PATH_MAX];
ddnatv_copy_cstr(normalized, sizeof(normalized), path);
normalize_path(normalized);
const char *mapped = rewrite_path_in_root(normalized, buffer, bufsize);
if (mapped != buffer) ddnatv_copy_cstr(buffer, bufsize, mapped);
return buffer;
}
static const char *rewrite_path_in_root(const char *path, char *buffer, size_t bufsize) {
if (!path) return NULL;
if (path[0] != '/' || g_ddnatv_root_len == 0) return path;
@@ -363,8 +354,6 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
}
}
if (strstr(path, "/..") && climbs_past_root("", path)) return rewrite_normalized_in_root(path, buffer, bufsize);
// Root directory
if (path[1] == '\0') {
ddnatv_append(buffer, bufsize, 0, g_ddnatv_root, g_ddnatv_root_len);
@@ -375,8 +364,6 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
const struct ddnatv_bind *b = &g_binds[i];
if (path[1] == b->dst[1] && is_path_prefix(path, b->dst, b->dst_len)) {
if (b->identity) return path;
if (strstr(path + b->dst_len, "/..") && climbs_past_root("", path + b->dst_len))
return rewrite_normalized_in_root(path, buffer, bufsize);
size_t n = ddnatv_append(buffer, bufsize, 0, b->src, b->src_len);
ddnatv_append(buffer, bufsize, n, path + b->dst_len, strlen(path + b->dst_len));
return resolve_bind_links(buffer, b->src_len, buffer, bufsize);
@@ -819,36 +806,10 @@ static void ddnatv_build_at_dirs(void) {
}
}
#if defined(__aarch64__)
static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t size) {
char link[32], host[PATH_MAX], dir_buf[PATH_MAX], guest[PATH_MAX];
if (dirfd == AT_FDCWD) ddnatv_copy_cstr(link, sizeof(link), "/proc/self/cwd");
else snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd);
long n = raw_readlinkat(AT_FDCWD, link, host, sizeof(host) - 1);
if (n <= 0 || host[0] != '/') return NULL;
host[n] = '\0';
const char *dir = guest_path_of_host_dir(host, dir_buf, sizeof(dir_buf));
if (!dir || strcmp(dir, host) == 0) return NULL;
if (get_rootfs_subpath(host) && !climbs_past_root(dir, rel)) return NULL;
size_t used = ddnatv_append(guest, sizeof(guest), 0, dir, strlen(dir));
used = ddnatv_append(guest, sizeof(guest), used, "/", 1);
used = ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel));
if (used + 1 >= sizeof(guest)) return NULL;
const char *mapped = rewrite_path_in_root(guest, buf, size);
if (mapped != buf) ddnatv_copy_cstr(buf, size, mapped);
return buf;
}
#endif
// The absolute host path for `rel` given relative to `dirfd`, or NULL when the call needs no change.
static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) {
#if defined(__aarch64__)
if (!rel || rel[0] == '\0' || rel[0] == '/') return NULL;
if (strstr(rel, "..")) {
const char *walked = map_parent_walk(dirfd, rel, buf, size);
if (walked || dirfd == AT_FDCWD) return walked;
}
if (dirfd == AT_FDCWD || g_nbinds == 0) return NULL;
if (dirfd == AT_FDCWD || !rel || rel[0] == '\0' || rel[0] == '/' || g_nbinds == 0) return NULL;
pthread_once(&g_at_once, ddnatv_build_at_dirs);
if (g_n_at_dirs == 0) return NULL;
struct stat st;
@@ -857,7 +818,6 @@ static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) {
if (g_at_dirs[i].ino != (unsigned long)st.st_ino || g_at_dirs[i].dev != (unsigned long)st.st_dev) continue;
char guest[PATH_MAX];
const char *base = g_at_dirs[i].guest;
if (base[1] && climbs_past_root(base, rel)) return NULL;
size_t used = ddnatv_append(guest, sizeof(guest), 0, base, strlen(base));
if (used > 1) used = ddnatv_append(guest, sizeof(guest), used, "/", 1);
ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel));
+9 -125
View File
@@ -1,148 +1,32 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c.
//
// shm_open(), shm_unlink() and the named semaphores of glibc open /dev/shm/NAME with system calls
// of their own, which the path hooks never see and Android has no /dev/shm for. They go through
// open(), renameat2() and unlink() here, which map /dev/shm.
// shm_open() and shm_unlink() of glibc open /dev/shm/NAME with a system call of their own, which
// the path hooks never see and Android has no /dev/shm for. They go through open() and unlink()
// here, which map /dev/shm.
#ifndef DDNATV_HOST_TEST
static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) {
static int posix_shm_path(const char *name, char *path, size_t size) {
if (!name) { errno = EINVAL; return -1; }
while (*name == '/') name++;
size_t len = strlen(name) + strlen(prefix);
if (len == strlen(prefix) || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
size_t len = strlen(name);
if (len == 0 || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL;
return -1;
}
if (snprintf(path, size, "/dev/shm/%s%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
if (snprintf(path, size, "/dev/shm/%s", name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
return 0;
}
int shm_open(const char *name, int oflag, mode_t mode) {
char path[PATH_MAX];
if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1;
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
return open(path, (oflag & (O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) | O_NOFOLLOW | O_CLOEXEC, mode);
}
int shm_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1;
return unlink(path);
}
struct posix_sem {
dev_t dev;
ino_t ino;
sem_t *addr;
unsigned int refs;
struct posix_sem *next;
};
static struct posix_sem *g_posix_sems;
static pthread_mutex_t g_posix_sems_lock = PTHREAD_MUTEX_INITIALIZER;
static void posix_sems_unlock(void) { pthread_mutex_unlock(&g_posix_sems_lock); }
static void posix_sems_hold(void) { pthread_mutex_lock(&g_posix_sems_lock); }
__attribute__((constructor)) static void posix_sems_across_fork(void) {
pthread_atfork(posix_sems_hold, posix_sems_unlock, posix_sems_unlock);
}
static void close_keeping_errno(int fd) {
int saved = errno;
close(fd);
errno = saved;
}
static sem_t *posix_sem_map(int fd) {
struct stat st;
if (fstat(fd, &st) < 0) return SEM_FAILED;
sem_t *sem = SEM_FAILED;
posix_sems_hold();
struct posix_sem *e = g_posix_sems;
while (e && (e->dev != st.st_dev || e->ino != st.st_ino)) e = e->next;
if (e) {
e->refs++;
sem = e->addr;
} else {
void *addr = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
e = addr == MAP_FAILED ? NULL : malloc(sizeof(*e));
if (e) {
*e = (struct posix_sem){st.st_dev, st.st_ino, addr, 1, g_posix_sems};
g_posix_sems = e;
sem = addr;
} else if (addr != MAP_FAILED) {
munmap(addr, sizeof(sem_t));
errno = ENOMEM;
}
}
posix_sems_unlock();
return sem;
}
static sem_t *posix_sem_open_fd(int fd) {
if (fd < 0) return SEM_FAILED;
sem_t *sem = posix_sem_map(fd);
close_keeping_errno(fd);
return sem;
}
sem_t *sem_open(const char *name, int oflag, ...) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return SEM_FAILED;
if (!(oflag & O_CREAT)) return posix_sem_open_fd(open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC));
va_list args;
va_start(args, oflag);
mode_t mode = va_arg(args, mode_t);
unsigned int value = va_arg(args, unsigned int);
va_end(args);
static unsigned int serial;
for (;;) {
if (!(oflag & O_EXCL)) {
int fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
if (fd >= 0 || errno != ENOENT) return posix_sem_open_fd(fd);
}
if (value > SEM_VALUE_MAX) { errno = EINVAL; return SEM_FAILED; }
sem_t initial;
memset(&initial, 0, sizeof(initial));
sem_init(&initial, 1, value);
char temp[PATH_MAX];
int fd;
do {
snprintf(temp, sizeof(temp), "/dev/shm/.sem-%d-%u", (int)getpid(), __atomic_fetch_add(&serial, 1, __ATOMIC_RELAXED));
fd = open(temp, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode);
} while (fd < 0 && errno == EEXIST);
if (fd < 0) return SEM_FAILED;
errno = EIO;
sem_t *sem = write(fd, &initial, sizeof(initial)) == (ssize_t)sizeof(initial) ? posix_sem_map(fd) : SEM_FAILED;
close_keeping_errno(fd);
if (sem != SEM_FAILED && renameat2(AT_FDCWD, temp, AT_FDCWD, path, RENAME_NOREPLACE) == 0) return sem;
int saved = errno;
if (sem != SEM_FAILED) sem_close(sem);
unlink(temp);
errno = saved;
if (errno != EEXIST || (oflag & O_EXCL)) return SEM_FAILED;
}
}
int sem_close(sem_t *sem) {
posix_sems_hold();
struct posix_sem **link = &g_posix_sems;
while (*link && (*link)->addr != sem) link = &(*link)->next;
struct posix_sem *e = *link;
if (e && --e->refs == 0) {
*link = e->next;
munmap(e->addr, sizeof(sem_t));
free(e);
}
posix_sems_unlock();
if (!e) { errno = EINVAL; return -1; }
return 0;
}
int sem_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return -1;
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
return unlink(path);
}
+36 -26
View File
@@ -526,12 +526,6 @@ static long nested_path_syscall(long number, unsigned long dirfd, unsigned long
return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0);
}
static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) {
long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0);
if (rc == 0) *real = *effective = *saved = 0;
return rc;
}
long syscall(long number, ...) {
va_list ap;
va_start(ap, number);
@@ -714,16 +708,6 @@ long syscall(long number, ...) {
return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4);
}
#endif
#if defined(__NR_connect)
if (number == __NR_connect) {
return (long)connect((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3);
}
#endif
#if defined(__NR_bind)
if (number == __NR_bind) {
return (long)bind((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3);
}
#endif
#if defined(__NR_truncate)
if (number == __NR_truncate) {
return (long)truncate((const char *)arg1, (off_t)arg2);
@@ -883,22 +867,48 @@ long syscall(long number, ...) {
if (number == __NR_getegid32) return 0;
#endif
#if defined(__NR_getresuid)
if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
if (number == __NR_getresuid) {
uid_t *ruid = (uid_t *)arg1;
uid_t *euid = (uid_t *)arg2;
uid_t *suid = (uid_t *)arg3;
if (ruid) *ruid = 0;
if (euid) *euid = 0;
if (suid) *suid = 0;
return 0;
}
#endif
#if defined(__NR_getresuid32)
if (number == __NR_getresuid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
if (number == __NR_getresuid32) {
uid_t *ruid = (uid_t *)arg1;
uid_t *euid = (uid_t *)arg2;
uid_t *suid = (uid_t *)arg3;
if (ruid) *ruid = 0;
if (euid) *euid = 0;
if (suid) *suid = 0;
return 0;
}
#endif
#if defined(__NR_getresgid)
if (number == __NR_getresgid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
if (number == __NR_getresgid) {
gid_t *rgid = (gid_t *)arg1;
gid_t *egid = (gid_t *)arg2;
gid_t *sgid = (gid_t *)arg3;
if (rgid) *rgid = 0;
if (egid) *egid = 0;
if (sgid) *sgid = 0;
return 0;
}
#endif
#if defined(__NR_getresgid32)
if (number == __NR_getresgid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
#endif
#if defined(__NR_getgroups)
if (number == __NR_getgroups) return (long)getgroups((int)arg1, (gid_t *)arg2);
#endif
#if defined(__NR_fchown)
if (number == __NR_fchown) return (long)fchown((int)arg1, (uid_t)arg2, (gid_t)arg3);
if (number == __NR_getresgid32) {
gid_t *rgid = (gid_t *)arg1;
gid_t *egid = (gid_t *)arg2;
gid_t *sgid = (gid_t *)arg3;
if (rgid) *rgid = 0;
if (egid) *egid = 0;
if (sgid) *sgid = 0;
return 0;
}
#endif
return call_orig_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6);
+11 -22
View File
@@ -84,19 +84,6 @@ static void init_ddnatv_hook(void) {
setenv("TZDIR", tzdir_buf, 0);
}
const char *curr_locpath = getenv("LOCPATH");
if (!curr_locpath || curr_locpath[0] == '\0') {
char locpath_buf[PATH_MAX];
snprintf(locpath_buf, sizeof(locpath_buf), "%s/usr/lib/locale", g_ddnatv_root);
setenv("LOCPATH", locpath_buf, 1);
}
if (!getenv("GCONV_PATH")) {
char gconv_buf[PATH_MAX];
snprintf(gconv_buf, sizeof(gconv_buf), "%s/usr/lib/aarch64-linux-gnu/gconv", g_ddnatv_root);
setenv("GCONV_PATH", gconv_buf, 0);
}
const char *curr_cert = getenv("SSL_CERT_FILE");
if (!curr_cert || curr_cert[0] == '\0' || strcmp(curr_cert, "/etc/ssl/certs/ca-certificates.crt") == 0) {
char cert_buf[PATH_MAX];
@@ -203,10 +190,15 @@ static void exe_from_cmdline(const char *cmdline_path, char *out, size_t outsz)
}
static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) {
char guest[PATH_MAX];
char back[PATH_MAX];
const char *out_path = guest_path_of_host_dir(real_exe, guest, sizeof(guest));
if (!out_path || strcmp(rewrite_path_in_root(out_path, back, sizeof(back)), real_exe) != 0) out_path = real_exe;
const char *out_path = real_exe;
if (g_ddnatv_root[0] != '\0') {
size_t rlen = g_ddnatv_root_len;
if (strncmp(real_exe, g_ddnatv_root, rlen) == 0 &&
(real_exe[rlen] == '/' || real_exe[rlen] == '\0')) {
out_path = real_exe + rlen;
if (out_path[0] == '\0') out_path = "/";
}
}
size_t len = strlen(out_path);
size_t copy_len = (len < bufsiz) ? len : bufsiz;
memcpy(buf, out_path, copy_len);
@@ -358,11 +350,8 @@ static ssize_t handle_proc_exe_at(int dirfd, const char *pathname, char *buf, si
static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) {
if (!path) return NULL;
// Relative paths must NEVER be rewritten to rootfs root
if (path[0] != '/') return path;
init_ddnatv_hook();
if (path[0] != '/') {
const char *walked = map_at(AT_FDCWD, path, buffer, bufsize);
return walked ? walked : path;
}
return rewrite_path_in_root(path, buffer, bufsize);
}
@@ -372,7 +361,7 @@ static const char *rewrite_path(const char *path, char *buffer, size_t bufsize)
// followed in the guest's view first. The rootfs's own links were made relative already.
static const char *rewrite_path_follow(const char *path, char *buffer, size_t bufsize) {
if (!path) return NULL;
if (path[0] != '/') return rewrite_path(path, buffer, bufsize);
if (path[0] != '/') return path;
init_ddnatv_hook();
int moved = 0;
for (int i = 0; i < g_nbinds; i++) {
+5 -11
View File
@@ -94,13 +94,6 @@ int listen(int sockfd, int backlog) {
return ret;
}
static void copy_unix_path(const struct sockaddr_un *sun, socklen_t addrlen, char *out) {
size_t max = addrlen - offsetof(struct sockaddr_un, sun_path);
if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path);
memcpy(out, sun->sun_path, max);
out[max] = '\0';
}
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
static int (*orig_bind)(int, const struct sockaddr *, socklen_t) = NULL;
if (!orig_bind) orig_bind = (int (*)(int, const struct sockaddr *, socklen_t))dlsym(RTLD_NEXT, "bind");
@@ -111,9 +104,7 @@ int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
struct sockaddr_un mod_sun;
memset(&mod_sun, 0, sizeof(mod_sun));
mod_sun.sun_family = AF_UNIX;
char guest[sizeof(sun->sun_path) + 1];
copy_unix_path(sun, addrlen, guest);
rewrite_unix_socket_path(guest, mod_sun.sun_path, sizeof(mod_sun.sun_path));
rewrite_unix_socket_path(sun->sun_path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
return orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1;
}
}
@@ -142,7 +133,10 @@ int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
memset(&mod_sun, 0, sizeof(mod_sun));
mod_sun.sun_family = AF_UNIX;
char guest[sizeof(sun->sun_path) + 1];
copy_unix_path(sun, addrlen, guest);
size_t max = addrlen - offsetof(struct sockaddr_un, sun_path);
if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path);
memcpy(guest, sun->sun_path, max);
guest[max] = '\0';
char followed[PATH_MAX];
const char *path = guest[0] == '/' ? follow_guest_link(guest, followed, sizeof(followed)) : guest;
rewrite_unix_socket_path(path, mod_sun.sun_path, sizeof(mod_sun.sun_path));
+1 -2
View File
@@ -23,8 +23,7 @@ while IFS= read -r dir; do
done < <(ls -d "${sdk_dir}"/build-tools/* 2>/dev/null | sort -rV)
[[ -n "${build_tools}" ]] || { echo "No build-tools with aapt, zipalign and apksigner under ${sdk_dir}." >&2; exit 1; }
# Lint vital is most of an incremental build and CI runs it.
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease -x lintVitalAnalyzeRelease
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease
(
cd "$(dirname "${signing_env}")"
set -a; . "${signing_env}"; set +a
-12
View File
@@ -1,7 +1,6 @@
from pathlib import Path
import importlib.util
import re
import shutil
import sys
from zipfile import ZipFile
@@ -35,14 +34,6 @@ def source_assets(overlay=OVERLAY):
return result
def stage(target=OVERLAY.parents[2] / 'app/src/main', overlay=OVERLAY):
for source, asset in source_assets(overlay).items():
path = target / asset
if not path.is_file() or path.read_bytes() != source.read_bytes():
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, path)
def check(apk, overlay=OVERLAY):
errors = check_extraction(overlay, SESSION_FILES.read_text()) if overlay == OVERLAY else []
with ZipFile(apk) as package:
@@ -69,9 +60,6 @@ def check(apk, overlay=OVERLAY):
if __name__ == '__main__':
if sys.argv[1:] == ['--stage']:
stage()
sys.exit()
errors = check(sys.argv[1])
if errors:
sys.exit('\n'.join(errors))
+1 -25
View File
@@ -48,19 +48,8 @@ def digest(path):
return result.hexdigest()
def copied(root):
# Helper scripts are staged verbatim on every Gradle build and checked against the APK by
# check_session_assets.py, so they are neither preparation inputs nor prepared outputs.
if str(Path(__file__).resolve().parent) not in sys.path:
sys.path.insert(0, str(Path(__file__).resolve().parent))
from check_session_assets import OVERLAY, source_assets
found = source_assets() if root == ROOT else source_assets(root / OVERLAY.relative_to(ROOT))
return {source.relative_to(root).as_posix(): 'app/src/main/' + asset for source, asset in found.items()}
def sources(root):
files, builds = [], set()
skipped = set(copied(root))
for name in SOURCE_PATHS:
path = root / name
files.extend(path.rglob('*') if path.is_dir() else [path])
@@ -68,18 +57,14 @@ def sources(root):
builds.update(manifest.parent / 'target' for manifest in path.rglob('Cargo.toml'))
return {path.relative_to(root).as_posix(): digest(path) for path in sorted(set(files))
if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'
and path.relative_to(root).as_posix() not in skipped
and not any(build in path.parents for build in builds)}
def outputs(root):
result = {}
skipped = set(copied(root).values())
for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal', 'hybris']:
base = root / 'app/src/main/assets' / tree
for path in base.rglob('*'):
if path.relative_to(root).as_posix() in skipped:
continue
if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts):
result['assets/' + tree + '/' + path.relative_to(base).as_posix()] = path.relative_to(root).as_posix()
for library in ['libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so']:
@@ -99,6 +84,7 @@ def required():
for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']]
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libddsession.so',
'libddfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
'usr/local/bin/droiddeck-gog-maintenance',
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime',
'usr/local/lib/droiddeck-pipewire.tzst']]
for arch in ['x86_64', 'i386']:
@@ -110,7 +96,6 @@ def required():
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-xclipse/' + name for name in
['libVkLayer_droiddeck_xclipse.so', 'VkLayer_droiddeck_xclipse.json']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-lse/liblse_emu.so']
paths += ['assets/linuxfs/usr/local/lib/droiddeck-vr/' + name for name in
['droiddeck/bin/linuxarm64/driver_droiddeck.so', 'droiddeck/bin/linuxarm64/xr-display-mode',
'droiddeck/driver.vrdrivermanifest',
@@ -193,10 +178,6 @@ def verify(root=ROOT, stale_sources_ok=False):
raise ValueError('Runtime inputs have not been prepared. Run tools/build_local.sh.')
if data.get('version') != 1:
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
copies = copied(root)
data['sources'] = {name: value for name, value in (data.get('sources') or {}).items() if name not in copies}
data['outputs'] = {name: output for name, output in (data.get('outputs') or {}).items()
if output.get('path') not in copies.values()}
current = sources(root)
if data.get('sources') != current:
if not stale_sources_ok:
@@ -214,11 +195,6 @@ def verify(root=ROOT, stale_sources_ok=False):
raise ValueError('Missing or changed runtime input: ' + name + '. Run tools/build_local.sh.')
if outputs(root) != {name: output['path'] for name, output in data['outputs'].items()}:
raise ValueError('Runtime file set changed. Run tools/build_local.sh.')
for source, asset in copies.items():
path = root / asset
if not path.is_file() or path.read_bytes() != (root / source).read_bytes():
raise ValueError(asset + ' is not a current copy of ' + source
+ '. Run python3 tools/release/check_session_assets.py --stage.')
return data
+2 -7
View File
@@ -10,19 +10,14 @@ paths=(
app/build/packs app/build/localPackAssets app/build/packs-local-aside app/build/quest-inputs
app/build/rustJniLibs app/build/vkbridgeJniLibs
app/src/main/assets/directaudio app/src/main/assets/droiddeck-esync app/src/main/assets/linuxfs
app/src/main/assets/desktop-removal app/src/main/assets/hybris
app/src/main/assets/desktop-removal
app/src/main/jniLibs/arm64-v8a
app/src/main/rust/stores/target
)
for path in "${paths[@]}"; do
[[ -e "${main_root}/${path}" ]] || continue
if [[ -d "${main_root}/${path}" ]]; then
if [[ -n "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]]; then
# A directory holding only tracked files (jniLibs) still lacks every built library.
[[ -z "$(git -C "${repo_root}" ls-files --others -- "${path}")" ]] || continue
cp -Rn "${main_root}/${path}/." "${repo_root}/${path}/"
continue
fi
[[ -z "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]] || continue
mkdir -p "$(dirname "${repo_root}/${path}")"
staged=$(mktemp -d "${repo_root}/${path}.seed.XXXXXX")
trap 'rm -rf "${staged}"' EXIT
-148
View File
@@ -1,148 +0,0 @@
#define _GNU_SOURCE
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ucontext.h>
#define MAX_THREADS 8
#define ROUNDS 20000
static uint64_t counter64;
static uint32_t counter32;
static uint16_t counter16;
static uint8_t counter8;
static uint64_t spin;
static void check(int ok, const char *what) {
if (!ok) {
printf("FAIL %s\n", what);
exit(1);
}
}
static uint64_t ldaddal64(uint64_t *p, uint64_t v) {
uint64_t old;
__asm__ volatile("ldaddal %x1, %x0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
return old;
}
static uint32_t ldadd32(uint32_t *p, uint32_t v) {
uint32_t old;
__asm__ volatile("ldadd %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
return old;
}
static uint16_t ldaddlh(uint16_t *p, uint16_t v) {
uint16_t old;
__asm__ volatile("ldaddlh %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
return old;
}
static uint8_t ldaddab(uint8_t *p, uint8_t v) {
uint8_t old;
__asm__ volatile("ldaddab %w1, %w0, [%2]" : "=r"(old) : "r"(v), "r"(p) : "memory");
return old;
}
static uint64_t casal64(uint64_t *p, uint64_t expected, uint64_t desired) {
__asm__ volatile("casal %x0, %x2, [%1]" : "+r"(expected) : "r"(p), "r"(desired) : "memory");
return expected;
}
static void *worker(void *arg) {
(void)arg;
for (int i = 0; i < ROUNDS; i++) {
ldaddal64(&counter64, 1);
ldadd32(&counter32, 1);
ldaddlh(&counter16, 1);
ldaddab(&counter8, 1);
uint64_t seen = __atomic_load_n(&spin, __ATOMIC_RELAXED);
while (casal64(&spin, seen, seen + 1) != seen) seen = __atomic_load_n(&spin, __ATOMIC_RELAXED);
}
return NULL;
}
static volatile sig_atomic_t app_handler_ran;
static void app_sigill(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)info;
app_handler_ran = 1;
((ucontext_t *)context)->uc_mcontext.pc += 4;
}
static __attribute__((noinline)) void single_forms(void) {
uint64_t v = 0xF0;
uint64_t old;
__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) {
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];
for (int i = 0; i < threads_wanted; i++) pthread_create(&threads[i], NULL, worker, NULL);
for (int i = 0; i < threads_wanted; i++) pthread_join(threads[i], NULL);
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;
}
-18
View File
@@ -146,24 +146,6 @@ class AppImageRunTest(unittest.TestCase):
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem"))
self.assertEqual("sysmem", env["TU_DEBUG"])
def test_an_arm64_app_uses_the_sessions_gl_libraries(self):
(self.dir / "arch").write_text("arm64")
self.bundle("usr/lib/libGLESv2.so.2", "usr/lib/libEGL.so.1", "usr/lib/libglfw.so.3", "usr/lib/libGLESv2.so.2.1.0")
_, log = self.launch(RUN_MODE)
lib = self.dir / "app/usr/lib"
self.assertEqual(["libGLESv2.so.2.1.0", "libglfw.so.3"], sorted(p.name for p in lib.iterdir()))
self.assertEqual(["libEGL.so.1", "libGLESv2.so.2"], sorted(p.name for p in (self.dir / "bundled-gl/usr/lib").iterdir()))
self.assertIn("the session's libGLESv2.so.2 replaces the bundled one", log)
_, log = self.launch(RUN_MODE)
self.assertNotIn("replaces the bundled one", log)
def test_other_architectures_keep_their_gl_libraries(self):
(self.dir / "arch").write_text("x86_64")
self.bundle("usr/lib/libGLESv2.so.2")
self.launch(RUN_MODE)
self.assertTrue((self.dir / "app/usr/lib/libGLESv2.so.2").exists())
self.assertFalse((self.dir / "bundled-gl").exists())
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -138,27 +138,6 @@ class BinfmtPreloadTest(unittest.TestCase):
program = self.file("arm64", bytes(arm64))
self.assertEqual(self.run_program("execve", program), (3, "errno %d" % errno.ENOEXEC, None))
def arm64_appimage(self, name, filesystem):
image = bytearray(128)
image[0:4], image[4], image[5], image[8:11], image[18] = b"\x7fELF", 2, 1, b"AI\x02", 183
image[0x28:0x30] = (64).to_bytes(8, "little")
image[0x3A:0x3C], image[0x3C:0x3E] = (32).to_bytes(2, "little"), (1).to_bytes(2, "little")
image[96:102] = filesystem
return self.file(name, bytes(image))
def test_an_arm64_appimage_goes_to_the_handler(self):
program = self.arm64_appimage("App.AppImage", b"hsqs\0\0")
for how in ("execve", "execvp"):
self.log.unlink(missing_ok=True)
target = program if how == "execve" else program.name
self.assertEqual(self.run_program(how, target, "--x"), (7, "", ["--exec", str(program), "--x"]))
self.log.unlink()
self.assertEqual(self.run_program("spawn", program, "y"), (0, "exit 7", ["--exec", str(program), "y"]))
def test_an_appimage_runtime_without_a_filesystem_keeps_its_error(self):
runtime = self.arm64_appimage("uruntime", bytes(6))
self.assertEqual(self.run_program("execve", runtime), (3, "errno %d" % errno.ENOEXEC, None))
def test_a_script_runs_as_itself(self):
script = self.file("script.sh", b"#!/bin/sh\nexit 5\n")
self.assertEqual(self.run_program("execve", script), (5, "", None))
@@ -209,24 +188,6 @@ class BinfmtPreloadTest(unittest.TestCase):
code = self.chromium_script()
self.assertEqual(self.run_program("execve", code, "--version"), (0, "--no-sandbox\n--version", None))
def test_a_chromium_app_named_on_path_receives_no_sandbox(self):
(self.dir / "code").symlink_to(self.chromium_script())
for how in ("execvp", "execvpe", "spawnp"):
out = self.run_program(how, "code", "--version")
self.assertEqual(out[1].splitlines()[:2], ["--no-sandbox", "--version"], how)
def test_a_path_match_that_cannot_run_does_not_decide_the_flags(self):
stale = self.dir / "stale"
stale.mkdir()
(stale / "util").write_text("#!/bin/sh\n")
(stale / "chrome-sandbox").touch()
util = self.dir / "util"
util.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n")
util.chmod(0o755)
for how in ("execvp", "execvpe", "spawnp"):
out = self.run_program(how, "util", "--version", PATH=f"{stale}:{self.dir}:/usr/bin:/bin")
self.assertEqual(out[1].splitlines()[:1], ["--version"], how)
def test_the_hand_off_switch_works_without_the_desktop(self):
tool = self.x86()
for how in ("execve", "execvp"):
-93
View File
@@ -1,93 +0,0 @@
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import sys
import tarfile
import tempfile
import unittest
from unittest import mock
COMPONENTS = Path(__file__).resolve().parents[1] / 'components'
sys.path.insert(0, str(COMPONENTS))
spec = importlib.util.spec_from_file_location('component_reuse', COMPONENTS / 'reuse.py')
reuse = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reuse)
prepare = reuse.prepare
class ComponentReuseTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
(self.root / 'tools/ci').mkdir(parents=True)
(self.root / 'tools/ci/toolchains.env').write_text('CI_ANDROID_NDK_VERSION=30.0.1\n')
self.local = {'runtime': 'a', 'proot': 'b'}
self.unregistered, self.submodules = [], []
for patcher in [mock.patch.object(prepare, 'registry', lambda root: dict.fromkeys(self.local)),
mock.patch.object(prepare, 'identity', lambda name, root: self.local[name]),
mock.patch.object(reuse, 'unregistered_changes', lambda tree, root: self.unregistered),
mock.patch.object(reuse, 'edited_submodules', lambda root: self.submodules)]:
patcher.start()
self.addCleanup(patcher.stop)
self.archive = self.root / 'prepared-components.tar.gz'
self.contents = {name + '/file': name.encode() for name in prepare.TREES}
self.contents.update({name: b'library' for name in prepare.LIBRARIES})
def write_archive(self, recipes, contents=None):
contents = contents or self.contents
manifest = dict(version=1, source_tree='tree', run='42', recipes=recipes,
files={name: hashlib.sha256(data).hexdigest() for name, data in self.contents.items()})
with tarfile.open(self.archive, 'w:gz') as archive:
for name, data in list(contents.items()) + [(prepare.MANIFEST, json.dumps(manifest).encode())]:
entry = tarfile.TarInfo(name)
entry.size = len(data)
entry.mode = 0o644
archive.addfile(entry, io.BytesIO(data))
def test_matching_components_replace_local_ones(self):
stale = self.root / prepare.TREES[0] / 'left-over'
stale.parent.mkdir(parents=True)
stale.write_text('from an older local build')
self.write_archive(dict(self.local))
self.assertTrue(reuse.reuse(self.archive, self.root))
self.assertEqual(b'library', (self.root / prepare.LIBRARIES[0]).read_bytes())
self.assertFalse(stale.exists())
def test_a_changed_component_is_not_reused(self):
self.write_archive(dict(self.local, proot='other'))
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
self.assertFalse(reuse.reuse(self.archive, self.root))
self.assertIn('proot', stdout.getvalue())
self.assertFalse((self.root / prepare.LIBRARIES[0]).exists())
def test_a_tampered_file_is_rejected_and_local_outputs_survive(self):
local = self.root / prepare.LIBRARIES[0]
local.parent.mkdir(parents=True)
local.write_bytes(b'local build')
self.write_archive(dict(self.local), dict(self.contents, **{prepare.LIBRARIES[0]: b'tampered'}))
with self.assertRaisesRegex(ValueError, 'do not match'):
reuse.reuse(self.archive, self.root)
self.assertEqual(b'local build', local.read_bytes())
def test_changed_sources_ci_builds_outside_recipes_are_not_reused(self):
self.unregistered = ['tools/linuxfs/xclipse-layer/xclipse_layer.c']
self.write_archive(dict(self.local))
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
self.assertFalse(reuse.reuse(self.archive, self.root))
self.assertIn('xclipse_layer.c', stdout.getvalue())
def test_an_edited_submodule_is_not_reused(self):
self.submodules = ['external/MaliBridge']
self.write_archive(dict(self.local))
with mock.patch('sys.stdout', new_callable=io.StringIO):
self.assertFalse(reuse.reuse(self.archive, self.root))
def test_identities_use_the_ci_runner_and_ndk(self):
seen = {}
with mock.patch.object(prepare, 'identity', lambda name, root: seen.update(
arch=reuse.os.environ['RUNNER_ARCH'], ndk=reuse.os.environ['NDK_VERSION']) or 'x'):
reuse.identities(reuse.ci_environment('X64', self.root), self.root)
self.assertEqual({'arch': 'X64', 'ndk': '30.0.1'}, seen)
+35 -9
View File
@@ -1,8 +1,11 @@
import os
from pathlib import Path
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-desktop-gpu"
PREFIX = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
FLAGS = " --no-sandbox --ozone-platform=x11"
def load():
@@ -21,6 +24,12 @@ class DesktopChromiumAppsTest(unittest.TestCase):
self.gpu = load()
self.electron = self.app("lib/chat/chat", sandbox=True)
self.plain = self.app("lib/editor/editor", sandbox=False)
bin_dir = self.root / "bin"
bin_dir.mkdir()
(bin_dir / "chat").symlink_to(self.electron)
old_path = os.environ.get("PATH", "")
os.environ["PATH"] = "%s:%s" % (bin_dir, old_path)
self.addCleanup(os.environ.__setitem__, "PATH", old_path)
def app(self, relative, sandbox):
path = self.root / relative
@@ -40,17 +49,34 @@ class DesktopChromiumAppsTest(unittest.TestCase):
def exec_lines(self, text):
return [l[5:] for l in text.splitlines() if l.startswith("Exec=")]
def test_electron_apps_keep_their_own_entries(self):
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron)))
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain))))
def test_an_electron_app_starts_without_the_sandbox_on_x11(self):
out = self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron))
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS + " %U",
PREFIX + str(self.electron) + FLAGS + " --new"])
self.assertIn("X-DroidDeck-GPU=1", out)
self.assertIn("Actions=new;", out)
self.assertNotIn("droiddeck-window", out)
def test_an_electron_game_goes_to_the_gpu_as_installed(self):
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;", actions="%s --new" % self.electron))
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + str(self.electron), str(self.electron),
"droiddeck-gpu %s --new" % self.electron])
def test_a_command_on_the_path_is_followed_to_its_install_folder(self):
out = self.gpu["wrap"](self.entry("chat %U"))
self.assertEqual(self.exec_lines(out), [PREFIX + "chat" + FLAGS + " %U"])
def test_with_the_gpu_off_no_entry_is_written(self):
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False))
def test_a_quoted_program_keeps_its_quotes(self):
out = self.gpu["wrap"](self.entry('"%s" %%U' % self.electron))
self.assertEqual(self.exec_lines(out), [PREFIX + '"%s"' % self.electron + FLAGS + " %U"])
def test_other_apps_are_left_alone(self):
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%F" % self.plain)))
self.assertIsNone(self.gpu["wrap"](self.entry("missing-program %F")))
def test_an_electron_game_goes_to_the_gpu_and_keeps_a_window_action(self):
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"))
fixed = PREFIX + str(self.electron) + FLAGS
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + fixed, fixed])
def test_with_the_gpu_off_electron_apps_are_still_fixed(self):
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False)
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS])
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"), False))
def test_games_that_are_not_chromium_are_unchanged(self):
-21
View File
@@ -526,21 +526,6 @@ class PrepareTest(FexTestCase):
for name in names:
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode())
def test_opengl_dispatch_library_comes_from_the_newer_runtime_when_the_base_lacks_it(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
self.write(sniper / "files/lib" / arch / "libGLdispatch.so.0", b"base dispatch")
self.write(provider / "files/lib" / arch / "libOpenGL.so.0.0.0", b"opengl " + arch.encode())
os.symlink("libOpenGL.so.0.0.0", provider / "files/lib" / arch / "libOpenGL.so.0")
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
root = Path(fex["rootfs"]) / "lib" / arch
self.assertEqual((root / "libOpenGL.so.0").read_bytes(), b"opengl " + arch.encode())
self.assertEqual((root / "libGLdispatch.so.0").read_bytes(), b"base dispatch")
def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
@@ -1070,12 +1055,6 @@ class LaunchTest(FexTestCase):
guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"})
self.assertNotIn("GLIBC_TUNABLES", guest)
def test_host_iconv_modules_stay_on_the_host(self):
guest = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/r/usr/lib/aarch64-linux-gnu/gconv"})
self.assertEqual(guest["GCONV_PATH"], "")
own = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/opt/gconv"})
self.assertEqual(own["GCONV_PATH"], "/opt/gconv")
def test_proton_runs_in_the_runtime_its_manifest_requires(self):
self.fex_tool()
self.runtime()
-29
View File
@@ -1,29 +0,0 @@
from pathlib import Path
import re
import unittest
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0015-gl-thunk-overlays-libopengl.patch"
def hunk(sign):
lines = [line for line in PATCH.read_text().splitlines() if not line.startswith(("diff ", "index ", "--- ", "+++ ", "@@"))]
return re.findall(r'"([^"]+)"', "\n".join(line[1:] for line in lines if line[:1] in (" ", sign)))
class FexGlThunkOverlayTest(unittest.TestCase):
def test_libopengl_joins_the_gl_overlay(self):
before, after = hunk("-"), hunk("+")
self.assertNotIn("@PREFIX_LIB@/libOpenGL.so.0", before)
self.assertIn("@PREFIX_LIB@/libOpenGL.so.0", after)
self.assertIn("@PREFIX_LIB@/libOpenGL.so.0.0.0", after)
self.assertEqual([path for path in before if path.startswith("@PREFIX_LIB@/libGL.")],
[path for path in after if path.startswith("@PREFIX_LIB@/libGL.")])
self.assertLess(after.index("@PREFIX_LIB@/libGL.so.1.7.0"), after.index("Vulkan"))
self.assertLess(after.index("@PREFIX_LIB@/libOpenGL.so.0.0.0"), after.index("Vulkan"))
def test_patch_touches_only_the_thunks_database(self):
self.assertEqual(["Data/ThunksDB.json"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
if __name__ == "__main__":
unittest.main()
-120
View File
@@ -1,120 +0,0 @@
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0014-guest-preload-drops-host-libraries.patch"
HARNESS = r"""
#include <cstdio>
#include <cstring>
#include <elf.h>
#include <fcntl.h>
#include <string>
#include <unistd.h>
namespace fextl { using string = std::string; }
namespace ELFLoader {
struct ELFContainer {
enum ELFType { TYPE_NONE, TYPE_X86_64, TYPE_X86_32, TYPE_OTHER_ELF };
static ELFType GetELFType(const std::string& Filename) {
int FD = open(Filename.c_str(), O_RDONLY | O_CLOEXEC);
if (FD == -1) return TYPE_NONE;
Elf64_Ehdr Header {};
ssize_t Read = pread(FD, &Header, sizeof(Header), 0);
close(FD);
if (Read < (ssize_t)sizeof(Header) || memcmp(Header.e_ident, ELFMAG, SELFMAG) != 0) return TYPE_NONE;
if (Header.e_machine == EM_X86_64) return TYPE_X86_64;
if (Header.e_machine == EM_386) return TYPE_X86_32;
return TYPE_OTHER_ELF;
}
};
}
struct Loader {
static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) { return RootFS + File; }
GUEST_PRELOAD
};
int main(int argc, char** argv) {
std::printf("%s", Loader::GuestPreload(argv[1], argv[2]).c_str());
}
"""
def x86_compiler():
for name in ("x86_64-linux-gnu-gcc", "gcc"):
path = shutil.which(name)
if path and subprocess.run([path, "-dumpmachine"], capture_output=True, text=True).stdout.startswith("x86_64"):
return path
return None
X86_CC = x86_compiler()
def patch_function():
lines = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
body = "\n".join(lines)
first = body.index(" static fextl::string GuestPreload(")
last = body.index("\n }\n", first) + len("\n }\n")
return body[first:last]
@unittest.skipUnless(shutil.which("g++") and X86_CC and shutil.which("aarch64-linux-gnu-gcc"), "needs g++, an x86-64 gcc and aarch64-linux-gnu-gcc")
class FexGuestPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.dir = Path(cls.tmp.name)
source = cls.dir / "harness.cpp"
source.write_text(HARNESS.replace("GUEST_PRELOAD", patch_function()))
cls.binary = cls.dir / "harness"
subprocess.run(["g++", "-std=c++20", "-O1", "-o", str(cls.binary), str(source)], check=True)
stub = cls.dir / "stub.c"
stub.write_text("int stub(void) { return 0; }\n")
cls.host = cls.dir / "host"
cls.rootfs = cls.dir / "rootfs"
cls.shadow = cls.host / "lib/libshadow.so"
cls.rootfs_shadow = Path(str(cls.rootfs) + str(cls.shadow))
for folder in (cls.host / "lib", cls.rootfs_shadow.parent):
folder.mkdir(parents=True)
cls.compile("aarch64-linux-gnu-gcc", stub, cls.host / "lib/libhost.so")
cls.compile(X86_CC, stub, cls.host / "lib/libguest.so")
cls.compile("aarch64-linux-gnu-gcc", stub, cls.shadow)
cls.compile(X86_CC, stub, cls.rootfs_shadow)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
@staticmethod
def compile(compiler, source, output):
subprocess.run([compiler, "-shared", "-fPIC", "-o", str(output), str(source)], check=True)
def preload(self, value, rootfs=None):
root = str(self.rootfs) if rootfs is None else rootfs
return subprocess.run([str(self.binary), value, root], check=True, capture_output=True, text=True).stdout
def test_host_libraries_leave_the_guest_list(self):
host, guest = self.host / "lib/libhost.so", self.host / "lib/libguest.so"
self.assertEqual(str(guest), self.preload(f"{host}:{guest}"))
self.assertEqual("", self.preload(str(host)))
def test_rootfs_copy_decides_before_the_host_path(self):
self.assertEqual(str(self.shadow), self.preload(str(self.shadow)))
self.assertEqual("", self.preload(str(self.shadow), ""))
def test_names_missing_files_and_separators_are_kept(self):
missing = str(self.dir / "missing.so")
guest = str(self.host / "lib/libguest.so")
self.assertEqual(f"libgamemodeauto.so.0:{missing}:{guest}",
self.preload(f" libgamemodeauto.so.0::{missing} {guest}:"))
def test_patch_adds_no_comments(self):
added = [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
self.assertFalse([line for line in added if line.startswith(("//", "/*"))])
self.assertEqual(["Source/Tools/FEXInterpreter/ELFCodeLoader.h"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
if __name__ == "__main__":
unittest.main()
-148
View File
@@ -1,148 +0,0 @@
import os
import re
import subprocess
import tempfile
import unittest
from pathlib import Path
from tools.tests.test_usr2_preload import runner
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0016-identity-syscalls-through-libc.patch"
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
IDENTITY = {"getuid", "getgid", "geteuid", "getegid", "setuid", "setgid", "setreuid", "setregid", "getgroups",
"setgroups", "setresuid", "getresuid", "setresgid", "getresgid", "setfsuid", "setfsgid", "fchown"}
def changed():
removed, added = {}, {}
for line in PATCH.read_text().splitlines():
found = REGISTER.search(line)
if found and line[:1] in "+-":
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
return removed, added
class FexIdentitySyscallsTest(unittest.TestCase):
def test_only_the_passthrough_table_changes(self):
self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH])
def test_each_identity_syscall_keeps_its_arity_and_goes_through_libc(self):
removed, added = changed()
self.assertEqual(sorted(removed), sorted(added))
self.assertEqual(IDENTITY, {number for _, _, number in added.values()})
for name, (template, arity, number) in added.items():
with self.subTest(name=name):
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
self.assertEqual("SyscallPathPassthrough", template)
def test_the_new_template_calls_the_libc_syscall(self):
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
self.assertEqual([" uint64_t Result = ::syscall(syscall_num);"], [line for line in added if "Result =" in line])
self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))])
def test_every_routed_syscall_is_answered_by_the_hook(self):
hook = HOOK.read_text()
for number in IDENTITY:
with self.subTest(number=number):
self.assertIn(f"number == __NR_{number})", hook)
PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(int argc, char **argv) {
unsigned int r = 7, e = 7, s = 7;
long rc = syscall(SYS_getresuid, &r, &e, &s);
printf("getresuid %ld %u %u %u\n", rc, r, e, s);
errno = 0;
rc = syscall(SYS_getresuid, NULL, &e, &s);
printf("getresuid-null %ld %d\n", rc, errno);
r = e = s = 7;
rc = syscall(SYS_getresgid, &r, &e, &s);
printf("getresgid %ld %u %u %u\n", rc, r, e, s);
errno = 0;
rc = syscall(SYS_getresgid, &r, NULL, &s);
printf("getresgid-null %ld %d\n", rc, errno);
unsigned int *locked = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
errno = 0;
rc = syscall(SYS_getresuid, &r, &e, locked);
printf("getresuid-readonly %ld %d\n", rc, errno);
errno = 0;
rc = syscall(SYS_getresgid, locked, &e, &s);
printf("getresgid-readonly %ld %d\n", rc, errno);
gid_t groups[8];
rc = syscall(SYS_getgroups, 8, groups);
printf("getgroups %ld %u\n", rc, rc > 0 ? groups[0] : 99u);
errno = 0;
rc = syscall(SYS_getgroups, 8, locked);
printf("getgroups-readonly %ld %d\n", rc, errno);
int fd = open(argv[1], O_RDONLY);
printf("fchown %ld\n", syscall(SYS_fchown, fd, 4321, 4321));
printf("getuid %ld\n", syscall(SYS_getuid));
return 0;
}
"""
class NativeHookIdentityTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
(tmp / "root").mkdir()
cls.file = tmp / "owned"
cls.file.write_text("")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def probe(self):
hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root"), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe"), str(self.file)], env=env,
capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stderr)
return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()}
def test_the_hook_answers_identity_syscalls_as_root(self):
result = self.probe()
self.assertEqual("0 0 0 0", result["getresuid"])
self.assertEqual("0 0 0 0", result["getresgid"])
self.assertEqual("1 0", result["getgroups"])
self.assertEqual("-1 14", result["getgroups-readonly"])
self.assertEqual("0", result["fchown"])
self.assertEqual("0", result["getuid"])
def test_a_missing_pointer_still_faults(self):
result = self.probe()
self.assertEqual("-1 14", result["getresuid-null"])
self.assertEqual("-1 14", result["getresgid-null"])
self.assertEqual("-1 14", result["getresuid-readonly"])
self.assertEqual("-1 14", result["getresgid-readonly"])
self.assertEqual(os.stat(self.file).st_uid, os.getuid())
if __name__ == "__main__":
unittest.main()
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more