From 10d3b801fabc0d605f1e6cb0f9bad01f61887b3b Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:57:43 +0800 Subject: [PATCH] Run original Xbox games from the Xbox store (#3638) Original Xbox games sold for PC through the Xbox store (Xbox360BackwardCompatibil.* packages: Fuzion Frenzy, BLiNX, Conker, Crimson Skies, Grabbed by the Ghoulies, Morrowind, Red Faction II, ...) now start and play on DroidDeck-Bionic. - droiddeck-xbox: keep the GameInput redistributable, remove its service class; run install actions with FEX's safe settings; find MicrosoftGame.config in any case and skip one that does not parse. - droiddeck-game-env: fix rule for these games turns on the emulator fixes in the Wine, FEX and VKD3D-Proton builds made for them. - Components: each installed game gets the Xbox FEX, VKD3D-Proton and DXVK builds, never over a player's choice (also not one made during the download). - Xbox store: these games show the size of their console package. - DroidDeck-Bionic launch.sh keeps the Wine and VKD3D-Proton switches; bionic pack uses the v18 layer with the fixes (released as DroidDeck-Bionic 14.1 r104). - Xbox backend: purchases that name a legacy marketplace offer reach the library. --- .../launcher/session/ComponentsManager.kt | 29 ++++++- .../launcher/session/SessionPrefs.kt | 3 + .../launcher/session/SessionService.kt | 3 + .../session/XboxBackCompatComponents.kt | 78 +++++++++++++++++++ .../launcher/stores/xbox/XboxCatalog.kt | 13 +++- .../launcher/stores/xbox/XboxManifest.kt | 4 + .../session/ComponentsBionicFexTest.kt | 10 +++ .../session/XboxBackCompatAssignTest.kt | 71 +++++++++++++++++ .../session/XboxBackCompatComponentsTest.kt | 33 ++++++++ .../launcher/stores/xbox/XboxCatalogTest.kt | 16 ++++ tools/bionic-runtime/build.sh | 8 +- tools/bionic-runtime/tool/launch.sh | 3 + .../overlay/usr/local/bin/droiddeck-game-env | 58 +++++++++++++- .../overlay/usr/local/bin/droiddeck-xbox | 71 ++++++++++++++++- tools/tests/test_bionic_paths.py | 13 ++++ tools/tests/test_game_environment.py | 42 ++++++++++ tools/tests/test_xbox_launch.py | 66 ++++++++++++++++ tools/xbox/README.md | 6 ++ .../xbox/droiddeck-legacy-offer-parent.patch | 45 +++++++++++ tools/xbox/prepare.py | 2 +- 20 files changed, 564 insertions(+), 10 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt create mode 100644 tools/xbox/droiddeck-legacy-offer-parent.patch diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt index 146509bba7..b9be461b01 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt @@ -30,6 +30,8 @@ object ComponentsManager { private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components" internal const val DD_NIGHTLY = "linux-nightly" internal const val DD_BIONIC = "bionic-stable" + /** FEX for original Xbox games on DroidDeck-Bionic: kept apart from [DD_BIONIC] so automatic FEX updates never pick it. */ + internal const val DD_XBOX = "bionic-xbox" private val RELEASES = linkedMapOf( "FexCore-Linux" to "fex", "Dxvk-Linux" to "dxvk", @@ -38,7 +40,8 @@ object ComponentsManager { "Vkd3d-proton-Linux" to "vkd3d", ) private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex") - private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC) + private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC) + + (DD_COMPONENTS to DD_XBOX) private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS) private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d") private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux") @@ -253,6 +256,28 @@ object ComponentsManager { saveState(context, state) } + internal enum class Assigned { SET, NOT_LISTED, CHANGED } + + /** + * Sets a game's component to a listed package, fetching it first when it is not stored. [expected] is the component + * the caller read when it decided: if the game's component is something else once the package is ready (the player + * chose one during the download), nothing is written. [onSet] runs under the same lock as the write. + */ + internal fun assignGameComponent(context: Context, scope: String, comp: String, file: String, release: String, + expected: String?, onSet: () -> Unit = {}): Assigned { + val wcp = File(packagesDir(context), safeName(file)) + if (!wcp.isFile || runCatching { packageInfo(context, wcp) }.isFailure) { + wcp.delete() + download(context, catalogItem(context, file, release) ?: return Assigned.NOT_LISTED) {} + } + synchronized(lock) { + if (gameComponents(context, scope)[comp] != expected) return Assigned.CHANGED + setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) } + onSet() + } + return Assigned.SET + } + fun clearGameComponents(context: Context, scope: String) = synchronized(lock) { require(GameEnvironment.validScope(scope)) val state = loadState(context) @@ -1124,7 +1149,7 @@ object ComponentsManager { internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) { DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value - DD_BIONIC -> "fex" + DD_BIONIC, DD_XBOX -> "fex" else -> null } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 38fca4ec19..a050da5789 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1778,6 +1778,9 @@ object SessionPrefs { name.removeSuffix(from) + to to moved } + fun storedAddedGameAppId(context: Context, folderPath: String): Long? = + prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L } + fun addedGameAppId(context: Context, folderPath: String, first: Long): Long = synchronized(addedGameLock) { val p = prefs(context) p.getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 16b9fd84e7..88a92efe1b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -617,6 +617,9 @@ class SessionService : Service() { val size = SessionState.outputSize val guest = ArrayList() val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP + runCatching { SessionEvents.step("components-xbox") { XboxBackCompatComponents.ensure(this) } } + .onSuccess { if (it != null) Log.i(TAG, it) } + .onFailure { Log.w(TAG, "original Xbox components", it) } runCatching { SessionEvents.step("components-republish") { ComponentsManager.republish(this) } } .onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") } .onFailure { Log.w(TAG, "component selections", it) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt b/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt new file mode 100644 index 0000000000..e547cd8963 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.gpu.GpuInfo +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreGameSidecar +import com.droiddeck.launcher.stores.StoreInstallRoot +import com.droiddeck.launcher.stores.xbox.XboxManifest + +/** + * Microsoft's original Xbox releases for PC run its emulator, which needs FEX and VKD3D-Proton builds with fixes of + * their own (each off unless droiddeck-game-env turns it on for these games) and a newer DXVK than some Protons carry. + * Each installed one gets them as its game components. A component the player chose for the game is never replaced; + * one set here follows this list, so a newer build replaces it, and one the player cleared stays cleared. + */ +internal object XboxBackCompatComponents { + private const val TAG = "XboxBackCompat" + private const val PREFS = "xbox-backcompat-components" + + internal data class Wanted(val comp: String, val file: String, val release: String) + + internal fun wanted(family: GpuInfo.Family?): List = listOf( + Wanted("fex", "FEXCore-2611.1-xbox-bionic.wcp", ComponentsManager.DD_XBOX), + Wanted("vkd3d", "vkd3d-proton-arm64ec-3.1-xbox-linux.wcp", "Vkd3d-proton-Linux"), + Wanted("dxvk", if (family == GpuInfo.Family.A6XX) "dxvk-gplasync-3.2-a6xx-1-linux.wcp" else "dxvk-gplasync-3.2-1-linux.wcp", + "Dxvk-gplasync-Linux"), + ) + + /** The file to set for one component of a game, or null to leave it as it is. */ + internal fun decide(current: String?, assigned: String?, wanted: String): String? = when { + current == null && assigned == null -> wanted + current != null && current == assigned && current != wanted -> wanted + else -> null + } + + internal class Game(val scope: String, val title: String) + + internal fun installed(context: Context): List = StoreInstallRoot.gameFolders(context).mapNotNull { folder -> + val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.store == Store.XBOX && it.isInstalled } ?: return@mapNotNull null + if (!XboxManifest.backCompat(folder)) return@mapNotNull null + val appId = SessionPrefs.storedAddedGameAppId(context, folder.path) ?: return@mapNotNull null + Game(appId.toString(), sidecar.title) + } + + fun ensure(context: Context): String? { + val games = installed(context) + if (games.isEmpty()) return null + val marks = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val wanted = wanted(runCatching { GpuInfo.detect().family }.getOrNull()) + val lines = mutableListOf() + for (game in games) { + val current = ComponentsManager.gameComponents(context, game.scope) + for (w in wanted) { + val key = "${game.scope}/${w.comp}" + val file = decide(current[w.comp], marks.getString(key, null), w.file) ?: continue + val label = ComponentsManager.LABEL[w.comp] + runCatching { + ComponentsManager.assignGameComponent(context, game.scope, w.comp, file, w.release, expected = current[w.comp]) { + marks.edit().putString(key, file).apply() + } + } + .onSuccess { result -> + lines += when (result) { + ComponentsManager.Assigned.SET -> "${game.title}: $label ${file.removeSuffix(".wcp")}" + ComponentsManager.Assigned.NOT_LISTED -> "${game.title}: $file is not listed; $label unchanged" + ComponentsManager.Assigned.CHANGED -> "${game.title}: $label was chosen during the download; kept" + } + } + .onFailure { e -> + Log.w(TAG, "${game.title}: $file", e) + lines += "${game.title}: $label unchanged (${e.message ?: e.javaClass.simpleName})" + } + } + } + return lines.joinToString("; ").ifEmpty { null } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt index 7afcaeb321..405b0b955d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt @@ -8,6 +8,9 @@ import org.json.JSONObject import java.time.Instant internal object XboxCatalog { + /** Package identity prefix of Microsoft's original Xbox releases for PC. */ + internal const val BACK_COMPAT_IDENTITY = "Xbox360BackwardCompatibil" + private val productId = Regex("[A-Z0-9]{12}") private val plans = setOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD") private val pcPlans = mapOf( @@ -148,6 +151,13 @@ internal object XboxCatalog { .flatMap { objects(it.optJSONArray("Packages")) } val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } } val installable = pc.any { installableFormat(it.optString("PackageFormat")) } + // An original Xbox game: its PC package is only Microsoft's emulator and an + // index; the game data comes from the console package, so that is its size. + val backCompat = pc.any { it.optString("PackageFamilyName").startsWith(BACK_COMPAT_IDENTITY, ignoreCase = true) } + val console = packages.filter { pkg -> + pkg.optString("PackageFormat").equals("XVC", true) || + objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Xbox" } + } // The installer needs the format, not just the fact that one exists: a // legacy container takes a different subcommand from a streamed package. val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty() @@ -172,7 +182,8 @@ internal object XboxCatalog { storeUrl = "https://www.xbox.com/games/store/$id", publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"), description = localized.optString("ProductDescription"), - sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L, + sizeBytes = if (!installable) 0L else (if (backCompat) console.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } else null) + ?.takeIf { it > 0 } ?: pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L, extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), "cloud" to flag(streams), "format" to format), ) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt index 1f6cb7851d..1c88e48655 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt @@ -80,6 +80,10 @@ internal object XboxManifest { dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty()) } + /** Microsoft's original Xbox releases for PC, which run its emulator. */ + fun backCompat(folder: File): Boolean = + runCatching { read(folder).name.startsWith(XboxCatalog.BACK_COMPAT_IDENTITY, ignoreCase = true) }.getOrDefault(false) + /** * A full trust package starts its executable directly. Anything else is activated * through the Windows app model, which this runtime has no host for, so starting diff --git a/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt index 99bd6ef90e..d0e3c22361 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt @@ -77,6 +77,16 @@ class ComponentsBionicFexTest { assertEquals("fex", ComponentsManager.assetComp("FexCore-Linux", "FEXCore-2611.1-linux.wcp")) } + @Test fun originalXboxFexIsListedButNeverAnAutomaticUpdate() { + assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_XBOX, "FEXCore-2611.1-xbox-bionic.wcp")) + fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "fex", release, "", 1L, "sha256:00") + val items = listOf(item("FEXCore-2611.1-bionic.wcp", ComponentsManager.DD_BIONIC), + item("FEXCore-2611.1-xbox-bionic.wcp", ComponentsManager.DD_XBOX), item("FEXCore-2611.1-PPA-bionic.wcp", ComponentsManager.DD_BIONIC)) + val line = ComponentUpdates.fexLine(proton(bionicTool)) + assertEquals("FEXCore-2611.1-bionic.wcp", ComponentUpdates.pick(items, line, emptySet())?.file) + assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-xbox-bionic.wcp")) + } + @Test fun aGameFexChoiceKeepsItsTwinInUseWhileTheOtherFlavorIsInstalled() { val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp"))) assertEquals(setOf("FEXCore-2611.1-linux.wcp"), ComponentsManager.packagesInUse(state, listOf(proton(ownTool)))) diff --git a/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt new file mode 100644 index 0000000000..cc6b4c2d07 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt @@ -0,0 +1,71 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.github.luben.zstd.ZstdOutputStream +import org.apache.commons.compress.archivers.tar.TarArchiveEntry +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +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 +import java.io.BufferedOutputStream +import java.io.File +import java.io.FileOutputStream + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class XboxBackCompatAssignTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + File(context.filesDir, "components").deleteRecursively() + LinuxRuntime.rootDir(context).deleteRecursively() + ComponentsManager.importPackage(context, wcp("a.src", "A"), "dxvk-a.wcp") + ComponentsManager.importPackage(context, wcp("b.src", "B"), "dxvk-b.wcp") + } + + @Test fun aChoiceMadeDuringTheDownloadIsKept() { + ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk-b.wcp") + var marked = false + val result = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-a.wcp", "unused", expected = null) { marked = true } + assertEquals(ComponentsManager.Assigned.CHANGED, result) + assertEquals("dxvk-b.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + assertFalse(marked) + } + + @Test fun anUnchangedComponentIsSetAndMarked() { + var marked = false + val result = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-a.wcp", "unused", expected = null) { marked = true } + assertEquals(ComponentsManager.Assigned.SET, result) + assertEquals("dxvk-a.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + assertTrue(marked) + val newer = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-b.wcp", "unused", expected = "dxvk-a.wcp") + assertEquals(ComponentsManager.Assigned.SET, newer) + assertEquals("dxvk-b.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + } + + private fun wcp(fileName: String, version: String): File { + val out = File(context.cacheDir, fileName) + val profile = JSONObject().put("type", "DXVK-Linux").put("versionName", version).put("description", "DXVK $version") + .toString().toByteArray(Charsets.UTF_8) + val dll = "dxvk-dll-$version".toByteArray(Charsets.UTF_8) + TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(out)))).use { tar -> + tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX) + tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() }) + tar.write(profile) + tar.closeArchiveEntry() + tar.putArchiveEntry(TarArchiveEntry("files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply { size = dll.size.toLong() }) + tar.write(dll) + tar.closeArchiveEntry() + } + return out + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt new file mode 100644 index 0000000000..b52a2cc085 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt @@ -0,0 +1,33 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.gpu.GpuInfo +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class XboxBackCompatComponentsTest { + private val fex = "FEXCore-2611.1-xbox-bionic.wcp" + + @Test fun aComponentIsSetOnceAndNeverOverAPlayersChoice() { + assertEquals(fex, XboxBackCompatComponents.decide(current = null, assigned = null, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = "FEXCore-2611.1-bionic.wcp", assigned = null, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = null, assigned = fex, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = fex, assigned = fex, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = "DD-FEXCore-2611+76-nightly.wcp", assigned = fex, wanted = "FEXCore-2612-xbox-bionic.wcp")) + } + + @Test fun aComponentSetHereFollowsANewerBuild() { + assertEquals("FEXCore-2612-xbox-bionic.wcp", XboxBackCompatComponents.decide(current = fex, assigned = fex, wanted = "FEXCore-2612-xbox-bionic.wcp")) + } + + @Test fun eachComponentComesFromTheReleaseThatListsIt() { + val wanted = XboxBackCompatComponents.wanted(GpuInfo.Family.A7XX) + assertEquals(listOf("fex", "vkd3d", "dxvk"), wanted.map { it.comp }) + assertEquals(ComponentsManager.DD_XBOX, wanted[0].release) + assertEquals("vkd3d-proton-arm64ec-3.1-xbox-linux.wcp" to "Vkd3d-proton-Linux", wanted[1].file to wanted[1].release) + assertEquals("dxvk-gplasync-3.2-1-linux.wcp" to "Dxvk-gplasync-Linux", wanted[2].file to wanted[2].release) + for (w in wanted) assertEquals(w.comp, ComponentsManager.assetComp(w.release, w.file)) + assertEquals("dxvk-gplasync-3.2-a6xx-1-linux.wcp", XboxBackCompatComponents.wanted(GpuInfo.Family.A6XX)[2].file) + assertEquals("dxvk-gplasync-3.2-1-linux.wcp", XboxBackCompatComponents.wanted(null)[2].file) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt index 810c2f8642..fcb2e77286 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt @@ -201,6 +201,22 @@ class XboxCatalogTest { assertTrue(retail.xboxPc); assertEquals("EAPPX", retail.extra["format"]); assertEquals(7L, retail.sizeBytes) } + @Test fun anOriginalXboxGameShowsTheSizeOfItsConsolePackage() { + fun pkg(family: String?, format: String, platform: String, size: Long) = JSONObject().put("PackageFormat", format) + .put("MaxDownloadSizeInBytes", size).apply { if (family != null) put("PackageFamilyName", family) } + .put("PlatformDependencies", JSONArray().put(JSONObject().put("PlatformName", platform))) + fun offer(vararg packages: JSONObject) = JSONObject().put("ProductId", game).put("ProductType", "Game") + .put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "Fuzion Frenzy"))) + .put("DisplaySkuAvailabilities", JSONArray().put(JSONObject().put("Sku", JSONObject().put("Properties", + JSONObject().put("Packages", JSONArray(packages.toList())))))) + val console = pkg(null, "XVC", "Windows.Xbox", 2_670_796_800L) + val emulator = pkg("Xbox360BackwardCompatibil.PrimaryFuzionFrenzyFuzio_ksqcvrsvwz2jp", "MSIXVC", "Windows.Desktop", 753_313L) + assertEquals(2_670_796_800L, XboxCatalog.product(offer(console, emulator), mapOf(game to "gamepass"))!!.sizeBytes) + assertEquals(753_313L, XboxCatalog.product(offer(emulator), mapOf(game to "gamepass"))!!.sizeBytes) + val native = pkg("Microsoft.SomeGame_8wekyb3d8bbwe", "MSIXVC", "Windows.Desktop", 40_000_000L) + assertEquals(40_000_000L, XboxCatalog.product(offer(console, native), mapOf(game to "owned"))!!.sizeBytes) + } + @Test fun aCloudOnlyEditionFoldsIntoThePcCardWithTheSameTitle() { val cloud = XboxCloudCatalog(gamePass = setOf(parent), all = emptySet()) val pc = XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), cloud)!! diff --git a/tools/bionic-runtime/build.sh b/tools/bionic-runtime/build.sh index 91314db4fd..11f496d62e 100755 --- a/tools/bionic-runtime/build.sh +++ b/tools/bionic-runtime/build.sh @@ -36,9 +36,11 @@ GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-im VULKAN_HEADERS_TAG=v1.4.341 # The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed. # Layer v18: DroidDeck-Proton 11-14.1 (Valve Wine a47c73f52fd7, as GE-Proton11-14), the build Bannerlator ships; it -# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40). -LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261124-v18/DroidDeck-proton-11.0-14.1-arm64ec.wcp -LAYER_SHA256=bf94176180e96584185835f9e80b168666f9fa752aa9583cfedb8fe493134ff6 # proton-wine 1a5735e7 (run 45926928349) +# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40). This build adds the +# original Xbox fixes on top of v18 (special APC delivery, boot video aperture, 0 timer resolution: each off unless +# droiddeck-game-env sets its variable; FileAllocationInfo, MFCreateWaveFormatEx NULL size). +LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261203-ogxbox/DroidDeck-proton-11.0-14.1-arm64ec.wcp +LAYER_SHA256=a779747c880c64bacc0171cf26822f3398eaf32f0b214bca3448a95bf4127a90 # proton-wine ee646200 (run 47122517177) LAYER_VERSION=14.1 # Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default # DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later). diff --git a/tools/bionic-runtime/tool/launch.sh b/tools/bionic-runtime/tool/launch.sh index b3b9bd25c1..be9cc347b7 100644 --- a/tools/bionic-runtime/tool/launch.sh +++ b/tools/bionic-runtime/tool/launch.sh @@ -52,6 +52,9 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;; DROIDDECK_GUEST_ROOT) ;; VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;; + # droiddeck-game-env's original Xbox switches for this layer's Wine and the Xbox VKD3D-Proton build + WINE_SPECIAL_APC_INTERRUPT|WINE_MF_DISPLAY_APERTURE|WINE_PRECISE_SLEEP) ;; + VKD3D_INTEROP_PRESENT|VKD3D_PACKED_422|VKD3D_PACKED_422_SWIZZLE) ;; # The exec handoff (../handoff.c): the app's spawn socket and list (the app starts a handed-off program from the # glibc root's shell, so its path too), and what a worker hands the program it runs (this script, when it runs # in one): the first Wine process's hook knows the worker's binder fds are not its own. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 4e56c7b17c..04992da01b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -13,6 +13,7 @@ import subprocess import sys import tempfile from pathlib import Path +import xml.etree.ElementTree as ElementTree GAME_PREFIX = "DROIDDECK_GAME_" GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR", "DROIDDECK_GAME_FRAME_ACQUIRE") @@ -67,6 +68,29 @@ DOTNET_FEX = { "FEX_X87REDUCEDPRECISION": "0", } STABILITY_FEX = dict(DOTNET_FEX, FEX_MULTIBLOCK="0") +# Microsoft's original Xbox releases for PC run its emulator (Emu.exe). The switches turn on fixes in the builds of +# DroidDeck-Bionic's Wine, FEX and VKD3D-Proton made for it, each off by default: Wine delivers the Windows 11 special +# APCs the emulator interrupts its CPU threads with; FEX keeps the x87 state across those interrupts, checks for one in +# a loop that branches back into its own block, and maps an image without a lock order that deadlocks; Wine gives the +# boot video's types a display aperture and reports a 0 timer resolution (DXVK's vblank wait otherwise spins a core); +# VKD3D-Proton presents frames DXVK drew through D3D11On12 and maps the packed 4:2:2 video formats. FEX keeps +# DOTNET_FEX (the emulator's menu is .NET) without vector and memcpy TSO and with reduced x87 precision: on an +# Adreno 750 the emulator's menus ran at ~58 fps instead of ~35. +XBOX_BACK_COMPAT_IDENTITY = "xbox360backwardcompatibil" +XBOX_BACK_COMPAT_ENV = dict( + DOTNET_FEX, + FEX_VECTORTSOENABLED="0", + FEX_MEMCPYSETTSOENABLED="0", + FEX_X87REDUCEDPRECISION="1", + WINE_SPECIAL_APC_INTERRUPT="1", + FEX_SYNCX87CONTEXT="1", + FEX_LOOPSUSPENDCHECK="1", + FEX_SAFEIMAGEMAP="1", + WINE_MF_DISPLAY_APERTURE="1", + WINE_PRECISE_SLEEP="1", + VKD3D_INTEROP_PRESENT="1", + VKD3D_PACKED_422="1", +) # Setup loader offset-table IDs, as innoextract's known_setup_loader_versions lists them. Loaders # from 5.1.5 keep the table in a resource; older ones also put "Inno" at file offset 0x30. INNO_LOADER_IDS = (b"rDlPtS", b"nS5W7dT\x83\xaa\x1b\x0fj") @@ -149,6 +173,31 @@ def game_files(exe): return names +def xbox_identity(exe): + """The identity name in the MicrosoftGame.config of the Xbox package the executable is in, or "".""" + folder = os.path.dirname(exe) + for _ in range(4): + # The Xbox store accepts the file name in any case (XboxManifest.read). + name = "MicrosoftGame.config" + if not os.path.isfile(os.path.join(folder, name)): + try: + name = next((entry for entry in sorted(os.listdir(folder)) if entry.lower() == "microsoftgame.config"), name) + except OSError: + pass + try: + with open(os.path.join(folder, name), "rb") as source: + root = ElementTree.fromstring(source.read(1 << 20)) + except (OSError, ElementTree.ParseError): + root = None + if root is not None: + return next((node.get("Name", "") for node in root.iter() if node.tag.rsplit("}", 1)[-1] == "Identity"), "") + parent = os.path.dirname(folder) + if parent == folder: + break + folder = parent + return "" + + class Game: def __init__(self, exe, args, app_id=""): @@ -158,6 +207,7 @@ class Game: self.app_id = app_id self.stem = os.path.splitext(os.path.basename(exe))[0].lower() self.files = game_files(exe) + self.xbox_back_compat = os.path.isabs(exe) and xbox_identity(exe).lower().startswith(XBOX_BACK_COMPAT_IDENTITY) def has_arg(self, name): return any(a == name or a.startswith(name + "=") for a in self.args) @@ -177,10 +227,16 @@ def is_godot(game): @fix def dotnet_memory_ordering(game): - if "coreclr.dll" in game.files: + if "coreclr.dll" in game.files and not game.xbox_back_compat: return DOTNET_FEX, [], ".NET runtime: FEX with full TSO" +@fix +def xbox_back_compat(game): + if game.xbox_back_compat: + return XBOX_BACK_COMPAT_ENV, [], "Original Xbox game: emulator fixes on, FEX with load/store TSO and reduced x87 precision" + + @fix def unity_memory_ordering(game): if {"unityplayer.so", "gameassembly.so", "unityplayer.dll"} & game.files: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox index 143aa07c27..231dba2f0c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox @@ -28,6 +28,19 @@ CLASSES = { 'Windows.Storage.Streams.DataWriter'), } CLASS_KEY = 'Software\\Microsoft\\WindowsRuntime\\ActivatableClassId\\' +# Microsoft's original Xbox releases for PC install GameInputRedist.msi. The emulator needs the GameInput it installs +# (Wine's builtin one lacks the interface it asks for), but through the GameInputService class it registers that +# GameInput starts a service needing Windows notification calls Wine lacks, and the emulator then stops with "Gaming +# Services must be installed". Without the class it runs the redistributable's GameInput in process. +BACK_COMPAT_IDENTITY = 'xbox360backwardcompatibil' +# droiddeck-game-env gives these games the emulator's switches and faster FEX settings. Their install actions run +# without the switches and with FEX's full memory ordering and x87 precision: under the faster settings +# GameInputRedist.msi's 32-bit msiexec spun a core and never finished. +EMULATOR_SWITCHES = ('WINE_SPECIAL_APC_INTERRUPT', 'WINE_MF_DISPLAY_APERTURE', 'WINE_PRECISE_SLEEP', 'FEX_SYNCX87CONTEXT', + 'FEX_LOOPSUSPENDCHECK', 'FEX_SAFEIMAGEMAP', 'VKD3D_INTEROP_PRESENT', 'VKD3D_PACKED_422') +INSTALLER_FEX = {'FEX_TSOENABLED': '1', 'FEX_VECTORTSOENABLED': '1', 'FEX_MEMCPYSETTSOENABLED': '1', + 'FEX_HALFBARRIERTSOENABLED': '1', 'FEX_X87REDUCEDPRECISION': '0'} +GAMEINPUT_SERVICE = 'Software\\Classes\\CLSID\\{B773D0F8-01F8-41E7-9F23-6871DA0AACFF}' VIEW_DRIVES = 'xwvutsrqponmlkjihgfe' @@ -145,8 +158,21 @@ def game_config(exe): return None for folder in list(path.parents)[:4]: config = folder / 'MicrosoftGame.config' - if config.is_file(): - return config + if not config.is_file(): + # The Xbox store accepts the file name in any case (XboxManifest.read). + try: + config = next((entry for entry in sorted(folder.iterdir()) + if entry.name.lower() == 'microsoftgame.config' and entry.is_file()), None) + except OSError: + config = None + if config is None: + continue + # As in droiddeck-game-env, a manifest that does not parse gives way to one in a parent folder. + try: + ElementTree.fromstring(config.read_bytes()) + except (OSError, ElementTree.ParseError): + continue + return config return None @@ -186,6 +212,40 @@ def windows_arguments(text): return arguments +def back_compat(config): + try: + root = ElementTree.fromstring(config.read_bytes()) + except (OSError, ElementTree.ParseError): + return False + return any(node.tag.rsplit('}', 1)[-1] == 'Identity' and node.get('Name', '').lower().startswith(BACK_COMPAT_IDENTITY) + for node in root.iter()) + + +def remove_gameinput_service(proton, prefix, env, installed=False): + # Just after an install action Wine may not have written system.reg yet; reg.exe sees its registry either way. + if not installed: + try: + registry = (prefix / 'system.reg').read_text(encoding='utf-8', errors='replace') + except OSError: + return + if '[%s]' % GAMEINPUT_SERVICE.replace('\\', '\\\\').lower() not in registry.lower(): + return + try: + code = subprocess.run([proton, 'run', 'reg.exe', 'delete', 'HKLM\\' + GAMEINPUT_SERVICE, '/f'], + stdout=sys.stderr, env=env, timeout=90).returncode + except subprocess.TimeoutExpired: + print('droiddeck-xbox: GameInput service class could not be removed (reg.exe timed out); launching with it', + file=sys.stderr) + return + except OSError as e: + print('droiddeck-xbox: GameInput service class could not be removed (%s); launching with it' % (e.strerror or e), + file=sys.stderr) + return + # reg.exe fails when the key is absent, which after an install action only means the action registered no class. + if code != 0 and not installed: + print('droiddeck-xbox: GameInput service class could not be removed; launching with it', file=sys.stderr) + + def install_actions(config): try: root = ElementTree.fromstring(config.read_bytes()) @@ -218,6 +278,10 @@ def run_install_actions(proton, prefix, exe, env): if config is None: return done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions' + original_xbox = back_compat(config) + if original_xbox: + env = dict({k: v for k, v in env.items() if k not in EMULATOR_SWITCHES}, **INSTALLER_FEX) + installed = False for name, target, arguments in install_actions(config): try: content = hashlib.sha256() @@ -243,11 +307,14 @@ def run_install_actions(proton, prefix, exe, env): if code != 0: print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr) continue + installed = True try: done.mkdir(parents=True, exist_ok=True) marker.touch() except OSError as error: print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr) + if original_xbox: + remove_gameinput_service(proton, prefix, env, installed) def view_drive(prefix, exe): diff --git a/tools/tests/test_bionic_paths.py b/tools/tests/test_bionic_paths.py index 55c371b303..e4931b48ae 100644 --- a/tools/tests/test_bionic_paths.py +++ b/tools/tests/test_bionic_paths.py @@ -2,6 +2,7 @@ import importlib.machinery import importlib.util import os import re +import runpy import shutil import subprocess import tempfile @@ -74,6 +75,18 @@ class ToolArguments(unittest.TestCase): self.assertEqual(['BANNER_AUDIO_DIRECT_MIC=1', 'BANNER_AUDIO_DIRECT_MS=60'], result.stdout.split()) + def test_original_xbox_switches_reach_wine(self): + game_env = runpy.run_path(str(BIN / 'droiddeck-game-env')) + switches = dict(game_env['XBOX_BACK_COMPAT_ENV'], VKD3D_PACKED_422_SWIZZLE='rbg1') + text = LAUNCH.read_text() + block = text[text.index('KEEP="'):text.index('export PATH=/system/bin')] + env = dict(switches, PATH=os.environ['PATH'], DROIDDECK_BIONIC_KEEP='PATH', OTHER='x') + result = subprocess.run(['sh', '-c', block + 'env\n'], env=env, text=True, capture_output=True, check=True) + kept = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line) + self.assertEqual(switches, {name: kept.get(name) for name in switches}) + self.assertNotIn('OTHER', kept) + + class SessionLogs(unittest.TestCase): SESSION = '/data/user/0/com.droiddeck.launcher/files/logs/2026-11-22-09-steam' diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index b927d18694..55cf9d29da 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -1592,6 +1592,48 @@ class GameEnvironmentTest(unittest.TestCase): (other / "Other.exe").touch() self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], [])) + def test_original_xbox_games_get_the_emulator_fixes_instead_of_the_dotnet_preset(self): + expected = {"FEX_TSOENABLED": "1", "FEX_VECTORTSOENABLED": "0", "FEX_MEMCPYSETTSOENABLED": "0", + "FEX_HALFBARRIERTSOENABLED": "1", "FEX_X87REDUCEDPRECISION": "1", "WINE_SPECIAL_APC_INTERRUPT": "1", + "FEX_SYNCX87CONTEXT": "1", "FEX_LOOPSUSPENDCHECK": "1", "FEX_SAFEIMAGEMAP": "1", + "WINE_MF_DISPLAY_APERTURE": "1", "WINE_PRECISE_SLEEP": "1", "VKD3D_INTEROP_PRESENT": "1", + "VKD3D_PACKED_422": "1"} + + def package(folder, identity): + (folder / "EmuMenu").mkdir(parents=True) + for name in ("Emu.exe", "EmuMenu/EmuMenu.exe", "EmuMenu/coreclr.dll"): + (folder / name).touch() + (folder / "MicrosoftGame.config").write_text( + '' + '' % identity) + + with tempfile.TemporaryDirectory() as tmp: + game = Path(tmp) / "Fuzion Frenzy" + package(game, "Xbox360BackwardCompatibil.PrimaryFuzionFrenzyFuzio") + for exe in (game / "Emu.exe", game / "EmuMenu/EmuMenu.exe"): + env, extra, notes = MODULE["engine_fixes"](str(exe), [], "2773102903") + self.assertEqual((env, extra), (expected, [])) + self.assertEqual(len(notes), 1) + self.assertTrue(notes[0].startswith("Original Xbox game")) + config = {"version": 1, "games": {"2773102903": {"FEX_X87REDUCEDPRECISION": "0", "VKD3D_PACKED_422": None}}} + result = MODULE["apply_config"]({}, config, "2773102903", env) + self.assertEqual(result["FEX_X87REDUCEDPRECISION"], "0") + self.assertNotIn("VKD3D_PACKED_422", result) + self.assertEqual(result["WINE_SPECIAL_APC_INTERRUPT"], "1") + store = Path(tmp) / "Psychonauts" + package(store, "Microsoft.PsychonautsforWindows10") + env, extra, notes = MODULE["engine_fixes"](str(store / "Emu.exe"), []) + self.assertEqual(env, MODULE["DOTNET_FEX"]) + self.assertEqual(notes, [".NET runtime: FEX with full TSO"]) + (store / "MicrosoftGame.config").write_text("Installers' + '' + '') + (game / 'MicrosoftGame.config').write_text( + '' + '%s' % actions) + # A fresh prefix: the redistributable installs, and its class goes even before Wine writes system.reg. + (prefix / 'system.reg').write_text('WINE REGISTRY Version 2\n') + # The installers run without the emulator's switches and with FEX's full ordering and precision. + game_env = {'A': '1', 'WINE_SPECIAL_APC_INTERRUPT': '1', 'VKD3D_PACKED_422': '1', 'FEX_LOOPSUSPENDCHECK': '1', + 'FEX_VECTORTSOENABLED': '0', 'FEX_X87REDUCEDPRECISION': '1'} + installer_env = {'A': '1', 'FEX_TSOENABLED': '1', 'FEX_VECTORTSOENABLED': '1', 'FEX_MEMCPYSETTSOENABLED': '1', + 'FEX_HALFBARRIERTSOENABLED': '1', 'FEX_X87REDUCEDPRECISION': '0'} + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), game_env) + self.assertEqual([call.args[0][:3] for call in child.call_args_list], + [['/p', 'run', 'msiexec'], ['/p', 'run', 'msiexec'], ['/p', 'run', 'reg.exe']]) + self.assertTrue(child.call_args_list[0].args[0][4].endswith('GameInputRedist.msi')) + self.assertEqual(child.call_args_list[2].args[0][3:], delete) + self.assertEqual([call.kwargs['env'] for call in child.call_args_list], [installer_env] * 3) + self.assertEqual(game_env['FEX_X87REDUCEDPRECISION'], '1') + # After the install action: a key reg.exe does not find stays quiet, a reg.exe that never answers is reported. + for outcome, reported in (({'return_value': subprocess.CompletedProcess([], 1)}, False), + ({'side_effect': subprocess.TimeoutExpired('reg.exe', 90)}, True), + ({'side_effect': FileNotFoundError(2, 'No such file or directory')}, True)): + with patch('subprocess.run', **outcome), patch('sys.stderr', new_callable=io.StringIO) as err: + xbox['remove_gameinput_service']('/p', prefix, {}, installed=True) + self.assertEqual('could not be removed' in err.getvalue(), reported, outcome) + # Installed earlier and the class is gone: nothing runs. + with patch('subprocess.run') as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + child.assert_not_called() + # A prefix where the redistributable ran before: only the class is removed. + (prefix / 'system.reg').write_text('WINE REGISTRY Version 2\n\n' + key + '@="GameInputService"\n\n') + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + self.assertEqual([call.args[0][2:] for call in child.call_args_list], [['reg.exe'] + delete]) + with patch('subprocess.run', side_effect=subprocess.TimeoutExpired('reg.exe', 90)), \ + patch('sys.stderr', new_callable=io.StringIO) as err: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + self.assertIn('could not be removed', err.getvalue()) + # Other packages keep the class. + (game / 'MicrosoftGame.config').write_text( + '%s' % actions) + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix / 'other', str(game / 'Emu.exe'), {'FEX_X87REDUCEDPRECISION': '1'}) + self.assertEqual([call.args[0][2] for call in child.call_args_list], ['msiexec', 'msiexec']) + self.assertEqual(child.call_args.kwargs['env'], {'FEX_X87REDUCEDPRECISION': '1'}) def test_a_failed_install_action_is_retried_on_the_next_launch(self): with tempfile.TemporaryDirectory() as root: diff --git a/tools/xbox/README.md b/tools/xbox/README.md index c0a6636aba..2411b7a777 100644 --- a/tools/xbox/README.md +++ b/tools/xbox/README.md @@ -125,6 +125,12 @@ download plus two copies of the largest container, and each container is deleted The download has no control channel: cancelling kills it and the next attempt starts that container from zero. +`droiddeck-legacy-offer-parent.patch` keeps an entitlement whose `satisfiedByProductId` is a GUID. +A purchased original Xbox or Xbox 360 title names its marketplace offer there (Red Faction II did), +not a Store product, so it is not a subscription plan; the backend dropped the whole row as malformed +and the game never reached the library. The row keeps its own status, trial, sharing and expiry +checks, and any other parent that is not a product id is still rejected. + `droiddeck-msixvc2.patch` installs MSIXVC2 packages, the format Xbox 360 backward-compatible titles ship in. The package Windows Update serves is only an index (`XboxPackage.cbor`, chunk and file tables); the files are encrypted, Brotli-compressed segments inside `.box` blobs on the Xbox diff --git a/tools/xbox/droiddeck-legacy-offer-parent.patch b/tools/xbox/droiddeck-legacy-offer-parent.patch new file mode 100644 index 0000000000..3efd79c277 --- /dev/null +++ b/tools/xbox/droiddeck-legacy-offer-parent.patch @@ -0,0 +1,45 @@ +diff --git a/crates/xodus-cli/src/commands/library.rs b/crates/xodus-cli/src/commands/library.rs +index 36191bf..43bf718 100644 +--- a/crates/xodus-cli/src/commands/library.rs ++++ b/crates/xodus-cli/src/commands/library.rs +@@ -11,6 +11,10 @@ fn product_id(id: &str) -> bool { + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()) + } + ++fn legacy_offer(id: &str) -> bool { ++ id.len() == 36 && uuid::Uuid::try_parse(id).is_ok() ++} ++ + fn entry(id: &str, item: &Value) -> Result { + if !product_id(id) || !item.is_object() { return Err("entitlement-product"); } + let status = item["status"].as_str().filter(|s|s.len()<40).ok_or("entitlement-status")?; +@@ -21,6 +25,9 @@ fn entry(id: &str, item: &Value) -> Result { + let parent = match item.get("satisfiedByProductId") { + None | Some(Value::Null) => None, + Some(Value::String(id)) if product_id(id) => Some(id.as_str()), ++ // An original Xbox or Xbox 360 purchase names its marketplace offer, a GUID: not a Store product, so not a ++ // subscription plan either. The row stands on its own status, trial, sharing and expiry checks. ++ Some(Value::String(id)) if legacy_offer(id) => None, + _ => return Err("entitlement-parent"), + }; + // Preserve typed Positron provenance for conditional library access. +@@ -271,6 +278,19 @@ mod tests { + json!({"status":"Active","isTrial":false,"sharingSource":"None","endDate":"2099-01-01T00:00:00Z"}) + } + ++ #[test] ++ fn a_purchase_naming_its_legacy_marketplace_offer_is_owned_on_its_own_checks() { ++ let mut raw = valid(); raw["satisfiedByProductId"] = json!("66acd000-77fe-1000-9115-d80258410896"); ++ assert!(entry(A, &raw).unwrap()["satisfiedByProductId"].is_null()); ++ raw["isTrial"] = json!(true); ++ assert_eq!(entry(A, &raw).unwrap()["isTrial"], json!(true)); ++ for parent in ["{66acd000-77fe-1000-9115-d80258410896}", "66acd00077fe10009115d80258410896", ++ "urn:uuid:66acd000-77fe-1000-9115-d80258410896", "9aaaaaaaaaaa", ""] { ++ let mut raw = valid(); raw["satisfiedByProductId"] = json!(parent); ++ assert_eq!(entry(A, &raw), Err("entitlement-parent"), "{parent}"); ++ } ++ } ++ + #[test] + fn positron_provenance_is_explicit_boolean_and_never_copied_from_untrusted_fields() { + for flag in [None, Some(json!(false)), Some(json!(true)), Some(Value::Null), diff --git a/tools/xbox/prepare.py b/tools/xbox/prepare.py index 5ff45b9c64..c74e3b7937 100755 --- a/tools/xbox/prepare.py +++ b/tools/xbox/prepare.py @@ -12,7 +12,7 @@ local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', ' 'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch', 'droiddeck-licensing-device-ticket.patch', 'droiddeck-dlc-mount.patch', 'droiddeck-legacy-packages.patch', 'droiddeck-legacy-install.patch', 'droiddeck-legacy-run.patch', - 'droiddeck-msixvc2.patch'] + 'droiddeck-msixvc2.patch', 'droiddeck-legacy-offer-parent.patch'] identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest() source = cache / ('source-' + identity[:16]) if not (source / '.prepared').is_file():