Compare commits

..
Author SHA1 Message Date
The412Banner 3c8d4c508d fix(gog): download gen1 depot files from the build's main.bin 2026-11-29 23:34:58 +00:00
39 changed files with 103 additions and 992 deletions

No files matched your search

+5 -17
View File
@@ -740,8 +740,7 @@ jobs:
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
# The cache path sits beside the workspace because runner homes are at different depths from it, and
# actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects
# "..". Runners that keep their own ~/.m2 skip the cache.
# actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache.
- name: Place Robolectric's Android jars beside the workspace
id: robolectric-jars
run: |
@@ -752,9 +751,7 @@ jobs:
echo "cache=false" >> "$GITHUB_OUTPUT"
else
mkdir -p "$jars" "$(dirname "$m2")"
jars=$(cd "$jars" && pwd)
ln -sfn "$jars" "$m2"
echo "path=$jars" >> "$GITHUB_OUTPUT"
ln -sfn "$(cd "$jars" && pwd)" "$m2"
echo "cache=true" >> "$GITHUB_OUTPUT"
fi
- name: Restore Robolectric's Android jars
@@ -762,7 +759,7 @@ jobs:
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache/restore@v4
with:
path: ${{ steps.robolectric-jars.outputs.path }}
path: ../robolectric-jars
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
- name: Count the restored Robolectric jars
@@ -776,16 +773,7 @@ jobs:
run: |
set -o pipefail
mkdir -p app/build
# A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next.
for wait in 60 180 0; do
status=0
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$?
if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://repo\.maven\.apache\.org/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://repo\.maven\.apache\.org/)' app/build/unit-tests.log; then
exit "$status"
fi
echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s"
sleep "$wait"
done
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
@@ -812,7 +800,7 @@ jobs:
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
uses: actions/cache/save@v4
with:
path: ${{ steps.robolectric-jars.outputs.path }}
path: ../robolectric-jars
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
- name: Upload unit test diagnostics
-22
View File
@@ -4130,17 +4130,6 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
return read_input(fd, buf, count);
}
extern "C" [[noreturn]] void __chk_fail(void);
/* Programs built with _FORTIFY_SOURCE (Flatpak runtimes among them) call these instead of read, poll
* and ppoll, and glibc's versions go straight to the kernel. */
EXPORT ssize_t __read_chk(int fd, void *buf, size_t count, size_t buflen) {
static auto next_read_chk = reinterpret_cast<ssize_t (*)(int, void *, size_t, size_t)>(dlsym(RTLD_NEXT, "__read_chk"));
if (count > buflen) __chk_fail();
if (next_read_chk && !is_fake_input_fd(fd)) return next_read_chk(fd, buf, count, buflen);
return read_input(fd, buf, count);
}
EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
if (!is_fake_input_fd(fd)) return syscall(SYS_readv, fd, iov, iovcnt);
if (iovcnt < 0 || iovcnt > IOV_MAX) {
@@ -4389,17 +4378,6 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
return my_ppoll(fds, nfds, timeout, sigmask);
}
EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
return poll(fds, nfds, timeout);
}
EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout,
const sigset_t *sigmask, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
return ppoll(fds, nfds, timeout, sigmask);
}
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout) {
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
@@ -61,19 +61,7 @@ object GameEnvironment {
}
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else knownGames[scope].orEmpty() + config.games[scope].orEmpty()
/**
* What some Steam games need here whatever the shared settings say; the game's own settings still win.
* GTA III dies at 0042A703 when a new game starts with FEX's reduced x87 precision, as the Rockstar store copy does.
*/
val knownGames: Map<String, Map<String, String?>> = mapOf(
"12100" to mapOf("FEX_X87REDUCEDPRECISION" to "0"),
)
/** [config] with [knownGames] folded under each game's own settings, for the guest to read. */
fun withKnownGames(config: Config): Config =
config.copy(games = config.games + knownGames.mapValues { (scope, known) -> known + config.games[scope].orEmpty() })
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
fun hasOverride(config: Config, scope: String, name: String): Boolean =
scope.isNotEmpty() && config.entries(scope).containsKey(name)
@@ -90,7 +78,7 @@ object GameEnvironment {
val entries = config.games[scope].orEmpty()
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
return FexPreset.all.firstOrNull { preset ->
val expected = presetFor(scope, preset.id)
val expected = FexPreset.environment(preset.id)
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
}?.id ?: CUSTOM_FEX_PRESET
}
@@ -100,16 +88,12 @@ object GameEnvironment {
require(preset == null || FexPreset.all.any { it.id == preset })
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
if (preset != null) {
val values = presetFor(scope, preset)
val values = FexPreset.environment(preset)
FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] }
}
return config.withEntries(scope, entries)
}
/** A FEX preset as a game gets it: picking one never undoes a fix the game is known to need. */
private fun presetFor(scope: String, preset: String): Map<String, String?> =
FexPreset.environment(preset) + knownGames[scope].orEmpty().filterKeys { it in FexPreset.environmentKeys }
const val CUSTOM_FEX_PRESET = "__custom__"
val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER)
@@ -112,9 +112,8 @@ object NativeGuest {
File(BwrapSpawner.hostPath(binds.map { BwrapSpawner.Bind.parse(it) }, root.path, cwd)).takeIf { it.isDirectory } ?: root
/** A process for [guest] (argv) started as proot would with [binds], in guest directory [cwd]. */
fun processBuilder(context: Context, root: File, binds: List<String>, guest: List<String>, cwd: String = "/root"): ProcessBuilder {
if (sessionMode == null) prepare(context, root)
return ProcessBuilder(command(root, guest.first(), guest.drop(1)))
fun processBuilder(context: Context, root: File, binds: List<String>, guest: List<String>, cwd: String = "/root"): ProcessBuilder =
ProcessBuilder(command(root, guest.first(), guest.drop(1)))
.directory(workingDirectory(root, binds, cwd))
.also { builder ->
builder.environment().apply {
@@ -122,7 +121,6 @@ object NativeGuest {
putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context)))
}
}
}
private const val RUNPATH_CONF = "etc/ld.so.conf.d/zz-droiddeck-native.conf"
private val SCAN_DIRS = listOf("usr/lib", "usr/local/lib", "opt")
@@ -151,7 +149,6 @@ object NativeGuest {
}
/** What a rootfs needs before anything runs in it natively; cheap once done. */
@Synchronized
fun prepare(context: Context, root: File) {
val relinked = relinkAbsoluteSymlinks(context, root)
if (relinked > 0) android.util.Log.i(TAG, "native userland: $relinked absolute symlinks made relative")
@@ -114,7 +114,7 @@ object GameEnvironmentStore {
) {
publishGameCores(context)
val stored = config ?: read(context)
val resolved = GameEnvironment.withKnownGames(stored).copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val json = encode(resolved)
val dxvk = TextureFiltering.dxvkOptions(
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
@@ -35,7 +35,6 @@ object SessionFiles {
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
"usr/share/applications/droiddeck-return-gaming.desktop" to "usr/share/applications/droiddeck-return-gaming.desktop",
"etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
)
@@ -121,8 +121,6 @@ object StoresState {
var unfinished by mutableStateOf<List<StoreInstallRoot.Unfinished>>(emptyList())
internal set
var steamPicking by mutableStateOf<CatalogItem?>(null)
fun isUnfinished(item: CatalogItem): Boolean = unfinished.any {
it.store == item.store && (it.id == item.id || (it.id == null && it.folder.name == StoreInstallRoot.folderName(item.title, item.id)))
}
@@ -136,7 +136,7 @@ internal object GogContent {
val file = JSONObject().put("path", path).put("size", size).put("directory", directory)
.put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty())
.put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product)
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?'))
.put("offset", entry.optLong("offset")).put("remotePath", remotePath(entry.optString("url"), build.generation))
val position = if (build.generation == 2) overlayPositions.putIfAbsent(path, files.length()) else null
if (position == null) files.put(file) else {
require(files.getJSONObject(position).getBoolean("directory") == directory)
@@ -149,6 +149,10 @@ internal object GogContent {
branch = build.branch, language = resolvedLanguage, manifest = sanitize(manifest), files = files, products = products.toList(), verified = true)
}
fun remotePath(url: String, generation: Int): String = url.substringBefore('?').let {
if (generation == 1 && !it.startsWith("https://")) it.substringAfterLast('/') else it
}
fun languageSelected(list: List<String>, selected: String): Boolean = list.any { it.equals("Neutral", true) } || StoreLanguage.depotMatchesResolved(list.toTypedArray(), selected)
fun cdnPath(hash: String): String {
@@ -6,6 +6,9 @@ import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionService
@@ -43,6 +46,8 @@ internal object SteamStore {
/** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */
private val REFUSALS = setOf(5, 15, 18, 26, 27, 63)
var picking by mutableStateOf<CatalogItem?>(null)
class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) {
companion object {
fun of(json: JSONObject): Plan? {
@@ -217,7 +222,7 @@ internal object SteamStore {
toast(context, R.string.steam_store_close_steam)
return
}
StoresState.steamPicking = item
picking = item
}
fun install(context: Context, item: CatalogItem, target: SteamClient.Target) {
@@ -94,16 +94,17 @@ internal object XboxManifest {
}
fun executable(folder: File): String {
val listed = read(folder).executables
for (path in listed) {
for (path in read(folder).executables) {
require(!path.startsWith('/') && !path.contains(':') && path.split('/').none { it == ".." || it.isEmpty() })
val file = path.split('/').fold<String, File?>(folder) { dir, part ->
dir?.listFiles().orEmpty().filter { it.name.equals(part, true) }.singleOrNull()
} ?: continue
var file = folder
for (part in path.split('/')) {
val matches = file.listFiles().orEmpty().filter { it.name.equals(part, true) }
require(matches.size == 1) { "Missing or ambiguous Xbox launch path." }
file = matches.single()
}
require(file.canonicalPath.startsWith(folder.canonicalPath + File.separator))
if (file.isFile) return forwarded(folder, file) ?: file.relativeTo(folder).invariantSeparatorsPath
}
require(listed.isEmpty()) { "Missing or ambiguous Xbox launch path." }
error("The Xbox package has no supported PC launch executable.")
}
@@ -847,7 +847,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
com.droiddeck.launcher.stores.StoresState.steamPicking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.StoresState.steamPicking = null } } }
com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } }
StepsLayer(screenAt)
UiZooSheet()
SessionDrawerPreview(s.secondScreenDisplays)
@@ -195,10 +195,6 @@ internal fun librarySources(
}
}
internal fun alwaysLibraryTabs(signedIn: Collection<Store>, stores: Boolean, soundMode: Boolean): Set<String> =
(if (soundMode) emptyList() else signedIn.map { it.librarySource }).toSet() +
listOfNotNull(Library.ADDED.takeIf { stores }, Store.BATTLENET.id.takeIf { stores })
internal object LibraryDisplay {
const val DEFAULT_LEVEL = 2
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
@@ -378,7 +374,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
.map { it.store.id }.toSet()
val sources = librarySources(
all, storeTabs.map { it.store.id },
alwaysLibraryTabs(owned.keys, stores, soundMode) + signInChips,
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.ADDED.takeIf { stores }, Store.BATTLENET.id.takeIf { stores }).toSet() + signInChips,
favorites, concealed,
offStores = if (soundMode) emptySet() else storeTabs.filterNot { it.shown }.map { it.store.id }.toSet(),
places = if (soundMode) DEFAULT_LIBRARY_PLACES else StoreTabsState.libraryPlaces,
@@ -270,7 +270,8 @@ pub fn run(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Gog
let offset = num(file, "offset");
let remote = text(file, "remotePath");
let endpoints = if remote.starts_with("https://") { vec![remote.to_string()] } else { urls(&plan["links"], text(file, "product"), remote.trim_start_matches('/')) };
transfer.fetch(&endpoints, Some((offset, offset + num(file, "size") - 1)), &stage, num(file, "size"))?;
transfer.fetch(&endpoints, Some((offset, offset + num(file, "size") - 1)), &stage, num(file, "size"))
.map_err(|e| format!("{e} file={} remote={remote}", text(file, "path")))?;
} else {
let mut output = OpenOptions::new().create(true).truncate(false).read(true).write(true).open(&stage).map_err(|e| e.to_string())?;
let mut offset = 0u64;
@@ -286,7 +287,8 @@ pub fn run(req: &GogRequest, cancel: &AtomicBool, events: &dyn GogEvents) -> Gog
std::io::copy(&mut source.take(old.size), &mut output).map_err(|e| e.to_string())?;
reused += old.size;
} else {
download_chunk(&mut transfer, &plan["links"], text(file, "product"), chunk, &stage.with_extension("packed"), &mut output)?;
download_chunk(&mut transfer, &plan["links"], text(file, "product"), chunk, &stage.with_extension("packed"), &mut output)
.map_err(|e| format!("{e} file={}", text(file, "path")))?;
}
offset += num(chunk, "size");
}
@@ -462,6 +464,20 @@ mod tests {
assert_eq!(server.bytes.load(Ordering::Relaxed), 4);
}
#[test]
fn failed_fetches_name_the_file_and_remote_path() {
let temp = Temp::new(); let missing = Server::new(HashMap::new(), true);
let ranged = json!([{"path":"support/1/setup.exe", "size":4, "chunks":[], "product":"1", "remotePath":"main.bin", "offset":0}]);
let result = execute(&temp.0, ranged, json!([]), &missing);
assert!(result.link_expiry, "{}", result.error);
assert_eq!(result.error, "HTTP 404 file=support/1/setup.exe remote=main.bin");
let (a, _, _) = chunk(b"data");
let chunked = json!([{"path":"Data/pack.dat", "size":4, "md5":md5_hex(b"data"), "chunks":[a], "product":"1"}]);
let result = execute(&temp.0, chunked, json!([]), &missing);
assert!(result.link_expiry, "{}", result.error);
assert_eq!(result.error, "HTTP 404 file=Data/pack.dat");
}
#[test]
fn bad_chunks_never_replace_original_and_expired_links_are_reported() {
let temp = Temp::new(); fs::write(temp.0.join("game"), b"old!").unwrap();
@@ -20,24 +20,6 @@ class GameEnvironmentTest {
assertEquals("1", GameEnvironment.effective(config, "", "43", forceSsbs = true)[GameEnvironment.FORCE_SSBS])
}
@Test fun knownGameFixesBeatSharedSettingsButNotTheGamesOwn() {
val shared = GameEnvironment.Config(shared = mapOf("FEX_X87REDUCEDPRECISION" to "1"))
assertEquals("0", GameEnvironment.effective(shared, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("1", GameEnvironment.effective(shared, "PERFORMANCE_TSO", "12110")["FEX_X87REDUCEDPRECISION"])
val own = shared.withEntries("12100", mapOf("FEX_X87REDUCEDPRECISION" to "1"))
assertEquals("1", GameEnvironment.effective(own, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("1", GameEnvironment.withKnownGames(own).games["12100"]?.get("FEX_X87REDUCEDPRECISION"))
assertEquals("0", GameEnvironment.withKnownGames(shared).games["12100"]?.get("FEX_X87REDUCEDPRECISION"))
}
@Test fun aGamePresetKeepsTheGamesKnownFix() {
val picked = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "12100", "PERFORMANCE")
assertEquals("0", GameEnvironment.effective(picked, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("PERFORMANCE", GameEnvironment.gameFexPreset(picked, "12100"))
val other = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "12110", "PERFORMANCE")
assertEquals("1", GameEnvironment.effective(other, "PERFORMANCE_TSO", "12110")["FEX_X87REDUCEDPRECISION"])
}
@Test fun gameOverridesSharedAndPresetWithoutLeakingToOtherGames() {
val config = GameEnvironment.Config(
shared = mapOf("FEX_MULTIBLOCK" to "0", "VKD3D_FEATURE_LEVEL" to "12_2"),
@@ -1,79 +0,0 @@
package com.droiddeck.launcher.runtime
import androidx.test.core.app.ApplicationProvider
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class NativeGuestPrepareTest {
private val svc = 0xd4000001.toInt()
private val rseq = 0xd28024a8.toInt()
private val enosys = 0x928004a0.toInt()
private fun unpatchedLoader(): ByteArray {
val data = ByteArray(0x200)
val b = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
b.put(0, 0x7f); b.put(1, 'E'.code.toByte()); b.put(2, 'L'.code.toByte()); b.put(3, 'F'.code.toByte())
b.put(4, 2); b.put(5, 1)
b.putShort(18, 183)
b.putLong(32, 64)
b.putShort(54, 56); b.putShort(56, 1)
b.putInt(64, 1); b.putInt(68, 5)
b.putLong(72, 0x100); b.putLong(96, 0x100)
b.putInt(0x100, rseq); b.putInt(0x104, svc)
return data
}
private fun rootWithUnpatchedLoader(): Pair<File, File> {
val root = Files.createTempDirectory("native-prepare").toFile()
val loader = File(root, "usr/lib/ld-linux-aarch64.so.1")
loader.parentFile!!.mkdirs()
loader.writeBytes(unpatchedLoader())
return root to loader
}
private fun instructionAfterRseq(loader: File): Int =
ByteBuffer.wrap(loader.readBytes()).order(ByteOrder.LITTLE_ENDIAN).getInt(0x104)
@After
fun endSession() {
NativeGuest.sessionMode = null
}
@Test
fun aProgramStartedOutsideASessionGetsALoaderThatSurvivesSeccomp() {
val (root, loader) = rootWithUnpatchedLoader()
NativeGuest.sessionMode = null
NativeGuest.processBuilder(ApplicationProvider.getApplicationContext(), root, emptyList(), listOf("/usr/bin/true"))
assertEquals(enosys, instructionAfterRseq(loader))
}
@Test
fun aProgramStartedInARunningSessionLeavesTheRootfsAsTheSessionPreparedIt() {
val (root, loader) = rootWithUnpatchedLoader()
val before = loader.readBytes()
NativeGuest.sessionMode = true
NativeGuest.processBuilder(ApplicationProvider.getApplicationContext(), root, emptyList(), listOf("/usr/bin/true"))
assertArrayEquals(before, loader.readBytes())
}
@Test
fun anAlreadyPreparedLoaderIsNotRewritten() {
val (root, loader) = rootWithUnpatchedLoader()
NativeGuest.processBuilder(ApplicationProvider.getApplicationContext(), root, emptyList(), listOf("/usr/bin/true"))
val modified = loader.lastModified()
val bytes = loader.readBytes()
loader.setLastModified(modified - 10_000)
NativeGuest.processBuilder(ApplicationProvider.getApplicationContext(), root, emptyList(), listOf("/usr/bin/true"))
assertArrayEquals(bytes, loader.readBytes())
assertEquals(modified - 10_000, loader.lastModified())
}
}
@@ -202,19 +202,11 @@ class GameEnvironmentStoreTest {
assertEquals("false", published.shared["MESA_SHADER_CACHE_DISABLE"])
assertFalse(published.shared.containsKey("VKD3D_FEATURE_LEVEL"))
assertFalse(published.shared.containsKey("VKD3D_SHADER_MODEL"))
assertEquals(config.games + GameEnvironment.knownGames, published.games)
assertEquals(config.games, published.games)
assertEquals(config.shared["LITERAL"], published.shared["LITERAL"])
assertEquals("", published.shared["EMPTY"])
}
@Test fun aKnownGamesFixReachesTheGuestWithoutBeingSavedAsTheUsersSetting() {
GameEnvironmentStore.save(context, GameEnvironment.Config())
assertEquals(emptyMap<String, Map<String, String?>>(), GameEnvironmentStore.read(context).games)
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertEquals(GameEnvironment.knownGames, published.games)
assertEquals("0", published.entries("12100")["FEX_X87REDUCEDPRECISION"])
}
@Test fun publishingPreservesExplicitSharedGraphicsCapabilities() {
val config = GameEnvironment.Config(shared = mapOf(
"VKD3D_FEATURE_LEVEL" to "12_1", "VKD3D_SHADER_MODEL" to "6_6",
@@ -274,7 +266,7 @@ class GameEnvironmentStoreTest {
assertEquals(original.entries("43"), saved.entries("43"))
assertEquals("PERFORMANCE_TSO", SessionPrefs.fexPreset(context))
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertEquals(saved.games + GameEnvironment.knownGames, published.games)
assertEquals(saved.games, published.games)
assertEquals("0", published.shared["FEX_HALFBARRIERTSOENABLED"])
assertEquals("1", published.entries("42")["FEX_HALFBARRIERTSOENABLED"])
}
@@ -270,9 +270,20 @@ class GogMaintenanceTest {
val game = snapshot.files.getJSONObject(1)
assertEquals("Data/World/Levels/Raycap/Raycap.snd", game.getString("path"))
assertEquals(384206096L, game.getLong("offset"))
assertEquals("1207658940/main.bin", game.getString("remotePath"))
assertEquals("main.bin", game.getString("remotePath"))
assertEquals("main.bin", support.getString("remotePath"))
assertTrue(requested.drop(1).all { "/1207658940/windows/31847977/" in it })
GogFiles.validate(snapshot.files, temporary.newFolder())
val secureLink = "https://cdn.example.invalid/token=abc/content-system/v1/depots/1207658940/windows/31847977/"
assertEquals(listOf("${secureLink}main.bin"), GogFallback.endpoints(JSONObject().put("1207658940", JSONArray().put(secureLink)),
game.getString("product"), game.getString("remotePath")))
}
@Test fun onlyRelativeGenerationOneUrlsAreReducedToTheirFileName() {
assertEquals("main.bin", GogContent.remotePath("1207663863/main.bin?expires=1", 1))
assertEquals("https://cdn.example.invalid/1207663863/main.bin", GogContent.remotePath("https://cdn.example.invalid/1207663863/main.bin?expires=1", 1))
assertEquals("1207663863/main.bin", GogContent.remotePath("1207663863/main.bin", 2))
assertEquals("", GogContent.remotePath("", 1))
}
@Test fun multipartPatchNamesVersionsLanguageAndChecksumsSurviveParsing() {
@@ -1,37 +0,0 @@
package com.droiddeck.launcher.stores.steam
import androidx.compose.runtime.State
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.runtime.snapshots.StateObject
import com.droiddeck.launcher.stores.StoresState
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import kotlin.concurrent.thread
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE)
class SteamPickingSnapshotTest {
@Test
fun theInstallPickerIsReadableInASnapshotOpenedBeforeTheSteamEngineStarts() {
StoresState.steamPicking = null
val snapshot = Snapshot.takeMutableSnapshot()
try {
thread { SteamStore.hashCode() }.join()
assertNull(snapshot.enter { StoresState.steamPicking })
} finally {
snapshot.dispose()
}
}
@Test
fun theSteamEngineHoldsNoComposeState() {
val stateFields = SteamStore::class.java.declaredFields.filter {
StateObject::class.java.isAssignableFrom(it.type) || State::class.java.isAssignableFrom(it.type)
}
assertTrue(stateFields.joinToString { it.name }, stateFields.isEmpty())
}
}
@@ -16,34 +16,6 @@ class XboxManifestTest {
java.io.File(root, "MicrosoftGame.Config").writeText("<Game><ExecutableList><Executable Name=\"bin\\GAME.EXE\" TargetDeviceFamily=\"PC\"/></ExecutableList></Game>")
assertEquals("Bin/Game.exe", XboxInstaller.executable(root))
}
@Test fun aListedExecutableThePackageDoesNotShipFallsThroughToTheNextOne() {
val root = temporary.newFolder()
java.io.File(root, "bin/x64_dx12").mkdirs()
java.io.File(root, "bin/x64_dx12/game.exe").writeText("encrypted")
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList>" +
"<Executable Name=\"bin\\x64\\game.exe\" TargetDeviceFamily=\"PC\"/>" +
"<Executable Name=\"Launcher\\start.exe\" TargetDeviceFamily=\"PC\"/>" +
"<Executable Name=\"bin\\x64_dx12\\game.exe\" TargetDeviceFamily=\"PC\"/></ExecutableList></Game>")
assertEquals("bin/x64_dx12/game.exe", XboxInstaller.executable(root))
}
@Test fun anAmbiguouslyCasedExecutableFallsThroughToTheNextOne() {
val root = temporary.newFolder()
java.io.File(root, "Game.exe").writeText("one")
java.io.File(root, "GAME.exe").writeText("two")
java.io.File(root, "Other.exe").writeText("three")
org.junit.Assume.assumeTrue(root.listFiles().orEmpty().count { it.name.equals("game.exe", true) } == 2)
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList>" +
"<Executable Name=\"game.exe\"/><Executable Name=\"Other.exe\"/></ExecutableList></Game>")
assertEquals("Other.exe", XboxInstaller.executable(root))
}
@Test fun aPackageWithNoneOfItsListedExecutablesStillFails() {
val root = temporary.newFolder()
java.io.File(root, "Unlisted.exe").writeText("encrypted")
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList>" +
"<Executable Name=\"bin\\Game.exe\"/><Executable Name=\"Game.exe\"/></ExecutableList></Game>")
val failure = assertThrows(IllegalArgumentException::class.java) { XboxInstaller.executable(root) }
assertEquals("Missing or ambiguous Xbox launch path.", failure.message)
}
@Test fun aLauncherMenuIsSkippedForTheProgramItNames() {
val root = temporary.newFolder()
java.io.File(root, "EmuMenu").mkdir()
@@ -9,25 +9,6 @@ import org.junit.Test
class XodusDiagnosticsTest {
private val rejected = Regex(Xodus.SIGN_IN_REJECTED)
@Test fun aDeviceLimitReachesTheInstallerWithoutBecomingASignInFailure() {
val line = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200"
val tail = listOf(line).filter { it.matches(Xodus.reportable) }
assertEquals(listOf(line), tail)
assertFalse(line.matches(rejected))
assertEquals(com.droiddeck.launcher.R.string.stores_xbox_device_group_full, XboxInstaller.licenseRefusal(tail))
}
@Test fun aLaterLicenseSuccessClearsTheDeviceLimitThroughTheDiagnosticFilter() {
val stderr = listOf(
"NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200",
"NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-parsed 200",
"NEXUS_EXTRACT_DIAGNOSTIC_V1 extract-failed"
)
val tail = stderr.filter { it.matches(Xodus.reportable) }
assertEquals(stderr, tail)
assertNull(XboxInstaller.licenseRefusal(tail))
}
@Test fun aContentLicenseRejectionIsRecognised() {
assertTrue("Microsoft content licensing rejected sign-in (HTTP 401). Sign in again in Settings.".matches(rejected))
}
@@ -122,19 +122,6 @@ class LibraryEntriesTest {
assertEquals(listOf("steam", "xbox", "itch", "gamejolt"), librarySources(entries, listOf("xbox", "itch", "gamejolt"), setOf("itch", "gamejolt")))
}
@Test fun everySignedInStoreKeepsItsTabWhenItsLibraryIsEmptyOrFailedToLoad() {
val entries = listOf(LibraryEntry("epic:1", "epic", "Game", null, null, true))
val order = listOf("epic", Store.ROCKSTAR.id, "gog")
val always = alwaysLibraryTabs(listOf(Store.STEAM, Store.ROCKSTAR), stores = true, soundMode = false)
assertEquals(listOf("steam", "epic", "rockstar", "battlenet", "added"), librarySources(entries, order, always))
}
@Test fun signedOutStoresAndSoundtrackModeDoNotGainEmptyTabs() {
assertEquals(setOf("added", "battlenet"), alwaysLibraryTabs(emptyList(), stores = true, soundMode = false))
assertEquals(setOf("added", "battlenet"), alwaysLibraryTabs(listOf(Store.STEAM, Store.ROCKSTAR), stores = true, soundMode = true))
assertEquals(emptySet<String>(), alwaysLibraryTabs(emptyList(), stores = false, soundMode = false))
}
@Test fun gameKeysNameEitherAnAppOrAStoreProduct() {
GameRef.parse("app:440").let { assertEquals(440, it.appId); assertNull(it.store) }
GameRef.parse("app:-12").let { assertEquals(-12, it.appId) }
@@ -0,0 +1,9 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true
+1 -5
View File
@@ -229,16 +229,12 @@ fi
if ! /usr/local/bin/droiddeck-pipewire start; then
echo "== pipewire: not running; screen capture has no picture"
fi
return_gaming=/run/droiddeck/return-gaming
mkdir -p /run/droiddeck
rm -f "$return_gaming"
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
dbus-run-session -- startplasma-wayland
rc=$?
/usr/local/bin/droiddeck-pipewire stop
echo "== droiddeck-desktop: Plasma ended ($rc)"
if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ] && [ -e "$return_gaming" ]; then
rm -f "$return_gaming"
if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ]; then
/usr/local/bin/droiddeck-steam-launch bigpicture
sleep 30
fi
@@ -1,9 +0,0 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=sh -c ": > /run/droiddeck/return-gaming; dbus-send --session --print-reply --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout >/dev/null || rm -f /run/droiddeck/return-gaming"
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true
@@ -1149,7 +1149,6 @@ case $mode in
droiddeck-steam-library "$steam_root" || true
step "setting up the ARM64 Proton compatibility tool"
steam-compatibility "$steam_root" || true
steam-compatibility "$steam_root" --seed-arm64-tools || true
if [ -z "${DD_DESKTOP:-}" ] && [ "${DD_STEAM_UI:-}" != desktop ]; then
droiddeck-steam-ui-scale "$steam_root" "${DD_WIDTH:-1280}" "${DD_HEIGHT:-720}" || true
fi
@@ -5,7 +5,6 @@ import re
import runpy
import shutil
import sys
import tempfile
TOOL = "droiddeck-proton-arm64"
TOOL_11 = "droiddeck-proton-11-arm64"
@@ -27,8 +26,6 @@ SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
ARM64_TOOL_DEPENDENCIES = (("1826330", "Proton EasyAntiCheat Runtime"),
("1070560", "Steam Linux Runtime 1.0 (scout)"))
# "0" = the app's "Valve Proton only when needed": Valve's ARM64 Proton is fetched only for a title or
# default set to a tool built from it, or while no own Proton build is installed.
VALVE_PROTON_ENV = "DD_VALVE_PROTON"
@@ -1015,15 +1012,10 @@ def manifest_text(appid, name, installdir, bare=False):
return text[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' if bare else text
def manifest_paths(steam_root, app):
for library in libraries(steam_root):
yield os.path.join(library, "steamapps", "appmanifest_%s.acf" % app)
def app_manifest(steam_root, app):
for path in manifest_paths(steam_root, app):
for library in libraries(steam_root):
try:
with open(path, encoding="utf-8", errors="replace") as f:
with open(os.path.join(library, "steamapps", "appmanifest_%s.acf" % app), encoding="utf-8", errors="replace") as f:
return tokenize(f.read())
except OSError:
continue
@@ -1038,57 +1030,6 @@ def manifest_flags(tokens):
return 0
def installed_manifest(path):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return bool(manifest_flags(tokenize(f.read())) & FULLY_INSTALLED)
except OSError:
return False
def seed_unavailable_arm64_tools(steam_root):
entries = appinfo_entries(os.path.join(steam_root, "appcache", "appinfo.vdf"),
[app for app, _ in ARM64_TOOL_DEPENDENCIES])
steamapps = os.path.join(steam_root, "steamapps")
os.makedirs(steamapps, exist_ok=True)
seeded = []
for app, display in ARM64_TOOL_DEPENDENCIES:
entry = entries.get(app)
if entry is not None:
if entry["type"] not in ("", "tool"):
continue
if "arm64" in entry["osarch"] or "aarch64" in entry["osarch"]:
continue
existing = [p for p in manifest_paths(steam_root, app) if os.path.isfile(p)]
if any(installed_manifest(p) for p in existing):
continue
name = (entry or {}).get("name") or display
installdir = (entry or {}).get("installdir") or name
path = existing[0] if existing else os.path.join(steamapps, "appmanifest_%s.acf" % app)
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8",
dir=os.path.dirname(path),
prefix=".appmanifest_", delete=False) as f:
temporary = f.name
f.write(manifest_text(app, name, installdir, True))
if existing:
os.replace(temporary, path)
else:
os.link(temporary, path)
except OSError as e:
print("steam-compatibility: could not mark %s installed (%s)" % (app, e))
continue
finally:
if temporary is not None:
try:
os.unlink(temporary)
except OSError:
pass
seeded.append(app)
return seeded
def valve_proton_on_demand():
return os.environ.get(VALVE_PROTON_ENV) == "0"
@@ -1860,11 +1801,6 @@ def main():
steam_root = sys.argv[1]
if "--valve-proton-needed" in sys.argv[2:]:
sys.exit(0 if valve_proton_needed(steam_root) else 1)
if "--seed-arm64-tools" in sys.argv[2:]:
seeded = seed_unavailable_arm64_tools(steam_root)
if seeded:
print("steam-compatibility: marked unavailable ARM64 tool(s) installed: %s" % ", ".join(seeded))
return
if "--x64" in sys.argv[2:]:
x64_repoint(steam_root, os.environ.get("DD_COMPAT_TOOL"), "--live" in sys.argv[2:])
return
+8 -113
View File
@@ -34,8 +34,6 @@
"NAME=\"Xbox 360 Controller (%d)\"\n" \
"PHYS=\"usb-fakeinput/input%d\"\n"
#define RING_SDL_ID 0x045e028eu
#define PARENT_NAME "droiddeck-input"
#define PARENT_SYSPATH_FORMAT "/sys/devices/droiddeck%d/" PARENT_NAME "%d"
#define EVENT_SYSPATH_FORMAT PARENT_SYSPATH_FORMAT "/event%d"
@@ -51,8 +49,6 @@ struct pad {
int live;
};
static const char *ring_uevent_format(void);
static struct pad pads[PAD_MAX];
static struct pad parents[PAD_MAX];
static int pad_count;
@@ -93,7 +89,7 @@ static void discover_pads(void) {
snprintf(pad->syspath, sizeof(pad->syspath), EVENT_SYSPATH_FORMAT, (int)slot, (int)slot,
(int)slot);
snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%ld", slot);
snprintf(pad->uevent, sizeof(pad->uevent), ring_uevent_format(), (int)slot, (int)slot);
snprintf(pad->uevent, sizeof(pad->uevent), PAD_UEVENT_FORMAT, (int)slot, (int)slot);
pad->devnum = makedev(13, EVENT_MINOR_BASE + (unsigned int)slot);
pad->node = (int)slot;
pad->live = 1;
@@ -141,68 +137,6 @@ static int any_virtual_pad(void) {
return 0;
}
static char *sdl_id_list_text(const char *list) {
char *text = NULL;
char *grown;
size_t length = 0;
size_t got;
FILE *file;
if (list[0] != '@') return strdup(list);
file = fopen(list + 1, "re");
if (file == NULL) return NULL;
do {
grown = realloc(text, length + 4097);
if (grown == NULL) {
free(text);
fclose(file);
return NULL;
}
text = grown;
got = fread(text + length, 1, 4096, file);
length += got;
} while (got > 0);
fclose(file);
text[length] = '\0';
return text;
}
static int sdl_id_list_entries(const char *list, int *has_ring) {
char *text = sdl_id_list_text(list);
char *spot = text;
uint32_t entry;
int entries = 0;
*has_ring = 0;
if (text == NULL) return 0;
while ((spot = strstr(spot, "0x")) != NULL) {
entry = (uint32_t)(uint16_t)strtol(spot, &spot, 0) << 16;
spot = strstr(spot, "0x");
if (spot == NULL) break;
entry |= (uint16_t)strtol(spot, &spot, 0);
entries++;
if (entry == RING_SDL_ID) *has_ring = 1;
}
free(text);
return entries;
}
static int sdl_bus_skips_ring_pad(void) {
const char *steam_virtual = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
const char *except = getenv("SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT");
const char *ignore = getenv("SDL_GAMECONTROLLER_IGNORE_DEVICES");
int has_ring;
if (steam_virtual != NULL && atoi(steam_virtual) != 0) return 1;
if (except != NULL && sdl_id_list_entries(except, &has_ring) > 0) return !has_ring;
return ignore != NULL && sdl_id_list_entries(ignore, &has_ring) > 0 && has_ring;
}
static const char *ring_uevent_format(void) {
if (uinput_enabled() && any_virtual_pad()) return PAD_PHYSICAL_UEVENT_FORMAT;
return sdl_bus_skips_ring_pad() ? PAD_UEVENT_FORMAT : PAD_PHYSICAL_UEVENT_FORMAT;
}
static void refresh_locked(int node) {
struct pad *pad = &pads[node];
@@ -233,7 +167,9 @@ static void refresh_locked(int node) {
} else {
snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%d", node);
pad->live = 1;
snprintf(pad->uevent, sizeof(pad->uevent), ring_uevent_format(), node, node);
if (uinput_enabled())
snprintf(pad->uevent, sizeof(pad->uevent),
any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT, node, node);
}
}
sync_parent(node);
@@ -505,48 +441,11 @@ static void *next_symbol(const char *name) {
char *dd_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *))
__attribute__((visibility("hidden")));
static int caller_in_library(void *caller, const char *library) {
static int caller_is_winebus(void *caller) {
Dl_info info;
if (dladdr(caller, &info) == 0 || info.dli_fname == NULL) return 0;
return strstr(info.dli_fname, library) != NULL;
}
static int caller_is_winebus(void *caller) { return caller_in_library(caller, "winebus.so"); }
typedef int (*sdl_rumble_fn)(void *, uint16_t, uint16_t, uint32_t);
static _Atomic(sdl_rumble_fn) real_sdl_rumble;
static __thread int winebus_sdl_call;
static int winebus_sdl_rumble(void *joystick, uint16_t low, uint16_t high, uint32_t duration) {
sdl_rumble_fn real = atomic_load_explicit(&real_sdl_rumble, memory_order_acquire);
int result;
if (!caller_is_winebus(__builtin_return_address(0))) return real(joystick, low, high, duration);
if (low != 0 || high != 0) duration = 0;
winebus_sdl_call = 1;
result = real(joystick, low, high, duration);
winebus_sdl_call = 0;
return result;
}
static void *winebus_sdl_rumble_dlsym(void *handle, const char *name) {
(void)handle;
(void)name;
return (void *)winebus_sdl_rumble;
}
static void *sdl_rumble_target(void *handle, void *(*forward)(void *, const char *)) {
sdl_rumble_fn expected = NULL;
sdl_rumble_fn found;
if (handle == RTLD_NEXT || handle == RTLD_DEFAULT) return NULL;
found = (sdl_rumble_fn)forward(handle, "SDL_JoystickRumble");
if (found == NULL) return NULL;
atomic_compare_exchange_strong_explicit(&real_sdl_rumble, &expected, found, memory_order_acq_rel,
memory_order_acquire);
if (atomic_load_explicit(&real_sdl_rumble, memory_order_acquire) != found) return NULL;
return (void *)winebus_sdl_rumble_dlsym;
return strstr(info.dli_fname, "winebus.so") != NULL;
}
__attribute__((visibility("hidden"))) int dd_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd,
@@ -555,8 +454,7 @@ __attribute__((visibility("hidden"))) int dd_winebus_rumble_ioctl(int (*real)(in
struct ff_effect *effect = arg;
__u16 length;
if (request != EVIOCSFF || effect == NULL || effect->type != FF_RUMBLE) return 0;
if (!caller_is_winebus(caller) && !(winebus_sdl_call && caller_in_library(caller, "libSDL"))) return 0;
if (request != EVIOCSFF || effect == NULL || effect->type != FF_RUMBLE || !caller_is_winebus(caller)) return 0;
length = effect->replay.length;
effect->replay.length = 0;
*rc = real(fd, request, arg);
@@ -1297,10 +1195,7 @@ static void *own_dlsym(void *handle, const char *name) {
__attribute__((visibility("hidden"), used)) void *inputudev_dlsym_target(void *handle, const char *name) {
void *forward = real_dlsym();
if (forward != NULL && name != NULL && strcmp(name, "SDL_JoystickRumble") == 0) {
void *rumble = sdl_rumble_target(handle, forward);
if (rumble != NULL) return rumble;
}
(void)handle;
if (name != NULL && strncmp(name, "udev_", 5) == 0 && own_udev_symbol(name) != NULL &&
!steam_client_process())
return (void *)own_dlsym;
+2 -4
View File
@@ -452,8 +452,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
char resolved_target[PATH_MAX];
// Only intercept binaries/scripts within DDNATV_ROOT
if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename) ||
is_bound_guest_program(target)) {
if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename)) {
struct exec_probe probe;
const char *elf_target = select_exec_target(target, resolved_target, sizeof(resolved_target), &probe);
if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target;
@@ -970,8 +969,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
}
char *const *orig_ep = envp ? envp : environ;
int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path) ||
is_bound_guest_program(target);
int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path);
struct exec_probe probe;
char resolved_target[PATH_MAX];
-8
View File
@@ -983,14 +983,6 @@ static int is_host_interpreter(const char *interp, const char *rewritten) {
return probe.android_interp;
}
static int is_bound_guest_program(const char *path) {
if (g_ddnatv_root[0] == '\0' || !is_identity_bound_path(path)) return 0;
struct exec_probe probe;
probe_exec_file(path, &probe);
if (probe.is_elf) return probe.is_dynamic && !probe.android_interp;
return probe.n >= 2 && probe.hdr[0] == '#' && probe.hdr[1] == '!';
}
// argv for running `script` with its interpreter: interp [arg] script args... (the script's own
// argv[0] is dropped, as the kernel does). free() the result.
static char **build_script_argv(const char *interp, const char *interp_arg, const char *script, char *const argv[]) {
-7
View File
@@ -234,13 +234,6 @@ static int is_mapped_guest_path(const char *path) {
return 0;
}
static int is_identity_bound_path(const char *path) {
if (!path || path[0] != '/') return 0;
for (int i = 0; i < g_nbinds; i++)
if (g_binds[i].identity && is_path_prefix(path, g_binds[i].dst, g_binds[i].dst_len)) return 1;
return 0;
}
// Android's own mounts and files, which must never be redirected into the rootfs.
// `path` starts with '/'; a prefix can only match when its second character does.
static int is_android_host_path(const char *path) {
-1
View File
@@ -32,7 +32,6 @@ def source_assets(overlay=OVERLAY):
result[desktop / name] = 'assets/linuxfs/usr/local/bin/' + name
result[desktop / 'firefox-droiddeck.js'] = 'assets/linuxfs/usr/lib/firefox/defaults/pref/droiddeck.js'
result[desktop / 'droiddeck-clipboard.desktop'] = 'assets/linuxfs/etc/xdg/autostart/droiddeck-clipboard.desktop'
result[desktop / 'droiddeck-return-gaming.desktop'] = 'assets/linuxfs/usr/share/applications/droiddeck-return-gaming.desktop'
result[desktop / 'fastfetch.jsonc'] = 'assets/linuxfs/etc/xdg/fastfetch/config.jsonc'
result[overlay.parent.parent / 'mangoapp/mangoapp'] = 'assets/linuxfs/usr/local/bin/mangoapp'
return result
-22
View File
@@ -24,28 +24,6 @@ class CiChecksTest(unittest.TestCase):
gradle = (ROOT / 'app/build.gradle').read_text()
self.assertIn("gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit])", gradle)
def test_robolectric_cache_saves_and_restores_the_same_absolute_path(self):
steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']
caches = [step['with'] for step in steps if step.get('uses', '').startswith('actions/cache')]
for cache in caches:
for path in cache['path'].split('\n'):
self.assertNotIn('..', path.split('/'))
robolectric = [cache['path'] for cache in caches if cache['key'].startswith('robolectric-')]
self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2)
def test_unit_test_retry_requires_maven_exception(self):
steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']
run = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
line = next(line for line in run.splitlines() if 'grep -Eq' in line)
pattern = shlex.split(line)[shlex.split(line).index('-Eq') + 1]
for log, expected in (
("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo.maven.apache.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0),
("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo.maven.apache.org/maven2/a.jar", 0),
("SomeTest > test FAILED: Too Many Requests", 1),
("Caused by: java.lang.AssertionError: HTTP 429", 1),
):
self.assertEqual(subprocess.run(['grep', '-Eq', pattern], input=log, text=True).returncode, expected)
def test_report_comment_lookup_ignores_human_marker(self):
if not shutil.which('jq'):
self.skipTest('jq required to execute comment selection')
-75
View File
@@ -1,75 +0,0 @@
import os
import re
import shlex
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DESKTOP = ROOT / "tools/linuxfs/desktop"
SCRIPT = (DESKTOP / "droiddeck-desktop").read_text()
ENTRY = (DESKTOP / "droiddeck-return-gaming.desktop").read_text()
class DesktopReturnGamingTest(unittest.TestCase):
def session(self, logout, rc=0, bottom=False):
with tempfile.TemporaryDirectory() as tmp:
run = Path(tmp, "run")
launched = Path(tmp, "launched")
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
inner = shlex.split(exec_line)[2].replace("dbus-send", "true")
plasma = Path(tmp, "plasma")
plasma.write_text("#!/bin/sh\n%s\nexit %d\n" % (inner if logout == "return" else ":", rc))
plasma.chmod(0o755)
steam = Path(tmp, "steam-launch")
steam.write_text('#!/bin/sh\necho "$*" > %s\n' % launched)
steam.chmod(0o755)
tail = SCRIPT[SCRIPT.index("return_gaming="):]
tail = tail.replace("dbus-run-session -- startplasma-wayland", str(plasma))
tail = tail.replace("/usr/local/bin/droiddeck-pipewire stop", ":")
tail = tail.replace("/usr/local/bin/droiddeck-steam-launch", str(steam))
tail = tail.replace("sleep 30", ":")
tail = tail.replace("/run/droiddeck", str(run))
plasma.write_text(plasma.read_text().replace("/run/droiddeck", str(run)))
env = {k: v for k, v in os.environ.items() if k != "DD_BOTTOM_DESKTOP"}
if bottom:
env["DD_BOTTOM_DESKTOP"] = "1"
run.mkdir()
(run / "return-gaming").write_text("")
status = subprocess.run(["sh", "-c", tail], env=env, capture_output=True, text=True).returncode
return status, launched.read_text().strip() if launched.exists() else None, (run / "return-gaming").exists()
def test_return_to_gaming_mode_opens_steam(self):
self.assertEqual(self.session("return"), (0, "bigpicture", False))
def test_log_out_goes_back_without_steam_even_after_an_earlier_request(self):
self.assertEqual(self.session("logout"), (0, None, False))
def test_a_failed_session_and_the_bottom_desktop_never_open_steam(self):
self.assertEqual(self.session("return", rc=1)[:2], (1, None))
self.assertEqual(self.session("return", bottom=True)[:2], (0, None))
def test_the_logout_request_outlives_starting_the_shutdown_service(self):
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
call = shlex.split(shlex.split(exec_line)[2].split(";")[-1])
self.assertEqual(call[0], "dbus-send")
self.assertIn("--print-reply", call)
def test_a_rejected_logout_request_forgets_the_return_to_gaming_mode(self):
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
with tempfile.TemporaryDirectory() as tmp:
inner = shlex.split(exec_line)[2].replace("/run/droiddeck", tmp)
for sender, kept in (("true", True), ("false", False)):
subprocess.run(["sh", "-c", inner.replace("dbus-send", sender, 1)], check=False)
self.assertEqual(Path(tmp, "return-gaming").exists(), kept)
def test_the_app_ships_the_shortcut_with_the_script(self):
source = (ROOT / "app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt").read_text()
self.assertIn('"usr/share/applications/droiddeck-return-gaming.desktop" to '
'"usr/share/applications/droiddeck-return-gaming.desktop"', source)
self.assertIn("droiddeck-return-gaming.desktop", (ROOT / "tools/release/check_session_assets.py").read_text())
if __name__ == "__main__":
unittest.main()
+3 -21
View File
@@ -29,21 +29,14 @@ PAD_TYPE_STEAM = 1
READER = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <poll.h>
#include <stdio.h>
#include <sys/uio.h>
#include <unistd.h>
ssize_t __read_chk(int fd, void *buffer, size_t size, size_t buffer_size);
int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fds_size);
static int vector_count;
static int fortified;
static ssize_t controller_read(int fd, void *buffer, size_t size)
{
if (fortified)
return __read_chk(fd, buffer, size, size);
if (!vector_count)
return read(fd, buffer, size);
struct iovec vectors[3] = {
@@ -60,8 +53,7 @@ static ssize_t controller_read(int fd, void *buffer, size_t size)
int main(int argc, char **argv)
{
fortified = argc > 1 && argv[1][0] == 'f';
vector_count = argc > 1 && !fortified ? (argv[1][0] == '1' ? 1 : 3) : 0;
vector_count = argc > 1 ? (argv[1][0] == '1' ? 1 : 3) : 0;
struct input_event events[64];
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0) {
@@ -70,17 +62,11 @@ int main(int argc, char **argv)
}
while (controller_read(fd, events, sizeof(events)) > 0)
;
struct pollfd idle = {fd, POLLIN, 0};
if (fortified && __poll_chk(&idle, 1, 0, sizeof(idle)) != 0)
return 3;
puts("ready");
fflush(stdout);
char go;
if (read(0, &go, 1) != 1)
return 1;
struct pollfd ready = {fd, POLLIN, 0};
if (fortified && (__poll_chk(&ready, 1, 1000, sizeof(ready)) != 1 || !(ready.revents & POLLIN)))
return 2;
ssize_t got = controller_read(fd, events, sizeof(events));
for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++)
printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type,
@@ -359,7 +345,7 @@ class FakeinputRingTest(unittest.TestCase):
subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True)
return library, binary
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER, fortified=False):
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER):
if not virtual:
program = program.replace("event16", "event0")
library, reader = self.build(bits, program, "reader")
@@ -373,7 +359,7 @@ class FakeinputRingTest(unittest.TestCase):
overlay_library = self.tmp / "overlay.so"
subprocess.run(["gcc", bits, "-shared", "-fPIC", "-o", str(overlay_library), str(source)], check=True)
env["LD_PRELOAD"] = str(overlay_library) + ":" + str(library)
command = [str(reader)] + (["fortified"] if fortified else [str(vectors)] if vectors else [])
command = [str(reader)] + ([str(vectors)] if vectors else [])
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
self.addCleanup(process.kill)
self.assertEqual(process.stdout.readline(), "ready\n")
@@ -395,10 +381,6 @@ class FakeinputRingTest(unittest.TestCase):
self.assertEqual(self.read_through("-m64"),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_a_fortified_guest_polls_and_reads_the_ring(self):
self.assertEqual(self.read_through("-m64", virtual=False, fortified=True),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_readv_reads_events_instead_of_the_backing_file(self):
self.assertEqual(self.read_through("-m64", vectors=1),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
+2 -64
View File
@@ -260,7 +260,6 @@ static void *(*next)(void *);
static void *(*by_name)(void *, const char *);
static const char *(*name)(void *);
static const char *(*value)(void *);
static const char *(*sysattr)(void *, const char *);
static void *sym(const char *symbol) { return dlsym(lib, symbol); }
@@ -464,20 +463,6 @@ static void run_every(int count, char **entries) {
printf("pad %d real calls %d\n", pad != NULL, real_calls != NULL ? *real_calls : -1);
}
static void print_product(const char *label, void *device) {
const char *uevent = device != NULL ? sysattr(device, "uevent") : NULL;
printf("%s %.*s\n", label, uevent != NULL ? (int)strcspn(uevent, "\n") : 4, uevent != NULL ? uevent : "none");
}
static void run_identity(void) {
int udev;
void *device = new_device(&udev, PAD);
print_product("pad", device);
print_product("parent", device != NULL ? get_parent(device) : NULL);
}
static void run_probe(void) {
int udev;
@@ -554,9 +539,7 @@ int main(int argc, char **argv) {
by_name = sym("udev_list_entry_get_by_name");
name = sym("udev_list_entry_get_name");
value = sym("udev_list_entry_get_value");
sysattr = sym("udev_device_get_sysattr_value");
if (strcmp(argv[1], "probe") == 0) run_probe();
else if (strcmp(argv[1], "identity") == 0) run_identity();
else if (strcmp(argv[1], "every") == 0) run_every(argc - 3, argv + 3);
else if (strcmp(argv[1], "stable") == 0) run_stable();
else if (strcmp(argv[1], "enumerate") == 0) run_enumerate();
@@ -614,13 +597,10 @@ class InputUdevPreloadTest(unittest.TestCase):
(pads / node).write_text("")
return pads
def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None, args=(), extra=None):
def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None, args=()):
env = dict(os.environ, LD_PRELOAD=":".join(str(self.dir / name) for name in ("libddsession.so", *preloads)),
FAKE_EVDEV_MEMFD_PATHS=slots, FAKE_EVDEV_DIR=str(pads or self.pads))
for key in ("FAKE_EVDEV_UINPUT", "FAKE_EVDEV_STEAM_VIRTUAL", "SDL_GAMECONTROLLER_IGNORE_DEVICES",
"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT"):
env.pop(key, None)
env.update(extra or {})
env.pop("FAKE_EVDEV_UINPUT", None)
result = subprocess.run([str(program or self.program), mode, str(self.udev), *args], env=env, capture_output=True, text=True,
timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
@@ -704,48 +684,6 @@ class InputUdevPreloadTest(unittest.TestCase):
"nothing added scan -1",
])
def identity(self, pads=None, **extra):
return self.run_program("identity", pads=pads, extra=extra)
@classmethod
def id_list(cls, name, text):
path = cls.dir / name
path.write_text(text)
return "@" + str(path)
def test_a_pad_wine_also_reads_through_sdl_is_described_as_the_pad_sdl_sees(self):
xbox = ["pad PRODUCT=3/45e/28e/110", "parent PRODUCT=3/45e/28e/110"]
for extra in ({}, {"FAKE_EVDEV_UINPUT": "1"}, {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x045e/0x028e"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "0"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-other.txt", "0x28de/0x1142\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "@" + str(self.dir / "missing.txt")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": self.id_list("except-ring.txt", "0x045E/0x028E\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x45e/0x28e"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": ""},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028f"}):
with self.subTest(**extra):
self.assertEqual(self.identity(**extra), xbox)
def test_a_pad_sdl_skips_keeps_the_steam_input_identity(self):
steam = ["pad PRODUCT=6/28de/11ff/110", "parent PRODUCT=6/28de/11ff/110"]
for extra in ({"FAKE_EVDEV_STEAM_VIRTUAL": "1"}, {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142,0x045E/0x028E"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x28de/0x11ff"},
{"FAKE_EVDEV_UINPUT": "1", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-ring.txt", "0x28de/0x1142\n0x045e/0x028e\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": self.id_list("except-other.txt", "0x28de/0x11ff\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-long.txt", "0x28de/0x1142\n" * 400 + "0x045e/0x028e\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x45e/0x28e"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"}):
with self.subTest(**extra):
self.assertEqual(self.identity(**extra), steam)
def test_a_pad_under_steam_inputs_own_virtual_pad_stays_an_xbox_pad(self):
pads = self.pad_dir("under-virtual", "event0", "event16")
(pads / ".uinput-event16.uevent").write_text('PRODUCT=6/28de/11ff/1\nNAME="Microsoft X-Box 360 pad 0"\n')
self.assertEqual(self.identity(pads, FAKE_EVDEV_UINPUT="1", SDL_GAMECONTROLLER_IGNORE_DEVICES="0x045e/0x028e"),
["pad PRODUCT=3/45e/28e/110", "parent PRODUCT=3/45e/28e/110"])
def test_a_program_that_closes_and_reopens_libudev_keeps_working(self):
self.assertEqual(self.run_program("reload"), ["reload real0 real1"])
@@ -120,14 +120,6 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
script.parent.mkdir(exist_ok=True)
script.write_text(f"#!{interpreter}\n")
script.chmod(0o755)
cls.app_files = tmp / "app-files"
cls.app_files.mkdir()
shutil.copy(cls.probe, cls.app_files / "tool")
shutil.copy(cls.android / "sh", cls.app_files / "android-tool")
for name, interpreter in (("guest.py", GUEST_TOOL), ("android.sh", f"{ANDROID_DIR}/sh")):
(cls.app_files / name).write_text(f"#!{interpreter}\n")
for entry in cls.app_files.iterdir():
entry.chmod(0o755)
@classmethod
def tearDownClass(cls):
@@ -228,32 +220,6 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
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_a_script_on_a_mount_at_its_host_path_runs_with_the_guest_interpreter(self):
script = str(self.app_files / "guest.py")
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, script, "x", binds=f"{self.app_files}:{self.app_files}")
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([str(self.root / GUEST_TOOL.lstrip("/")), script, "x"], call[-3:])
def test_a_glibc_program_on_a_mount_at_its_host_path_starts_through_the_guest_ldso(self):
tool = str(self.app_files / "tool")
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, tool, "x", binds=f"{self.app_files}:{self.app_files}")
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([tool, "x"], call[-2:])
def test_android_programs_on_a_mount_at_its_host_path_stay_on_the_host(self):
tool = str(self.app_files / "android-tool")
script = str(self.app_files / "android.sh")
sh = str(self.android / "sh")
binds = f"{self.app_files}:{self.app_files}|{self.android}:{ANDROID_DIR}"
for how in ("exec", "spawn"):
with self.subTest(how=how):
self.assertEqual([tool, tool, "x"], self.call(how, tool, "x", binds=binds))
self.assertEqual([sh, sh, script, "x"], self.call(how, script, "x", binds=binds))
def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self):
sh = str(self.android / "sh")
for how in ("exec", "spawn"):
@@ -1,205 +0,0 @@
import runpy
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from tools.tests.test_droiddeck_fex import AppInfoTest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
SESSION = BIN / "droiddeck-session"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
EAC = 1826330
SCOUT = 1070560
EAC_ID = str(EAC)
SCOUT_ID = str(SCOUT)
EAC_NAME = "Proton EasyAntiCheat Runtime"
SCOUT_NAME = "Steam Linux Runtime 1.0 (scout)"
def tool(name, osarch="", kind="tool", installdir=None):
return {
"common": {"name": name, "oslist": "linux", "osarch": osarch, "type": kind},
"config": {"installdir": installdir or name},
}
class SteamToolManifestSeedTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
self.steam = self.root / "Steam"
(self.steam / "appcache").mkdir(parents=True)
(self.steam / "steamapps").mkdir()
self.entries = {EAC: tool(EAC_NAME), SCOUT: tool(SCOUT_NAME)}
self.write_appinfo()
def write_appinfo(self, entries=None):
COMPAT["APPINFO_CACHE"].clear()
(self.steam / "appcache/appinfo.vdf").write_bytes(
AppInfoTest.appinfo(self.entries if entries is None else entries))
def manifest(self, app, root=None):
return (root or self.steam) / ("steamapps/appmanifest_%s.acf" % app)
def seed(self):
return COMPAT["seed_unavailable_arm64_tools"](str(self.steam))
def test_seeds_bare_manifests_for_unavailable_tool_dependencies(self):
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
for app, name in ((EAC_ID, EAC_NAME), (SCOUT_ID, SCOUT_NAME)):
text = self.manifest(app).read_text()
for expected in ('"appid" "%s"' % app, '"Universe" "1"', '"StateFlags" "4"',
'"name" "%s"' % name, '"installdir" "%s"' % name,
'"AutoUpdateBehavior" "1"'):
self.assertIn(expected, text)
self.assertFalse(self.manifest("976730").exists())
def test_seeding_is_idempotent(self):
self.seed()
first = {app: self.manifest(app).read_text() for app in (EAC_ID, SCOUT_ID)}
self.assertEqual(self.seed(), [])
self.assertEqual({app: self.manifest(app).read_text() for app in first}, first)
def test_a_real_install_in_another_library_is_never_overwritten(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
existing = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"4"\n}\n' % SCOUT_ID
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(existing)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertEqual((other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text(), existing)
def test_a_partial_install_in_another_library_is_completed_in_place(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
partial = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"2"\n}\n' % SCOUT_ID
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(partial)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertIn('"StateFlags" "4"',
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text())
def test_a_real_install_in_any_library_wins_over_a_partial_one(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
partial = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"2"\n}\n' % SCOUT_ID
installed = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"4"\n}\n' % SCOUT_ID
self.manifest(SCOUT_ID).write_text(partial)
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(installed)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), partial)
self.assertEqual((other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text(), installed)
def test_a_failed_write_leaves_no_manifest_behind(self):
real_link = COMPAT["os"].link
def fail_for_scout(source, target):
if SCOUT_ID in str(target):
raise OSError("disk full")
return real_link(source, target)
with mock.patch.object(COMPAT["os"], "link", side_effect=fail_for_scout):
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertEqual(sorted(p.name for p in (self.steam / "steamapps").iterdir()),
["appmanifest_%s.acf" % EAC_ID])
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_new_manifest_publication_preserves_a_concurrent_install(self):
real_link = COMPAT["os"].link
installed = COMPAT["manifest_text"](SCOUT_ID, "Existing tool", "Existing", False)
def publish(source, target):
if SCOUT_ID in str(target):
Path(target).write_text(installed)
return real_link(source, target)
with mock.patch.object(COMPAT["os"], "link", side_effect=publish):
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), installed)
self.assertEqual(self.seed(), [])
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
def test_partial_staged_write_is_not_published_and_retry_repairs(self):
real_temporary = COMPAT["tempfile"].NamedTemporaryFile
def temporary(*args, **kwargs):
output = real_temporary(*args, **kwargs)
real_write = output.write
def write(text):
if SCOUT_ID in text:
real_write(text[:text.index(' "installdir"')])
output.flush()
raise OSError("disk full")
return real_write(text)
output.write = write
return output
with mock.patch.object(COMPAT["tempfile"], "NamedTemporaryFile", side_effect=temporary):
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_failed_replacement_preserves_partial_manifest_and_retry_repairs(self):
partial = '"AppState" { "appid" "%s" "StateFlags" "2" }' % SCOUT_ID
self.manifest(SCOUT_ID).write_text(partial)
with mock.patch.object(COMPAT["os"], "replace", side_effect=OSError("disk full")):
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), partial)
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_tools_with_an_arm64_depot_are_skipped(self):
entries = dict(self.entries)
entries[SCOUT] = tool(SCOUT_NAME, osarch="arm64")
self.write_appinfo(entries)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
def test_an_app_that_is_not_a_tool_is_skipped(self):
entries = dict(self.entries)
entries[SCOUT] = tool(SCOUT_NAME, kind="game")
self.write_appinfo(entries)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
def test_missing_appinfo_uses_the_display_names(self):
(self.steam / "appcache/appinfo.vdf").unlink()
COMPAT["APPINFO_CACHE"].clear()
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
self.assertIn('"name" "%s"' % SCOUT_NAME, self.manifest(SCOUT_ID).read_text())
def test_flag_seeds_without_running_full_compatibility_setup(self):
with mock.patch.object(COMPAT["sys"], "argv",
["steam-compatibility", str(self.steam), "--seed-arm64-tools"]):
COMPAT["main"]()
self.assertTrue(self.manifest(EAC_ID).is_file())
self.assertTrue(self.manifest(SCOUT_ID).is_file())
self.assertFalse((self.steam / "compatibilitytools.d").exists())
def test_session_seeds_only_on_the_arm64_client_path(self):
arm64, x64 = SESSION.read_text().split(
" else\n _dd_x64_tool=$(droiddeck-steam-x64 --default-tool)", 1)
self.assertIn('steam-compatibility "$steam_root" --seed-arm64-tools', arm64)
self.assertNotIn("--seed-arm64-tools", x64)
if __name__ == "__main__":
unittest.main()
+4 -69
View File
@@ -40,39 +40,6 @@ void upload(unsigned short type, unsigned short length) {
}
"""
SDL = r"""
#include <linux/input.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
int SDL_JoystickRumble(void *joystick, uint16_t low, uint16_t high, uint32_t duration) {
struct ff_effect effect;
(void)joystick;
printf("sdl %u %u duration %u\n", low, high, duration);
memset(&effect, 0, sizeof(effect));
effect.id = -1;
effect.type = FF_RUMBLE;
effect.replay.length = 0xffff;
effect.u.rumble.strong_magnitude = low;
effect.u.rumble.weak_magnitude = high;
return ioctl(3, EVIOCSFF, &effect);
}
"""
SDL_CALLER = r"""
#include <dlfcn.h>
#include <stdint.h>
int rumble(const char *library, uint16_t low, uint16_t high, uint32_t duration) {
void *sdl = dlopen(library, RTLD_NOW | RTLD_LOCAL);
int (*call)(void *, uint16_t, uint16_t, uint32_t) = (int (*)(void *, uint16_t, uint16_t, uint32_t))dlsym(sdl, "SDL_JoystickRumble");
call(0, low, high, duration);
return 0;
}
"""
PROGRAM = r"""
#include <dlfcn.h>
#include <linux/input.h>
@@ -80,21 +47,8 @@ PROGRAM = r"""
void upload(unsigned short type, unsigned short length);
int rumble(const char *library, unsigned short low, unsigned short high, unsigned int duration);
int main(int argc, char **argv) {
void *winebus = dlopen(argv[1], RTLD_NOW);
if (argv[2][0] == 's') {
int (*from_winebus)(const char *, unsigned short, unsigned short, unsigned int) =
(int (*)(const char *, unsigned short, unsigned short, unsigned int))dlsym(winebus, "rumble");
for (const char *step = argv[3]; *step; step++) {
if (*step == 'w') from_winebus(argv[4], 65535, 32768, 1000);
if (*step == 'z') from_winebus(argv[4], 0, 0, 0);
if (*step == 'p') rumble(argv[4], 65535, 32768, 1000);
}
fflush(stdout);
return 0;
}
void (*from_winebus)(unsigned short, unsigned short) = (void (*)(unsigned short, unsigned short))dlsym(winebus, "upload");
if (argv[2][0] == 'w') from_winebus(argv[3][0] == 'r' ? FF_RUMBLE : FF_PERIODIC, 1000);
else upload(FF_RUMBLE, 1000);
@@ -111,8 +65,7 @@ class WinebusRumblePreloadTest(unittest.TestCase):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
for name, text in (("shim.c", SHIM), ("upload.c", UPLOAD), ("program.c", PROGRAM), ("sdl.c", SDL),
("sdl_caller.c", SDL_CALLER)):
for name, text in (("shim.c", SHIM), ("upload.c", UPLOAD), ("program.c", PROGRAM)):
(build / name).write_text(text)
cls.lib = cls.dir / "libddsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib),
@@ -120,13 +73,10 @@ class WinebusRumblePreloadTest(unittest.TestCase):
cls.shim = cls.dir / "libshim.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.shim), str(build / "shim.c")], check=True)
cls.winebus = cls.dir / "winebus.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "upload.c"),
str(build / "sdl_caller.c"), "-ldl"], check=True)
cls.sdl_library = cls.dir / "libSDL2-2.0.so.0"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.sdl_library), str(build / "sdl.c")], check=True)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "upload.c")], check=True)
cls.program = cls.dir / "program"
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "upload.c"),
str(build / "sdl_caller.c"), "-ldl"], check=True)
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "upload.c"), "-ldl"],
check=True)
@classmethod
def tearDownClass(cls):
@@ -138,21 +88,6 @@ class WinebusRumblePreloadTest(unittest.TestCase):
capture_output=True, text=True, timeout=10, check=True)
return result.stdout.splitlines()
def sdl(self, steps):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.lib, self.shim))
result = subprocess.run([str(self.program), str(self.winebus), "sdl", steps, str(self.sdl_library)], env=env,
capture_output=True, text=True, timeout=10, check=True)
return result.stdout.splitlines()
def test_rumble_winebus_starts_through_sdl_is_held_until_the_next_update(self):
self.assertEqual(self.sdl("wz"), ["sdl 65535 32768 duration 0", "shim type %d length 0" % 0x50,
"sdl 0 0 duration 0", "shim type %d length 0" % 0x50])
def test_sdl_rumble_from_other_code_keeps_its_duration_and_length(self):
self.assertEqual(self.sdl("p"), ["sdl 65535 32768 duration 1000", "shim type %d length 65535" % 0x50])
self.assertEqual(self.sdl("wp"), ["sdl 65535 32768 duration 0", "shim type %d length 0" % 0x50,
"sdl 65535 32768 duration 1000", "shim type %d length 65535" % 0x50])
def test_winebus_rumble_reaches_the_shim_held_and_comes_back_unchanged(self):
self.assertEqual(self.upload("winebus"), ["shim type %d length 0" % 0x50, "caller length 1000"])
@@ -0,0 +1,9 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true