Compare commits

..
Author SHA1 Message Date
The412Banner 291cc67537 fix(library): a Steam game whose files were deleted can be uninstalled 2026-11-30 19:40:53 +00:00
MaxsTechReview 5f129fb4db fix(native): allocated getcwd and realpath results name the guest mount (#3481)
getcwd(NULL, ...) and realpath(path, NULL) returned the host path of a
session mount whenever its guest path was longer than the host path,
because the translation had to fit the buffer the C library allocated.
Shells export that host path as PWD, and Wine prefers a valid PWD, so a
program started from an added game folder on a removable card got a
working directory it could not open and started in the Windows folder.
Grow the allocated result to fit the guest path.
2026-11-30 14:24:10 -05:00
MaxsTechReview 7404fba5a3 fix(battlenet): an install folder chosen in Battle.net on the library's drive is kept (#3479)
* fix(battlenet): an install folder chosen in Battle.net on the library's drive is kept

Every open set Battle.net's default install folder back to the library folder whenever the two differed, so a folder the user picked in Battle.net on the same drive was replaced on the next open. The folder is now only moved to the library when it is unset, missing, or on another drive.

* fix(battlenet): check the trimmed folder against the rootfs drives
2026-11-30 14:24:05 -05:00
MaxsTechReview 54ca518553 fix(storage): a card library the session cannot open by its raw path is opened by its storage path (#3475)
A game storage folder saved as a raw volume path is opened through the volume's /storage path when only that one is usable, and its private directories are kept under either path. Battle.net is only given a library folder when the configured one is attached, so a missing card no longer moves its install folder to internal storage.
2026-11-30 12:00:05 -05:00
MaxsTechReview 72c8b8426d fix(input): Windows games see the gamepad again when the pad is not read through SDL (#3469)
Since each pad was described to Wine's udev backend with the identity its
SDL backend sees, the udev backend left every pad to SDL. Where SDL does
not open the pad, such as a session without proot, Windows games lost both
the gamepad and the on-screen controls.

The udev backend owns the pads again with the Steam Input identity it had
before. SDL inside Wine's bus driver now reads the same identity for those
pads and skips them as it skips any Steam Input pad, so each pad is still
listed once and both triggers keep reading together.
2026-11-30 08:53:12 -05:00
26 changed files with 456 additions and 588 deletions

No files matched your search

-42
View File
@@ -1,13 +1,9 @@
#include <errno.h>
#include <fcntl.h>
#include <jni.h>
#include <limits.h>
#include <linux/futex.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
@@ -31,41 +27,3 @@ Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass cla
(void)clazz;
return syscall(SYS_tgkill, tgid, tid, signal) == 0 ? 0 : errno;
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_session_PageCacheNative_fadviseDontNeed(JNIEnv *env, jclass clazz, jstring path) {
(void)clazz;
const char *chars = (*env)->GetStringUTFChars(env, path, NULL);
if (!chars) return ENOMEM;
char *copy = strdup(chars);
(*env)->ReleaseStringUTFChars(env, path, chars);
if (!copy) return ENOMEM;
int rc = EINVAL;
int fd = -1;
if (copy[0] != '/') goto done;
fd = open("/", O_RDONLY | O_CLOEXEC | O_DIRECTORY);
if (fd < 0) { rc = errno; goto done; }
char *part = copy + 1;
while (*part) {
char *slash = strchr(part, '/');
if (slash) *slash = '\0';
if (!*part || !strcmp(part, ".") || !strcmp(part, "..")) goto done;
int next = openat(fd, part, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK |
(slash ? O_DIRECTORY : 0));
if (next < 0) { rc = errno; goto done; }
close(fd);
fd = next;
if (!slash) {
struct stat st;
if (fstat(fd, &st) < 0) { rc = errno; goto done; }
if (!S_ISREG(st.st_mode) || st.st_size < (8LL << 20)) goto done;
rc = posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
break;
}
part = slash + 1;
}
done:
free(copy);
if (fd >= 0) close(fd);
return rc;
}
@@ -3182,10 +3182,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun removeGame(g: Library.SteamGame) {
if (g.soundtrack) { removeSoundtrack(g); return }
val folder = g.gameFiles ?: return
val folder = g.gameFiles
when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) {
com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit
com.droiddeck.launcher.frontend.GameRemoval.Kind.SHORTCUT -> removeAddedGame(folder.path, g.gameId, g.name)
com.droiddeck.launcher.frontend.GameRemoval.Kind.SHORTCUT -> if (folder != null) removeAddedGame(folder.path, g.gameId, g.name)
com.droiddeck.launcher.frontend.GameRemoval.Kind.STORE -> {
val installed = com.droiddeck.launcher.frontend.GameRemoval.storeGame(g)
if (installed != null) {
@@ -3193,7 +3193,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
return
}
if (g.library == Library.ADDED) {
removeAddedGame(folder.path, g.gameId, g.name)
if (folder != null) removeAddedGame(folder.path, g.gameId, g.name)
return
}
val target = com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
@@ -16,10 +16,10 @@ object GameRemoval {
else -> Kind.STORE
}
class SteamFiles(val dir: File, val manifest: File, val partial: File?)
class SteamFiles(val dir: File?, val manifest: File, val partial: File?)
fun steamFiles(game: Library.SteamGame): SteamFiles? {
val dir = game.gameFiles ?: return null
val dir = game.gameFiles ?: return leftover(game)
val common = dir.parentFile ?: return null
if (common.name != (if (game.soundtrack) "music" else "common")) return null
val steamapps = common.parentFile ?: return null
@@ -31,8 +31,10 @@ object GameRemoval {
}
fun delete(target: SteamFiles): Boolean {
StoreInstalls.deleteTree(target.dir)
if (target.dir.exists()) return false
target.dir?.let { dir ->
StoreInstalls.deleteTree(dir)
if (dir.exists()) return false
}
target.partial?.let { StoreInstalls.deleteTree(it) }
target.manifest.delete()
return !target.manifest.exists()
@@ -47,6 +49,12 @@ object GameRemoval {
return InstalledStoreGame(sidecar, folder)
}
private fun leftover(game: Library.SteamGame): SteamFiles? {
val manifest = game.manifest?.takeIf { it.isFile && declares(it, game.appId) } ?: return null
val steamapps = manifest.parentFile ?: return null
return SteamFiles(null, manifest, File(steamapps, "downloading/${game.appId}"))
}
private fun declares(manifest: File, appId: Int): Boolean =
runCatching { manifest.readText() }.getOrNull()?.let { Regex("\"appid\"\\s+\"$appId\"").containsMatchIn(it) } == true
}
@@ -20,9 +20,10 @@ object Library {
val logo: File? = null,
val installedAt: Long = 0L,
val soundtrack: Boolean = false,
val manifest: File? = null,
) {
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt, soundtrack)
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt, soundtrack, manifest)
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
val launchKey: String get() = if (storeId != null) "$source:$storeId" else gameIdString
@@ -167,6 +168,7 @@ object Library {
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
icon = images.icon(),
logo = images.find(STEAM_LOGOS),
manifest = manifest,
))
}
}
@@ -59,13 +59,18 @@ object GameStorage {
return when {
pref == SessionPrefs.GAME_STORAGE_OFF -> null
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) }
else -> Option(SessionPrefs.gameStorageLabel(context), pref).takeIf { attached(File(pref)) }
else -> reachable(pref).let { path -> Option(SessionPrefs.gameStorageLabel(context), path).takeIf { attached(File(path)) } }
}
}
fun disconnected(context: Context): Boolean {
val pref = SessionPrefs.gameStorage(context)
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(pref))
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(reachable(pref)))
}
internal fun reachable(path: String, usable: (File) -> Boolean = { it.isDirectory && it.canWrite() }): String {
val alias = UsbLink.storagePath(path)
return if (alias != path && !usable(File(path)) && usable(File(alias))) alias else path
}
internal fun attached(
@@ -1,126 +0,0 @@
package com.droiddeck.launcher.session
import android.util.Log
import java.io.File
import java.nio.file.Files
internal object PageCacheTrim {
private const val TAG = "PageCacheTrim"
private const val MIN_FILE_BYTES = 8L shl 20
private const val POLL_MS = 3000L
private const val RESCAN_MS = 120_000L
private const val MIN_TRIM_MS = 30_000L
data class Mem(val freeKb: Long, val fileKb: Long)
data class Trim(val before: Mem, val after: Mem?, val files: Int, val failed: Int, val ms: Long)
fun parse(meminfo: String): Mem? {
fun field(name: String): Long? =
Regex("""(?m)^${Regex.escape(name)}:\s+(\d+) kB""").find(meminfo)?.groupValues?.get(1)?.toLongOrNull()
val free = field("MemFree") ?: return null
val file = field("Active(file)") ?: return null
val inactive = field("Inactive(file)") ?: return null
return Mem(free, file + inactive)
}
fun shouldTrim(mem: Mem, baselineFileKb: Long): Boolean {
val built = mem.fileKb - baselineFileKb
if (built <= 0) return false
return (mem.freeKb < 2560 * 1024 && built >= 768 * 1024) ||
(mem.freeKb < 1024 * 1024 && built >= 128 * 1024)
}
fun describe(trim: Trim): String {
val after = trim.after
return "trim: free ${trim.before.freeKb / 1024} -> ${after?.freeKb?.div(1024)} MB, " +
"file cache ${trim.before.fileKb / 1024} -> ${after?.fileKb?.div(1024)} MB, " +
"${trim.files} file(s), ${trim.failed} failed, ${trim.ms} ms"
}
internal class Worker(
private val roots: () -> List<File>,
private val alive: () -> Boolean,
private val readMem: () -> Mem?,
private val clock: () -> Long,
private val advise: (String) -> Int,
private val report: (String) -> Unit,
) {
private var baseline: Long? = null
private var files = emptyList<File>()
private var scanned: Long? = null
private var trimmed: Long? = null
fun poll() {
if (!alive()) return
val before = readMem() ?: return
val base = baseline
if (base == null) {
baseline = before.fileKb
return
}
val now = clock()
if (!shouldTrim(before, base) || trimmed?.let { now - it < MIN_TRIM_MS } == true) return
val began = now
if (scanned?.let { now - it >= RESCAN_MS } != false) {
val found = mutableListOf<File>()
for (root in roots()) {
if (!alive()) return
if (Files.isSymbolicLink(root.toPath())) continue
val directory = root.canonicalFile
for (file in directory.walkTopDown().onEnter {
alive() && !Files.isSymbolicLink(it.toPath())
}) {
if (!alive()) return
if (!Files.isSymbolicLink(file.toPath()) && file.isFile && file.length() >= MIN_FILE_BYTES) {
found.add(file)
}
}
}
files = found.distinctBy { it.path }
scanned = clock()
}
var failed = 0
for (file in files) {
if (!alive()) return
if (advise(file.path) != 0) failed++
}
if (!alive()) return
val after = readMem()
if (!alive()) return
baseline = after?.fileKb ?: before.fileKb
val completed = clock()
trimmed = completed
report(describe(Trim(before, after, files.size, failed, completed - began)))
}
}
fun start(roots: () -> List<File>, alive: () -> Boolean, report: (String) -> Unit = {}) {
Thread({
val worker = Worker(
roots, alive,
{ parse(File("/proc/meminfo").readText()) },
{ System.nanoTime() / 1_000_000 },
PageCacheNative::fadviseDontNeed,
{ message -> Log.i(TAG, message); report(message) },
)
var failureLogged = false
while (alive()) {
runCatching { worker.poll() }.onFailure {
if (!failureLogged) Log.w(TAG, "file cache trim failed: $it")
failureLogged = true
}
if (!alive()) break
Thread.sleep(POLL_MS)
}
}, "page-cache-trim").apply { isDaemon = true }.start()
}
}
internal object PageCacheNative {
init {
System.loadLibrary("sdnative")
}
@JvmStatic external fun fadviseDontNeed(path: String): Int
}
@@ -46,7 +46,16 @@ object SecondaryLibrary {
}
fun privateRoot(files: File, library: File): File {
val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray())
val own = privateDir(files, library.canonicalPath)
if (own.exists()) return own
val raw = UsbLink.rawPath(library.absolutePath)
val alias = if (raw != library.absolutePath) raw else UsbLink.storagePath(library.absolutePath)
if (alias == library.absolutePath) return own
return privateDir(files, runCatching { File(alias).canonicalPath }.getOrDefault(alias)).takeIf { it.exists() } ?: own
}
private fun privateDir(files: File, path: String): File {
val digest = MessageDigest.getInstance("SHA-256").digest(path.toByteArray())
.joinToString("") { "%02x".format(it.toInt() and 255) }
return File(files, "steam-libraries/$digest")
}
@@ -430,12 +430,6 @@ class SessionService : Service() {
stopSession(0)
return START_NOT_STICKY
}
val trimGen = gen
PageCacheTrim.start(
roots = { listOfNotNull(File(filesDir, "linuxfs"), GameStorage.effective(applicationContext)?.let { File(it.path) }) },
alive = { SessionState.running && sessionGen == trimGen },
report = { message -> SessionEvents.record("session.page_cache_trim", mapOf("detail" to message)) },
)
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) RivalClients.stopBeforeSession(this)
SessionState.firstFrameSeen = false
SessionState.guestPid = -1
@@ -7,6 +7,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
@@ -130,13 +131,13 @@ object BattleNetClient {
StoresState.post { opener?.invoke(args) }
}
fun library(context: Context, root: File = preferred(context)): List<String> =
AddedGames.guestPath(context, StoreInstallRoot.storeDir(root, Store.BATTLENET))?.let { listOf("--library", it) }.orEmpty()
fun library(context: Context, root: File? = preferred(context)): List<String> =
root?.let { AddedGames.guestPath(context, StoreInstallRoot.storeDir(it, Store.BATTLENET)) }?.let { listOf("--library", it) }.orEmpty()
internal fun preferred(context: Context): File {
internal fun preferred(context: Context): File? {
val second = StoreInstallRoot.libraryRoot(context)?.absolutePath
return StoreInstallRoot.targets(context).firstOrNull { it.root.absolutePath == second && (it.root.isDirectory || it.root.mkdirs()) }?.root
?: StoreInstallRoot.internalRoot(context)
?: StoreInstallRoot.internalRoot(context).takeIf { second == null && !GameStorage.disconnected(context) }
}
fun installGame(context: Context, uid: String, root: File) {
@@ -886,7 +886,8 @@ internal fun RemoveButton(title: String, game: Library.SteamGame?, installed: In
}
val g = game ?: return
val kind = GameRemoval.kind(g)
if (kind == GameRemoval.Kind.LAUNCHER || g.gameFiles?.isDirectory != true) return
val leftover = remember(g) { g.gameFiles == null && GameRemoval.steamFiles(g) != null }
if (kind == GameRemoval.Kind.LAUNCHER || (g.gameFiles?.isDirectory != true && !leftover)) return
var asking by remember(g.gameId) { mutableStateOf(false) }
val shortcut = kind == GameRemoval.Kind.SHORTCUT
val label = stringResource(if (shortcut) R.string.edit_remove else R.string.common_uninstall)
@@ -0,0 +1,69 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
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 = [33])
class GameRemovalTest {
private val app get() = RuntimeEnvironment.getApplication()
private lateinit var apps: File
@Before fun setUp() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setSteamClientArch(app, "arm64")
apps = File(SessionPrefs.steamRoot(app, "arm64"), "steamapps").apply { mkdirs() }
}
private fun manifest(appId: Int, name: String, dir: String) =
File(apps, "appmanifest_$appId.acf").apply {
writeText("\"AppState\"\n{\n\t\"appid\"\t\t\"$appId\"\n\t\"name\"\t\t\"$name\"\n\t\"StateFlags\"\t\t\"4\"\n\t\"installdir\"\t\t\"$dir\"\n}\n")
}
@Test fun aGameWhoseFilesWereDeletedCanStillBeRemoved() {
val acf = manifest(17470, "Example", "Example")
val partial = File(apps, "downloading/17470").apply { mkdirs() }
File(partial, "chunk").writeText("x")
val game = Library.steamGames(app, arch = "arm64").single()
assertNull(game.gameFiles)
val target = requireNotNull(GameRemoval.steamFiles(game))
assertNull(target.dir)
assertEquals(acf, target.manifest)
assertTrue(GameRemoval.delete(target))
assertFalse(acf.exists())
assertFalse(partial.exists())
assertEquals(emptyList<Library.SteamGame>(), Library.steamGames(app, arch = "arm64"))
}
@Test fun anInstalledGameStillRemovesItsFolder() {
val acf = manifest(440, "Installed", "Installed")
val folder = File(apps, "common/Installed").apply { mkdirs() }
File(folder, "game.exe").writeText("x")
val game = Library.steamGames(app, arch = "arm64").single()
assertEquals(folder, game.gameFiles)
val target = requireNotNull(GameRemoval.steamFiles(game))
assertEquals(folder, target.dir)
assertTrue(GameRemoval.delete(target))
assertFalse(folder.exists())
assertFalse(acf.exists())
}
@Test fun aRowWithoutFilesOrManifestOffersNoRemoval() {
assertNull(GameRemoval.steamFiles(Library.SteamGame(17470, "Example", null, "steam")))
val other = manifest(570, "Other", "Other")
assertNull(GameRemoval.steamFiles(Library.SteamGame(17470, "Example", null, "steam", manifest = other)))
assertTrue(other.exists())
}
}
@@ -114,6 +114,19 @@ class GameStorageTest {
assertFalse(GameStorage.disconnected(app))
}
@Test fun aRawCardPathTheProcessCannotUseFallsBackToItsStoragePath() {
val usable = setOf("/storage/A042-9B16/Games")
assertEquals("/storage/A042-9B16/Games", GameStorage.reachable("/mnt/media_rw/A042-9B16/Games") { it.path in usable })
}
@Test fun aUsableRawPathAndOtherPathsAreKept() {
assertEquals("/mnt/media_rw/A042-9B16/Games", GameStorage.reachable("/mnt/media_rw/A042-9B16/Games") { true })
assertEquals("/mnt/media_rw/0000-0000/Games", GameStorage.reachable("/mnt/media_rw/0000-0000/Games") { false })
assertEquals("/storage/A042-9B16/Games", GameStorage.reachable("/storage/A042-9B16/Games") { false })
val folder = tmp.newFolder("library").path
assertEquals(folder, GameStorage.reachable(folder) { false })
}
@Test fun onlyAVfatMountCountsAsFat32() {
val mounts = """
/dev/fuse /storage/emulated fuse rw 0 0
@@ -1,199 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.RandomAccessFile
import java.nio.file.Files
class PageCacheTrimTest {
private val meminfo = "MemFree: 1048576 kB\nActive(file): 2097152 kB\nInactive(file): 1048576 kB\n"
private fun mem(freeMb: Long, fileMb: Long) = PageCacheTrim.Mem(freeMb * 1024, fileMb * 1024)
@Test fun parsesFreeAndFileLru() = assertEquals(PageCacheTrim.Mem(1048576, 3145728), PageCacheTrim.parse(meminfo))
@Test fun rejectsMissingFields() {
assertNull(PageCacheTrim.parse("MemFree: 1 kB\n"))
assertNull(PageCacheTrim.parse("MemFree: 1 kB\nActive(file): 2 kB\n"))
}
@Test fun trimsWhenCacheBuiltUpAndFreeIsLow() = assertTrue(PageCacheTrim.shouldTrim(mem(2000, 2000), 1000 * 1024))
@Test fun skipsSmallBuildUp() = assertFalse(PageCacheTrim.shouldTrim(mem(2000, 1200), 1000 * 1024))
@Test fun skipsWhenPlentyFree() = assertFalse(PageCacheTrim.shouldTrim(mem(6000, 5000), 1000 * 1024))
@Test fun lowFreeAcceptsSmallerBuildUp() = assertTrue(PageCacheTrim.shouldTrim(mem(500, 1200), 1000 * 1024))
@Test fun noNewFileCacheNeedsNoTrim() = assertFalse(PageCacheTrim.shouldTrim(mem(500, 900), 1000 * 1024))
@Test fun describesWhatWasDropped() = assertEquals(
"trim: free 2000 -> 2600 MB, file cache 2000 -> 1400 MB, 4 file(s), 1 failed, 12 ms",
PageCacheTrim.describe(PageCacheTrim.Trim(mem(2000, 2000), mem(2600, 1400), 4, 1, 12)),
)
@get:Rule val temporary = TemporaryFolder()
private class Harness(val root: File) {
var current = PageCacheTrim.Mem(500 * 1024, 1024 * 1024)
var now = 0L
var active = true
var reads = 0
val advised = mutableListOf<String>()
val reports = mutableListOf<String>()
var onAdvice: () -> Unit = {}
val worker = PageCacheTrim.Worker(
{ listOf(root) }, { active }, { reads++; current }, { now },
{ advised.add(it); onAdvice(); 0 }, { reports.add(it) },
)
fun grow() { current = current.copy(fileKb = current.fileKb + 128 * 1024) }
}
private fun large(root: File, name: String): File = File(root, name).also {
RandomAccessFile(it, "rw").use { handle -> handle.setLength(8L shl 20) }
}
@Test fun startupAndInvalidSamplesDoNotDiscardWarmCache() {
val root = temporary.newFolder()
large(root, "data")
val h = Harness(root)
h.worker.poll()
h.worker.poll()
assertTrue(h.advised.isEmpty())
h.grow()
h.worker.poll()
assertEquals(1, h.advised.size)
var sample: PageCacheTrim.Mem? = null
val worker = PageCacheTrim.Worker({ error("unexpected scan") }, { true }, { sample }, { 0L },
{ error("unexpected advice") }, { error("unexpected report") })
worker.poll()
sample = mem(500, 4096)
worker.poll()
worker.poll()
}
@Test fun cancellationStopsAdviceAndReportingAndRestartGetsFreshBaseline() {
val root = temporary.newFolder()
large(root, "a")
large(root, "b")
val h = Harness(root)
h.worker.poll()
h.grow()
h.onAdvice = { h.active = false }
h.worker.poll()
assertEquals(1, h.advised.size)
assertTrue(h.reports.isEmpty())
val replacement = Harness(root)
replacement.current = h.current
replacement.worker.poll()
assertTrue(replacement.advised.isEmpty())
h.worker.poll()
assertEquals(1, h.advised.size)
}
@Test fun cancellationDuringRootSelectionStopsTraversal() {
val root = temporary.newFolder()
large(root, "a")
var active = true
var sample = mem(500, 1024)
val worker = PageCacheTrim.Worker({ active = false; listOf(root) }, { active },
{ sample }, { 0L }, { error("cancelled advice") }, { error("cancelled report") })
worker.poll()
sample = mem(500, 2048)
worker.poll()
}
@Test fun cooldownStartsAtCompletionAndRescansAreBounded() {
val root = temporary.newFolder()
large(root, "a")
val h = Harness(root)
h.worker.poll()
h.grow()
h.onAdvice = { h.now += 40_000 }
h.worker.poll()
large(root, "b")
h.grow()
h.now += 29_999
h.worker.poll()
assertEquals(1, h.advised.size)
h.now++
h.onAdvice = {}
h.worker.poll()
assertEquals(2, h.advised.size)
h.now = 120_000
h.grow()
h.worker.poll()
assertEquals(4, h.advised.size)
}
@Test fun excludesSmallFilesAndLinksAndOtherStorage() {
val root = temporary.newFolder()
val outside = temporary.newFolder()
val allowed = large(root, "payload")
val other = large(outside, "payload")
File(root, "small").writeText("small")
Files.createSymbolicLink(File(root, "link").toPath(), other.toPath())
Files.createSymbolicLink(File(root, "directory").toPath(), outside.toPath())
val h = Harness(root)
h.worker.poll()
h.grow()
h.worker.poll()
assertEquals(listOf(allowed.canonicalPath), h.advised)
assertTrue(other.exists())
assertEquals("small", File(root, "small").readText())
}
@Test fun highFreeMemoryDoesNotTouchAnyProgramFiles() {
val root = temporary.newFolder()
large(root, "program-one")
large(root, "program-two")
val h = Harness(root)
h.current = mem(6000, 1024)
h.worker.poll()
h.current = mem(6000, 8192)
h.worker.poll()
assertTrue(h.advised.isEmpty())
assertTrue(h.reports.isEmpty())
}
@Test fun emptyScansAreThrottledAndEventuallyDiscoverNewFiles() {
val root = temporary.newFolder()
val h = Harness(root)
h.worker.poll()
h.grow()
h.worker.poll()
assertEquals(1, h.reports.size)
large(root, "new")
h.now = 30_000
h.grow()
h.worker.poll()
assertTrue(h.advised.isEmpty())
h.now = 120_000
h.grow()
h.worker.poll()
assertEquals(1, h.advised.size)
}
@Test fun cancellationDuringFinalSampleSuppressesReporting() {
val root = temporary.newFolder()
large(root, "a")
var active = true
var reads = 0
var advised = 0
val worker = PageCacheTrim.Worker({ listOf(root) }, { active }, {
reads++
if (reads == 3) active = false
mem(500, if (reads == 1) 1024 else 2048)
}, { 0L }, { advised++; 0 }, { error("cancelled report") })
worker.poll()
worker.poll()
assertEquals(1, advised)
assertFalse(active)
}
}
@@ -21,6 +21,24 @@ class SecondaryLibraryTest {
assertFalse(SecondaryLibrary.privateRoot(files, content).exists())
}
@Test fun aCardReachedThroughItsOtherPathKeepsItsPrivateDirectories() {
val files = tmp.newFolder("files")
val raw = SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/A042-9B16/Games")).apply { mkdirs() }
assertEquals(raw, SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")))
val storage = SecondaryLibrary.privateRoot(files, File("/storage/B2BD-BCFC/Games")).apply { mkdirs() }
assertEquals(storage, SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/B2BD-BCFC/Games")))
}
@Test fun aLibraryWithItsOwnPrivateDirectoriesKeepsThem() {
val files = tmp.newFolder("files")
val own = SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")).apply { mkdirs() }
val raw = File(own.parentFile, SecondaryLibrary.privateRoot(tmp.newFolder("other"), File("/mnt/media_rw/A042-9B16/Games")).name)
raw.mkdirs()
assertEquals(own, SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")))
assertEquals(raw, SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/A042-9B16/Games")))
assertFalse(SecondaryLibrary.privateRoot(files, File("/storage/emulated/0/Games")).exists())
}
@Test fun aWritableAliasIsSelectedAndItsProbeIsRemoved() {
val library = tmp.newFolder("shared")
val candidate = File(tmp.root, "direct")
@@ -0,0 +1,34 @@
package com.droiddeck.launcher.stores.battlenet
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class BattleNetLibraryTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@Test fun aMissingLibraryLeavesBattleNetsInstallFolderAlone() {
SessionPrefs.setGameStorage(app, "/storage/0000-0000/Games", "SD card")
assertTrue(BattleNetClient.library(app).isEmpty())
}
@Test fun anAttachedLibraryIsHandedToBattleNet() {
SessionPrefs.setGameStorage(app, tmp.newFolder("card").path, "SD card")
assertEquals("--library", BattleNetClient.library(app).firstOrNull())
}
@Test fun internalStorageIsHandedToBattleNetWhenItIsTheChoice() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
assertEquals("--library", BattleNetClient.library(app).firstOrNull())
}
}
-21
View File
@@ -85,27 +85,6 @@ session log says so once a minute.
With no shortage nothing is compressed. A game that fits in memory is never touched, and Steam
is no longer compressed on a timer.
## File page cache
The session worker samples `MemFree` and `Active(file)` plus `Inactive(file)` every three
seconds. Its first valid sample establishes the growth baseline without discarding startup cache.
When `MemFree` is under 2.5 GiB with 768 MiB of file-LRU growth, or under 1 GiB with 128 MiB of
growth, it requests `posix_fadvise(DONTNEED)` on regular files of at least 8 MiB under the Linux
root and selected game storage. This mechanism originated in Kurt Himebauch's PR #3439; #3465
hardens the same worker and native bridge rather than introducing another reclaim path.
Scans are at least two minutes apart, including empty scans. Passes are at least 30 seconds
apart measured from completion, using a monotonic clock. Traversal and advice stop when session
ownership is lost. Native opens reject symbolic links in every component, use nonblocking mode,
and validate the opened descriptor's file type and size. Each completed pass is logged to the
session log and `events.jsonl`.
Advice is a best-effort request, not evidence that memory was freed or that a low-memory kill
was prevented. It can cause later disk reads. File cache is shared by inode, so another reader of
the same eligible file may also need to reread it. Files outside the selected roots, mapped pages,
anonymous memory, GPU allocations and explicit user settings are not targeted. Reporter testing
is still required to establish whether this prevents the base Thor's idle-session termination.
## Reading the client back
Once the client has been compressed, it is read back in one request when the game has exited,
@@ -350,6 +350,17 @@ def keeps_open(root):
return isinstance(client, dict) and LAUNCH_BEHAVIOR[0] in client and client[LAUNCH_BEHAVIOR[0]] != LAUNCH_BEHAVIOR[1]
def chosen_folder(root, current, library):
current = current.strip()
folder = windows_path(root, current) if current else None
if not folder or rootfs_drive(root, current) or not os.path.isdir(folder):
return False
try:
return volume_root(os.path.realpath(folder)) == volume_root(os.path.realpath(library))
except OSError:
return False
def write_config(root, library=None):
path = os.path.join(drive_c(root), *CONFIG)
key, value = LAUNCH_BEHAVIOR
@@ -374,6 +385,7 @@ def write_config(root, library=None):
client["HardwareAcceleration"] = "false"
changes.append("acceleration")
if library and isinstance(client.setdefault("Install", {}), dict) \
and not chosen_folder(root, str(client["Install"].get("DefaultInstallPath", "")), library) \
and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(root, library).rstrip("\\"):
client["Install"]["DefaultInstallPath"] = install_path(root, library)
changes.append("library")
+59 -60
View File
@@ -6,6 +6,7 @@
#include <dlfcn.h>
#include <errno.h>
#include <limits.h>
#include <link.h>
#include <linux/input.h>
#include <pthread.h>
#include <stdatomic.h>
@@ -15,6 +16,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <unistd.h>
@@ -34,7 +36,8 @@
"NAME=\"Xbox 360 Controller (%d)\"\n" \
"PHYS=\"usb-fakeinput/input%d\"\n"
#define RING_SDL_ID 0x045e028eu
#define STEAM_VIRTUAL_VENDOR 0x28de
#define STEAM_VIRTUAL_PRODUCT 0x11ff
#define PARENT_NAME "droiddeck-input"
#define PARENT_SYSPATH_FORMAT "/sys/devices/droiddeck%d/" PARENT_NAME "%d"
@@ -141,66 +144,8 @@ 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;
return uinput_enabled() && any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT;
}
static void refresh_locked(int node) {
@@ -514,6 +459,60 @@ static int caller_in_library(void *caller, const char *library) {
static int caller_is_winebus(void *caller) { return caller_in_library(caller, "winebus.so"); }
static int note_winebus(struct dl_phdr_info *info, size_t size, void *data) {
(void)size;
if (info->dlpi_name == NULL || strstr(info->dlpi_name, "winebus.so") == NULL) return 0;
*(int *)data = 1;
return 1;
}
static int winebus_reads_udev(void) {
const char *x360 = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
int loaded = 0;
if (x360 != NULL && atoi(x360) != 0) return 0;
dl_iterate_phdr(note_winebus, &loaded);
return loaded;
}
static int ring_pad_fd(int fd) {
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
const char *entry;
struct stat opened;
struct stat ring;
char path[PATH_MAX];
if (spec == NULL || fstat(fd, &opened) != 0) return 0;
for (entry = spec; *entry != '\0';) {
char *end;
long slot = strtol(entry, &end, 10);
const char *next = strchr(entry, ';');
size_t length;
if (end != entry && *end == '=' && slot >= 0 && slot < RING_MAX) {
length = next != NULL ? (size_t)(next - end - 1) : strlen(end + 1);
if (length < sizeof(path)) {
memcpy(path, end + 1, length);
path[length] = '\0';
if (stat(path, &ring) == 0 && ring.st_dev == opened.st_dev && ring.st_ino == opened.st_ino) return 1;
}
}
if (next == NULL) break;
entry = next + 1;
}
return 0;
}
__attribute__((visibility("hidden"))) void dd_ring_pad_sdl_id(int fd, unsigned long request, void *arg,
void *caller, int rc) {
struct input_id *id = arg;
if (rc != 0 || request != EVIOCGID || id == NULL) return;
if (!caller_in_library(caller, "libSDL") || !winebus_reads_udev() || !ring_pad_fd(fd)) return;
id->vendor = STEAM_VIRTUAL_VENDOR;
id->product = STEAM_VIRTUAL_PRODUCT;
}
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;
+3
View File
@@ -424,6 +424,8 @@ int dd_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute
int dd_vdec_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int dd_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
void dd_ring_pad_sdl_id(int fd, unsigned long request, void *arg, void *caller, int rc)
__attribute__((visibility("hidden")));
int dd_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg,
int *rc) __attribute__((visibility("hidden")));
@@ -444,6 +446,7 @@ int ioctl(int fd, unsigned long request, ...) {
if (dd_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
if (dd_writewatch_ioctl(real, fd, request, arg, &rc)) return rc;
if (!dd_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
dd_ring_pad_sdl_id(fd, request, arg, __builtin_return_address(0), rc);
dd_kgsl_track(real, fd, request, arg, &rc);
dd_kgsl_chip_id_fixup(request, arg, rc);
if (arg == NULL || !is_link_query(request)) return rc;
+4 -5
View File
@@ -739,10 +739,8 @@ char *getcwd(char *buf, size_t size) {
static char *(*orig_getcwd)(char *, size_t) = NULL;
if (!orig_getcwd) orig_getcwd = (char *(*)(char *, size_t))dlsym(RTLD_NEXT, "getcwd");
char *res = orig_getcwd ? orig_getcwd(buf, size) : NULL;
if (res) {
size_t len = strlen(res);
guest_path_of_mount_source(res, len, buf ? size : len + 1, NULL);
}
if (res && !buf) return guest_path_of_allocated_mount_source(res);
if (res) guest_path_of_mount_source(res, strlen(res), size, NULL);
return res;
}
@@ -790,7 +788,8 @@ char *realpath(const char *path, char *resolved_path) {
}
}
}
if (res) guest_path_of_mount_source(res, strlen(res), resolved_path ? PATH_MAX : strlen(res) + 1, NULL);
if (res && !resolved_path) return guest_path_of_allocated_mount_source(res);
if (res) guest_path_of_mount_source(res, strlen(res), PATH_MAX, NULL);
return res;
}
+14
View File
@@ -975,6 +975,20 @@ static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int
return best->dst_len + rest;
}
static char *guest_path_of_allocated_mount_source(char *res) {
size_t len = strlen(res);
char tmp[PATH_MAX];
if (len >= sizeof(tmp)) return res;
memcpy(tmp, res, len + 1);
int converted = 0;
size_t n = guest_path_of_mount_source(tmp, len, sizeof(tmp), &converted);
if (!converted) return res;
char *grown = realloc(res, n + 1);
if (!grown) return res;
memcpy(grown, tmp, n + 1);
return grown;
}
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
if (ret <= 0) return ret;
if ((size_t)ret < bufsiz) {
+31
View File
@@ -295,6 +295,37 @@ class DriveTest(Temp):
self.assertEqual(BNET["install_path"](self.root, str(self.card)), "D:\\")
self.assertEqual(sorted(os.listdir(self.devices)), ["d:"])
def test_a_folder_chosen_in_battlenet_on_the_library_drive_is_kept(self):
path = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"])
BNET["write_config"](self.root)
self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library")
(self.card / "Battle.net").mkdir()
config = json.loads(path.read_text())
config["Client"]["Install"]["DefaultInstallPath"] = "D:\\Battle.net"
path.write_text(json.dumps(config))
self.assertIsNone(BNET["write_config"](self.root, str(self.library)))
self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Battle.net")
def test_a_chosen_folder_inside_the_native_rootfs_is_not_kept_whatever_its_spacing(self):
BNET["write_config"](self.root, str(self.library))
rootfs = self.card / "files/linuxfs"
(rootfs / "Games").mkdir(parents=True)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
for current in ("D:\\files\\linuxfs\\Games", " D:\\files\\linuxfs\\Games"):
self.assertFalse(BNET["chosen_folder"](self.root, current, str(self.library)))
def test_a_folder_on_another_drive_or_missing_moves_to_the_library(self):
path = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"])
BNET["write_config"](self.root, str(self.library))
internal = self.tmp / "root/Games/Stores/Battle.net"
internal.mkdir(parents=True)
for current in ("Z:" + str(internal), "D:\\Gone"):
config = json.loads(path.read_text())
config["Client"]["Install"]["DefaultInstallPath"] = current
path.write_text(json.dumps(config))
self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library")
self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Games\\Battle.net")
def test_drives_in_use_and_the_ones_proton_owns_are_left_alone(self):
self.devices.mkdir(parents=True)
os.symlink("/somewhere/else", self.devices / "d:")
+7 -28
View File
@@ -707,36 +707,15 @@ class InputUdevPreloadTest(unittest.TestCase):
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):
def test_a_ring_pad_keeps_the_steam_input_identity_whatever_sdl_is_told(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"},
for extra in ({}, {"FAKE_EVDEV_UINPUT": "1"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "0"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "1"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142,0x045E/0x028E"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "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"}):
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": ""},
{"FAKE_EVDEV_UINPUT": "1", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"}):
with self.subTest(**extra):
self.assertEqual(self.identity(**extra), steam)
+25
View File
@@ -88,6 +88,18 @@ int main(int argc, char **argv) {
printf("%s\t%s\n", argv[i], ok ? cwd : "-");
continue;
}
if (strncmp(argv[i], "cdnull:", 7) == 0) {
char *got = chdir(argv[i] + 7) == 0 ? getcwd(NULL, 0) : NULL;
printf("%s\t%s\n", argv[i], got ? got : "-");
free(got);
continue;
}
if (strncmp(argv[i], "realnull:", 9) == 0) {
char *got = realpath(argv[i] + 9, NULL);
printf("%s\t%s\n", argv[i], got ? got : "-");
free(got);
continue;
}
if (strncmp(argv[i], "lstat:", 6) == 0) {
int ok = lstat(argv[i] + 6, &st) == 0;
printf("%s\t%d\t%d\n", argv[i], ok, ok && S_ISLNK(st.st_mode));
@@ -324,6 +336,19 @@ class NativeHookMountTest(unittest.TestCase):
arg = f"cd:/pfx/native/dosdevices/z:{GAME}/"
self.assertEqual(self.run_probe(arg)[arg], [GAME])
def test_allocated_working_directory_and_real_path_name_a_longer_guest_mount(self):
guest = "/root/Games/" + "g" * len(str(self.library))
binds = f"{self.library}:{guest}"
args = [f"cd:{guest}/Some Game", f"cdnull:{guest}/Some Game", f"realnull:{guest}/Some Game/game.txt"]
result = self.run_probe(*args, binds=binds)
self.assertEqual(result[args[0]], [f"{guest}/Some Game"])
self.assertEqual(result[args[1]], [f"{guest}/Some Game"])
self.assertEqual(result[args[2]], [f"{guest}/Some Game/game.txt"])
def test_allocated_working_directory_names_a_shorter_guest_mount(self):
arg = f"cdnull:{GAME}"
self.assertEqual(self.run_probe(arg)[arg], [GAME])
def test_rootfs_path_under_a_mount_point_reaches_the_mount(self):
path = f"{self.root}{GAME}/game.txt"
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
-85
View File
@@ -1,85 +0,0 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
class PageCacheNativeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp = tempfile.TemporaryDirectory()
cls.root = Path(cls.temp.name)
javac = shutil.which("javac")
if not javac:
raise unittest.SkipTest("javac headers unavailable")
include = Path(javac).resolve().parents[1] / "include"
source = Path("app/src/main/cpp/sdnative/sdnative.c").resolve()
harness = cls.root / "harness.c"
harness.write_text(
'#include <stdio.h>\n'
f'#include "{source}"\n'
'static const char *get(JNIEnv *e, jstring s, jboolean *b) {\n'
' (void)e; (void)b; return (const char *)s;\n}\n'
'static void release(JNIEnv *e, jstring s, const char *c) {\n'
' (void)e; (void)s; (void)c;\n}\n'
'int main(int argc, char **argv) {\n'
' if (argc != 2) return 2;\n'
' struct JNINativeInterface_ table = {0};\n'
' table.GetStringUTFChars = get;\n'
' table.ReleaseStringUTFChars = release;\n'
' JNIEnv env = &table;\n'
' printf("%d", Java_com_droiddeck_launcher_session_PageCacheNative_fadviseDontNeed(\n'
' &env, NULL, (jstring)argv[1]));\n'
' return 0;\n}\n'
)
cls.binary = cls.root / "native-check"
subprocess.run([
"cc", "-D_GNU_SOURCE", "-std=c11", "-Wall", "-Wextra", "-Werror",
f"-I{include}", f"-I{include / 'linux'}", str(harness), "-o", str(cls.binary),
], check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
cls.temp.cleanup()
def advise(self, path):
return int(subprocess.check_output([str(self.binary), str(path)], timeout=3))
def test_regular_file_preserves_contents(self):
path = self.root / "large"
with path.open("wb") as handle:
handle.write(b"payload")
handle.truncate(8 << 20)
self.assertEqual(0, self.advise(path))
with path.open("rb") as handle:
self.assertEqual(b"payload", handle.read(7))
self.assertEqual(8 << 20, path.stat().st_size)
def test_replacement_fifo_does_not_block(self):
path = self.root / "fifo"
os.mkfifo(path)
self.assertNotEqual(0, self.advise(path))
def test_rejects_small_file_directory_missing_and_relative_path(self):
path = self.root / "small"
path.write_text("small")
for candidate in [path, self.root, self.root / "missing", "relative"]:
with self.subTest(candidate=candidate):
self.assertNotEqual(0, self.advise(candidate))
self.assertEqual("small", path.read_text())
def test_rejects_final_and_parent_symlink_replacements(self):
outside = self.root / "outside"
outside.mkdir()
payload = outside / "payload"
with payload.open("wb") as handle:
handle.truncate(8 << 20)
final = self.root / "final"
final.symlink_to(payload)
parent = self.root / "parent"
parent.symlink_to(outside, target_is_directory=True)
self.assertNotEqual(0, self.advise(final))
self.assertNotEqual(0, self.advise(parent / "payload"))
self.assertNotEqual(0, self.advise(str(outside) + "/../outside/payload"))
+125
View File
@@ -0,0 +1,125 @@
from pathlib import Path
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
SHIM = r"""
#include <linux/input.h>
#include <stdarg.h>
#include <string.h>
int ioctl(int fd, unsigned long request, ...) {
va_list ap;
va_start(ap, request);
struct input_id *id = va_arg(ap, struct input_id *);
va_end(ap);
(void)fd;
if (request != EVIOCGID) return -1;
memset(id, 0, sizeof(*id));
id->bustype = 3;
id->vendor = 0x045e;
id->product = 0x028e;
return 0;
}
"""
QUERY = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
void query(const char *path) {
struct input_id id;
int fd = open(path, O_RDONLY | O_CLOEXEC);
int rc = ioctl(fd, EVIOCGID, &id);
printf("%d %04x:%04x\n", rc, id.vendor, id.product);
close(fd);
}
"""
PROGRAM = r"""
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>
void query(const char *path);
int main(int argc, char **argv) {
(void)argc;
if (strcmp(argv[1], "-") != 0) dlopen(argv[1], RTLD_NOW);
if (strcmp(argv[2], "program") == 0) {
query(argv[3]);
} else {
void *sdl = dlopen(argv[2], RTLD_NOW | RTLD_LOCAL);
void (*sdl_query)(const char *) = (void (*)(const char *))dlsym(sdl, "query");
sdl_query(argv[3]);
}
fflush(stdout);
return 0;
}
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("cc"), "needs Linux and cc")
class RingPadSdlIdentityTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
for name, text in (("shim.c", SHIM), ("query.c", QUERY), ("program.c", PROGRAM), ("empty.c", "int bus;\n")):
(build / name).write_text(text)
cls.lib = cls.dir / "libddsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
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 / "empty.c")], 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 / "query.c")], check=True)
cls.program = cls.dir / "program"
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "query.c"), "-ldl"],
check=True)
cls.ring = cls.dir / "ring0"
cls.ring.write_text("")
cls.virtual = cls.dir / "ring16"
cls.virtual.write_text("")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def query(self, winebus=True, caller="sdl", path=None, **extra):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.lib, self.shim),
FAKE_EVDEV_MEMFD_PATHS="0=%s;16=%s" % (self.ring, self.virtual))
env.pop("FAKE_EVDEV_STEAM_PAD_AS_X360", None)
env.update(extra)
result = subprocess.run([str(self.program), str(self.winebus) if winebus else "-",
str(self.sdl_library) if caller == "sdl" else "program", str(path or self.ring)],
env=env, capture_output=True, text=True, timeout=10, check=True)
return result.stdout.strip()
def test_sdl_in_a_winebus_process_sees_a_ring_pad_as_the_steam_input_pad(self):
self.assertEqual(self.query(), "0 28de:11ff")
def test_sdl_outside_winebus_keeps_the_pad_identity(self):
self.assertEqual(self.query(winebus=False), "0 045e:028e")
def test_other_callers_and_devices_keep_their_identity(self):
self.assertEqual(self.query(caller="program"), "0 045e:028e")
self.assertEqual(self.query(path=self.virtual), "0 045e:028e")
def test_a_winebus_without_a_udev_bus_keeps_the_pad_for_sdl(self):
self.assertEqual(self.query(FAKE_EVDEV_STEAM_PAD_AS_X360="1"), "0 045e:028e")
if __name__ == "__main__":
unittest.main()