diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c3b3f50cf6..abb5207142 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -164,6 +164,9 @@ 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: @@ -367,6 +370,10 @@ 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 }} @@ -685,6 +692,16 @@ 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. + - name: Cache Robolectric's Android jars + uses: actions/cache@v4 + with: + path: ~/.m2/repository/org/robolectric/android-all-instrumented + key: robolectric-android-all-${{ steps.robolectric.outputs.version }} - name: Unit tests id: unit-tests env: diff --git a/AGENTS.md b/AGENTS.md index 447807615b..494b630d9c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,41 @@ - Comments should be rare, factual, and explain only non-obvious external constraints or business invariants. -# Working on the device +# 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 ''` and `python3 -m unittest discover -s tools/tests -p 'test_*.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= 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('', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display `. +- 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//logs`, or `gh run download -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 --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. - `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. diff --git a/app/build.gradle b/app/build.gradle index 634a41eec0..f2cb40169b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -125,7 +125,8 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines() android { namespace 'com.droiddeck.launcher' compileSdk 34 - ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724' + 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() defaultConfig { applicationId "com.droiddeck.launcher" @@ -232,6 +233,9 @@ 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 } @@ -261,11 +265,9 @@ if (vitureSdkDir) { tasks.named('preBuild').configure { dependsOn(stageVitureNotices) } } -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')) +def stageSessionScripts = tasks.register('stageSessionScripts', Exec) { + workingDir rootProject.projectDir + commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage' } tasks.named('preBuild').configure { dependsOn(stageSessionScripts) } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3cee3538dc..c99a6cb0d3 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -243,6 +243,7 @@ android:exported="false" android:screenOrientation="user" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" + android:windowSoftInputMode="adjustResize" android:theme="@style/AppTheme" /> 0); + const char *d = num + i; + while (*d && *d == *execfn) d++, execfn++; + return !*d && seq(execfn, "/exe"); +} + +static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) { + const char *root = env_get(envp, "DDNATV_ROOT"); + if (!root || interp[0] != '/') return interp; + size_t a = slen(root), b = slen(interp); + if (a + b + 1 > size) return interp; + for (size_t i = 0; i < a; i++) buf[i] = root[i]; + for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i]; + if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp; + return buf; +} + __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { long argc = (long)sp[0]; char **argv = (char **)(sp + 1); @@ -211,25 +274,66 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1); long naux = 0; while (auxv[naux * 2] != AT_NULL) naux++; - if (argc < 3) die("usage: libddexec.so [args...]", 0, 0); + int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0)); + const char *path; + char **args = argv + 2; + long nargs = argc - 2; + char interp_buf[4096]; + char hook_buf[4096]; + if (reexec) { + path = env_get(envp, "DDNATV_REAL_EXE"); + if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0); + args = argv; + nargs = argc; + const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH"); + char prog_interp[256]; + interp_of(path, prog_interp, sizeof(prog_interp)); + if (prog_interp[0] && lib_path && lib_path[0]) { + const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf)); + const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf)); + if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf)); + long n = argc > 1 ? argc - 1 : 0; + char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *)); + long k = 0; + v[k++] = (char *)ld_so; + if (hook == (const char *)hook_buf) { + v[k++] = (char *)"--preload"; + v[k++] = (char *)hook; + } + v[k++] = (char *)"--library-path"; + v[k++] = (char *)lib_path; + v[k++] = (char *)"--argv0"; + v[k++] = argc > 0 ? argv[0] : (char *)path; + v[k++] = (char *)path; + for (long i = 0; i < n; i++) v[k++] = argv[1 + i]; + v[k] = 0; + args = v; + nargs = k; + path = ld_so; + } + } else if (argc < 3) { + die("usage: libddexec.so [args...]", 0, 0); + } else { + path = argv[1]; + } uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096); - const char *path = argv[1]; struct image prog, interp; load(path, &prog, page); int has_interp = prog.interp[0] != 0; - if (has_interp) load(prog.interp, &interp, page); + if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page); // The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one. // The strings stay where the kernel put them. static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN}; long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0])); - long new_argc = argc - 2; + long new_argc = nargs; long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2; - uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); + uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp; + uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); uintptr_t *w = nsp; *w++ = (uintptr_t)new_argc; - for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2]; + for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i]; *w++ = 0; for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i]; *w++ = 0; diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index be2deadbed..58e7e12b2c 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -21,6 +21,7 @@ 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt index e5e74f791f..79e2017962 100644 --- a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt @@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat checkAgain = null checkComponentUpdates(again) } - if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show() + if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; ")) refreshComponents() } }, "component-updates").start() diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index af3eddf8e7..9497fe0a68 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -254,6 +254,12 @@ 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) } @@ -375,6 +381,10 @@ 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) + } } } @@ -2166,9 +2176,7 @@ 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()) ui.post { - android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show() - } + if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; ")) } ui.post { componentsQueueBusy = false @@ -3209,6 +3217,7 @@ 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) @@ -3430,18 +3439,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun install(release: LinuxRuntimeInstaller.Release) { com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release) - followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) } + followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) } } - private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) { + private fun followRuntimeOperation(onboarding: Boolean = false, 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 @@ -3450,7 +3465,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() + if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() } } }, "runtime-operation").start() } @@ -3461,9 +3476,10 @@ 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.unfavourable(this))) return + !com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(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) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt index aaaa2cf34f..bb12dd31af 100644 --- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt @@ -8,7 +8,9 @@ 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 @@ -60,10 +62,15 @@ 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 @@ -170,16 +177,46 @@ 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 || SessionState.running || LinuxRuntimeInstaller.isBusy() || + ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() || SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || - !LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return + !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 if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) { protonBusyId = ProtonExtras.OWN protonProblem = null diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 96aeb08be3..dc0559251b 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -154,6 +154,8 @@ 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 @@ -594,6 +596,7 @@ 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) @@ -933,11 +936,6 @@ 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 @@ -1535,6 +1533,8 @@ 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,6 +2659,7 @@ 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) @@ -3664,8 +3665,9 @@ 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) { - drawerPage = sessionDrawerPages(glasses.present) - .step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) + // 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) releaseDrawerDirection() } return true @@ -4396,6 +4398,27 @@ 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 @@ -5958,7 +5981,11 @@ 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 openDualScreenControls() + } else { + if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu() + SessionState.bottomMenu = false + if (!menuShownOnBottom()) openDualScreenControls() + } startedScreens++ SessionService.setActivityVisible(this, true, sessionActivityDisplayId) Glasses.rescan() diff --git a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt index cd10300f4f..f284c98d36 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt @@ -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 } + enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH } data class State( val wifi: Boolean = false, @@ -28,6 +28,7 @@ object SteamIntegration { val shortcuts: Boolean = false, val shortcutsRestricted: Boolean = false, val shortcutsTried: Boolean = false, + val bluetooth: Boolean = false, val suggested: Boolean = true, ) @@ -39,9 +40,16 @@ 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 { diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt index 3fb876ac23..a05dad8e8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt @@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.ArrowUpward import androidx.compose.material.icons.filled.Checklist import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.FileCopy +import androidx.compose.material.icons.filled.FileOpen import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.InsertDriveFile @@ -101,8 +102,18 @@ private fun FileContextMenuItems( onToggleFavorite: () -> Unit, onProperties: () -> Unit, onDismissMenu: () -> Unit, + onOpen: () -> Unit, ) { val isDir = file.isDirectory + if (!isDir) { + DropdownMenuItem( + text = { Text(stringResource(R.string.fm_edit_open)) }, + leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onOpen() }, + modifier = Modifier.focusGlide(), + ) + MenuItemDivider() + } DropdownMenuItem( text = { Text(stringResource(R.string.fm_select)) }, leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) }, @@ -180,6 +191,7 @@ internal fun FileItemRow( onCut: () -> Unit, onDelete: () -> Unit, onRename: () -> Unit, + onOpen: () -> Unit = {}, isFavorite: Boolean = false, onToggleFavorite: () -> Unit = {}, onProperties: () -> Unit = {}, @@ -291,6 +303,7 @@ internal fun FileItemRow( file = file, isFavorite = isFavorite, onSelect = onSelect, + onOpen = onOpen, onRename = onRename, onCopy = onCopy, onCut = onCut, @@ -517,6 +530,7 @@ internal fun FileGridTile( isFavorite: Boolean = false, onSelect: () -> Unit = {}, onRename: () -> Unit = {}, + onOpen: () -> Unit = {}, onCopy: () -> Unit = {}, onCut: () -> Unit = {}, onDelete: () -> Unit = {}, @@ -605,6 +619,7 @@ internal fun FileGridTile( file = file, isFavorite = isFavorite, onSelect = onSelect, + onOpen = onOpen, onRename = onRename, onCopy = onCopy, onCut = onCut, diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt index 9945083226..7025769d87 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -191,6 +191,7 @@ fun FileManagerScreen( var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) } var showNewFolderDialog by remember { mutableStateOf(false) } var renameTarget by remember { mutableStateOf(null) } + var editingTarget by remember { mutableStateOf(null) } var propertiesTarget by remember { mutableStateOf(null) } var isOperationRunning by remember { mutableStateOf(false) } var operationLabel by remember { mutableStateOf("") } @@ -294,7 +295,7 @@ fun FileManagerScreen( if (isOperationActive()) pendingNavigation = action else navigate(action) } - BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) { + BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) { requestNavigation(FileManagerNavigation.BACK) } @@ -696,6 +697,14 @@ fun FileManagerScreen( val compactToolbar = LocalConfiguration.current.screenWidthDp < 600 Column(modifier = Modifier.fillMaxSize()) { + editingTarget?.let { target -> + TextEditorScreen( + file = target, + onExit = { editingTarget = null }, + modifier = Modifier.fillMaxSize(), + ) + return@Column + } if (pickMode && !pickerTitle.isNullOrEmpty()) { Text( text = pickerTitle, @@ -1194,6 +1203,8 @@ fun FileManagerScreen( pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() onPick?.invoke(file) } + } else { + editingTarget = file } }, onMenu = { showMenuFor = file }, @@ -1205,6 +1216,7 @@ fun FileManagerScreen( selectedPaths = selectedPaths + file.absolutePath showMenuFor = null }, + onOpen = { editingTarget = file; showMenuFor = null }, onRename = { renameTarget = file; showMenuFor = null }, onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, @@ -1273,6 +1285,8 @@ fun FileManagerScreen( pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() onPick?.invoke(file) } + } else { + editingTarget = file } }, onMenu = { showMenuFor = file }, @@ -1286,6 +1300,7 @@ fun FileManagerScreen( onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, onDelete = { selectedEntry = file; showMenuFor = null }, + onOpen = { editingTarget = file; showMenuFor = null }, onRename = { renameTarget = file; showMenuFor = null }, isFavorite = isFav, onToggleFavorite = { diff --git a/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt new file mode 100644 index 0000000000..2d9c0a3fea --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt @@ -0,0 +1,726 @@ +package com.droiddeck.launcher.files + +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Save +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.ui.focusGlide +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.InputStream +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.Charset +import java.nio.charset.CodingErrorAction +import java.nio.file.Files +import kotlin.math.roundToInt + +internal const val EDITOR_FONT_SIZE_SP = 13 +internal const val EDITOR_LINE_HEIGHT_SP = 18 +internal const val EDITOR_TAB_WIDTH = 4 +internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024 +internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024 + +internal enum class EditorCharset(val label: String, private val charsetName: String) { + UTF8("UTF-8", "UTF-8"), + GB18030("GB18030", "GB18030"), + ; + + val charset: Charset get() = Charset.forName(charsetName) +} + +internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY } + +internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE } + +internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean) + +internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean { + val limit = minOf(bytes.size, sample) + for (i in 0 until limit) if (bytes[i].toInt() == 0) return true + return false +} + +private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try { + charset.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString() +} catch (e: CharacterCodingException) { + null +} + +internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText { + strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) } + strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) } + return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true) +} + +internal fun resolveEditorSaveTarget(file: File): File { + val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false) + if (!isLink) return file + // rename(2) replaces the link itself, so stage next to and rename onto the real target + return runCatching { file.canonicalFile }.getOrDefault(file) +} + +internal fun readCapped(input: InputStream, limit: Long): ByteArray? { + val out = ByteArrayOutputStream() + val buffer = ByteArray(64 * 1024) + var total = 0L + while (true) { + val n = input.read(buffer) + if (n < 0) return out.toByteArray() + total += n + if (total > limit) return null + out.write(buffer, 0, n) + } +} + +internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String { + if (text.indexOf('\t') < 0) return text + val out = StringBuilder(text.length) + var column = 0 + for (c in text) { + when (c) { + '\n' -> { + out.append(c) + column = 0 + } + '\t' -> { + val pad = width - (column % width) + repeat(pad) { out.append(' ') } + column += pad + } + else -> { + out.append(c) + column++ + } + } + } + return out.toString() +} + +internal fun lineCountOf(text: String): Int { + var lines = 1 + for (i in text.indices) if (text[i] == '\n') lines++ + return lines +} + +internal fun lineIndexOfOffset(text: String, offset: Int): Int { + val end = offset.coerceIn(0, text.length) + var line = 0 + var i = 0 + while (i < end) { + if (text[i] == '\n') line++ + i++ + } + return line +} + +internal fun columnOfOffset(text: String, offset: Int): Int { + val end = offset.coerceIn(0, text.length) + var start = end + while (start > 0 && text[start - 1] != '\n') start-- + return end - start + 1 +} + +internal fun findEditorMatches( + text: String, + query: String, + matchCase: Boolean = false, + limit: Int = 10000, +): List { + if (query.isEmpty()) return emptyList() + val out = ArrayList() + var at = 0 + while (out.size < limit) { + val found = text.indexOf(query, at, ignoreCase = !matchCase) + if (found < 0) break + out.add(found until found + query.length) + at = found + query.length + } + return out +} + +internal fun replaceEditorMatches(text: String, matches: List, replacement: String): String { + if (matches.isEmpty()) return text + val out = StringBuilder(text.length) + var cursor = 0 + for (m in matches) { + if (m.first < cursor || m.last >= text.length) continue + out.append(text, cursor, m.first).append(replacement) + cursor = m.last + 1 + } + out.append(text, cursor, text.length) + return out.toString() +} + +@Composable +internal fun TextEditorScreen( + file: File, + onExit: () -> Unit, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val density = LocalDensity.current + + var text by remember { mutableStateOf("") } + var selection by remember { mutableStateOf(TextRange.Zero) } + var composing by remember { mutableStateOf(null) } + var loadState by remember { mutableStateOf(EditorLoadState.LOADING) } + var lock by remember { mutableStateOf(EditorLock.NONE) } + var charset by remember { mutableStateOf(EditorCharset.UTF8) } + var dirty by remember { mutableStateOf(false) } + var saving by remember { mutableStateOf(false) } + var showDiscard by remember { mutableStateOf(false) } + var showSearch by remember { mutableStateOf(false) } + var query by remember { mutableStateOf("") } + var replacement by remember { mutableStateOf("") } + var matchCase by remember { mutableStateOf(false) } + var matchIndex by remember { mutableIntStateOf(0) } + + val scrollState = rememberScrollState() + val textHorizontalState = rememberScrollState() + var viewportHeight by remember { mutableIntStateOf(0) } + var viewportWidth by remember { mutableIntStateOf(0) } + + val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() } + val lineHeightPx = with(density) { lineHeightDp.toPx() } + val totalLines = remember(text) { lineCountOf(text) } + val cursorLine = lineIndexOfOffset(text, selection.end) + val cursorColumn = columnOfOffset(text, selection.end) + val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) } + val readOnly = lock != EditorLock.NONE + val bodyStyle = TextStyle( + fontFamily = FontFamily.Monospace, + fontSize = EDITOR_FONT_SIZE_SP.sp, + lineHeight = EDITOR_LINE_HEIGHT_SP.sp, + color = MaterialTheme.colorScheme.onBackground, + ) + val textMeasurer = rememberTextMeasurer() + val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() } + + LaunchedEffect(file) { + loadState = EditorLoadState.LOADING + val size = withContext(Dispatchers.IO) { file.length() } + if (size > EDITOR_MAX_OPEN_BYTES) { + loadState = EditorLoadState.TOO_LARGE + return@LaunchedEffect + } + val read = withContext(Dispatchers.IO) { + runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } } + } + val bytes = read.getOrNull() + if (bytes == null) { + loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE + return@LaunchedEffect + } + val decoded = decodeEditorText(bytes) + text = expandEditorTabs(decoded.text) + charset = decoded.charset + lock = when { + editorIsBinary(bytes) -> EditorLock.BINARY + decoded.lossy -> EditorLock.LOSSY + bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE + !file.canWrite() -> EditorLock.PERMISSION + else -> EditorLock.NONE + } + selection = TextRange.Zero + loadState = EditorLoadState.READY + } + + suspend fun revealLine(line: Int) { + val current = scrollState.value + val top = line * lineHeightPx + val target = when { + top < current -> top + top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight + else -> return + } + val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue) + if (clamped != current) scrollState.scrollTo(clamped) + } + + LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) { + if (loadState != EditorLoadState.READY) return@LaunchedEffect + revealLine(lineIndexOfOffset(text, selection.end)) + if (viewportWidth > 0 && charWidthPx > 0) { + val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx + val current = textHorizontalState.value + val target = when { + x < current -> x + x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth + else -> null + } + if (target != null) { + val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue) + if (clamped != current) textHorizontalState.scrollTo(clamped) + } + } + } + + LaunchedEffect(query, matchCase) { + if (query.isEmpty()) return@LaunchedEffect + matchIndex = 0 + val first = matches.firstOrNull() ?: return@LaunchedEffect + selection = TextRange(first.first, first.last + 1) + composing = TextRange.Zero + } + + LaunchedEffect(text) { matchIndex = 0 } + + fun gotoMatch(delta: Int) { + if (matches.isEmpty()) return + matchIndex = Math.floorMod(matchIndex + delta, matches.size) + val m = matches[matchIndex] + selection = TextRange(m.first, m.last + 1) + composing = TextRange.Zero + } + + fun replaceCurrent() { + if (readOnly) return + val m = matches.getOrNull(matchIndex) ?: return + text = text.replaceRange(m.first, m.last + 1, replacement) + dirty = true + matchIndex = 0 + selection = TextRange(m.first + replacement.length) + composing = TextRange.Zero + } + + fun replaceAll() { + if (readOnly || matches.isEmpty()) return + val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE) + text = replaceEditorMatches(text, all, replacement) + dirty = true + matchIndex = 0 + selection = TextRange.Zero + composing = TextRange.Zero + } + + fun save() { + if (readOnly || saving || loadState != EditorLoadState.READY) return + val snapshot = text + val bytes = snapshot.toByteArray(charset.charset) + saving = true + scope.launch { + val ok = withContext(Dispatchers.IO) { + runCatching { + val target = resolveEditorSaveTarget(file) + val parent = target.parentFile + if (parent == null) { + target.writeBytes(bytes) + } else { + val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent) + try { + tmp.writeBytes(bytes) + runCatching { + Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath())) + } + if (!tmp.renameTo(target)) error("rename to ${target.name} failed") + } finally { + tmp.delete() + } + } + }.isSuccess + } + saving = false + if (ok) { + if (text == snapshot) dirty = false + } else { + Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show() + } + } + } + + fun tryExit() { + if (saving) return + if (dirty && !readOnly) showDiscard = true else onExit() + } + + BackHandler { tryExit() } + + if (showDiscard) { + OutlinedAlertDialog( + onDismissRequest = { showDiscard = false }, + title = { Text(stringResource(R.string.fm_edit_discard_title)) }, + text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) }, + confirmButton = { + TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.fm_edit_discard)) + } + }, + dismissButton = { + TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.common_cancel)) + } + }, + ) + } + + Column( + modifier = modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.surfaceContainer) + .padding(horizontal = 8.dp, vertical = 6.dp), + ) { + IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) { + Icon( + Icons.Filled.ArrowBack, + stringResource(R.string.fm_back), + tint = MaterialTheme.colorScheme.primary, + ) + } + Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) { + Text( + text = file.name, + color = MaterialTheme.colorScheme.onBackground, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (dirty) { + Text( + text = "\u2022 " + stringResource(R.string.fm_edit_modified), + color = MaterialTheme.colorScheme.primary, + fontSize = 11.sp, + maxLines = 1, + ) + } + } + if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) { + Text( + text = stringResource( + if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 10.sp, + maxLines = 1, + modifier = Modifier + .background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small) + .padding(horizontal = 6.dp, vertical = 2.dp), + ) + Spacer(Modifier.width(6.dp)) + } + IconButton( + onClick = { showSearch = !showSearch }, + enabled = loadState == EditorLoadState.READY, + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.Search, + stringResource(R.string.fm_edit_find), + tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton( + onClick = { save() }, + enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving, + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.Save, + stringResource(R.string.fm_edit_save), + tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + if (showSearch && loadState == EditorLoadState.READY) { + Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp), + ) { + OutlinedTextField( + value = query, + onValueChange = { query = it; matchIndex = 0 }, + singleLine = true, + placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) }, + textStyle = MaterialTheme.typography.bodySmall, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }), + modifier = Modifier.weight(1f).focusGlide(), + ) + Text( + text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp), + ) + IconButton( + onClick = { gotoMatch(-1) }, + enabled = matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.KeyboardArrowUp, + stringResource(R.string.fm_edit_find_previous), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + IconButton( + onClick = { gotoMatch(1) }, + enabled = matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.KeyboardArrowDown, + stringResource(R.string.fm_edit_find_next), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) { + Text( + text = "Aa", + color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 13.sp, + ) + } + IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) { + Icon( + Icons.Filled.Close, + stringResource(R.string.common_cancel), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp), + ) { + OutlinedTextField( + value = replacement, + onValueChange = { replacement = it }, + singleLine = true, + placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) }, + textStyle = MaterialTheme.typography.bodySmall, + modifier = Modifier.weight(1f).focusGlide(), + ) + TextButton( + onClick = { replaceCurrent() }, + enabled = !readOnly && matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) + } + TextButton( + onClick = { replaceAll() }, + enabled = !readOnly && matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp) + } + } + } + } + + Box( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .onSizeChanged { viewportHeight = it.height }, + ) { + when (loadState) { + EditorLoadState.LOADING -> CircularProgressIndicator( + modifier = Modifier.align(Alignment.Center), + ) + + EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.align(Alignment.Center).padding(24.dp), + ) { + Text( + text = stringResource( + if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large + else R.string.fm_edit_open_failed, + if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length()) + else file.name, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 14.sp, + textAlign = TextAlign.Center, + ) + } + + EditorLoadState.READY -> Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(scrollState), + ) { + Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) { + LineNumbers( + scrollState = scrollState, + viewportHeight = viewportHeight, + lineHeightDp = lineHeightDp, + lineHeightPx = lineHeightPx, + totalLines = totalLines, + cursorLine = cursorLine, + style = bodyStyle, + mutedColor = MaterialTheme.colorScheme.onSurfaceVariant, + cursorColor = MaterialTheme.colorScheme.primary, + ) + Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) { + BasicTextField( + value = TextFieldValue(text = text, selection = selection, composition = composing), + onValueChange = { next -> + val changed = next.text != text + text = next.text + selection = next.selection + composing = next.composition + if (changed) dirty = true + }, + readOnly = readOnly, + textStyle = bodyStyle, + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Text, + capitalization = KeyboardCapitalization.None, + ), + modifier = Modifier.fillMaxHeight().focusGlide(), + ) + } + } + } + } + } + + if (loadState == EditorLoadState.READY) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp), + ) { + Text( + text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + ) + Spacer(Modifier.weight(1f)) + Text( + text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + ) + } + } + } +} + +@Composable +private fun LineNumbers( + scrollState: ScrollState, + viewportHeight: Int, + lineHeightDp: Dp, + lineHeightPx: Float, + totalLines: Int, + cursorLine: Int, + style: TextStyle, + mutedColor: Color, + cursorColor: Color, + modifier: Modifier = Modifier, +) { + val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1) + val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx) + .toInt() + .coerceIn(firstLine, totalLines - 1) + Column( + horizontalAlignment = Alignment.End, + modifier = modifier + .width(IntrinsicSize.Min) + .padding(top = lineHeightDp * firstLine.toFloat()), + ) { + for (line in firstLine..lastLine) { + Text( + text = (line + 1).toString(), + color = if (line == cursorLine) cursorColor else mutedColor, + textAlign = TextAlign.End, + maxLines = 1, + style = style, + modifier = Modifier.fillMaxWidth().height(lineHeightDp), + ) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt index d6fe58ad7f..4da77ee6d7 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt @@ -47,6 +47,7 @@ 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 @@ -533,6 +534,10 @@ 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 diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt index 7fb5cdc04b..4362c9308c 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt @@ -56,7 +56,7 @@ object BattleNet { Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"), ) - val STORE: List get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" } + val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" } // Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity. private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs") diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt index a5fb9a4a40..af25344b77 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -72,6 +72,8 @@ 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) => { @@ -91,7 +93,8 @@ 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 inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " + + val key = JSONObject.quote(service) + val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " + "if (!s || typeof s[$name] !== 'function') return { missing: true }; " + "return { value: $run }; })()" return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" + @@ -170,6 +173,7 @@ 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>() @@ -232,19 +236,25 @@ 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 - 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") + return instanceFor(instances(context, inspector), 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 = @@ -260,34 +270,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): Boolean { + private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? { 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 true } + listed.getOrNull()?.let { if (done(it)) return it } Thread.sleep(1_000) } - return false + return null } - fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean { + fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? { connect(context, inspector) - if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false + if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null return settle(context, inspector, guid) { list -> list.any { it.id == projectId } } } - fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean { + fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? { connect(context, inspector) - if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false + if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } } } - fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean { + fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? { 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 false + if (failed == null || failed.length() > 0) return null return settle(context, inspector, guid) { list -> list.none { it.id == project.id } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt index 40cdd0e471..b76172edb1 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt @@ -275,12 +275,15 @@ 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) { - val staged = File(file.path + ".staged") - java.io.FileOutputStream(staged).use { out -> - out.write(text.toByteArray()) - out.fd.sync() + 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") } - if (!staged.renameTo(file)) throw IOException("Could not replace $file") } private fun writeResolver(properties: LinkProperties?) { @@ -333,6 +336,8 @@ 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() diff --git a/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt new file mode 100644 index 0000000000..5a3fb555dd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt @@ -0,0 +1,102 @@ +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 + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index 0d0e20c41d..f5a01d984d 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -23,6 +23,7 @@ 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 @@ -217,24 +218,12 @@ object ProtonExtras { @Synchronized fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { - if (installInProgress) return context.getString(R.string.pextra_busy) + if (installInProgress || prefetching) return context.getString(R.string.pextra_busy) installInProgress = true return try { installNow(context, tool, onProgress) } finally { installInProgress = false } } - 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) - } - + private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? { val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag) onProgress(downloading, 0) var downloaded = false @@ -252,6 +241,41 @@ 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() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 34d96eab4b..9ec5f5cba4 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -95,7 +95,11 @@ object SessionFiles { return all } - fun stage(context: Context, root: File, startsSession: Boolean = false) { + 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) { 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) @@ -660,6 +664,7 @@ 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}" /** @@ -709,7 +714,12 @@ 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)) } - return seedRecentSort(out, 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 } // The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort, @@ -729,9 +739,11 @@ 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 indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t" + val before = text.substring(lineStart, parent.close) + val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t" val section = lines.joinToString(newline) { indent + it } + newline - return text.substring(0, lineStart) + section + text.substring(lineStart) + if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart) + return text.substring(0, parent.close) + newline + section + text.substring(parent.close) } private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds") diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 1928588c13..422db659f6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -63,6 +63,13 @@ 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() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 15d2844d34..144fad8894 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -2705,6 +2705,7 @@ 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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index 5a61619d12..caa78440a0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -13,7 +13,7 @@ object SettingsReset { internal val SESSION_KEYS = setOf( "orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", - "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", + "drawerWidthDp", "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", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt new file mode 100644 index 0000000000..fecdc8e0b8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt @@ -0,0 +1,104 @@ +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" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt index 85ea9fad69..fab04097d3 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt @@ -103,7 +103,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog XboxContent.complete(app, item, folder) return folder.path } - val exe = executable(folder) + val exe = runCatching { executable(folder) }.onFailure { + StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}") + }.getOrThrow() 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))) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt index d966dea1e8..b33d1d0d77 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt @@ -21,8 +21,9 @@ 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 } - require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." } - val manifest = (config + legacy).single() + val manifests = config.ifEmpty { legacy } + require(manifests.size == 1) { "Missing or ambiguous game manifest." } + val manifest = manifests.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) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 5251fb12bf..052241a8b9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -110,6 +110,9 @@ 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 @@ -120,7 +123,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 - ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also { + ?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also { scans[target.addOns.path] = key to it report(target, it) } @@ -131,6 +134,26 @@ 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 { @@ -174,11 +197,9 @@ internal class CurseLink(val app: UserApps.App) { return Linked(url, guid) } - fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked -> + fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked -> val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns) - val project = CurseForgeApp.owner(projects, folder) ?: return@call false - if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState() - true + CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() } } internal val stopped: Job get() = work @@ -322,7 +343,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd scope.launch { val done = withContext(Dispatchers.IO) { runCatching { - via.call(context, into) { + via.change(context, into) { if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id) else CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index f447b15686..429db30258 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -11,6 +11,7 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.shrinkHorizontally +import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandHorizontally import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically @@ -228,8 +229,14 @@ private fun AgentPageContent( } val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) } val inlineControls: (@Composable () -> Unit)? = if (inline) ({ - ModelChip(panel, togglePanel, inputModifier, compact = true) - ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) }) + // The open menu needs the row's width for its own buttons. + androidx.compose.animation.AnimatedVisibility(!menuOpen, enter = expandHorizontally(expandFrom = Alignment.Start) + fadeIn(), + exit = shrinkHorizontally(shrinkTowards = Alignment.Start) + fadeOut()) { + Row(verticalAlignment = Alignment.CenterVertically) { + ModelChip(panel, togglePanel, inputModifier, compact = true) + ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) }) + } + } menu() }) else null // A host with a title bar shows the top bar there. @@ -245,8 +252,11 @@ private fun AgentPageContent( LaunchedEffect(AgentHost.approvals.size, panel) { if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE } + androidx.compose.foundation.layout.BoxWithConstraints(modifier.fillMaxSize()) { + // On a short page the picker would take it all and leave no conversation, so it scrolls within a share of the page. + val panelMax = maxHeight * 0.5f Column( - modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> + Modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> val k = e.nativeKeyEvent if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false if (k.action == KeyEvent.ACTION_UP) composer.open() @@ -269,8 +279,8 @@ private fun AgentPageContent( else -> { if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() } when (panel) { - AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() } - AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() } + AgentPanel.MODEL -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentModelPicker() } + AgentPanel.USAGE -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentUsage() } else -> Unit } val list = rememberLazyListState() @@ -322,11 +332,12 @@ private fun AgentPageContent( } } androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { - AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest) + AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest, hideAttach = inline && menuOpen) } } } } + } } /** Whether the editor has the cursor; [open] puts it there. */ @@ -397,10 +408,12 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val working = AgentHost.state == AgentHost.State.WORKING + // Closed, the outline sits flush against the lone button. + val shape = if (open) Shape16 else Shape12 Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f)) - .border(1.dp, pal.line, Shape16).padding(end = 2.dp), + modifier = Modifier.clip(shape).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f)) + .border(1.dp, pal.line, shape).then(if (open) Modifier.padding(top = 3.dp, bottom = 3.dp, end = 4.dp) else Modifier), ) { androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(), exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) { @@ -423,7 +436,7 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP } } } - HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu") { onOpen(!open) } + HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu", startPadding = if (open) null else 0.dp) { onOpen(!open) } } } @@ -437,12 +450,13 @@ private fun AgentPanelBar(title: String, onClose: () -> Unit) { @Composable internal fun HeaderAction( - icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit, + icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, + startPadding: Dp? = null, onClick: () -> Unit, ) { val pal = LocalPalette.current Box( contentAlignment = Alignment.Center, - modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12) + modifier = Modifier.padding(start = startPadding ?: if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12) .background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant) .clickable(enabled = enabled, onClick = onClick) .then(if (tag != null) Modifier.testTag(tag) else Modifier), @@ -715,7 +729,7 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit. @Composable private fun AgentComposer( composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, - onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, + onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, hideAttach: Boolean = false, ) { val context = LocalContext.current var draft by draftState @@ -747,13 +761,13 @@ private fun AgentComposer( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), ) { AgentActivity(labOpen) { labOpen = !labOpen } } - AgentEditor(composer, draftState, visible, controls, send) + AgentEditor(composer, draftState, visible, controls, send, hideAttach) } } /** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */ @Composable -private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) { +private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit, hideAttach: Boolean = false) { val context = LocalContext.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -852,14 +866,14 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String if (stacked) Column { text(Modifier.fillMaxWidth()) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - if (attach) AttachButton() - if (AgentAttachments.gameFrame != null) GameFrameButton() - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() } + AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } + AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() } actions() } } else Row(verticalAlignment = Alignment.Bottom) { - if (attach) AttachButton() - if (AgentAttachments.gameFrame != null) GameFrameButton() + AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } + AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } text(Modifier.weight(1f)) if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() } actions() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt index 21057d1dea..46ea147324 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt @@ -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().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) + page = sessionDrawerPages().let { it.strip().step(it.tabFor(page), if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) } } true } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt index 92a6d0b365..c45baa29f1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt @@ -33,6 +33,8 @@ 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 @@ -109,13 +111,21 @@ internal fun VeilRing() { } } -private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float = +private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray = when (val o = shape.createOutline(size, dir, density)) { - is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x - is Outline.Rectangle -> 0f - is Outline.Generic -> minOf(size.width, size.height) / 2f + 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 } } +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, @@ -190,7 +200,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val density = LocalDensity.current val dir = LocalLayoutDirection.current val edges = remember { List(4) { Animatable(0f) } } - val corner = remember { Animatable(0f) } + val corners = remember { List(4) { Animatable(0f) } } val solid = remember { Animatable(0f) } val alpha = remember { Animatable(0f) } val scope = rememberCoroutineScope() @@ -259,14 +269,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 endCorner = cornerOf(s.shape, size, dir, density) + val endCorners = cornersOf(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)) } - launch { corner.animateTo(r, Motion.tw(90)) } + corners.forEach { c -> launch { c.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 @@ -281,7 +291,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { flight.cancel() val at = glide.boundsOf(s) ?: b launch { solid.animateTo(0f, Motion.tw(150)) } - launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) } + // 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)) } } } listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v -> jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) } } @@ -289,9 +301,11 @@ 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 = cornerOf(s.shape, size, dir, density) + val r = cornersOf(s.shape, size, dir, density) jobs[4]?.cancel() - jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) } + 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)) } } + } } snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) -> if (Motion.scale == 0f) { @@ -302,7 +316,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 - corner.snapTo(cornerOf(src.shape, size, dir, density)) + cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) } alpha.snapTo(1f) } shown = src @@ -343,10 +357,11 @@ 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 @@ -394,21 +409,13 @@ 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 rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f) + val radii = FloatArray(4) { corners[it].value } val f = solid.value - 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.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f) if (f < 0.99f) { - 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, - ) + 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) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 70c49a5518..c99bee629d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -51,6 +51,7 @@ 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 @@ -248,6 +249,7 @@ 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 -> @@ -1273,3 +1275,65 @@ 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) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 5f9d6d0ebc..bb4cc867cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -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.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false) + val done = runCatching { link.change(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 } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt index 30a9c554f9..c1c918ef32 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt @@ -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 = { true }, + movable = { it != SessionDrawerPage.MORE.name }, rowHeight = STORE_ROW, handleWidth = STORE_HANDLE, releaseSignal = releaseSignal, onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } }, @@ -66,6 +66,8 @@ 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt index 39c4badb7e..2b3a4a5413 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -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) return@LaunchedEffect + if (holds || !open || Steps.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) FocusRequester.Cancel else FocusRequester.Default } } + .focusProperties { exit = { if (open && !Steps.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), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index c8d87ffbd4..cd85c8a0a1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -27,7 +27,7 @@ internal object DeveloperTools { internal object NavTabs { const val MORE = "more" val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", "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_SHELVED = setOf("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") diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index 5dd8ba682f..b2bc10c8a4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -12,10 +12,11 @@ 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 { @@ -27,7 +28,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 + fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION && page != SessionDrawerPage.MORE fun load(context: Context) { order = arrange(SessionPrefs.drawerPageOrder(context)) @@ -81,6 +82,22 @@ 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)] diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index ffca74a17f..b84a27be75 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -39,6 +39,7 @@ 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 @@ -95,6 +96,14 @@ 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 @@ -174,6 +183,7 @@ 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) { @@ -186,6 +196,7 @@ 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 { @@ -261,6 +272,8 @@ 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, @@ -418,6 +431,8 @@ 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) { @@ -428,11 +443,17 @@ 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) { - if (host.open != null) host.open = null else a.onClose() + when { + host.open != null -> host.open = null + insideMore -> onPageChange(SessionDrawerPage.MORE) + else -> a.onClose() + } } BackHandler(enabled = open && confirmStop) { confirmStop = false } - val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop) + val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore) LaunchedEffect(layerOpen) { onLayerChange(layerOpen) } var seenBackRequest by remember { mutableStateOf(backRequest) } LaunchedEffect(backRequest) { @@ -442,9 +463,10 @@ 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 } + LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false } LaunchedEffect(a.selectedGameProfileId) { if (host.open == "fex") host.open = null } @@ -506,17 +528,22 @@ 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 - val sheetWidth = if (docked) maxWidth else minOf(420.dp, maxWidth * 0.92f) + // 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 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(sheetWidth)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) { + FocusGlideHost(Modifier.fillMaxHeight().width(if (docked) sheetWidth else sheetWidth + DRAWER_HANDLE_STRIP)) { 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() @@ -527,6 +554,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont DrawerPages.rearrange(drawerContext, held) releaseSignal++ } ?: run { managing = false } + insideMore -> onPageChange(SessionDrawerPage.MORE) else -> a.onClose() } } @@ -604,16 +632,14 @@ 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.step(page, -1)) + host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), -1)) } - DrawerPageTabs(page = page, pages = pages, compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) } + DrawerPageTabs(page = pages.tabFor(page), pages = pages.strip(), 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.step(page, 1)) + host.open = null; onPageChange(pages.strip().step(pages.tabFor(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), @@ -888,6 +914,7 @@ 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)) { @@ -965,6 +992,12 @@ 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) } }, @@ -1152,6 +1185,70 @@ 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, @@ -1338,12 +1435,92 @@ 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 - if (!choosesDisplay && !swapsGame) return + val hasSecondScreen = a.secondScreenDisplays.isNotEmpty() + if (!hasSecondScreen && !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)), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index f9c81f4e42..2d995dda2f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -31,6 +31,7 @@ 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 @@ -154,8 +155,24 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() }, words = { val runtimeStatus: @Composable () -> Unit = { - 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, + 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, 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt index 2827e3c7cd..e7b6a09b19 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt @@ -23,6 +23,7 @@ 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 @@ -61,6 +62,7 @@ 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) } @@ -116,6 +118,7 @@ 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( @@ -164,6 +167,7 @@ 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) { @@ -171,6 +175,7 @@ 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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt index 73e68986de..b888f08065 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt @@ -45,6 +45,7 @@ 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 @@ -174,6 +175,7 @@ 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) @@ -241,8 +243,12 @@ internal fun StepOut( LaunchedEffect(open, measured) { if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect delay(Motion.ms(300).toLong()) - withFrameNanos { } - runCatching { first.requestFocus() } + // 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() } + } } LaunchedEffect(open, grown, inputMode.inputMode) { @@ -289,6 +295,7 @@ 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()) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt index 0e081d5cda..391957cf58 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt @@ -213,10 +213,10 @@ internal fun SortableRows( } @Composable -private fun MoreLine() { +internal fun MoreLine(height: androidx.compose.ui.unit.Dp = TAB_ROW) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - Column(Modifier.fillMaxWidth().height(TAB_ROW).testTag("tab-more-line")) { + Column(Modifier.fillMaxWidth().height(height).testTag("tab-more-line")) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f45ecc7218..936489c2c6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -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>First run downloads Steam. This may take a few minutes.</item> + <item>DroidDeck downloads Steam in the background while you set up, so your first launch is quicker.</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,6 +704,9 @@ <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> @@ -864,6 +867,7 @@ <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> @@ -2217,6 +2221,23 @@ <string name="fm_favorite_removed">Removed \"%1$s\" from Favorites</string> <string name="fm_empty_directory">Empty directory</string> <string name="fm_up_one_level">Up one level</string> + <string name="fm_edit_open">Open</string> + <string name="fm_edit_save">Save</string> + <string name="fm_edit_read_only">Read only</string> + <string name="fm_edit_binary">Binary</string> + <string name="fm_edit_modified">Modified</string> + <string name="fm_edit_position">Ln %1$d, Col %2$d</string> + <string name="fm_edit_find">Find</string> + <string name="fm_edit_find_previous">Find previous</string> + <string name="fm_edit_find_next">Find next</string> + <string name="fm_edit_replace">Replace</string> + <string name="fm_edit_replace_all">All</string> + <string name="fm_edit_discard_title">Discard changes?</string> + <string name="fm_edit_discard_text">Changes to \"%1$s\" will be lost.</string> + <string name="fm_edit_discard">Discard</string> + <string name="fm_edit_save_failed">Couldn\'t save \"%1$s\"</string> + <string name="fm_edit_open_failed">Couldn\'t open \"%1$s\"</string> + <string name="fm_edit_too_large">Too large to open (%1$s)</string> <string name="fm_choose_folder">Choose a folder</string> <string name="fm_choose_file">Choose a file</string> <string name="ctrl_tint_steam_blue">Steam blue</string> @@ -4132,6 +4153,8 @@ <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> @@ -4405,4 +4428,19 @@ <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> diff --git a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt index 2e06a6d8fe..dacf38c34c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt @@ -35,6 +35,7 @@ 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 @@ -49,6 +50,7 @@ class ProtonMenuAutoTest { } AutoComponents.online = { true } AutoComponents.unfavourable = { false } + AutoComponents.firstRunHeldBack = { false } SessionState.running = false SessionState.phase = SessionPhase.IDLE SessionState.stopRequested = false @@ -63,6 +65,7 @@ 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") @@ -77,6 +80,7 @@ class ProtonMenuAutoTest { menu.protonPercent = -1 AutoComponents.online = online AutoComponents.unfavourable = constrained + AutoComponents.firstRunHeldBack = firstRunHeldBack SessionState.running = false SessionState.phase = SessionPhase.IDLE SessionState.stopRequested = false diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt index dc12206545..bdb58b2a39 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt @@ -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(100)) + Files.write(outside.resolve("save.dat"), ByteArray(1 shl 20)) 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) < 100) + assertTrue(AgentStorage.size(item) < 1 shl 20) AgentStorage.delete(item) assertFalse(Files.exists(item)) assertTrue(Files.exists(outside.resolve("save.dat"))) diff --git a/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt b/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt new file mode 100644 index 0000000000..7fb3a7a68b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt @@ -0,0 +1,143 @@ +package com.droiddeck.launcher.files + +import java.io.ByteArrayInputStream +import java.io.File +import java.nio.charset.Charset +import java.nio.file.Files +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class TextEditorLogicTest { + + @Test + fun nulByteMarksBinary() { + val clean = "hello world".toByteArray() + assertFalse(editorIsBinary(clean)) + val withNul = byteArrayOf(1, 2, 0, 3) + assertTrue(editorIsBinary(withNul)) + } + + @Test + fun binaryScanStopsAtSampleLimit() { + val bytes = ByteArray(9000) { if (it == 8999) 0 else 65 } + assertFalse(editorIsBinary(bytes)) + assertTrue(editorIsBinary(bytes, sample = 9000)) + } + + @Test + fun utf8TextDecodesAsUtf8() { + val decoded = decodeEditorText("你好, world".toByteArray(Charsets.UTF_8)) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertFalse(decoded.lossy) + assertEquals("你好, world", decoded.text) + } + + @Test + fun gbkBytesFallBackToGb18030() { + val gbk = "你好".toByteArray(Charset.forName("GBK")) + val decoded = decodeEditorText(gbk) + assertEquals(EditorCharset.GB18030, decoded.charset) + assertFalse(decoded.lossy) + assertEquals("你好", decoded.text) + } + + @Test + fun undecodableBytesStayLossyUtf8() { + val decoded = decodeEditorText(byteArrayOf(0xFF.toByte())) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertTrue(decoded.lossy) + } + + @Test + fun literalReplacementCharStaysCleanUtf8() { + val decoded = decodeEditorText("�A".toByteArray(Charsets.UTF_8)) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertFalse(decoded.lossy) + } + + @Test + fun readCappedRefusesOverLimit() { + val data = ByteArray(100) { 65 } + assertArrayEquals(data, readCapped(ByteArrayInputStream(data), 100L)) + assertNull(readCapped(ByteArrayInputStream(data), 99L)) + } + + @Test + fun tabsExpandToTabStops() { + assertEquals("ab c", expandEditorTabs("ab\tc")) + assertEquals(" x", expandEditorTabs("\tx")) + assertEquals("abcd e", expandEditorTabs("abcd\te")) + assertEquals("abc def g", expandEditorTabs("abc\tdef\tg")) + assertEquals("a \n b", expandEditorTabs("a\t\n\tb")) + assertEquals("plain text", expandEditorTabs("plain text")) + } + + @Test + fun lineCountCountsTrailingEmptyLine() { + assertEquals(1, lineCountOf("")) + assertEquals(1, lineCountOf("abc")) + assertEquals(2, lineCountOf("a\nb")) + assertEquals(2, lineCountOf("a\n")) + } + + @Test + fun offsetMapsToZeroBasedLineAndOneBasedColumn() { + val text = "ab\ncd" + assertEquals(0, lineIndexOfOffset(text, 0)) + assertEquals(0, lineIndexOfOffset(text, 2)) + assertEquals(1, lineIndexOfOffset(text, 3)) + assertEquals(1, lineIndexOfOffset(text, 5)) + assertEquals(1, columnOfOffset(text, 0)) + assertEquals(3, columnOfOffset(text, 2)) + assertEquals(2, columnOfOffset(text, 4)) + assertEquals(3, columnOfOffset(text, 5)) + } + + @Test + fun findMatchesHonorsCaseAndLimit() { + val text = "abcABCabc" + val all = findEditorMatches(text, "abc", matchCase = false) + assertEquals(listOf(0..2, 3..5, 6..8), all) + val exact = findEditorMatches(text, "abc", matchCase = true) + assertEquals(listOf(0..2, 6..8), exact) + assertEquals(2, findEditorMatches(text, "abc", matchCase = false, limit = 2).size) + assertEquals(emptyList<IntRange>(), findEditorMatches(text, "")) + assertEquals(listOf(0..1), findEditorMatches("aaa", "aa")) + } + + @Test + fun replaceSpansEveryMatch() { + val text = "one two one" + val matches = findEditorMatches(text, "one", matchCase = true) + assertEquals("1 two 1", replaceEditorMatches(text, matches, "1")) + assertEquals(text, replaceEditorMatches(text, emptyList(), "x")) + } + + @Test + fun saveTargetResolvesSymbolicLink() { + val dir = Files.createTempDirectory("editor-link").toFile() + try { + val target = File(dir, "real.txt").apply { writeText("hi") } + val link = File(dir, "link.txt") + Files.createSymbolicLink(link.toPath(), target.toPath()) + assertEquals(target.canonicalFile, resolveEditorSaveTarget(link)) + } finally { + dir.deleteRecursively() + } + } + + @Test + fun saveTargetKeepsRegularFile() { + val dir = Files.createTempDirectory("editor-plain").toFile() + try { + val plain = File(dir, "plain.txt").apply { writeText("hi") } + assertEquals(plain, resolveEditorSaveTarget(plain)) + } finally { + dir.deleteRecursively() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt index ea0c471faa..2ada13c310 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -354,13 +354,15 @@ class BattleNetTest { assertEquals(codes.distinct(), codes) assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes) assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" }) - assertFalse(BattleNet.STORE.any { it.code == "WoWC" || it.code == "WoWF" }) + assertFalse(BattleNet.STORE.any { it.code == "WoWC" }) + assertEquals("wow_forever", BattleNet.STORE.first { it.code == "WoWF" }.uid) assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid) assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) }) val installed = listOf("fenris", "diablo3_enus", null) val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code } assertFalse("Fen" in offered || "D3" in offered) - assertTrue("OSI" in offered) + assertTrue("OSI" in offered && "WoWF" in offered) + assertFalse("WoWF" in BattleNet.STORE.filter { BattleNet.notInstalled(it, listOf("wow_forever")) }.map { it.code }) } @Test fun aBattleNetGameStartsWithoutSteamThroughItsShortcutUntilThatIsSwitchedOff() { diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt index 47d892993b..6400c0162e 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -5,6 +5,7 @@ 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 @@ -158,6 +159,7 @@ 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[")) @@ -292,6 +294,37 @@ 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(" ") @@ -305,6 +338,7 @@ 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) @@ -328,8 +362,11 @@ class CurseForgeAppTest { projects.forEach { it.put("status", 1) } true } - "detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g") - "getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) + "detectGameFromPath" -> { + known = true + JSONObject().put("gameInstanceGuid", "g") + } + "getGameInstances" -> if (known) JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) else JSONArray() "deleteMods" -> { projects.removeAll { p -> (p.getString("installedModId") in expression).also { gone -> @@ -467,7 +504,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) - assertTrue(CurseForgeApp.update(context, url, "g", "298842")) + assertNotNull(CurseForgeApp.update(context, url, "g", "298842")) assertTrue("updateMod" in curse.methods) assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update }) } @@ -479,7 +516,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")!! - assertTrue(CurseForgeApp.uninstall(context, url, "g", project)) + assertNotNull(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) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt index ee745b7d14..dea3a46859 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt @@ -155,4 +155,37 @@ 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()) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt new file mode 100644 index 0000000000..dc2b0b5e10 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt @@ -0,0 +1,44 @@ +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) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt new file mode 100644 index 0000000000..7b73b81e91 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt @@ -0,0 +1,22 @@ +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")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt index 468b5728f8..9d5d76fa92 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt @@ -59,6 +59,27 @@ 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) diff --git a/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt b/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt new file mode 100644 index 0000000000..c95873aa2d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt @@ -0,0 +1,16 @@ +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) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt b/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt new file mode 100644 index 0000000000..d1409cce25 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt @@ -0,0 +1,21 @@ +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() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt index d23072471a..cb0a7bf0cc 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt @@ -87,6 +87,34 @@ 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 diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt index 0ea4048e3a..2811284d0e 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -133,6 +133,88 @@ 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() diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt index 4228dee0c3..c36673d3ba 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -40,8 +40,8 @@ class NavTabsTest { } @Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() { - assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", NavTabs.MORE), navigationKeys(state())) - assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("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", "trinkets", "soundtracks", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state())) } @Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() { place("desktop", TabPlace.MORE) val s = state() - assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) + assertEquals(listOf("desktop", "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.BAR) + place("stores", TabPlace.MORE) 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", "trinkets", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "stores", NavTabs.MORE), navigationKeys(state())) } @Test fun anOldLayoutKeepsWhatItsSwitchesShowed() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index 019f47784c..18911a3521 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -8,15 +8,45 @@ class SessionDrawerPageTest { val pages = sessionDrawerPages(hasAgent = false) assertEquals(SessionDrawerPage.CONTROLLER, pages.first()) assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1)) - assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1)) - assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1)) + assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1)) assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) - assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1)) - assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1)) + assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 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)) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt index 807b729f6d..76be29b5da 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt @@ -41,7 +41,8 @@ class SteamIntegrationGroupTest { compose.onNodeWithTag("integration-action-brightness").performClick() compose.onNodeWithTag("integration-action-home").performClick() compose.onNodeWithTag("integration-action-shortcuts").performClick() - assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests) + compose.onNodeWithTag("integration-action-bluetooth").performClick() + assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS, Feature.BLUETOOTH), requests) } @Test fun switchesReflectAndroidGrants() { @@ -50,7 +51,8 @@ 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.onNodeWithText("3 of 4 on").assertExists() + compose.onNodeWithTag("integration-action-bluetooth").assert(stateIs("Off")) + compose.onNodeWithText("3 of 5 on").assertExists() } @Test fun shortcutsDoNotNeedHome() { diff --git a/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin b/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin new file mode 100644 index 0000000000..d6d0a4d676 --- /dev/null +++ b/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin @@ -0,0 +1 @@ +com.droiddeck.launcher.session.TestJvmUncaughtHandler diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index d4b99759d5..1a02e3420f 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -291,6 +291,18 @@ alone would then read as an installed client. spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames): FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all three see it on the first signal, as natively. + - `0013-path-syscalls-through-libc`: FEX passes most path system calls of the guest (`mkdirat`, + `unlinkat`, `renameat`, `renameat2`, `symlinkat`, `linkat`, `mknodat`, `fchmodat`, `fchmodat2`, + `fchownat`, `utimensat`, `truncate`, `chdir`, `chroot`, `inotify_add_watch`) straight to the kernel + with an inline `svc`, which the native userland's path hook never sees, so an x86-64 program wrote + `/opt/...` or `/root/...` to the Android root instead of the rootfs, and `cd` into a rootfs folder + failed. They now go through libc's `syscall()`, which the hook maps like every other path; without + the hook it is the same system call. `tools/tests/test_native_hook_path_syscalls.py` checks the hook + side, including that an allocator which opens files before the hook has started does not hang. + FEX also mirrors each guest signal handler with `syscall(SYS_rt_sigaction, ...)`; for `SIGSYS` the + hook records the guest handler as it does for `sigaction()` and keeps its own installed, so a + program that sets a crash handler is no longer killed by the next blocked system call + (`tools/tests/test_native_hook_sigsys_mask.py`). - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/gradle.properties b/gradle.properties index 3289cc4c5d..16bca3f56d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,6 +4,5 @@ org.gradle.configuration-cache=true org.gradle.parallel=true android.useAndroidX=true android.nonTransitiveRClass=true -ndkVersion=27.3.13750724 org.gradle.tooling.parallel=true diff --git a/tools/build_local.sh b/tools/build_local.sh index d90a458d2c..2c76362956 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -24,6 +24,7 @@ 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} @@ -63,6 +64,11 @@ 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 @@ -112,101 +118,6 @@ 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) @@ -223,46 +134,289 @@ if [[ -z "${github_repo}" ]]; then github_repo=${github_repo%.git} 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 +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 -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}" + rm -rf "${xbox_out}" && mkdir -p "${xbox_out}" && cp -R "${stored}/." "${xbox_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" -fi +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}" -. "${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" + 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 + + 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}" + 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" + 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 + . "${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 +fi 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}") @@ -273,94 +427,6 @@ 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" @@ -384,21 +450,23 @@ else echo "${syncthing_inputs}" > "${proot_out}/.syncthing-inputs" fi -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 +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" 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 @@ -419,19 +487,23 @@ else fi cd "${repo_root}" -python3 tools/quest/build-driver.py "${NDK}" +[[ "${ci_components}" == 1 ]] || 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 ! restore_step xbox "${xbox_key}" "${xbox_out}"; then +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 bash tools/xbox/build-local.sh save_step xbox "${xbox_key}" "${xbox_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}" +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 fi if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then upc_out="${linuxfs_dir}/usr/local/lib/droiddeck-ubisoft" diff --git a/tools/ci/clear-runner-scratch.sh b/tools/ci/clear-runner-scratch.sh new file mode 100755 index 0000000000..aab34a2e92 --- /dev/null +++ b/tools/ci/clear-runner-scratch.sh @@ -0,0 +1,14 @@ +#!/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 diff --git a/tools/components/reuse.py b/tools/components/reuse.py new file mode 100644 index 0000000000..1eb02dca9d --- /dev/null +++ b/tools/components/reuse.py @@ -0,0 +1,150 @@ +"""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/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)) diff --git a/tools/fex/patches/0013-path-syscalls-through-libc.patch b/tools/fex/patches/0013-path-syscalls-through-libc.patch new file mode 100644 index 0000000000..1aa641b311 --- /dev/null +++ b/tools/fex/patches/0013-path-syscalls-through-libc.patch @@ -0,0 +1,144 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 11ff163..4c3be85 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, + } + #endif + ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) { ++ uint64_t Result = ::syscall(syscall_num, arg1); ++ SYSCALL_ERRNO(); ++} ++ ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough2(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2); ++ SYSCALL_ERRNO(); ++} ++ ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough3(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3); ++ SYSCALL_ERRNO(); ++} ++ ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough4(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4); ++ SYSCALL_ERRNO(); ++} ++ ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4, arg5); ++ SYSCALL_ERRNO(); ++} ++ + 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)>); + REGISTER_SYSCALL_IMPL(fdatasync, SyscallPassthrough1<SYSCALL_DEF(fdatasync)>); +- REGISTER_SYSCALL_IMPL(truncate, SyscallPassthrough2<SYSCALL_DEF(truncate)>); ++ REGISTER_SYSCALL_IMPL(truncate, SyscallPathPassthrough2<SYSCALL_DEF(truncate)>); + REGISTER_SYSCALL_IMPL(getcwd, SyscallPassthrough2<SYSCALL_DEF(getcwd)>); +- REGISTER_SYSCALL_IMPL(chdir, SyscallPassthrough1<SYSCALL_DEF(chdir)>); ++ 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)>); +@@ -280,7 +315,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(mlock, SyscallPassthrough2<SYSCALL_DEF(mlock)>); + REGISTER_SYSCALL_IMPL(munlock, SyscallPassthrough2<SYSCALL_DEF(munlock)>); + REGISTER_SYSCALL_IMPL(pivot_root, SyscallPassthrough2<SYSCALL_DEF(pivot_root)>); +- REGISTER_SYSCALL_IMPL(chroot, SyscallPassthrough1<SYSCALL_DEF(chroot)>); ++ REGISTER_SYSCALL_IMPL(chroot, SyscallPathPassthrough1<SYSCALL_DEF(chroot)>); + REGISTER_SYSCALL_IMPL(sync, SyscallPassthrough0<SYSCALL_DEF(sync)>); + REGISTER_SYSCALL_IMPL(acct, SyscallPassthrough1<SYSCALL_DEF(acct)>); + REGISTER_SYSCALL_IMPL(mount, SyscallPassthrough5<SYSCALL_DEF(mount)>); +@@ -312,17 +347,17 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(keyctl, SyscallPassthrough5<SYSCALL_DEF(keyctl)>); + REGISTER_SYSCALL_IMPL(ioprio_set, SyscallPassthrough2<SYSCALL_DEF(ioprio_set)>); + REGISTER_SYSCALL_IMPL(ioprio_get, SyscallPassthrough3<SYSCALL_DEF(ioprio_get)>); +- REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPassthrough3<SYSCALL_DEF(inotify_add_watch)>); ++ REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPathPassthrough3<SYSCALL_DEF(inotify_add_watch)>); + REGISTER_SYSCALL_IMPL(inotify_rm_watch, SyscallPassthrough2<SYSCALL_DEF(inotify_rm_watch)>); + REGISTER_SYSCALL_IMPL(migrate_pages, SyscallPassthrough4<SYSCALL_DEF(migrate_pages)>); +- REGISTER_SYSCALL_IMPL(mkdirat, SyscallPassthrough3<SYSCALL_DEF(mkdirat)>); +- REGISTER_SYSCALL_IMPL(mknodat, SyscallPassthrough4<SYSCALL_DEF(mknodat)>); +- REGISTER_SYSCALL_IMPL(fchownat, SyscallPassthrough5<SYSCALL_DEF(fchownat)>); +- REGISTER_SYSCALL_IMPL(unlinkat, SyscallPassthrough3<SYSCALL_DEF(unlinkat)>); +- REGISTER_SYSCALL_IMPL(renameat, SyscallPassthrough4<SYSCALL_DEF(renameat)>); +- REGISTER_SYSCALL_IMPL(linkat, SyscallPassthrough5<SYSCALL_DEF(linkat)>); +- REGISTER_SYSCALL_IMPL(symlinkat, SyscallPassthrough3<SYSCALL_DEF(symlinkat)>); +- REGISTER_SYSCALL_IMPL(fchmodat, SyscallPassthrough3<SYSCALL_DEF(fchmodat)>); ++ REGISTER_SYSCALL_IMPL(mkdirat, SyscallPathPassthrough3<SYSCALL_DEF(mkdirat)>); ++ REGISTER_SYSCALL_IMPL(mknodat, SyscallPathPassthrough4<SYSCALL_DEF(mknodat)>); ++ REGISTER_SYSCALL_IMPL(fchownat, SyscallPathPassthrough5<SYSCALL_DEF(fchownat)>); ++ REGISTER_SYSCALL_IMPL(unlinkat, SyscallPathPassthrough3<SYSCALL_DEF(unlinkat)>); ++ REGISTER_SYSCALL_IMPL(renameat, SyscallPathPassthrough4<SYSCALL_DEF(renameat)>); ++ REGISTER_SYSCALL_IMPL(linkat, SyscallPathPassthrough5<SYSCALL_DEF(linkat)>); ++ REGISTER_SYSCALL_IMPL(symlinkat, SyscallPathPassthrough3<SYSCALL_DEF(symlinkat)>); ++ REGISTER_SYSCALL_IMPL(fchmodat, SyscallPathPassthrough3<SYSCALL_DEF(fchmodat)>); + REGISTER_SYSCALL_IMPL(unshare, SyscallPassthrough1<SYSCALL_DEF(unshare)>); + REGISTER_SYSCALL_IMPL(splice, SyscallPassthrough6<SYSCALL_DEF(splice)>); + REGISTER_SYSCALL_IMPL(tee, SyscallPassthrough4<SYSCALL_DEF(tee)>); +@@ -343,7 +378,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(kcmp, SyscallPassthrough5<SYSCALL_DEF(kcmp)>); + REGISTER_SYSCALL_IMPL(sched_setattr, SyscallPassthrough3<SYSCALL_DEF(sched_setattr)>); + REGISTER_SYSCALL_IMPL(sched_getattr, SyscallPassthrough4<SYSCALL_DEF(sched_getattr)>); +- REGISTER_SYSCALL_IMPL(renameat2, SyscallPassthrough5<SYSCALL_DEF(renameat2)>); ++ REGISTER_SYSCALL_IMPL(renameat2, SyscallPathPassthrough5<SYSCALL_DEF(renameat2)>); + REGISTER_SYSCALL_IMPL(getrandom, SyscallPassthrough3<SYSCALL_DEF(getrandom)>); + REGISTER_SYSCALL_IMPL(memfd_create, SyscallPassthrough2<SYSCALL_DEF(memfd_create)>); + REGISTER_SYSCALL_IMPL(membarrier, SyscallPassthrough2<SYSCALL_DEF(membarrier)>); +@@ -468,7 +503,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(get_robust_list, SyscallPassthrough3<SYSCALL_DEF(get_robust_list)>); + REGISTER_SYSCALL_IMPL_X64(sync_file_range, SyscallPassthrough4<SYSCALL_DEF(sync_file_range)>); + REGISTER_SYSCALL_IMPL_X64(vmsplice, SyscallPassthrough4<SYSCALL_DEF(vmsplice)>); +- REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPassthrough4<SYSCALL_DEF(utimensat)>); ++ REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPathPassthrough4<SYSCALL_DEF(utimensat)>); + REGISTER_SYSCALL_IMPL_X64(fallocate, SyscallPassthrough4<SYSCALL_DEF(fallocate)>); + REGISTER_SYSCALL_IMPL_X64(timerfd_settime, SyscallPassthrough4<SYSCALL_DEF(timerfd_settime)>); + REGISTER_SYSCALL_IMPL_X64(timerfd_gettime, SyscallPassthrough2<SYSCALL_DEF(timerfd_gettime)>); +@@ -492,7 +527,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(cachestat, UnimplementedSyscallSafe); + } + if (Handler->IsHostKernelVersionAtLeast(6, 6, 0)) { +- REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPassthrough4<SYSCALL_DEF(fchmodat2)>); ++ REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPathPassthrough4<SYSCALL_DEF(fchmodat2)>); + } else { + REGISTER_SYSCALL_IMPL_X64(fchmodat2, UnimplementedSyscallSafe); + } +@@ -529,7 +564,7 @@ namespace x32 { + REGISTER_SYSCALL_IMPL_X32(timer_settime64, SyscallPassthrough4<SYSCALL_DEF(timer_settime)>); + REGISTER_SYSCALL_IMPL_X32(timerfd_gettime64, SyscallPassthrough2<SYSCALL_DEF(timerfd_gettime)>); + REGISTER_SYSCALL_IMPL_X32(timerfd_settime64, SyscallPassthrough4<SYSCALL_DEF(timerfd_settime)>); +- REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPassthrough4<SYSCALL_DEF(utimensat)>); ++ REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPathPassthrough4<SYSCALL_DEF(utimensat)>); + REGISTER_SYSCALL_IMPL_X32(ppoll_time64, SyscallPassthrough5<SYSCALL_DEF(ppoll)>); + REGISTER_SYSCALL_IMPL_X32(io_pgetevents_time64, SyscallPassthrough6<SYSCALL_DEF(io_pgetevents)>); + REGISTER_SYSCALL_IMPL_X32(mq_timedsend_time64, SyscallPassthrough5<SYSCALL_DEF(mq_timedsend)>); diff --git a/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch b/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch new file mode 100644 index 0000000000..204c5c5dc6 --- /dev/null +++ b/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch @@ -0,0 +1,51 @@ +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]); + } + } diff --git a/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch b/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch new file mode 100644 index 0000000000..b1557d3c39 --- /dev/null +++ b/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch @@ -0,0 +1,15 @@ +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": { diff --git a/tools/fex/patches/0016-identity-syscalls-through-libc.patch b/tools/fex/patches/0016-identity-syscalls-through-libc.patch new file mode 100644 index 0000000000..3823e28e1d --- /dev/null +++ b/tools/fex/patches/0016-identity-syscalls-through-libc.patch @@ -0,0 +1,106 @@ +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)>); diff --git a/tools/linuxfs/desktop/droiddeck-desktop-gpu b/tools/linuxfs/desktop/droiddeck-desktop-gpu index a0173f7b6d..a25e21e366 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop-gpu +++ b/tools/linuxfs/desktop/droiddeck-desktop-gpu @@ -1,7 +1,6 @@ #!/usr/bin/python3 import os import re -import shutil HOME = os.environ.get("HOME", "/root") SYSTEM_DIR = "/usr/share/applications" @@ -10,8 +9,6 @@ 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(): @@ -27,33 +24,6 @@ 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] @@ -75,24 +45,8 @@ 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(";"))) - gpu = gpu_on and bool(cats & {"Game", "Emulator"}) - browser = chromium(exec_line) - if not gpu and not browser: + if not (gpu_on and cats & {"Game", "Emulator"}): 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: @@ -111,8 +65,7 @@ def wrap(text, gpu_on=True): wrapped_rest = [] for l in rest: if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "): - action = l[5:].strip() - l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action) + l = "Exec=" + gpu_exec(l[5:].strip()) wrapped_rest.append(l) if wrapped_rest and wrapped_rest[0].strip(): wrapped_rest.insert(0, "") diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run index b4a1910f24..d0d33c595e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run @@ -45,11 +45,20 @@ 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:$(cat "$dir/arch" 2>/dev/null) in + case $fex:$arch 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") ;; diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index e8edb67d5e..7c1dd3176f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -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", + "libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0", )) PROVIDED_NEEDS = { "libwayland-client.so.0": ("libffi.so.8",), @@ -670,6 +670,8 @@ 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" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index c58790f87a..642cc7a836 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -65,12 +65,14 @@ 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" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0 +[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0 work=$(mktemp -d) trap 'rm -rf "$work"' EXIT @@ -167,6 +169,46 @@ 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 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale index c1c2cc6ebc..2a9585efe7 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale @@ -10,6 +10,7 @@ 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]*|"(?:\\.|[^"\\])*"|[{}]') @@ -137,6 +138,10 @@ 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) @@ -179,6 +184,11 @@ 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: @@ -186,7 +196,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)): + for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)): try: step(sys.argv[1]) except (OSError, ValueError, RecursionError) as error: diff --git a/tools/linuxfs/preload/binfmt.c b/tools/linuxfs/preload/binfmt.c index 94cecdeb86..484a81094b 100644 --- a/tools/linuxfs/preload/binfmt.c +++ b/tools/linuxfs/preload/binfmt.c @@ -21,6 +21,29 @@ 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) { @@ -32,17 +55,26 @@ 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[20]; + unsigned char head[sizeof(Elf64_Ehdr)]; 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 || error == EACCES ? 1 : 0; + kind = machine == EM_X86_64 || machine == EM_386 || appimage(fd, head, n) || 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) { @@ -58,21 +90,6 @@ 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++; @@ -117,12 +134,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() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp); + if (handing_off() && dd_program_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() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error); + if (handing_off() && dd_program_lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error); errno = error; return -1; } @@ -144,7 +161,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 = lookup(file, resolved, sizeof resolved) ? resolved : file; + const char *path = dd_program_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"); @@ -156,7 +173,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 = lookup(file, path, sizeof path); + int found = dd_program_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"); diff --git a/tools/linuxfs/preload/clockpause.c b/tools/linuxfs/preload/clockpause.c index 8fe0b7ce77..70b4179329 100644 --- a/tools/linuxfs/preload/clockpause.c +++ b/tools/linuxfs/preload/clockpause.c @@ -25,7 +25,6 @@ #define CP_FDS 65536 static const int64_t *cp_shift; -static int cp_state; static size_t cp_cond_byte; static unsigned char cp_cond_mask; static unsigned char cp_fds[CP_FDS / 8]; @@ -94,25 +93,14 @@ static void cp_init(void) { } static int64_t cp_offset(void) { - const int64_t *shift; - int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE); - if (state == 0) { - int expected = 0; - if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { - cp_init(); - __atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE); - } - return 0; - } - if (state != 2) return 0; - shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE); + const int64_t *shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE); if (!shift) return 0; int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED); return value > 0 ? value : 0; } __attribute__((constructor)) static void cp_start(void) { - cp_offset(); + cp_init(); } static int cp_mono(clockid_t clock) { diff --git a/tools/linuxfs/preload/net.c b/tools/linuxfs/preload/net.c index de3cfdaee7..388b92da6a 100644 --- a/tools/linuxfs/preload/net.c +++ b/tools/linuxfs/preload/net.c @@ -277,6 +277,7 @@ __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); @@ -377,7 +378,8 @@ 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 *const *argv = dd_webhelper_argv(file, argv_in, environ); + char resolved[PATH_MAX]; + char *const *argv = dd_webhelper_argv(dd_program_lookup(file, resolved, sizeof resolved) ? resolved : 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); diff --git a/tools/linuxfs/preload/vdec.c b/tools/linuxfs/preload/vdec.c index 7d3761e290..3bd38f3bc9 100644 --- a/tools/linuxfs/preload/vdec.c +++ b/tools/linuxfs/preload/vdec.c @@ -29,6 +29,8 @@ #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; @@ -135,6 +137,8 @@ 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; @@ -318,7 +322,8 @@ 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->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height, + .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, .stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE, }; struct vdec_result r; @@ -563,8 +568,12 @@ 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; @@ -574,6 +583,7 @@ 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; @@ -615,13 +625,184 @@ 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 && bytes) vd_decode(v, b->index, bytes, b->timestamp); + 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); 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; @@ -652,9 +833,15 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) { return 0; } if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL; - 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); + 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; + } b->index = d.index; b->memory = V4L2_MEMORY_DMABUF; b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY; diff --git a/tools/linuxfs/preload/webhelper.c b/tools/linuxfs/preload/webhelper.c index 81aba8e8a5..bbccd890b1 100644 --- a/tools/linuxfs/preload/webhelper.c +++ b/tools/linuxfs/preload/webhelper.c @@ -26,40 +26,83 @@ static char *join_features(const char *have, const char *add) { return strcat(out, add); } -static int electron_node_mode(char *const envp[]) { - static const char variable[] = "ELECTRON_RUN_AS_NODE="; +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, sizeof variable - 1)) - return envp[i][sizeof variable - 1] != 0; - return 0; + if (!strncmp(envp[i], variable, n) && envp[i][n] == '=') return envp[i] + n + 1; + return NULL; } -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); +static int electron_node_mode(char *const envp[]) { + const char *mode = env_value(envp, "ELECTRON_RUN_AS_NODE"); + return mode && *mode; +} + +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); if (!out) return argv; - out[0] = argv[0]; - out[1] = (char *)"--no-sandbox"; - for (int i = 1; i < argc; i++) out[i + 1] = argv[i]; + 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]; 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); + if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv, envp); const char *spec = getenv("DD_WEBHELPER_ARGS"); if (!spec || !*spec) spec = WEBHELPER_DEFAULT; if (!strcmp(spec, "stock")) return argv; diff --git a/tools/nativeguest/ddnatv-hook.c b/tools/nativeguest/ddnatv-hook.c index 58f688da4c..4070f55c85 100644 --- a/tools/nativeguest/ddnatv-hook.c +++ b/tools/nativeguest/ddnatv-hook.c @@ -41,6 +41,7 @@ #include <elf.h> #include <sys/sendfile.h> #include <sys/mman.h> +#include <semaphore.h> #include <sched.h> #include <time.h> #include <sys/xattr.h> diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c index e881ba1f71..8f3daf8086 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -72,7 +72,7 @@ static char *map_preload_paths(const char *value) { return out; } -static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { +static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) { init_ddnatv_hook(); int count = 0; int has_preload = 0; @@ -164,6 +164,9 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) { continue; } + if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) { + continue; + } new_env[dst++] = envp[i]; } @@ -178,6 +181,15 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { new_env[dst++] = str; } } + if (chosen_real_exe && lib_path && lib_path[0] != '\0') { + size_t len = strlen(lib_path); + char *str = malloc(20 + len + 1); + if (str) { + memcpy(str, "DDNATV_LIBRARY_PATH=", 20); + memcpy(str + 20, lib_path, len + 1); + new_env[dst++] = str; + } + } char hook_buf[PATH_MAX]; const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL; diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index ce91b699b5..e9c115d477 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -44,8 +44,8 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d resolve_symlinks(next_path, out, out_size, depth + 1); } -static char **ensure_hook_in_envp(char *const envp[], const char *real_exe) { - return prepare_ddnatv_env(envp, real_exe); +static char **ensure_hook_in_envp(char *const envp[], const char *real_exe, const char *lib_path) { + return prepare_ddnatv_env(envp, real_exe, lib_path); } // The file whose header decides how to start `target`: the symlink-resolved ELF (so ld.so and @@ -162,7 +162,7 @@ static int exec_interp_missing(int fd) { syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz) return ENOEXEC; interp[ph.p_filesz] = 0; - int ifd = (int)syscall(SYS_openat, AT_FDCWD, interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int ifd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (ifd < 0) return errno; syscall(SYS_close, ifd); return 0; @@ -174,7 +174,7 @@ static int exec_interp_missing(int fd) { // a shell walking $PATH moves on at ENOENT and EACCES, and runs a file without "#!" as a script at // ENOEXEC. static int exec_preflight(const char *path) { - int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int fd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (fd < 0) return errno; struct stat st; int err = 0; @@ -263,6 +263,60 @@ static int is_ldconfig_name(const char *name) { return strcmp(name, "ldconfig") == 0 || strcmp(name, "ldconfig.real") == 0; } +struct ldso_direct { + char prog[PATH_MAX]; + char lib_path[PATH_MAX * 6]; +}; + +// ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads +// gets the --library-path a start of its own gets, or ldd reports its libraries as not found, +// and its path mapped into the rootfs, since ld.so opens it without the hook +static char **ldso_direct_argv(char *const argv[], char *const envp[], struct ldso_direct *buf, int *err) { + *err = 0; + int caller_lib_path = 0; + int pi = ldso_program_index(argv, &caller_lib_path); + if (pi <= 0) return NULL; + int argc = 0; + while (argv[argc]) argc++; + const char *prog = argv[pi]; + if (caller_lib_path) { + // the caller's own --library-path stays as it is; only the program is mapped (when it is + // in the rootfs: a caller can also name a file by its real path) + if (prog[0] == '/') { + const char *mapped = rewrite_path(prog, buf->prog, sizeof(buf->prog)); + int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1; + if (fd >= 0) { + syscall(SYS_close, fd); + prog = mapped; + } + } + char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 1)); + if (!out) { + *err = ENOMEM; + return NULL; + } + for (int i = 0; i <= argc; i++) out[i] = argv[i]; + out[pi] = (char *)prog; + return out; + } + if (prog[0] == '/') prog = rewrite_path(prog, buf->prog, sizeof(buf->prog)); + struct exec_probe prog_probe; + probe_exec_file(prog, &prog_probe); + build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath, + prog[0] == '/' ? prog : NULL, buf->lib_path, sizeof(buf->lib_path)); + char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); + if (!out) { + *err = ENOMEM; + return NULL; + } + out[0] = argv[0]; + out[1] = (char *)"--library-path"; + out[2] = buf->lib_path; + for (int i = 1; i <= argc; i++) out[i + 2] = argv[i]; + out[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well + return out; +} + static int ddnatv_execve(const char *filename, char *const argv[], char *const envp[], int depth) { orig_execve_f_type orig_execve = real_execve(); if (!orig_execve) { @@ -374,7 +428,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOMEM; return -1; } - char **new_env = ensure_hook_in_envp(envp, elf_target); + char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path); int ret = run_execve(orig_execve, ld_so, new_argv, new_env); if (errno == EACCES && chmod(ld_so, 0755) == 0) { // ld.so without its exec bit (an unusual restore): fix it once and retry @@ -388,65 +442,17 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } } - // ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads - // gets the --library-path a start of its own gets, or ldd reports its libraries as not found, - // and its path mapped into the rootfs, since ld.so opens it without the hook if (probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) { - int caller_lib_path = 0; - int pi = ldso_program_index(argv, &caller_lib_path); - if (pi > 0 && caller_lib_path) { - // the caller's own --library-path stays as it is; only the program is mapped (when it is - // in the rootfs: a caller can also name a file by its real path) - char prog_buf[PATH_MAX]; - const char *prog = argv[pi]; - if (prog[0] == '/') { - const char *mapped = rewrite_path(prog, prog_buf, sizeof(prog_buf)); - int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1; - if (fd >= 0) { - syscall(SYS_close, fd); - prog = mapped; - } - } - int argc = 0; - while (argv[argc]) argc++; - char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 1)); - if (!new_argv) { - errno = ENOMEM; - return -1; - } - for (int i = 0; i <= argc; i++) new_argv[i] = argv[i]; - new_argv[pi] = (char *)prog; - prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); - int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); - int saved_errno = errno; - free_modified_env(ddnatv_env, envp); - free(new_argv); - errno = saved_errno; - return ret; + struct ldso_direct direct; + int err; + char **new_argv = ldso_direct_argv(argv, envp, &direct, &err); + if (err) { + errno = err; + return -1; } - if (pi > 0) { - char prog_buf[PATH_MAX]; - const char *prog = argv[pi][0] == '/' ? rewrite_path(argv[pi], prog_buf, sizeof(prog_buf)) : argv[pi]; - struct exec_probe prog_probe; - probe_exec_file(prog, &prog_probe); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath, - prog[0] == '/' ? prog : NULL, ld_lib_path, sizeof(ld_lib_path)); - int argc = 0; - while (argv[argc]) argc++; - char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); - if (!new_argv) { - errno = ENOMEM; - return -1; - } - new_argv[0] = argv[0]; - new_argv[1] = (char *)"--library-path"; - new_argv[2] = ld_lib_path; - for (int i = 1; i <= argc; i++) new_argv[i + 2] = argv[i]; - new_argv[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well + if (new_argv) { prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -470,7 +476,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e return -1; } int ret; - if (is_host_interpreter(rewritten_interp)) { + if (is_host_interpreter(interp, 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; @@ -480,7 +486,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ELOOP; ret = -1; } else { - char **ddnatv_env = prepare_ddnatv_env(envp, NULL); + char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL); ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -500,7 +506,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } if (static_elf) prepare_static_program(static_elf); - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -823,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(rewritten_interp)) { + if (is_host_interpreter(interp, 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; @@ -942,17 +948,21 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, // Android programs get Android's environment, as execve() gives them: the glibc hook in // LD_PRELOAD crashes them. - char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target) : clean_env_for_system(orig_ep); + int via_ld_so = has_ld_so && strcmp(elf_target, ld_so) != 0; + char ld_lib_path[PATH_MAX * 6]; + ld_lib_path[0] = '\0'; + if (via_ld_so) + build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); + char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL) + : clean_env_for_system(orig_ep); int ret = -1; - if (has_ld_so && strcmp(elf_target, ld_so) != 0) { + if (via_ld_so) { ensure_exec_bit(elf_target, probe.mode); if (probe.android_interp) prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) char hook_buf[PATH_MAX]; const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf)); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); char **new_argv = build_ldso_argv(ld_so, hook_so, ld_lib_path, elf_target, prog_name, argv); if (!new_argv) { ret = ENOMEM; @@ -968,9 +978,19 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, } } else { if (in_root && probe.is_elf && !probe.is_dynamic) prepare_static_program(elf_target); - if (orig_posix_spawn) { - ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, argv, new_envp); + char **spawn_argv = (char **)argv; + int err = 0; + struct ldso_direct direct; + if (in_root && probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) { + char **direct_argv = ldso_direct_argv(argv, orig_ep, &direct, &err); + if (direct_argv) spawn_argv = direct_argv; } + if (err) { + ret = err; + } else if (orig_posix_spawn) { + ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, spawn_argv, new_envp); + } + if (spawn_argv != argv) free(spawn_argv); } if (!orig_posix_spawn) { diff --git a/tools/nativeguest/hook/exec_probe.c b/tools/nativeguest/hook/exec_probe.c index f877175e58..be708e9158 100644 --- a/tools/nativeguest/hook/exec_probe.c +++ b/tools/nativeguest/hook/exec_probe.c @@ -10,6 +10,13 @@ // 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; @@ -966,10 +973,14 @@ static void parse_shebang(char *hdr, char **interp, char **interp_arg) { *interp_arg = arg; } -// 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); +// 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; } // argv for running `script` with its interpreter: interp [arg] script args... (the script's own diff --git a/tools/nativeguest/hook/identity.c b/tools/nativeguest/hook/identity.c index 9599d7e0b2..ab48039d9d 100644 --- a/tools/nativeguest/hook/identity.c +++ b/tools/nativeguest/hook/identity.c @@ -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) list[0] = 0; + if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1; return 1; } // What programs built with _FORTIFY_SOURCE call when the buffer's size is known (the check is diff --git a/tools/nativeguest/hook/paths.c b/tools/nativeguest/hook/paths.c index fc6c49e507..94e2ad336f 100644 --- a/tools/nativeguest/hook/paths.c +++ b/tools/nativeguest/hook/paths.c @@ -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)); - src = kernel_src; + if (strncmp(kernel_src, "/proc/", 6) != 0 || kernel_src[6] < '0' || kernel_src[6] > '9') src = kernel_src; } b->src = strdup(src); b->dst = strdup(dst); @@ -188,6 +188,25 @@ 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, '/'); @@ -215,25 +234,6 @@ 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,6 +335,15 @@ 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; @@ -354,6 +363,8 @@ 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); @@ -364,6 +375,8 @@ 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); @@ -806,10 +819,36 @@ 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 (dirfd == AT_FDCWD || !rel || rel[0] == '\0' || rel[0] == '/' || g_nbinds == 0) return NULL; + 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; pthread_once(&g_at_once, ddnatv_build_at_dirs); if (g_n_at_dirs == 0) return NULL; struct stat st; @@ -818,6 +857,7 @@ 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)); diff --git a/tools/nativeguest/hook/posix_shm.c b/tools/nativeguest/hook/posix_shm.c index afd8a6f655..95ac489157 100644 --- a/tools/nativeguest/hook/posix_shm.c +++ b/tools/nativeguest/hook/posix_shm.c @@ -1,32 +1,148 @@ // Part of libddnatv-hook.so, included by ddnatv-hook.c. // -// 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. +// 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. #ifndef DDNATV_HOST_TEST -static int posix_shm_path(const char *name, char *path, size_t size) { +static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) { if (!name) { errno = EINVAL; return -1; } while (*name == '/') name++; - size_t len = strlen(name); - if (len == 0 || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) { + size_t len = strlen(name) + strlen(prefix); + if (len == strlen(prefix) || 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", name) >= (int)size) { errno = ENAMETOOLONG; return -1; } + if (snprintf(path, size, "/dev/shm/%s%s", prefix, 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; + 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; return unlink(path); } diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 7bf0a8b692..159f330716 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -519,6 +519,19 @@ static int close_range_all(unsigned int first, unsigned int last, int flags) { static __thread int t_syscall_redirect = 0; +static long nested_path_syscall(long number, unsigned long dirfd, unsigned long pathname, unsigned long arg3, unsigned long arg4) { + char nested_buf[PATH_MAX]; + const char *path = (const char *)pathname; + if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); + 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); @@ -563,6 +576,38 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_rt_sigprocmask + if (number == __NR_rt_sigprocmask && arg2 && (arg1 == SIG_BLOCK || arg1 == SIG_SETMASK) && arg4 == sizeof(uint64_t)) { + uint64_t mask; + memcpy(&mask, (const void *)arg2, sizeof(mask)); + mask &= ~(1ULL << (SIGSYS - 1)); + return call_orig_syscall(number, arg1, (unsigned long)&mask, arg3, arg4, 0, 0); + } +#endif + +#ifdef __NR_rt_sigaction + if (number == __NR_rt_sigaction && arg1 == SIGSYS && arg4 == sizeof(uint64_t)) { + struct { void *handler; unsigned long flags; void *restorer; uint64_t mask; } kact, kold; + struct sigaction act, old; + memset(&act, 0, sizeof(act)); + if (arg2) { + memcpy(&kact, (const void *)arg2, sizeof(kact)); + act.sa_sigaction = (void (*)(int, siginfo_t *, void *))kact.handler; + act.sa_flags = (int)kact.flags; + memcpy(&act.sa_mask, &kact.mask, sizeof(kact.mask)); + } + remember_app_sigsys(arg2 ? &act : NULL, arg3 ? &old : NULL); + if (arg3) { + memset(&kold, 0, sizeof(kold)); + kold.handler = (void *)old.sa_sigaction; + kold.flags = (unsigned long)(unsigned int)old.sa_flags; + memcpy(&kold.mask, &old.sa_mask, sizeof(kold.mask)); + memcpy((void *)arg3, &kold, sizeof(kold)); + } + return 0; + } +#endif + #ifdef __NR_seccomp if (number == __NR_seccomp) { return (long)seccomp((unsigned int)arg1, (unsigned int)arg2, (void *)arg3); @@ -618,16 +663,94 @@ long syscall(long number, ...) { } #endif + if (g_initialized) { +#ifdef __NR_openat + if (number == __NR_openat) { + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); + t_syscall_redirect++; + long ret = (long)openat((int)arg1, (const char *)arg2, (int)arg3, (mode_t)arg4); + t_syscall_redirect--; + return ret; + } +#endif +#if defined(__NR_mkdirat) + if (number == __NR_mkdirat) { + return (long)mkdirat((int)arg1, (const char *)arg2, (mode_t)arg3); + } +#endif +#if defined(__NR_unlinkat) + if (number == __NR_unlinkat) { + return (long)unlinkat((int)arg1, (const char *)arg2, (int)arg3); + } +#endif +#if defined(__NR_renameat) + if (number == __NR_renameat) { + return (long)renameat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4); + } +#endif +#if defined(__NR_renameat2) + if (number == __NR_renameat2) { + return (long)renameat2((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (unsigned int)arg5); + } +#endif +#if defined(__NR_symlinkat) + if (number == __NR_symlinkat) { + return (long)symlinkat((const char *)arg1, (int)arg2, (const char *)arg3); + } +#endif +#if defined(__NR_fchmodat) + if (number == __NR_fchmodat) { + return (long)fchmodat((int)arg1, (const char *)arg2, (mode_t)arg3, 0); + } +#endif +#if defined(__NR_fchownat) + if (number == __NR_fchownat) { + return (long)fchownat((int)arg1, (const char *)arg2, (uid_t)arg3, (gid_t)arg4, (int)arg5); + } +#endif +#if defined(__NR_utimensat) + if (number == __NR_utimensat) { + if (!arg2) return call_orig_syscall(number, arg1, arg2, arg3, arg4, 0, 0); + 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); + } +#endif +#if defined(__NR_chdir) + if (number == __NR_chdir) { + return (long)chdir((const char *)arg1); + } +#endif +#if defined(__NR_chroot) + if (number == __NR_chroot) { + return (long)chroot((const char *)arg1); + } +#endif +#if defined(__NR_inotify_add_watch) + if (number == __NR_inotify_add_watch) { + return (long)inotify_add_watch((int)arg1, (const char *)arg2, (uint32_t)arg3); + } +#endif + } + #ifdef __NR_openat2 if (number == __NR_openat2) { // libddsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested // call maps the path and goes straight to the kernel - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, arg4, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); t_syscall_redirect++; long ret = (long)openat2((int)arg1, (const char *)arg2, (struct ddnatv_open_how *)arg3, (size_t)arg4); t_syscall_redirect--; @@ -649,12 +772,7 @@ long syscall(long number, ...) { #if defined(__NR_faccessat) if (number == __NR_faccessat) { - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, 0, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, 0); t_syscall_redirect++; long ret = (long)faccessat((int)arg1, (const char *)arg2, (int)arg3, 0); t_syscall_redirect--; @@ -765,48 +883,22 @@ long syscall(long number, ...) { if (number == __NR_getegid32) return 0; #endif #if defined(__NR_getresuid) - 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; - } + if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresuid32) - 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; - } + if (number == __NR_getresuid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresgid) - 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; - } + if (number == __NR_getresgid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresgid32) - 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; - } + 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); #endif return call_orig_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6); diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index 24f8a81317..9befbed47e 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -84,6 +84,19 @@ 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]; @@ -190,15 +203,10 @@ 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) { - 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 = "/"; - } - } + 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; size_t len = strlen(out_path); size_t copy_len = (len < bufsiz) ? len : bufsiz; memcpy(buf, out_path, copy_len); @@ -350,8 +358,11 @@ 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); } @@ -361,7 +372,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 path; + if (path[0] != '/') return rewrite_path(path, buffer, bufsize); init_ddnatv_hook(); int moved = 0; for (int i = 0; i < g_nbinds; i++) { diff --git a/tools/nativeguest/hook/sockets.c b/tools/nativeguest/hook/sockets.c index 2903505f9b..b4b12f8005 100644 --- a/tools/nativeguest/hook/sockets.c +++ b/tools/nativeguest/hook/sockets.c @@ -94,6 +94,13 @@ 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"); @@ -104,7 +111,9 @@ 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; - rewrite_unix_socket_path(sun->sun_path, mod_sun.sun_path, sizeof(mod_sun.sun_path)); + 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)); return orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1; } } @@ -133,10 +142,7 @@ 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]; - 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'; + copy_unix_path(sun, addrlen, guest); 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)); diff --git a/tools/quick_deploy.sh b/tools/quick_deploy.sh index 1166feaa6b..559670ce99 100755 --- a/tools/quick_deploy.sh +++ b/tools/quick_deploy.sh @@ -23,7 +23,8 @@ 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; } -./gradlew -q -PallowStaleRuntime=true :app:assembleRelease +# Lint vital is most of an incremental build and CI runs it. +./gradlew -q -PallowStaleRuntime=true :app:assembleRelease -x lintVitalAnalyzeRelease ( cd "$(dirname "${signing_env}")" set -a; . "${signing_env}"; set +a diff --git a/tools/release/check_session_assets.py b/tools/release/check_session_assets.py index 940e722481..8a87e1af9d 100644 --- a/tools/release/check_session_assets.py +++ b/tools/release/check_session_assets.py @@ -1,6 +1,7 @@ from pathlib import Path import importlib.util import re +import shutil import sys from zipfile import ZipFile @@ -34,6 +35,14 @@ 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: @@ -60,6 +69,9 @@ 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)) diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index 89488e1ba5..440c682cd8 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -48,8 +48,19 @@ 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]) @@ -57,14 +68,18 @@ 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']: @@ -84,7 +99,6 @@ 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']: @@ -178,6 +192,10 @@ 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: @@ -195,6 +213,11 @@ 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 diff --git a/tools/seed_worktree.sh b/tools/seed_worktree.sh index e5079e7111..45bbc56bed 100755 --- a/tools/seed_worktree.sh +++ b/tools/seed_worktree.sh @@ -10,14 +10,19 @@ 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/desktop-removal app/src/main/assets/hybris 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 - [[ -z "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]] || continue + 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 mkdir -p "$(dirname "${repo_root}/${path}")" staged=$(mktemp -d "${repo_root}/${path}.seed.XXXXXX") trap 'rm -rf "${staged}"' EXIT diff --git a/tools/tests/test_appimage_run.py b/tools/tests/test_appimage_run.py index 14ac8ad676..84c92f49b8 100644 --- a/tools/tests/test_appimage_run.py +++ b/tools/tests/test_appimage_run.py @@ -146,6 +146,24 @@ 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() diff --git a/tools/tests/test_binfmt_preload.py b/tools/tests/test_binfmt_preload.py index e207b5c9ca..38c2dc4038 100644 --- a/tools/tests/test_binfmt_preload.py +++ b/tools/tests/test_binfmt_preload.py @@ -138,6 +138,27 @@ 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)) @@ -188,6 +209,24 @@ 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"): diff --git a/tools/tests/test_clock_pause_preload.py b/tools/tests/test_clock_pause_preload.py index 3d3f0dd76b..7b92a444bc 100644 --- a/tools/tests/test_clock_pause_preload.py +++ b/tools/tests/test_clock_pause_preload.py @@ -107,6 +107,51 @@ int main(void) { } """ +EARLY_LIBRARY = r""" +#include <pthread.h> +#include <time.h> + +pthread_mutex_t early_lock = PTHREAD_MUTEX_INITIALIZER; + +__attribute__((constructor)) static void early_start(void) { + struct timespec ts; + pthread_mutex_lock(&early_lock); + clock_gettime(CLOCK_MONOTONIC, &ts); + pthread_mutex_unlock(&early_lock); +} +""" + +EARLY_PROGRAM = r""" +#define _GNU_SOURCE +#include <fcntl.h> +#include <pthread.h> +#include <stdarg.h> +#include <stdio.h> +#include <sys/syscall.h> +#include <time.h> +#include <unistd.h> + +extern pthread_mutex_t early_lock; + +int open(const char *path, int flags, ...) { + va_list args; + va_start(args, flags); + mode_t mode = (mode_t)va_arg(args, int); + va_end(args); + pthread_mutex_lock(&early_lock); + pthread_mutex_unlock(&early_lock); + return (int)syscall(SYS_openat, AT_FDCWD, path, flags, mode); +} + +int main(void) { + struct timespec mono, boot; + clock_gettime(CLOCK_MONOTONIC, &mono); + clock_gettime(CLOCK_BOOTTIME, &boot); + printf("gap %lld\n", (long long)(((boot.tv_sec - mono.tv_sec) * 1000000000LL + boot.tv_nsec - mono.tv_nsec) / 1000000LL)); + return 0; +} +""" + SHIFT_MS = 10000 @@ -128,6 +173,13 @@ class ClockPausePreloadTest(unittest.TestCase): subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.shell), str(build / "program.c")], check=True) cls.other = build / "kwin_wayland" shutil.copy(cls.shell, cls.other) + (build / "early.c").write_text(EARLY_LIBRARY) + (build / "early_program.c").write_text(EARLY_PROGRAM) + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-pthread", "-o", str(build / "libearly.so"), + str(build / "early.c")], check=True) + cls.early = build / "early_program" + subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.early), str(build / "early_program.c"), + "-L", str(build), "-learly", "-Wl,-rpath," + str(build)], check=True) @classmethod def tearDownClass(cls): @@ -153,6 +205,11 @@ class ClockPausePreloadTest(unittest.TestCase): self.assertGreaterEqual(paused[name], 50, name) self.assertLess(paused[name], 1000, name) + def test_clock_read_inside_a_library_constructor_does_not_reenter_the_program(self): + plain = self.run_program(self.early, 0) + paused = self.run_program(self.early, SHIFT_MS) + self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50) + def test_program_without_preload_keeps_the_real_clock(self): plain = self.run_program(self.other, 0, preload=False) paused = self.run_program(self.other, SHIFT_MS, preload=False) diff --git a/tools/tests/test_component_reuse.py b/tools/tests/test_component_reuse.py new file mode 100644 index 0000000000..5d67e34c1a --- /dev/null +++ b/tools/tests/test_component_reuse.py @@ -0,0 +1,93 @@ +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) diff --git a/tools/tests/test_ddexec_reexec.py b/tools/tests/test_ddexec_reexec.py new file mode 100644 index 0000000000..640db1706c --- /dev/null +++ b/tools/tests/test_ddexec_reexec.py @@ -0,0 +1,154 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +SOURCE = REPO / "app/src/main/cpp/ddexec/ddexec.c" +SYSROOT = Path("/usr/aarch64-linux-gnu") + +LIBRARY = r""" +int dd_probe_value(void) { return 7; } +""" + +HOOK = r""" +#include <unistd.h> + +__attribute__((constructor)) static void hooked(void) { write(1, "hooked\n", 7); } +""" + +PROGRAM = r""" +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <sys/auxv.h> +#include <sys/syscall.h> + +int dd_probe_value(void); + +int main(int argc, char **argv, char **envp) { + if (dd_probe_value() != 7) return 4; + if (argc > 1 && strcmp(argv[1], "again") == 0) { + for (int i = 0; i < argc; i++) printf("%s%s", i ? "|" : "", argv[i]); + printf("\n%s\n", (char *)getauxval(AT_EXECFN)); + return 0; + } + char *next[] = {"first", "again", "x y", NULL}; + syscall(SYS_execveat, -100, "/proc/self/exe", next, envp, 0); + return 3; +} +""" + + +def ndk_clang(): + sdk = Path(os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") or Path.home() / "Android/Sdk") + for ndk in sorted((sdk / "ndk").glob("*"), reverse=True): + clang = ndk / "toolchains/llvm/prebuilt/linux-x86_64/bin/clang" + if clang.exists(): + return str(clang) + return shutil.which("clang") + + +class DdexecReexecTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cc, prefix = runner() + clang = ndk_clang() + if cc is None or clang is None or not shutil.which("bwrap") or not SYSROOT.is_dir(): + raise unittest.SkipTest("no aarch64 toolchain, runner or bwrap") + cls.qemu = list(prefix[:3]) if prefix else [] + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.loader = tmp / "libddexec.so" + subprocess.run([clang, "--target=aarch64-linux-android29", "-shared", "-fPIC", "-O2", "-ffreestanding", + "-fno-builtin", "-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-nostdlib", + "-Wl,-e,_start", "-Wl,-z,noexecstack", "-Wl,--no-undefined", "-Wl,-Bsymbolic", + "-Wl,-z,max-page-size=16384", "-o", str(cls.loader), str(SOURCE)], check=True) + cls.libdir = tmp / "own-lib" + cls.libdir.mkdir() + (tmp / "lib.c").write_text(LIBRARY) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.libdir / "libddprobe.so"), str(tmp / "lib.c")], + check=True) + (tmp / "prog.c").write_text(PROGRAM) + cls.program = tmp / "prog" + subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"], + check=True) + cls.root = tmp / "root" + (cls.root / "usr/lib").mkdir(parents=True) + (cls.root / "lib").mkdir() + shutil.copy2(SYSROOT / "lib/ld-linux-aarch64.so.1", cls.root / "lib/ld-linux-aarch64.so.1") + (tmp / "hook.c").write_text(HOOK) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.root / "usr/lib/libddnatv-hook.so"), str(tmp / "hook.c")], + check=True) + probe = subprocess.run(["bwrap", "--dev-bind", "/", "/", "true"], capture_output=True) + if probe.returncode != 0: + raise unittest.SkipTest("bwrap cannot create a namespace here") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def env(self, real_exe, library_path=None, root=SYSROOT): + env = {k: v for k, v in os.environ.items() if not k.startswith(("DDNATV_", "LD_", "QEMU_"))} + env["DDNATV_ROOT"] = str(root) + env["LD_LIBRARY_PATH"] = f"{SYSROOT / 'lib'}:{self.libdir}" if library_path is None else str(SYSROOT / "lib") + if real_exe: + env["DDNATV_REAL_EXE"] = str(real_exe) + if library_path: + env["DDNATV_LIBRARY_PATH"] = library_path + return env + + def reexec(self, execfn, real_exe, library_path=None, root=SYSROOT): + jail = ["bwrap", "--dev-bind", "/", "/", "--tmpfs", "/proc"] + parent = str(Path(execfn).parent) + jail += ["--dir", parent, "--ro-bind", str(self.loader), execfn] + start = self.qemu + ["-0", "first", execfn] if self.qemu else ["bash", "-c", 'exec -a first "$0" "$@"', execfn] + cmd = jail + start + ["again", "x y"] + return subprocess.run(cmd, env=self.env(real_exe, library_path, root), capture_output=True, text=True, timeout=120) + + def test_reexec_through_proc_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_thread_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/thread-self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_finds_libraries_through_the_recorded_library_path(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_ld_so_preloads_the_hook_of_the_root(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}", self.root) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["hooked", "first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_without_a_known_program_fails_cleanly(self): + out = self.reexec("/proc/self/exe", None) + self.assertEqual(127, out.returncode) + self.assertIn("DDNATV_REAL_EXE", out.stderr) + + def test_a_started_program_keeps_its_own_arguments(self): + ldso = SYSROOT / "lib/ld-linux-aarch64.so.1" + cmd = self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path", f"{SYSROOT / 'lib'}:{self.libdir}", + str(self.program), "again", "a"] + out = subprocess.run(cmd, env=self.env(self.program), capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines()) + + def test_the_usage_check_still_applies_outside_a_reexec(self): + out = subprocess.run(self.qemu + [str(self.loader), str(self.program)], env=self.env(self.program), + capture_output=True, text=True, timeout=120) + self.assertEqual(127, out.returncode) + self.assertIn("usage", out.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_desktop_chromium_apps.py b/tools/tests/test_desktop_chromium_apps.py index f8d6056d21..8f5525d6d3 100644 --- a/tools/tests/test_desktop_chromium_apps.py +++ b/tools/tests/test_desktop_chromium_apps.py @@ -1,11 +1,8 @@ -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(): @@ -24,12 +21,6 @@ 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 @@ -49,34 +40,17 @@ class DesktopChromiumAppsTest(unittest.TestCase): def exec_lines(self, text): return [l[5:] for l in text.splitlines() if l.startswith("Exec=")] - 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_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_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_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_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]) + def test_with_the_gpu_off_no_entry_is_written(self): + self.assertIsNone(self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False)) self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"), False)) def test_games_that_are_not_chromium_are_unchanged(self): diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 825cd8b8d4..ce474de509 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -526,6 +526,21 @@ 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() @@ -1055,6 +1070,12 @@ 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() diff --git a/tools/tests/test_fex_gl_thunk_overlay.py b/tools/tests/test_fex_gl_thunk_overlay.py new file mode 100644 index 0000000000..e06d59e632 --- /dev/null +++ b/tools/tests/test_fex_gl_thunk_overlay.py @@ -0,0 +1,29 @@ +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() diff --git a/tools/tests/test_fex_guest_preload.py b/tools/tests/test_fex_guest_preload.py new file mode 100644 index 0000000000..4b2f200bc0 --- /dev/null +++ b/tools/tests/test_fex_guest_preload.py @@ -0,0 +1,120 @@ +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() diff --git a/tools/tests/test_fex_identity_syscalls.py b/tools/tests/test_fex_identity_syscalls.py new file mode 100644 index 0000000000..3c2101c824 --- /dev/null +++ b/tools/tests/test_fex_identity_syscalls.py @@ -0,0 +1,148 @@ +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() diff --git a/tools/tests/test_fex_path_syscalls.py b/tools/tests/test_fex_path_syscalls.py new file mode 100644 index 0000000000..203f2eaac1 --- /dev/null +++ b/tools/tests/test_fex_path_syscalls.py @@ -0,0 +1,49 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0013-path-syscalls-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);") + + +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 FexPathSyscallsTest(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_path_syscall_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(sorted(removed), sorted(added)) + self.assertGreater(len(added), 10) + 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_templates_call_the_libc_syscall(self): + added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + calls = [line for line in added if "syscall(" in line and "Result" in line] + self.assertEqual(5, len(calls)) + self.assertTrue(all("::syscall(syscall_num" in line for line in calls)) + self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))]) + + def test_every_routed_syscall_is_rewritten_by_the_hook(self): + hook = HOOK.read_text() + for name, (_, _, number) in changed()[1].items(): + with self.subTest(name=name): + self.assertIn(f"number == __NR_{number})", hook) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py new file mode 100644 index 0000000000..d7c861085d --- /dev/null +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -0,0 +1,220 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" +GUEST_LDSO = "/usr/lib/ld-linux-aarch64.so.1" +GUEST_TOOL = "/usr/local/bin/tool" +BOUND_DIR = "/opt/runtime" +ANDROID_DIR = "/opt/android" +HOST_SHELL = "/data/local/tmp/droiddeck-hook-probe-sh" + +RECORDER = r""" +#define _GNU_SOURCE +#include <spawn.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +static void show(const char *path, char *const argv[], char *const envp[]) { + printf("call\t%s", path); + for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); + printf("\n"); + for (int i = 0; envp && envp[i]; i++) + if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20); + fflush(stdout); +} + +int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + show(path, argv, envp); + if (pid) *pid = 1; + return 0; +} + +int execve(const char *path, char *const argv[], char *const envp[]) { + show(path, argv, envp); + _exit(0); +} +""" + +PROBE = r""" +#include <spawn.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +extern char **environ; + +int main(int argc, char **argv) { + if (argc < 3) return 2; + if (strcmp(argv[1], "spawn") == 0) { + pid_t pid; + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_adddup2(&actions, 1, 1); + int ret = posix_spawn(&pid, argv[2], &actions, NULL, argv + 2, environ); + posix_spawn_file_actions_destroy(&actions); + printf("ret\t%d\n", ret); + return 0; + } + execve(argv[2], argv + 2, environ); + printf("ret\t-1\n"); + return 1; +} +""" + + +def guest_loader(prefix): + roots = [Path(prefix[prefix.index("-L") + 1])] if prefix and "-L" in prefix else [Path("/")] + for root in roots: + for name in ("lib/ld-linux-aarch64.so.1", "lib64/ld-linux-aarch64.so.1", "usr/lib/ld-linux-aarch64.so.1"): + if (root / name).exists(): + return root / name + return None + + +class NativeHookLdsoSpawnTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + loader = guest_loader(cls.prefix) + if loader is None: + raise unittest.SkipTest("no aarch64 glibc loader to put in the rootfs") + 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 / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + for guest, source in ((GUEST_LDSO, loader), (GUEST_TOOL, cls.probe)): + host = cls.root / guest.lstrip("/") + host.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(source, host) + host.chmod(0o755) + (cls.root / "usr/lib/aarch64-linux-gnu").mkdir(parents=True, exist_ok=True) + cls.runtime = tmp / "runtime" + cls.runtime.mkdir() + shutil.copy(cls.probe, cls.runtime / "bash") + (cls.runtime / "bash").chmod(0o755) + cls.android = tmp / "root-android" + cls.android.mkdir() + subprocess.run([cls.cc, "-O1", "-Wl,--dynamic-linker=/system/bin/linker64", "-o", str(cls.android / "sh"), + str(tmp / "probe.c")], check=True) + for name, interpreter in (("bound.sh", f"{BOUND_DIR}/bash"), ("host.sh", HOST_SHELL), + ("android.sh", f"{ANDROID_DIR}/sh")): + script = cls.root / "opt" / name + script.parent.mkdir(exist_ok=True) + script.write_text(f"#!{interpreter}\n") + script.chmod(0o755) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def call(self, how, *argv, binds=None, real_exe=None): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + if binds: + hook_env["DDNATV_BINDS"] = binds + if real_exe: + hook_env["DDNATV_REAL_EXE"] = real_exe + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")} + 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(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120) + calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")] + self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")] + self.assertEqual(1, len(calls), out.stdout + out.stderr) + if how == "spawn": + self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) + return calls[0] + + def test_spawned_ldso_list_loads_the_program_from_the_rootfs(self): + call = self.call("spawn", GUEST_LDSO, "--list", GUEST_TOOL) + argv = call[1:] + self.assertEqual(str(self.root / GUEST_TOOL.lstrip("/")), argv[-1]) + self.assertEqual("--list", argv[-2]) + self.assertIn("--library-path", argv[:-2]) + + def test_spawn_and_exec_start_ldso_with_the_same_arguments(self): + for args in (("--list", GUEST_TOOL), (GUEST_TOOL, "x"), ("--library-path", "/opt/own", "--list", GUEST_TOOL)): + with self.subTest(args=args): + self.assertEqual(self.call("exec", GUEST_LDSO, *args), self.call("spawn", GUEST_LDSO, *args)) + + def test_a_callers_own_library_path_is_kept(self): + call = self.call("spawn", GUEST_LDSO, "--library-path", "/opt/own", "--list", GUEST_TOOL) + self.assertEqual([GUEST_LDSO, "--library-path", "/opt/own", "--list", str(self.root / GUEST_TOOL.lstrip("/"))], call[1:]) + + def test_ldso_without_a_program_is_spawned_unchanged(self): + call = self.call("spawn", GUEST_LDSO, "--version") + self.assertEqual([GUEST_LDSO, "--version"], call[1:]) + + def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): + self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x")) + + def test_a_program_started_through_ldso_records_its_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + argv = self.call(how, GUEST_TOOL, "x")[1:] + self.assertEqual([argv[argv.index("--library-path") + 1]], self.library_paths) + + def test_ldso_started_by_name_records_no_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + self.call(how, GUEST_LDSO, "--list", GUEST_TOOL) + self.assertEqual([], self.library_paths) + + def test_a_program_from_a_bind_starts_itself_again_through_proc_self_exe(self): + bash = str(self.runtime / "bash") + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/proc/self/exe", "x", binds=f"/proc:/proc|{self.runtime}:{BOUND_DIR}", real_exe=bash) + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([bash, "x"], call[-2:]) + + def test_a_rootfs_program_starts_itself_again_through_proc_self_exe(self): + tool = str(self.root / GUEST_TOOL.lstrip("/")) + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/proc/self/exe", "x", binds="/proc:/proc", real_exe=tool) + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([tool, "x"], call[-2:]) + + def test_a_script_interpreter_from_a_bind_runs_as_a_guest_program(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/bound.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}") + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([str(self.runtime / "bash"), str(self.root / "opt/bound.sh"), "x"], call[-3:]) + + def test_a_script_interpreter_outside_the_rootfs_and_its_binds_stays_on_the_host(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/host.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}") + self.assertEqual([HOST_SHELL, HOST_SHELL, str(self.root / "opt/host.sh"), "x"], call) + + def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self): + sh = str(self.android / "sh") + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/android.sh", "x", binds=f"{self.android}:{ANDROID_DIR}") + self.assertEqual([sh, sh, str(self.root / "opt/android.sh"), "x"], call) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_mounts.py b/tools/tests/test_native_hook_mounts.py index ff46a0fa18..ca56256aa7 100644 --- a/tools/tests/test_native_hook_mounts.py +++ b/tools/tests/test_native_hook_mounts.py @@ -12,14 +12,54 @@ PROBE = r""" #include <dirent.h> #include <fcntl.h> #include <stdio.h> +#include <stdlib.h> #include <string.h> #include <sys/stat.h> +#include <sys/wait.h> #include <unistd.h> int main(int argc, char **argv) { char cwd[4096]; for (int i = 1; i < argc; i++) { struct stat st; + if (strncmp(argv[i], "env:", 4) == 0) { + const char *value = getenv(argv[i] + 4); + printf("%s\t%s\n", argv[i], value ? value : "-"); + continue; + } + if (strncmp(argv[i], "parent:", 7) == 0) { + char dir[4096]; + snprintf(dir, sizeof(dir), "%s", argv[i] + 7); + char *rel = strchr(dir, '|'), *want = NULL; + if (rel) *rel++ = 0; + if (rel && (want = strchr(rel, '|'))) *want++ = 0; + int fd = open(dir, O_RDONLY | O_DIRECTORY); + struct stat expected; + int ok = fd >= 0 && fstatat(fd, rel ? rel : "..", &st, 0) == 0 && stat(want ? want : "/", &expected) == 0; + printf("%s\t%d\n", argv[i], ok && st.st_dev == expected.st_dev && st.st_ino == expected.st_ino); + if (fd >= 0) close(fd); + continue; + } + if (strncmp(argv[i], "fork:", 5) == 0) { + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { + int p[2]; + char path[64], data[8] = "-"; + if (pipe(p) == 0 && write(p[1], "x", 1) == 1 && dup2(p[0], 63) == 63) { + snprintf(path, sizeof(path), "%s/63", argv[i] + 5); + int fd = open(path, O_RDONLY); + ssize_t n = fd >= 0 ? read(fd, data, sizeof(data) - 1) : -1; + if (n > 0) data[n] = 0; + if (fd >= 0) close(fd); + } + printf("%s\t%s\n", argv[i], data); + fflush(stdout); + _exit(0); + } + waitpid(pid, NULL, 0); + continue; + } if (strncmp(argv[i], "cd:", 3) == 0) { int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL; printf("%s\t%s\n", argv[i], ok ? cwd : "-"); @@ -76,6 +116,8 @@ class NativeHookMountTest(unittest.TestCase): cls.root = tmp / "root" cls.library = tmp / "storage/PC GAMES" (cls.root / "etc").mkdir(parents=True) + (cls.root / "deep/er/est").mkdir(parents=True) + (cls.root / "linked").symlink_to("deep/er/est") (cls.root / "etc/hostname").write_text("rootfs") (cls.root / "mnt/library/Some Game").mkdir(parents=True) (cls.root / "mnt/library/Some Game/game.txt").write_text("mount point") @@ -117,10 +159,11 @@ class NativeHookMountTest(unittest.TestCase): def tearDownClass(cls): cls.tmp.cleanup() - def run_probe(self, *args): - binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}" + def run_probe(self, *args, binds=None): + if binds is None: + binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}" hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)} - env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "LOCPATH", "GCONV_PATH")} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] else: @@ -131,6 +174,18 @@ class NativeHookMountTest(unittest.TestCase): self.assertEqual(out.returncode, 0, out.stderr) return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()} + def test_dev_fd_in_a_forked_child_names_the_child_descriptors(self): + out = self.run_probe("fork:/dev/fd", binds="/proc/self/fd:/dev/fd") + self.assertEqual(["x"], out["fork:/dev/fd"]) + + def test_a_mount_named_through_proc_self_root_reports_its_guest_path(self): + arg = f"cd:{GAME}/" + self.assertEqual(self.run_probe(arg, binds=f"/proc/self/root{self.library}:/mnt/library")[arg], [GAME]) + + def test_a_proc_mount_that_names_no_process_reports_its_guest_path(self): + arg = "cd:/mnt/sys/kernel/" + self.assertEqual(self.run_probe(arg, binds="/proc/self/root/proc/sys:/mnt/sys")[arg], ["/mnt/sys/kernel"]) + def test_drive_link_stored_as_rootfs_path_reaches_the_mount(self): path = f"/pfx/native/dosdevices/z:{GAME}/game.txt" self.assertEqual(self.run_probe(path)[path], ["1", "library"]) @@ -147,6 +202,42 @@ class NativeHookMountTest(unittest.TestCase): path = f"/pfx/guest/dosdevices/z:{GAME}/game.txt" self.assertEqual(self.run_probe(path)[path], ["1", "library"]) + def test_glibc_locale_and_iconv_data_come_from_the_rootfs(self): + result = self.run_probe("env:LOCPATH", "env:GCONV_PATH") + self.assertEqual(result["env:LOCPATH"], [f"{self.root}/usr/lib/locale"]) + self.assertEqual(result["env:GCONV_PATH"], [f"{self.root}/usr/lib/aarch64-linux-gnu/gconv"]) + + def test_parent_of_root_stays_at_root(self): + self.assertEqual(self.run_probe("parent:/")["parent:/"], ["1"]) + + def test_parent_of_root_without_mounts_stays_at_root(self): + self.assertEqual(self.run_probe("parent:/", binds="")["parent:/"], ["1"]) + + def test_parent_of_mount_ancestor_is_guest_root(self): + self.assertEqual(self.run_probe("parent:/mnt")["parent:/mnt"], ["1"]) + + def test_parent_walks_from_any_directory_stay_at_root(self): + cases = ["parent:/etc|../..", "parent:/mnt/library|../../..", "parent:/|../etc/.."] + self.assertEqual(self.run_probe(*cases), {case: ["1"] for case in cases}) + + def test_parent_walk_from_a_linked_mount_ancestor_follows_the_real_directory(self): + binds = f"{self.library}:/linked/library" + case = "parent:/linked|../..|/deep" + self.assertEqual(self.run_probe(case, binds=binds)[case], ["1"]) + + def test_absolute_paths_above_root_stay_at_root(self): + result = self.run_probe("cd:/..", "cd:/etc/../..", "/../etc/hostname") + self.assertEqual(result["cd:/.."], [str(self.root)]) + self.assertEqual(result["cd:/etc/../.."], [str(self.root)]) + self.assertEqual(result["/../etc/hostname"], ["1", "rootfs"]) + + def test_relative_parent_of_cwd_stays_in_guest(self): + result = self.run_probe("cd:/", "cd:..", "cd:./../..", "../etc/hostname", f"cd:{GAME}", "cd:../..") + self.assertEqual(result["cd:.."], [str(self.root)]) + self.assertEqual(result["cd:./../.."], [str(self.root)]) + self.assertEqual(result["cd:../.."], [str(self.root / "mnt")]) + self.assertEqual(result["../etc/hostname"], ["1", "rootfs"]) + def test_rootfs_paths_outside_mounts_are_unchanged(self): paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"] result = self.run_probe(*paths) diff --git a/tools/tests/test_native_hook_named_semaphores.py b/tools/tests/test_native_hook_named_semaphores.py new file mode 100644 index 0000000000..09abea076b --- /dev/null +++ b/tools/tests/test_native_hook_named_semaphores.py @@ -0,0 +1,159 @@ +from pathlib import Path +import os +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <semaphore.h> +#include <stdio.h> +#include <sys/wait.h> +#include <unistd.h> + +static void show(const char *name, int ok) { printf("%s\t%d\n", name, ok); fflush(stdout); } + +int main(int argc, char **argv) { + const char *name = argv[1]; + sem_t *sem = sem_open(name, O_CREAT | O_EXCL, 0600, 1); + show("create", sem != SEM_FAILED); + show("exclusive", sem_open(name, O_CREAT | O_EXCL, 0600, 1) == SEM_FAILED && errno == EEXIST); + sem_t *again = sem_open(name, O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1); + int value = -1; + show("existing", again == sem && sem_getvalue(again, &value) == 0 && value == 1); + show("too-large", sem_open("/ddsem-absent", O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1) == SEM_FAILED && errno == EINVAL); + show("wait", sem_wait(sem) == 0 && sem_trywait(again) == -1 && errno == EAGAIN); + pid_t child = fork(); + if (child == 0) { + sem_t *other = sem_open(name, 0); + _exit(other != SEM_FAILED && sem_post(other) == 0 && sem_close(other) == 0 ? 0 : 1); + } + int status = 0; + waitpid(child, &status, 0); + show("shared", WIFEXITED(status) && WEXITSTATUS(status) == 0 && sem_trywait(sem) == 0); + show("close", sem_close(again) == 0 && sem_post(sem) == 0 && sem_close(sem) == 0 && sem_close(sem) == -1 && errno == EINVAL); + show("unlink", sem_unlink(name) == 0); + show("gone", sem_open(name, 0) == SEM_FAILED && errno == ENOENT); + return 0; +} +""" + +KEEP = r""" +#include <fcntl.h> +#include <semaphore.h> +int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; } +""" + +FORKER = r""" +#include <fcntl.h> +#include <pthread.h> +#include <semaphore.h> +#include <stdio.h> +#include <sys/wait.h> +#include <unistd.h> + +static const char *name; +static _Atomic int done; + +static void *churn(void *arg) { + while (!done) { + sem_t *sem = sem_open(name, O_CREAT, 0600, 0); + if (sem != SEM_FAILED) sem_close(sem); + } + return arg; +} + +int main(int argc, char **argv) { + name = argv[1]; + pthread_t thread; + if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1; + int finished = 0; + for (int i = 0; i < 200; i++) { + pid_t pid = fork(); + if (pid < 0) break; + if (pid == 0) { + alarm(10); + sem_t *sem = sem_open(name, O_CREAT, 0600, 0); + _exit(sem == SEM_FAILED || sem_close(sem) != 0); + } + int status; + if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++; + } + done = 1; + pthread_join(thread, NULL); + sem_unlink(name); + printf("finished\t%d\n", finished); + return 0; +} +""" + +CALLS = ("create", "exclusive", "existing", "too-large", "wait", "shared", "close", "unlink", "gone") + + +class NativeHookNamedSemaphoresTest(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(dir="/tmp") + 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) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.shm = tmp / "root/tmp/shm" + cls.shm.mkdir(parents=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_hooked(self, program, *args): + hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "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(program), *args], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return dict(line.split("\t") for line in out.stdout.splitlines()) + + def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self): + name = f"/ddsem-{os.getpid()}" + self.assertEqual({call: "1" for call in CALLS}, self.run_hooked(self.probe, name)) + self.assertFalse(Path(f"/dev/shm/sem.{name[1:]}").exists()) + self.assertEqual([], list(self.shm.iterdir())) + + def test_a_child_forked_while_another_thread_opens_a_semaphore_can_open_one(self): + source = self.probe.with_name("forker.c") + source.write_text(FORKER) + forker = self.probe.with_name("forker") + subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True) + self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}")) + + def test_a_created_semaphore_keeps_its_name_and_mode(self): + name = f"ddsem-kept-{os.getpid()}" + source = self.probe.with_name("keep.c") + source.write_text(KEEP) + keep = self.probe.with_name("keep") + subprocess.run([self.cc, "-O1", "-pthread", "-o", str(keep), str(source)], check=True) + self.run_hooked(keep, name) + made = self.shm / f"sem.{name}" + self.addCleanup(made.unlink) + umask = os.umask(0) + os.umask(umask) + self.assertEqual([made.name], [p.name for p in self.shm.iterdir()]) + self.assertEqual(0o640 & ~umask, made.stat().st_mode & 0o777) + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_path_syscalls.py b/tools/tests/test_native_hook_path_syscalls.py new file mode 100644 index 0000000000..be0967cbb0 --- /dev/null +++ b/tools/tests/test_native_hook_path_syscalls.py @@ -0,0 +1,189 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#define _GNU_SOURCE +#include <fcntl.h> +#include <limits.h> +#include <stddef.h> +#include <stdio.h> +#include <string.h> +#include <sys/socket.h> +#include <sys/syscall.h> +#include <sys/un.h> +#include <unistd.h> + +static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); } + +int main(int argc, char **argv) { + const char *dir = argv[1]; + char p[PATH_MAX], q[PATH_MAX], cwd[PATH_MAX]; + snprintf(p, sizeof(p), "%s/made", dir); + show("mkdirat", syscall(SYS_mkdirat, AT_FDCWD, p, 0755)); + snprintf(p, sizeof(p), "%s/made/file", dir); + long fd = syscall(SYS_openat, AT_FDCWD, p, O_WRONLY | O_CREAT | O_CLOEXEC, 0644); + show("openat", fd); + if (fd >= 0) close((int)fd); + show("truncate", syscall(SYS_truncate, p, 4)); + show("fchmodat", syscall(SYS_fchmodat, AT_FDCWD, p, 0600)); + show("utimensat", syscall(SYS_utimensat, AT_FDCWD, p, NULL, 0)); + fd = syscall(SYS_openat, AT_FDCWD, p, O_RDONLY | O_CLOEXEC); + show("futimens", fd >= 0 ? syscall(SYS_utimensat, (int)fd, NULL, NULL, 0) : -1); + if (fd >= 0) close((int)fd); + snprintf(q, sizeof(q), "%s/made/moved", dir); + show("renameat", syscall(SYS_renameat, AT_FDCWD, p, AT_FDCWD, q)); + show("renameat2", syscall(SYS_renameat2, AT_FDCWD, q, AT_FDCWD, p, 0)); + snprintf(q, sizeof(q), "%s/made/link", dir); + show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q)); + show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0)); + snprintf(q, sizeof(q), "%s/made/sock", dir); + struct sockaddr_un addr = {.sun_family = AF_UNIX}, extra = {.sun_family = AF_UNIX}; + size_t len = strlen(q); + int fits = len + sizeof("-extra") <= sizeof(addr.sun_path); + if (fits) { + memcpy(addr.sun_path, q, len); + memcpy(extra.sun_path, q, len); + memcpy(extra.sun_path + len, "-extra", sizeof("-extra")); + } + int server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + show("bind", fits ? syscall(SYS_bind, server, &addr, sizeof(addr)) : -1); + listen(server, 1); + show("connect", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1); + close(client); + close(server); + syscall(SYS_unlinkat, AT_FDCWD, q, 0); + server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + show("bind-length", fits ? syscall(SYS_bind, server, &extra, offsetof(struct sockaddr_un, sun_path) + len) : -1); + listen(server, 1); + show("connect-length", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1); + close(client); + close(server); + syscall(SYS_unlinkat, AT_FDCWD, q, 0); + snprintf(q, sizeof(q), "%s/made", dir); + show("chdir", syscall(SYS_chdir, q)); + show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1); + show("unlinkat-file", syscall(SYS_unlinkat, AT_FDCWD, p, 0)); + show("unlinkat-dir", syscall(SYS_unlinkat, AT_FDCWD, q, AT_REMOVEDIR)); + return 0; +} +""" + +ALLOCATOR = r""" +#define _GNU_SOURCE +#include <fcntl.h> +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/syscall.h> +#include <unistd.h> + +extern void *__libc_malloc(size_t); +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static int ready; + +void *malloc(size_t size) { + if (!ready) { + pthread_mutex_lock(&lock); + if (!ready) { + long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/stat", O_RDONLY | O_CLOEXEC); + if (fd >= 0) close((int)fd); + ready = 1; + } + pthread_mutex_unlock(&lock); + } + return __libc_malloc(size); +} + +int main(void) { + puts("ready"); + return 0; +} +""" + +EARLY = r""" +#include <stdlib.h> + +__attribute__((constructor)) static void early(void) { free(malloc(1)); } +""" + +CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat", + "bind", "connect", "bind-length", "connect-length", "chdir", "cwd", "unlinkat-file", "unlinkat-dir") + + +class NativeHookPathSyscallsTest(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(dir="/tmp") + 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) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + (cls.root / "opt").mkdir(parents=True) + (tmp / "allocator.c").write_text(ALLOCATOR) + cls.allocator = tmp / "allocator" + subprocess.run([cls.cc, "-O1", "-rdynamic", "-pthread", "-o", str(cls.allocator), str(tmp / "allocator.c")], check=True) + (tmp / "early.c").write_text(EARLY) + cls.early = tmp / "early.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.early), str(tmp / "early.c")], check=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_program(self, argv, hook_env): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + 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) + return subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120) + + def run_probe(self, guest_dir, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + out = self.run_program([str(self.probe), guest_dir], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: int(line.split("\t")[1]) for line in out.stdout.splitlines()} + + def test_guest_paths_through_syscall_land_in_the_root(self): + results = self.run_probe("/opt") + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + self.assertEqual([], list((self.root / "opt").iterdir())) + + def test_paths_already_in_the_root_are_kept(self): + results = self.run_probe(str(self.root / "opt")) + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + + def test_without_the_hook_guest_paths_reach_the_host(self): + results = self.run_probe("/opt/droiddeck-hook-probe-missing", hook=False) + self.assertEqual(0, results["mkdirat"]) + self.assertEqual(0, results["openat"]) + self.assertEqual(0, results["chdir"]) + + def test_an_allocator_opening_files_before_the_hook_starts_does_not_hang(self): + hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": "/proc:/proc", + "LD_PRELOAD": f"{self.hook}:{self.early}"} + out = self.run_program([str(self.allocator)], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual("ready", out.stdout.strip()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_proc_exe.py b/tools/tests/test_native_hook_proc_exe.py index fdf6e615ab..59b60d9af4 100644 --- a/tools/tests/test_native_hook_proc_exe.py +++ b/tools/tests/test_native_hook_proc_exe.py @@ -57,6 +57,16 @@ class NativeHookProcExeTest(unittest.TestCase): (cls.root / "usr/bin").mkdir(parents=True) cls.kwin = cls.root / "usr/bin/kwin_wayland" shutil.copy(tmp / "sleeper", cls.kwin) + cls.runtime = tmp / "runtime" + cls.runtime.mkdir() + cls.bound = cls.runtime / "chrome" + shutil.copy(tmp / "sleeper", cls.bound) + cls.shadowed = cls.runtime / "bin/chrome" + cls.shadowed.parent.mkdir() + shutil.copy(tmp / "sleeper", cls.shadowed) + cls.override = tmp / "override" + cls.override.mkdir() + shutil.copy(tmp / "sleeper", cls.override / "chrome") # The child's /proc/<pid>/exe must name the loader, as DroidDeck's libddexec.so does. cls.loader = tmp / "lib/libddexec.so" cls.loader.parent.mkdir() @@ -85,8 +95,10 @@ class NativeHookProcExeTest(unittest.TestCase): self.assertEqual("ready", child.stdout.readline().strip()) return child.pid - def readlink(self, *paths): + def readlink(self, *paths, binds=None): hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + if binds: + hook_env["DDNATV_BINDS"] = binds 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}")] @@ -108,6 +120,17 @@ class NativeHookProcExeTest(unittest.TestCase): at = f"at:/proc/{pid}" self.assertEqual("/usr/bin/kwin_wayland", self.readlink(at)[at]) + def test_a_guest_program_from_a_bind_is_named_by_its_guest_path(self): + pid = self.start(loader=True, real_exe=str(self.bound), program=self.bound) + link = f"/proc/{pid}/exe" + self.assertEqual("/app/extra/chrome", self.readlink(link, binds=f"/proc:/proc|{self.runtime}:/app/extra")[link]) + + def test_a_guest_program_shadowed_by_a_nested_bind_keeps_its_own_path(self): + pid = self.start(loader=True, real_exe=str(self.shadowed), program=self.shadowed) + link = f"/proc/{pid}/exe" + binds = f"/proc:/proc|{self.runtime}:/app|{self.override}:/app/bin" + self.assertEqual(str(self.shadowed), self.readlink(link, binds=binds)[link]) + def test_a_program_named_only_in_the_environment_is_not_believed(self): pid = self.start(loader=True, real_exe=str(self.kwin)) link = f"/proc/{pid}/exe" diff --git a/tools/tests/test_native_hook_sigsys_mask.py b/tools/tests/test_native_hook_sigsys_mask.py new file mode 100644 index 0000000000..2d28c2954d --- /dev/null +++ b/tools/tests/test_native_hook_sigsys_mask.py @@ -0,0 +1,144 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#define _GNU_SOURCE +#include <pthread.h> +#include <signal.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include <sys/syscall.h> +#include <unistd.h> + +static uint64_t current(void) { + uint64_t mask = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof(mask)); + return mask; +} + +struct kact { void *handler; unsigned long flags; void *restorer; uint64_t mask; }; + +static void own(int sig, siginfo_t *info, void *ctx) { (void)sig; (void)info; (void)ctx; } + +static long raw_sigaction(int sig, const struct kact *act, struct kact *old) { + register long x8 __asm__("x8") = SYS_rt_sigaction; + register long x0 __asm__("x0") = sig; + register long x1 __asm__("x1") = (long)act; + register long x2 __asm__("x2") = (long)old; + register long x3 __asm__("x3") = 8; + __asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory"); + return x0; +} + +static void handlers(void) { + struct kact act = { (void *)own, SA_SIGINFO, NULL, 0 }, seen, kernel; + syscall(SYS_rt_sigaction, SIGSYS, &act, NULL, 8); + syscall(SYS_rt_sigaction, SIGSYS, NULL, &seen, 8); + raw_sigaction(SIGSYS, NULL, &kernel); + printf("sigaction\t%d\t%d\n", seen.handler == (void *)own, kernel.handler == (void *)own); + struct kact usr1 = { (void *)own, SA_SIGINFO, NULL, 0 }; + syscall(SYS_rt_sigaction, SIGUSR1, &usr1, NULL, 8); + raw_sigaction(SIGUSR1, NULL, &kernel); + printf("sigaction-usr1\t%d\n", kernel.handler == (void *)own); +} + +static void show(const char *how) { + uint64_t mask = current(); + printf("%s\t%d\t%d\n", how, !!(mask & (1ULL << (SIGSYS - 1))), !!(mask & (1ULL << (SIGUSR1 - 1)))); + uint64_t none = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, &none, NULL, sizeof(none)); +} + +int main(int argc, char **argv) { + uint64_t all = ~0ULL; + sigset_t set; + sigfillset(&set); + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "syscall-setmask") == 0) syscall(SYS_rt_sigprocmask, SIG_SETMASK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-block") == 0) syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-unblock") == 0) { + syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + uint64_t usr1 = 1ULL << (SIGUSR1 - 1); + syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &usr1, NULL, sizeof(usr1)); + } + else if (strcmp(argv[i], "sigprocmask") == 0) sigprocmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "pthread_sigmask") == 0) pthread_sigmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "sigaction") == 0) { + handlers(); + continue; + } + show(argv[i]); + } + return 0; +} +""" + +WAYS = ("syscall-setmask", "syscall-block", "sigprocmask", "pthread_sigmask") + + +class NativeHookSigsysMaskTest(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) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + cls.root.mkdir() + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def masks(self, *ways, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + 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(self.probe), *ways], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: tuple(int(v) for v in line.split("\t")[1:]) for line in out.stdout.splitlines()} + + def test_blocking_every_signal_leaves_sigsys_open(self): + masks = self.masks(*WAYS) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((0, 1), masks[way]) + + def test_unblocking_is_unchanged(self): + self.assertEqual((0, 0), self.masks("syscall-unblock")["syscall-unblock"]) + + def test_a_sigsys_handler_set_through_syscall_keeps_the_hooks(self): + seen = self.masks("sigaction") + self.assertEqual((1, 0), seen["sigaction"]) + self.assertEqual((1,), seen["sigaction-usr1"]) + + def test_without_the_hook_a_sigsys_handler_reaches_the_kernel(self): + self.assertEqual((1, 1), self.masks("sigaction", hook=False)["sigaction"]) + + def test_without_the_hook_every_signal_is_blocked(self): + masks = self.masks(*WAYS, hook=False) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((1, 1), masks[way]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_runtime_inputs.py b/tools/tests/test_runtime_inputs.py index 92f2ae1c79..2bfbfb4dc3 100644 --- a/tools/tests/test_runtime_inputs.py +++ b/tools/tests/test_runtime_inputs.py @@ -1,6 +1,7 @@ import importlib.util import gzip import io +import json from pathlib import Path, PureWindowsPath import subprocess import tarfile @@ -122,6 +123,40 @@ class RuntimeInputsTest(unittest.TestCase): runtime.verify(self.root, stale_sources_ok=True) self.assertIn('tools/linuxfs/preload/test.c', stderr.getvalue()) + def helper(self, content): + source = self.root / 'tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper' + source.parent.mkdir(parents=True, exist_ok=True) + source.write_text(content) + staged = self.root / 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper' + staged.parent.mkdir(parents=True, exist_ok=True) + staged.write_text(content) + return source, staged + + def test_an_edited_helper_script_needs_no_new_preparation(self): + self.helper('old helper') + runtime.record(self.root) + self.helper('new helper') + runtime.verify(self.root) + + def test_a_staged_helper_that_lags_its_source_is_rejected(self): + source, _ = self.helper('old helper') + runtime.record(self.root) + source.write_text('new helper') + with self.assertRaisesRegex(ValueError, 'not a current copy'): + runtime.verify(self.root, stale_sources_ok=True) + + def test_a_manifest_that_hashed_helper_scripts_still_verifies(self): + source, staged = self.helper('old helper') + runtime.record(self.root) + manifest = self.root / runtime.MANIFEST + data = json.loads(manifest.read_text()) + data['sources']['tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper'] = 'old' + data['outputs']['assets/linuxfs/usr/local/bin/droiddeck-test-helper'] = { + 'path': 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper', 'sha256': 'old'} + manifest.write_text(json.dumps(data)) + self.helper('new helper') + runtime.verify(self.root) + def test_dev_loop_still_rejects_changed_outputs(self): runtime.record(self.root) (self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary') diff --git a/tools/tests/test_session_assets.py b/tools/tests/test_session_assets.py index 5f7f8675d1..563ea1212e 100644 --- a/tools/tests/test_session_assets.py +++ b/tools/tests/test_session_assets.py @@ -50,3 +50,10 @@ class SessionAssetsTest(unittest.TestCase): mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/sub/login1"' self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'], assets.check_extraction(self.overlay, mapping)) + + def test_stage_refreshes_a_changed_helper(self): + target = self.root / 'main' + assets.stage(target, self.overlay) + self.helper.write_bytes(b'new helper') + assets.stage(target, self.overlay) + self.assertEqual(b'new helper', (target / self.name).read_bytes()) diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index f888b7ed13..4af6d09dd1 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -314,6 +314,46 @@ done(28 if end < len(data) else 0) def download(self): return self.steam / 'package/droiddeck-download' + def cache_manifest(self): + plain = b'plain-package' + packed = b'packed-package' + (self.cdn / 'a.zip.1111').write_bytes(plain) + (self.cdn / 'b.zip.vz.2222_14').write_bytes(packed) + (self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text( + '"linuxarm64"\n{\n\t"version" "123456"\n' + '\t"a_all"\n\t{\n' + f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(plain)}"\n\t\t"sha2" "{hashlib.sha256(plain).hexdigest()}"\n' + '\t}\n' + '\t"b_all"\n\t{\n' + '\t\t"file" "b.zip.9999"\n\t\t"size" "99"\n\t\t"sha2" "00"\n' + '\t\t"zipvz" "b.zip.vz.2222_14"\n' + f'\t\t"sha2vz" "{hashlib.sha256(packed).hexdigest()}"\n' + '\t}\n}\n') + + def test_the_cache_pass_keeps_every_package_under_the_names_steam_looks_for(self): + self.cache_manifest() + result = self.install(None, '--cache') + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes()) + self.assertEqual(b'packed-package', (package / 'b.zip.vz.2222_14').read_bytes()) + self.assertFalse((package / 'b.zip.9999').exists()) + self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + + def test_the_cache_pass_is_not_repeated_for_the_same_client_version(self): + self.cache_manifest() + self.assertEqual(0, self.install(None, '--cache').returncode) + requests = len(self.requests.read_text().splitlines()) + self.assertEqual(0, self.install(None, '--cache').returncode) + self.assertEqual(requests + 1, len(self.requests.read_text().splitlines())) + + def test_a_cached_package_is_not_fetched_again(self): + self.cache_manifest() + (self.steam / 'package').mkdir(parents=True) + (self.steam / 'package/a.zip.1111').write_bytes(b'plain-package') + self.assertEqual(0, self.install(None, '--cache').returncode) + self.assertNotIn('a.zip.1111', self.requests.read_text()) + def test_progress_is_counted_in_megabytes_across_parts(self): self.two_parts() result = self.install() diff --git a/tools/tests/test_steam_ui_scale.py b/tools/tests/test_steam_ui_scale.py index 5440dcd497..9a65305e2b 100644 --- a/tools/tests/test_steam_ui_scale.py +++ b/tools/tests/test_steam_ui_scale.py @@ -16,6 +16,8 @@ initialize_native_resolution = MODULE['initialize_native_resolution'] NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION'] seed_no_screensaver_in_game = MODULE['seed_no_screensaver_in_game'] initialize_screensaver = MODULE['initialize_screensaver'] +seed_bouncing_logo = MODULE['seed_bouncing_logo'] +initialize_screensaver_choice = MODULE['initialize_screensaver_choice'] class SteamUiScaleTest(unittest.TestCase): @@ -182,6 +184,16 @@ class SteamScreensaverTest(unittest.TestCase): self.assertEqual('0', screensaver.get('WhileInGame')) self.assertIn('\t\t\t"WhileInGame"\t\t"0"\n\t\t}\n', updated) + def test_fresh_client_gets_the_bouncing_logo(self): + self.assertTrue(initialize_screensaver_choice(self.root)) + screensaver = parse(self.config.read_text()).get('InstallConfigStore').get('Customization').get('Screensaver') + self.assertEqual('steam-bouncinglogo', screensaver.get('CurrentScreensaver')) + self.assertTrue(self.config.with_name('droiddeck-screensaver-choice-initialized').exists()) + + def test_a_screensaver_already_picked_is_kept(self): + text = '"InstallConfigStore" { "Customization" { "Screensaver" { "CurrentScreensaver" "other" } } }' + self.assertEqual((text, False), seed_bouncing_logo(text)) + def test_users_choice_is_kept(self): text = '"InstallConfigStore" { "Customization" { "Screensaver" { "WhileInGame" "1" } } }' self.assertEqual((text, False), seed_no_screensaver_in_game(text)) diff --git a/tools/tests/test_vdec_emulator.py b/tools/tests/test_vdec_emulator.py index bf16a3fc39..3fd3091542 100644 --- a/tools/tests/test_vdec_emulator.py +++ b/tools/tests/test_vdec_emulator.py @@ -113,12 +113,12 @@ int main(void) { f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14; uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage; - if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15; + if (bpl != 4096 || size != 4096 * 2304 * 3 / 2) return 15; r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF }; if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16; int out[3]; for (int i = 0; i < 3; i++) { - struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 }; + struct create_dumb c = { .height = 2304, .width = 4096, .bpp = 16 }; if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17; struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC }; if (drm_ioctl(card, 0xc00c642d, &h)) return 18; @@ -148,7 +148,7 @@ int main(void) { struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp }; if (call(VIDIOC_DQBUF, &cb)) return 25; unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0); - printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size); + printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 2304], cp.bytesused == size); munmap(m, size); pf = (struct pollfd){ .fd = vfd, .events = 0x306 }; if (poll(&pf, 1, 0) != 1) return 26; @@ -166,7 +166,7 @@ int main(void) { size = f.fmt.pix_mp.plane_fmt[0].sizeimage; r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF }; if (call(VIDIOC_REQBUFS, &r)) return 31; - struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 }; + struct create_dumb big = { .height = 2304, .width = 4096, .bpp = 16 }; if (drm_ioctl(card, 0xc02064b2, &big)) return 32; struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC }; if (drm_ioctl(card, 0xc00c642d, &bh)) return 33; @@ -183,7 +183,7 @@ int main(void) { struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp }; if (call(VIDIOC_DQBUF, &db)) return 37; unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0); - printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]); + printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)4096 * 2304]); dd_vdec_closed(vfd); return 0; } @@ -261,7 +261,7 @@ class VdecEmulatorTest(unittest.TestCase): self.assertEqual(done.stdout.split('\n')[:6], ['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu']) self.assertEqual([c[1:6] for c in server.configs], - [(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)]) + [(1, 1280, 720, 4096, 2304), (1, 1280, 720, 4096, 2304)]) self.assertEqual([p[:3] for p in server.packets], [(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)]) diff --git a/tools/tests/test_vdec_stream_size.py b/tools/tests/test_vdec_stream_size.py new file mode 100644 index 0000000000..4bf5fca3f3 --- /dev/null +++ b/tools/tests/test_vdec_stream_size.py @@ -0,0 +1,140 @@ +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +VDEC = ROOT / 'tools/linuxfs/preload/vdec.c' + + +class Bits: + def __init__(self): + self.bits = [] + + def u(self, value, count): + self.bits += [(value >> (count - 1 - i)) & 1 for i in range(count)] + + def ue(self, value): + value += 1 + length = value.bit_length() + self.u(0, length - 1) + self.u(value, length) + + def bytes(self): + bits = self.bits + [1] + while len(bits) % 8: + bits.append(0) + raw = bytes(int(''.join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)) + out = bytearray() + for i, byte in enumerate(raw): + if len(out) >= 2 and out[-1] == 0 and out[-2] == 0 and byte <= 3: + out.append(3) + out.append(byte) + return bytes(out) + + +def sps(width_mbs, height_units, profile=100, frame_mbs_only=1, poc_type=2): + b = Bits() + b.u(profile, 8) + b.u(0, 8) + b.u(51, 8) + b.ue(0) + if profile in (100, 110, 122, 244): + b.ue(1) + b.ue(0) + b.ue(0) + b.u(0, 1) + b.u(0, 1) + b.ue(0) + b.ue(poc_type) + if poc_type == 0: + b.ue(4) + b.ue(1) + b.u(0, 1) + b.ue(width_mbs - 1) + b.ue(height_units - 1) + b.u(frame_mbs_only, 1) + if not frame_mbs_only: + b.u(0, 1) + b.u(1, 1) + b.u(0, 1) + return b'\x00\x00\x00\x01\x67' + b.bytes() + b'\x00\x00\x00\x01\x65\x88\x84\x00' + + +def hevc_sps(width, height, sub_layers_minus1=0): + b = Bits() + b.u(0, 4) + b.u(sub_layers_minus1, 3) + b.u(1, 1) + b.u(0, 88) + b.u(93, 8) + for _ in range(sub_layers_minus1): + b.u(0, 2) + if sub_layers_minus1: + for _ in range(sub_layers_minus1, 8): + b.u(0, 2) + b.ue(0) + b.ue(1) + b.ue(width) + b.ue(height) + b.u(0, 1) + return b'\x00\x00\x00\x01\x42\x01' + b.bytes() + b'\x00\x00\x00\x01\x26\x01\xaf' + + +DRIVER = r''' +#include "vdec.c" +#include <stdio.h> + +int main(int argc, char **argv) { + FILE *f = fopen(argv[1], "rb"); + static uint8_t data[4096]; + size_t n = fread(data, 1, sizeof data, f); + uint32_t w = 0, h = 0; + int rc = argc > 2 ? vd_stream_size_h265(data, n, &w, &h) : vd_stream_size_h264(data, n, &w, &h); + printf("%d %u %u\n", rc, w, h); + return 0; +} +''' + + +class StreamSizeTest(unittest.TestCase): + def run_driver(self, data, hevc=False): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / 'driver.c').write_text(DRIVER) + (tmp / 'stream.bin').write_bytes(data) + exe = tmp / 'driver' + subprocess.run(['gcc', '-std=gnu11', '-DDD_VDEC_ANY_ARCH', '-I', str(VDEC.parent), '-o', str(exe), str(tmp / 'driver.c'), str(VDEC.parent / 'venc.c'), '-ldl', '-lpthread'], + check=True, capture_output=True, text=True) + return subprocess.run([str(exe), str(tmp / 'stream.bin')] + (['h265'] if hevc else []), check=True, capture_output=True, text=True).stdout.split() + + def test_reads_an_ultrawide_stream_size(self): + self.assertEqual(['0', '3440', '1440'], self.run_driver(sps(215, 90))) + + def test_reads_a_small_stream_size(self): + self.assertEqual(['0', '800', '464'], self.run_driver(sps(50, 29))) + + def test_interlaced_streams_double_the_height(self): + self.assertEqual(['0', '1920', '1088'], self.run_driver(sps(120, 34, frame_mbs_only=0))) + + def test_baseline_profile_has_no_chroma_fields(self): + self.assertEqual(['0', '1280', '720'], self.run_driver(sps(80, 45, profile=66))) + + def test_emulation_prevention_bytes_are_removed(self): + self.assertEqual(['0', '256', '256'], self.run_driver(sps(16, 16, profile=66))) + + def test_reads_an_h265_stream_size(self): + self.assertEqual(['0', '3440', '1440'], self.run_driver(hevc_sps(3440, 1440), hevc=True)) + + def test_h265_sizes_round_up_to_sixteen(self): + self.assertEqual(['0', '1920', '1088'], self.run_driver(hevc_sps(1920, 1080, sub_layers_minus1=2), hevc=True)) + + def test_a_truncated_sps_is_rejected(self): + self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x67\x64\x00\x33\xac\xb4\x02\x80\x2d')[0]) + + def test_a_stream_without_an_sps_is_left_alone(self): + self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x65\x88\x84\x00\x00\x01')[0]) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_webhelper_preload.py b/tools/tests/test_webhelper_preload.py index 3847e9988f..5b530566c1 100644 --- a/tools/tests/test_webhelper_preload.py +++ b/tools/tests/test_webhelper_preload.py @@ -15,8 +15,11 @@ int main(int argc, char **argv) { const char *mode = getenv("TEST_NODE_MODE_CHILD"); static char node[64]; snprintf(node, sizeof node, "ELECTRON_RUN_AS_NODE=%s", mode ? mode : ""); - char *node_env[] = {node, NULL}; - char *plain_env[] = {"PATH=/usr/bin", NULL}; + const char *x = getenv("TEST_DISPLAY"); + static char display[64]; + snprintf(display, sizeof display, "DISPLAY=%s", x ? x : ""); + char *node_env[] = {node, x ? display : NULL, NULL}; + char *plain_env[] = {"PATH=/usr/bin", x ? display : NULL, NULL}; char *const *envp = mode ? node_env : plain_env; char *const *out = dd_webhelper_argv(argv[1], argv + 1, (char *const *)envp); for (int i = 0; out[i]; i++) printf("%s\n", out[i]); @@ -42,8 +45,10 @@ class WebhelperPreloadTest(unittest.TestCase): def tearDownClass(cls): shutil.rmtree(cls.tmp, ignore_errors=True) - def argv(self, *args, spec=None, node_child=False, parent_node=False): - env = {k: v for k, v in os.environ.items() if k != "DD_WEBHELPER_ARGS"} + def argv(self, *args, spec=None, node_child=False, parent_node=False, display=None): + env = {k: v for k, v in os.environ.items() if k not in ("DD_WEBHELPER_ARGS", "TEST_DISPLAY")} + if display is not None: + env["TEST_DISPLAY"] = display env.pop("ELECTRON_RUN_AS_NODE", None) if spec is not None: env["DD_WEBHELPER_ARGS"] = spec @@ -104,6 +109,50 @@ class WebhelperPreloadTest(unittest.TestCase): chrome = self.chromium("chromium-parent-mode", "chrome") self.assertEqual(self.argv(chrome, parent_node=True), [chrome, "--no-sandbox"]) + def test_a_link_to_an_electron_app_gets_the_sandbox_flag(self): + app = self.chromium("vesktop", "vesktop") + link = self.tmp / "bin-vesktop" + link.symlink_to(app) + self.assertEqual(self.argv(str(link), "%U"), [str(link), "--no-sandbox", "%U"]) + + def test_an_app_whose_sandbox_helper_is_one_folder_up_gets_the_flag(self): + root = self.tmp / "nested" + (root / "bin").mkdir(parents=True) + (root / "chrome-sandbox").touch() + (root / "bin/app").touch() + self.assertEqual(self.argv(str(root / "bin/app")), [str(root / "bin/app"), "--no-sandbox"]) + + def test_a_chromium_app_starting_a_program_from_its_own_folder_leaves_it_alone(self): + handler = self.chromium("chrome-app", "chrome_crashpad_handler") + browser = self.tmp / "chrome-app/chrome" + shutil.copy(self.program, browser) + out = subprocess.run([str(browser), handler, "--database=/tmp/x"], env={"TEST_DISPLAY": ":0"}, + capture_output=True, text=True, check=True).stdout.splitlines() + self.assertEqual([handler, "--database=/tmp/x"], out) + + def test_a_chromium_app_starting_another_chromium_app_still_flags_it(self): + other = self.chromium("other-app", "chrome") + editor = self.tmp / "editor-app/code" + self.chromium("editor-app", "code") + shutil.copy(self.program, editor) + out = subprocess.run([str(editor), other], env={}, capture_output=True, text=True, check=True).stdout.splitlines() + self.assertEqual([other, "--no-sandbox"], out) + + def test_with_an_x_display_chromium_apps_use_x11(self): + chrome = self.chromium("chromium-x11", "chrome") + self.assertEqual(self.argv(chrome, "--new-window", display=":0"), + [chrome, "--no-sandbox", "--ozone-platform=x11", "--new-window"]) + self.assertEqual(self.argv(chrome, "--no-sandbox", display=":0"), + [chrome, "--ozone-platform=x11", "--no-sandbox"]) + + def test_an_explicit_platform_and_sandbox_choice_is_kept(self): + chrome = self.chromium("chromium-own-flags", "chrome") + own = [chrome, "--no-sandbox", "--ozone-platform=wayland"] + self.assertEqual(self.argv(*own, display=":0"), own) + + def test_other_programs_with_an_x_display_are_left_alone(self): + self.assertEqual(self.argv("/usr/bin/steam", display=":0"), ["/usr/bin/steam"]) + def test_stock_turns_it_off(self): args = [WEBHELPER, "--enable-features=A"] self.assertEqual(self.argv(*args, spec="stock"), args)