Compare commits

...
Author SHA1 Message Date
The412Banner cfe07b0848 fix(ea): Steam copies of EA games get the CPUID of their own exe's bitness
Merges main, keeping the steam request key from #3021 in prepare_ea.
prepare_steam_ea now puts the game exe in the sidecar it passes to
prepare_ea, so ea_game_hardware sends the 64-bit CPUID for a 64-bit game.
2026-11-27 18:33:17 +00:00
MaxsTechReview ef1c208ed7 perf(ui): the idle home screen draws 30 frames a second (#3340)
* perf(ui): the idle home screen draws 30 frames a second

* test(ui): the idle frame gate draws 30 frames a second

* fix(home): the settled mark keeps full elapsed time at faster animation scales

* Advance the home mark in steps of at most 50 ms

* Skip the home mark step when animations are switched off mid-frame

* Bound the home mark advance for very small animation scales
2026-11-27 12:48:44 -05:00
MaxsTechReview 27171d8ffd perf(input): controller readers wake when input lands instead of polling (#3341)
* perf(input): controller readers wake when input lands instead of polling

* fix(input): an idle controller read stays a cancellation point

* Keep the cancellation point out of builds without thread cancellation
2026-11-27 12:37:54 -05:00
MaxsTechReview cc63b40387 fix(input): a direct touch reaches the game when the finger lands (#3339)
A direct touch is forwarded on touch-down by default instead of on release; the saved long-press right click behaviour is unchanged for users who chose it. Short taps keep a 50 ms minimum press.
2026-11-27 12:07:10 -05:00
The412Banner 89ef2f1e90 fix(session): Steam starts without waiting for the added-games scan (#2734) 2026-11-27 10:30:41 -05:00
FryMcNugget b08d8e8e19 feat(ea): start Steam's copies of EA games without the EA app (#3021) 2026-11-27 08:32:55 -05:00
xlulx 2dc74f7574 fix(bionic): DroidDeck's DirectAudio settings, the microphone among them, reach Bionic Wine's audio driver (#3277) 2026-11-27 08:27:32 -05:00
Kurt Himebauch 0dea571c63 fix(mesa): zink reclaims memory a client freed once it goes idle (#3320) 2026-11-27 08:25:45 -05:00
MaxsTechReview 5f088283af fix(session): Game cores changed during a session apply to the next launch (#3314) 2026-11-27 06:36:19 -05:00
MaxsTechReview 281a64f6c5 Keep SD card downloads cancellable and let uninstall stop them (#3313) 2026-11-27 05:26:48 -05:00
The412Banner 6346b5ebdf fix(ea): retake the hardware probe when its 64-bit CPUID run fails 2026-11-22 15:29:17 +00:00
The412Banner 2702ba2db8 fix(ea): bind activation licences to the CPUID of the game's own bitness
The machine hash of activation versions 2 and 3 includes CPUID leaf 1 ECX,
and FEX reports AVX to 64-bit (ARM64EC) processes but not to 32-bit (WOW64)
ones. The hardware probe only ran a 32-bit CPUID program, so 64-bit games
rejected their licence and looped through ActivationUI. The probe now runs
CPUID in both bitnesses, the game gets the values its exe sees, and the
cache is retaken when the Proton or FEX build changes.
2026-11-22 14:39:35 +00:00
47 changed files with 2074 additions and 200 deletions

No files matched your search

+41 -8
View File
@@ -25,6 +25,7 @@
#include <gnu/lib-names.h>
#endif
#include <fcntl.h>
#include <linux/futex.h>
#include <linux/input.h>
#include <linux/joystick.h>
#include <linux/uinput.h>
@@ -711,6 +712,19 @@ ring_header_is_valid(const FakeInputRingHeader *ring) {
ring->capacity == FAKE_INPUT_RING_CAPACITY;
}
__attribute__((visibility("hidden"))) static int ring_wait(const FakeInputRingHeader *ring, uint64_t seen, long ns) {
struct timespec wait = {0, ns};
if (syscall(SYS_futex, &ring->write_seq, FUTEX_WAIT, static_cast<uint32_t>(seen), &wait, nullptr, 0) == 0 ||
errno == EAGAIN || errno == ETIMEDOUT)
return 0;
if (errno == EINTR) return -1;
return nanosleep(&wait, nullptr);
}
__attribute__((visibility("hidden"))) static void ring_wake(const FakeInputRingHeader *ring) {
syscall(SYS_futex, &ring->write_seq, FUTEX_WAKE, INT_MAX, nullptr, nullptr, 0);
}
struct SnapshotState {
uint64_t sequence = 0;
uint64_t write_seq = 0;
@@ -1167,6 +1181,7 @@ __attribute__((visibility("hidden"))) static void flush_uinput(UinputWriter &w)
__atomic_thread_fence(__ATOMIC_RELEASE);
__atomic_store_n(&ring->snapshot_seq, sequence + 2, __ATOMIC_RELEASE);
__atomic_store_n(&ring->write_seq, write_seq, __ATOMIC_RELEASE);
ring_wake(ring);
}
__attribute__((visibility("hidden"))) static ssize_t
@@ -1540,6 +1555,12 @@ __attribute__((visibility("hidden"))) static void sleep_us(int us) {
nanosleep(&interval, nullptr);
}
__attribute__((visibility("hidden"))) static void
report_wait(const FakeInputRingHeader *ring, bool fresh, uint64_t seen, int us) {
if (fresh) ring_wait(ring, seen, us * 1000L);
else sleep_us(us);
}
__attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
@@ -1712,7 +1733,8 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
int32_t axes[8] = {};
DeckExtras extras;
while (live_pad_type() == PAD_TYPE_DECK) {
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
bool fresh = read_snapshot(self->ring, snap);
if (fresh && snap.generation == ring_generation(self->ring)) {
buttons = snap.buttons;
memcpy(axes, snap.axes, sizeof(axes));
}
@@ -1722,7 +1744,7 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
errno != EAGAIN && errno != EWOULDBLOCK)
break;
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
}
syscall(SYS_close, self->peer);
munmap(self->ring, self->mapping_size);
@@ -1828,7 +1850,8 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
SonyTouch touch;
const uint64_t start_us = monotonic_us();
while (live_pad_type() == type) {
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
bool fresh = read_snapshot(self->ring, snap);
if (fresh && snap.generation == ring_generation(self->ring)) {
buttons = snap.buttons;
memcpy(axes, snap.axes, sizeof(axes));
}
@@ -1838,7 +1861,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
errno != EAGAIN && errno != EWOULDBLOCK)
break;
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
}
syscall(SYS_close, self->peer);
munmap(self->ring, self->mapping_size);
@@ -2037,7 +2060,8 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
DeckExtras extras;
const uint64_t start_us = monotonic_us();
while (live_pad_type() == PAD_TYPE_STEAM) {
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
bool fresh = read_snapshot(self->ring, snap);
if (fresh && snap.generation == ring_generation(self->ring)) {
buttons = snap.buttons;
memcpy(axes, snap.axes, sizeof(axes));
}
@@ -2048,7 +2072,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
errno != EAGAIN && errno != EWOULDBLOCK)
break;
sleep_us(controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
}
syscall(SYS_close, self->peer);
munmap(self->ring, self->mapping_size);
@@ -4016,6 +4040,7 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
errno = ENODEV;
return -1;
}
bool idle = false;
for (int attempt = 0; attempt < 8; ++attempt) {
size_t requested = count / sizeof(struct input_event);
if (fake.keyframe_remaining == 0) {
@@ -4037,7 +4062,10 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
capture_keyframe(fake, snap);
} else {
size_t events = std::min<uint64_t>(requested, snap.write_seq - fake.read_seq);
if (events == 0) break;
if (events == 0) {
idle = true;
break;
}
const uint8_t *ring_events = reinterpret_cast<const uint8_t *>(fake.ring) +
FAKE_INPUT_RING_HEADER_SIZE;
std::vector<struct input_event> input_events(events);
@@ -4083,9 +4111,14 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
errno = EAGAIN;
return -1;
}
const FakeInputRingHeader *ring = fake.ring;
uint64_t seen = fake.read_seq;
guard.unlock();
#ifdef __GLIBC__
pthread_testcancel();
#endif
struct timespec sleep_time = {0, backoff_ns};
int result = nanosleep(&sleep_time, nullptr);
int result = idle ? ring_wait(ring, seen, backoff_ns) : nanosleep(&sleep_time, nullptr);
guard.lock();
if (result < 0) return -1;
if (low_latency(LATENCY_CONTROLLER)) backoff_ns = kLowLatencyRingWaitUs * 1000;
+10
View File
@@ -1,6 +1,9 @@
#include <errno.h>
#include <jni.h>
#include <limits.h>
#include <linux/futex.h>
#include <stdatomic.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <unistd.h>
@@ -11,6 +14,13 @@ Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env,
atomic_thread_fence(memory_order_release);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_input_FakeInputWriter_nativeWake(JNIEnv *env, jclass clazz, jobject buffer, jint offset) {
(void)clazz;
uint8_t *base = (*env)->GetDirectBufferAddress(env, buffer);
if (base) syscall(SYS_futex, base + offset, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass clazz, jint tgid, jint tid, jint signal) {
(void)env;
@@ -349,7 +349,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var gestureSettingsOpen by mutableStateOf(false)
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
private var steamImportAnswered: String? = null
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_NONE)
private var relativeMouseMode by mutableIntStateOf(0)
@Volatile private var appliedRelativeMouseMode: Int? = null
private val agentReadyListener: () -> Unit = {
@@ -233,14 +233,14 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
timed(folder) { for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true) }
}
}
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
scanGame(context, folder, out, single = entry, reuse = true)
timed(folder) { scanGame(context, folder, out, single = entry, reuse = true) }
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
@@ -250,6 +250,15 @@ object AddedGames {
return out.distinctBy { it.folder.canonicalPath }
}
private const val SLOW_FOLDER_MS = 1_000L
private inline fun timed(folder: File, block: () -> Unit) {
val began = android.os.SystemClock.elapsedRealtime()
block()
val took = android.os.SystemClock.elapsedRealtime() - began
if (took >= SLOW_FOLDER_MS) Log.i(TAG, "games: scanning ${folder.path} took ${took}ms")
}
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
val folder = File(folderPath)
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
@@ -564,8 +573,10 @@ object AddedGames {
class Listed(val appId: Long, val name: String, val launchOptions: String)
fun listingFile(context: Context): File = File(context.filesDir, "session/added-games.json")
fun listed(context: Context): List<Listed>? = runCatching {
val file = File(context.filesDir, "session/added-games.json")
val file = listingFile(context)
if (!file.isFile) return null
val entries = org.json.JSONArray(file.readText())
(0 until entries.length()).mapNotNull { i ->
@@ -575,7 +586,7 @@ object AddedGames {
fun writeListing(context: Context, games: List<Game>,
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
val file = listingFile(context).apply { parentFile?.mkdirs() }
val json = StringBuilder("[")
games.forEachIndexed { i, g ->
if (i > 0) json.append(',')
@@ -596,10 +607,24 @@ object AddedGames {
if (games.isNotEmpty() || i > 0) json.append(',')
json.append(entry.toString())
}
file.writeText(json.append(']').toString())
val text = json.append(']').toString()
synchronized(listing) {
val partial = File(file.parentFile, file.name + ".part")
try {
partial.writeText(text)
java.nio.file.Files.move(partial.toPath(), file.toPath(),
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
} catch (e: java.io.IOException) {
Log.w(TAG, "games: listing not replaced: ${e.message}")
partial.delete()
if (!file.isFile) file.writeText(text)
}
}
return file
}
private val listing = Any()
private fun artGuestPath(context: Context, file: File): String? {
val files = context.filesDir.absolutePath
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
@@ -1,17 +1,31 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.os.SystemClock
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.util.concurrent.Callable
import java.util.concurrent.Executors
object AddedGamesPublisher {
private const val TAG = "AddedGamesPublisher"
private const val CLIENT_WAIT_MS = 600_000L
private const val POLL_MS = 1_000L
private const val RETRY_MS = 5_000L
@VisibleForTesting
@Volatile
internal var now = false
@VisibleForTesting
@Volatile
internal var live: (Context, List<AddedGames.Game>, (AddedGames.Game) -> Boolean) -> Boolean = SteamLiveShortcuts::sync
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
fun later(context: Context, live: () -> Unit = {}) {
@@ -23,10 +37,56 @@ object AddedGamesPublisher {
if (now) work.run() else worker.execute(work)
}
fun republish(context: Context) {
fun republish(context: Context): List<AddedGames.Game> {
val games = AddedGames.scan(context)
AddedGames.writeListing(context, games)
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(context)
val arch = SessionPrefs.activeSteamClientArch(context)
LibraryCache.save(context, Library.launchableGames(context, added = games, arch = arch), arch == "x86_64")
return games
}
fun sessionListing(context: Context): File {
val app = context.applicationContext
val started = AddedGames.listed(app)?.map { it.appId }?.toSet()
?: return AddedGames.writeListing(app, AddedGames.scan(app).also { log(it) })
val session = SessionState.sessionId
val work = Runnable {
try {
val began = SystemClock.elapsedRealtime()
val games = serial { republish(app) }
Log.i(TAG, "session refresh: ${games.size} game(s) in ${SystemClock.elapsedRealtime() - began} ms")
log(games)
val fresh = games.filter { (it.appId and 0xFFFFFFFFL) !in started }
if (fresh.isNotEmpty()) deliver(app, session, fresh)
} catch (e: Exception) {
Log.w(TAG, "session refresh: ${e.message}")
}
}
if (now) work.run() else Thread(work, "added-games-refresh").apply { priority = Thread.MIN_PRIORITY }.start()
return AddedGames.listingFile(app)
}
internal fun log(games: List<AddedGames.Game>) {
if (games.isNotEmpty()) Log.i(TAG, "added games: " + games.joinToString { "${it.name} (${it.exe.name})" })
}
private fun deliver(app: Context, session: String?, games: List<AddedGames.Game>) {
val until = SystemClock.uptimeMillis() + CLIENT_WAIT_MS
while (current(session)) {
val ready = SessionState.phase == SessionPhase.READY
if (ready && serial { !current(session) || (SessionState.phase == SessionPhase.READY && syncUnremoved(app, games)) }) return
if (now || SystemClock.uptimeMillis() >= until) return
Thread.sleep(if (ready) RETRY_MS else POLL_MS)
}
}
private fun current(session: String?): Boolean =
SessionState.running && !SessionState.stopRequested && SessionState.sessionId == session
private fun syncUnremoved(app: Context, games: List<AddedGames.Game>): Boolean {
val removed = SessionPrefs.removedAddedGames(app).toSet()
return live(app, games) { it.folder.path !in removed }
}
private fun <T> serial(block: () -> T): T = if (now) block() else worker.submit(Callable { block() }).get()
}
@@ -51,11 +51,12 @@ object GameExePicker {
val entries = dir.listFiles()?.sortedBy { it.name.lowercase() } ?: continue
for (f in entries) {
if (visited >= WALK_BUDGET) break@walk
if (isLink(f)) continue
if (f.isDirectory) {
val attrs = attributes(f) ?: continue
if (attrs.isSymbolicLink) continue
if (attrs.isDirectory) {
visited++
if (depth < MAX_DEPTH && !skipDir(f, f.relativeTo(folder).invariantSeparatorsPath)) next.add(f)
} else if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) {
} else if (attrs.isRegularFile && f.name.endsWith(".exe", ignoreCase = true)) {
visited++
if (!JUNK_EXE_RE.matches(f.nameWithoutExtension)) found.add(f to depth)
}
@@ -98,7 +99,9 @@ object GameExePicker {
return SKIP_PATHS.any { rel == it || rel.endsWith("/$it") }
}
private fun isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
private fun attributes(f: File): java.nio.file.attribute.BasicFileAttributes? = runCatching {
java.nio.file.Files.readAttributes(f.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, java.nio.file.LinkOption.NOFOLLOW_LINKS)
}.getOrNull()
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.MotionEvent
import kotlin.math.abs
@@ -22,8 +23,9 @@ class DirectTouchHold(
private var downY = 0f
private var downId = 0
private var delayMs = 0L
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_NONE
private var forwarded = false
private var forwardedAt = 0L
private var held = false
private var pressing = false
private var upX = 0f
@@ -125,8 +127,11 @@ class DirectTouchHold(
upX = event.x
upY = event.y
liftId = event.getPointerId(event.actionIndex)
liftPending = true
handler.postDelayed(lift, LIFT_MS)
val wait = MIN_PRESS_MS - (SystemClock.uptimeMillis() - forwardedAt)
if (wait > 0L) {
liftPending = true
handler.postDelayed(lift, wait)
} else lift.run()
}
MotionEvent.ACTION_CANCEL -> cancel()
}
@@ -136,9 +141,10 @@ class DirectTouchHold(
private fun forwardDown() {
touch.down(downId, downX, downY)
forwarded = true
forwardedAt = SystemClock.uptimeMillis()
}
private companion object {
const val LIFT_MS = 50L
const val MIN_PRESS_MS = 50L
}
}
@@ -149,6 +149,8 @@ public class FakeInputWriter {
private static native void nativeStoreFence();
private static native void nativeWake(ByteBuffer ring, int offset);
public static void storeFence() {
nativeStoreFence();
}
@@ -455,6 +457,7 @@ public class FakeInputWriter {
writeSnapshotLocked(ring);
nativeStoreFence();
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
nativeWake(ring, RING_WRITE_SEQ_OFFSET);
}
return true;
}
@@ -15,7 +15,7 @@ data class TouchGestureConfig(
val longPressAction: String = ACTION_RIGHT_CLICK,
val longPressMouseBehavior: String = MOUSE_BEHAVIOR_HOLD,
val longPressDelay: Int = DEFAULT_DELAY_MS,
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
val directHoldBehavior: String = MOUSE_BEHAVIOR_NONE,
val doubleTapEnabled: Boolean = true,
val doubleTapDelay: Int = DEFAULT_DELAY_MS,
val twoFingerDragEnabled: Boolean = true,
@@ -167,7 +167,7 @@ data class TouchGestureConfig(
),
longPressDelay = obj.optInt(KEY_LONG_PRESS_DELAY, DEFAULT_DELAY_MS),
directHoldBehavior = normalizeDirectHoldBehavior(
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_CLICK)
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_NONE)
),
doubleTapEnabled = obj.optBoolean(KEY_DOUBLE_TAP_ENABLED, true),
doubleTapDelay = obj.optInt(KEY_DOUBLE_TAP_DELAY, DEFAULT_DELAY_MS),
@@ -13,6 +13,7 @@ object GameEnvironmentStore {
private const val TAG = "GameEnvironmentStore"
private const val SETTINGS = "game-environment.json"
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
private const val GAME_CORES_FILE = "root/.config/droiddeck/game-cores"
const val DXVK_CONFIG = "dxvkConfig"
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
const val GAME_DEBUG_LOGS = "gameDebugLogs"
@@ -108,10 +109,12 @@ object GameEnvironmentStore {
@Synchronized
fun publish(
context: Context,
config: GameEnvironment.Config = read(context),
config: GameEnvironment.Config? = null,
gameDebugLogsOverride: Boolean? = null,
) {
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
publishGameCores(context)
val stored = config ?: read(context)
val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val json = encode(resolved)
val dxvk = TextureFiltering.dxvkOptions(
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
@@ -140,6 +143,26 @@ object GameEnvironmentStore {
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
}
@Synchronized
fun publishGameCores(context: Context) {
val file = File(LinuxRuntime.rootDir(context), GAME_CORES_FILE)
val pending = File(file.path + ".new")
try {
check(file.parentFile!!.isDirectory || file.parentFile!!.mkdirs())
java.io.FileOutputStream(pending).use {
it.write((com.droiddeck.launcher.core.CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(context)) + "\n").toByteArray(Charsets.UTF_8))
it.fd.sync()
}
java.nio.file.Files.move(
pending.toPath(), file.toPath(),
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING,
)
} catch (error: Exception) {
Log.e(TAG, "Could not update game cores", error)
if (!file.delete() && file.exists()) Log.e(TAG, "Could not remove outdated game cores")
}
}
private fun write(file: File, text: String) {
check(file.parentFile!!.isDirectory || file.parentFile!!.mkdirs())
val atomic = AtomicFile(file)
@@ -1008,6 +1008,7 @@ object SessionPrefs {
fun setGameCpus(context: Context, list: String) {
prefs(context).edit().putString("gameCpus", list).apply()
GameEnvironmentStore.publishGameCores(context)
}
fun noXalia(context: Context): Boolean = prefs(context).getBoolean("noXalia", true)
@@ -693,12 +693,14 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
}
if (steamHere || noSteamGame) {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
val listing = if (steamHere) SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGamesPublisher.sessionListing(this) } else {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
com.droiddeck.launcher.frontend.AddedGamesPublisher.log(added)
SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
}
guest.add("DD_ADDED_GAMES=" + listing.path)
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
// Proton builds up to 11.12 report X11 text fields under this name.
@@ -19,25 +19,33 @@ object SteamLiveShortcuts {
private const val EVAL_TIMEOUT_MS = 20_000L
private const val THAW_WAIT_MS = 15_000L
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }): Boolean {
val wanted = games.filter(include)
if (wanted.isEmpty() || !clientRunning()) return
if (wanted.isEmpty()) return true
if (!clientRunning()) return false
val list = JSONArray()
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL).put("launch", g.launchOptions))
val js = """
(async () => {
const want = ${list};
let added = 0;
let added = 0, missed = 0;
for (const w of want) {
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++; else missed++;
}
return added;
return JSON.stringify({ added, missed });
})()
""".trimIndent()
val result = evaluate(context, js) ?: return
Log.i(TAG, "live shortcuts: $result added")
if (result != "0") StoresState.logLine("Steam: $result shortcut(s) added to the running client")
return synced(evaluate(context, js))
}
internal fun synced(result: String?): Boolean {
val counts = result?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return false
val added = counts.optInt("added")
val missed = counts.optInt("missed")
Log.i(TAG, "live shortcuts: $added added" + if (missed > 0) ", $missed not added" else "")
if (added > 0) StoresState.logLine("Steam: $added shortcut(s) added to the running client")
return missed == 0
}
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
@@ -122,10 +122,16 @@ object StoreInstalls {
fun discard(context: Context, folder: File, caches: List<File>) {
val app = context.applicationContext
inBackground(folder) { discardNow(app, folder, caches) }
}
fun deleteLater(dir: File) = inBackground(dir) { deleteTree(dir) }
private fun inBackground(folder: File, work: () -> Unit) {
beginDiscard(folder)
val worker = Thread({
try {
discardNow(app, folder, caches)
work()
} finally {
endDiscard(folder)
}
@@ -318,7 +318,7 @@ object StoresState {
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
uninstalling[key] = 0f
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
if (!com.droiddeck.launcher.stores.download.DownloadQueue.holdForRemovalWhenFree(key)) {
if (!com.droiddeck.launcher.stores.download.DownloadQueue.stopForRemoval(app, key)) {
logLine("kept \"${game.sidecar.title}\": its download or update is still running")
main.post { uninstalling.remove(key); onDone() }
return@background
@@ -9,6 +9,7 @@ import java.util.concurrent.atomic.AtomicBoolean
object DownloadQueue {
private const val TAG = "StoreDownloads"
private const val REMOVAL_WAIT_MS = 30_000L
interface DownloadJob {
fun run(handle: JobHandle): String?
@@ -120,17 +121,24 @@ object DownloadQueue {
fun releaseRemoval(key: String) { synchronized(lock) { removing.remove(key); (lock as Object).notifyAll() } }
fun holdForRemovalWhenFree(key: String): Boolean = synchronized(lock) {
while (true) {
val item = items[key]
if (item?.entry?.isActive == true || item?.job != null) return@synchronized false
if (key !in cleaningUp && key !in removing) break
(lock as Object).wait()
fun stopForRemoval(context: Context, key: String): Boolean {
if (synchronized(lock) { busyLocked(key) }) cancel(context, key)
val deadline = android.os.SystemClock.uptimeMillis() + REMOVAL_WAIT_MS
return synchronized(lock) {
while (true) {
val busy = busyLocked(key)
if (!busy && key !in cleaningUp && key !in removing) break
val left = deadline - android.os.SystemClock.uptimeMillis()
if (busy && left <= 0) return@synchronized false
(lock as Object).wait(if (busy) left else 0L)
}
removing.add(key)
true
}
removing.add(key)
true
}
private fun busyLocked(key: String): Boolean = items[key].let { it?.entry?.isActive == true || it?.job != null }
private fun beginCleanup(key: String): Boolean = synchronized(lock) {
if (key in removing) return@synchronized false
cleaningUp.merge(key, 1, Int::plus)
@@ -412,6 +420,7 @@ object DownloadQueue {
}
item.job = null
publishLocked()
(lock as Object).notifyAll()
}
when (item.entry.state) {
DownloadState.INSTALLED -> {
@@ -73,35 +73,72 @@ object EaLaunch {
/** Answers the guest's request right before an EA game starts: session, licence and the LSX endpoint. */
fun prepare(context: Context, request: JSONObject): JSONObject {
val app = context.applicationContext
request.optJSONObject("steam")?.let { return prepareSteam(app, request, it) }
val id = request.optString("id")
val reply = JSONObject().put("ok", false)
val (folder, recorded) = installed(app, id) ?: return reply.put("reason", "not-installed")
val (folder, recorded) = installed(app, id) ?: return JSONObject().put("ok", false).put("reason", "not-installed")
val sidecar = backfill(folder, recorded)
runCatching { com.droiddeck.launcher.stores.StoreLaunch.refreshLauncher(folder, sidecar) }
File(folder, ENV_FILE).delete()
val account = EaAuth.load(app) ?: return reply.put("reason", "signed-out")
val access = EaAuth.accessToken(app) ?: return reply.put("reason", "sign-in-expired")
val contentId = sidecar.extra["contentId"].orEmpty()
val locale = sidecar.extra["locale"].orEmpty().ifEmpty { "en_US" }
val core = EaOoa.coreDir(folder, sidecar.exe)
val known = (sidecar.extra["contentIds"].orEmpty().split(',') + sidecar.extra["multiplayerId"].orEmpty()).map { it.trim() }.filter { it.isNotEmpty() }.toSet()
val game = Started(folder, id, sidecar.extra["contentId"].orEmpty(), known, sidecar.extra["contentIds"].orEmpty().split(','),
sidecar.title, sidecar.installVersion, sidecar.extra["locale"].orEmpty().ifEmpty { "en_US" }, sidecar.exe)
val (reply, env) = start(app, game, request)
if (env != null) {
val tmp = File(folder, "$ENV_FILE.tmp")
tmp.writeText(env.entries.joinToString("\r\n", postfix = "\r\n") { "${it.key}=${it.value}" })
tmp.renameTo(File(folder, ENV_FILE))
}
return reply
}
private val OFFER = Regex("Origin\\.OFR\\.[0-9]+\\.[0-9]+")
private val CONTENT = Regex("[A-Za-z0-9._-]{1,64}")
/** Steam's copy of an EA game, which Steam would hand to the EA app; the env comes back in the reply. */
private fun prepareSteam(app: Context, request: JSONObject, steam: JSONObject): JSONObject {
val failed = JSONObject().put("ok", false)
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).canonicalFile
val folder = File(root, steam.optString("folder").removePrefix("/")).canonicalFile
if (!folder.path.startsWith(root.path + File.separator) || !folder.isDirectory) return failed.put("reason", "no-folder")
fun strings(name: String, pattern: Regex) = steam.optJSONArray(name)?.let { a -> (0 until a.length()).map { a.optString(it) } }
.orEmpty().filter { pattern.matches(it) }.distinct()
val offers = strings("offers", OFFER)
val contents = strings("contentIds", CONTENT)
if (offers.isEmpty() || contents.isEmpty()) return failed.put("reason", "no-offer")
val game = Started(folder, offers.first(), contents.first(), contents.toSet(), contents, steam.optString("title").ifEmpty { folder.name },
steam.optString("version"), steam.optString("locale").ifEmpty { "en_US" }, steam.optString("exe"))
val (reply, env) = start(app, game, request)
if (env != null) reply.put("id", game.offerId).put("env", JSONObject(env.toMap()))
return reply
}
private class Started(
val folder: File, val offerId: String, val contentId: String, val contentIds: Set<String>, val licenceIds: List<String>,
val title: String, val version: String, val locale: String, val exe: String,
)
private fun start(app: Context, game: Started, request: JSONObject): Pair<JSONObject, LinkedHashMap<String, String>?> {
val reply = JSONObject().put("ok", false)
val id = game.offerId
val account = EaAuth.load(app) ?: return reply.put("reason", "signed-out") to null
val access = EaAuth.accessToken(app) ?: return reply.put("reason", "sign-in-expired") to null
val contentId = game.contentId
val locale = game.locale
val core = EaOoa.coreDir(game.folder, game.exe)
val hashVersion = core?.let(EaOoa::activationVersion) ?: 1
val hardware = request.optJSONObject("hardware")?.let(EaOoa.Hardware::fromJson)?.takeIf { it.complete(hashVersion) }
val legacy = EaOoa.legacyCore(core)
val lifetime = if (legacy) 14400 else 550
val opaque = EaAuth.mint(app, EaAuth.CLIENT_ID, "token", EaAuth.OPAQUE_SCOPES, "OPAQUE", lifetime).orEmpty()
val known = (sidecar.extra["contentIds"].orEmpty().split(',') + sidecar.extra["multiplayerId"].orEmpty()).map { it.trim() }.filter { it.isNotEmpty() }.toSet()
val lsx = EaLsx.start(app, EaLsx.Game(id, contentId, sidecar.title, sidecar.installVersion, locale, hardware, hashVersion, opaque,
System.currentTimeMillis() + (lifetime - 30) * 1000L, known))
val lsx = EaLsx.start(app, EaLsx.Game(id, contentId, game.title, game.version, locale, hardware, hashVersion, opaque,
System.currentTimeMillis() + (lifetime - 30) * 1000L, game.contentIds))
val env = environment(id, contentId, locale, if (legacy && opaque.isNotEmpty()) opaque else access, access, opaque, EaAuth.load(app) ?: account)
val tmp = File(folder, "$ENV_FILE.tmp")
tmp.writeText(env.entries.joinToString("\r\n", postfix = "\r\n") { "${it.key}=${it.value}" })
tmp.renameTo(File(folder, ENV_FILE))
val licenses = JSONArray()
val notes = ArrayList<String>()
if (core != null) {
val ids = (listOf(contentId) + sidecar.extra["contentIds"].orEmpty().split(',')).map { it.trim() }.filter { it.isNotEmpty() }.distinct()
val ids = (listOf(contentId) + game.licenceIds).map { it.trim() }.filter { it.isNotEmpty() }.distinct()
if (hardware == null) notes += "no-hardware" else {
val hash = EaOoa.machineHash(hardware, hashVersion)
for (content in ids) {
@@ -125,7 +162,7 @@ object EaLaunch {
}
val licenseNote = if (core == null) "none-needed" else "v$hashVersion " + notes.joinToString(",")
Log.i(TAG, "prepared $id lsx=$lsx legacy=$legacy opaque=${opaque.isNotEmpty()} licence=$licenseNote")
return reply.put("ok", true).put("lsx", lsx).put("license", licenseNote).put("licenses", licenses)
return reply.put("ok", true).put("lsx", lsx).put("license", licenseNote).put("licenses", licenses) to env
}
}
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.formatBytes
@@ -215,7 +216,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
val before = EpicClient.read(app)
val needApp = !(before.version == launcher.version && File(state, "app/${launcher.version}/.droiddeck-ready").isFile)
val needRuntime = !(before.runtimeVersion == runtime.version && File(state, "runtime/${runtime.version}/.droiddeck-ready").isFile)
val dir = EpicClient.downloadsDir(app).apply { mkdirs() }
val dir = EpicClient.downloadsDir(app).also { StoreInstalls.awaitDiscard(it) }.apply { mkdirs() }
val gles = EpicClientSources.gles()
val appPart = if (needApp) Part(listOf(launcher.url), File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true) else null
val desktopParts = if (needApp) EpicClientSources.DESKTOP.map { Part(it.urls, File(dir, it.file), it.sha256, false, it.size) } else emptyList()
@@ -265,7 +266,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
runCatching { connection?.disconnect() }
if (deleteFiles) EpicClient.downloadsDir(app).deleteRecursively()
if (deleteFiles) StoreInstalls.deleteLater(EpicClient.downloadsDir(app))
}
private fun length(url: String): Long {
@@ -282,7 +282,7 @@ internal object SteamStore {
if (key in StoresState.uninstalling) return
StoresState.uninstalling[key] = 0f
Thread({
if (!DownloadQueue.holdForRemovalWhenFree(key)) {
if (!DownloadQueue.stopForRemoval(app, key)) {
StoresState.logLine("Steam: kept $appId, its download is still running")
StoresState.post { StoresState.uninstalling.remove(key); onDone() }
return@Thread
@@ -137,7 +137,7 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
delete = deleteFiles
val process = child
if (process == null) {
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteLater(folder)
else if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
return
}
@@ -15,7 +15,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameMillis
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
@@ -99,7 +99,7 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
var vx = speed * 0.8f
var vy = -speed * 0.6f
while (true) {
if (clock.page == Size.Zero) { withFrameMillis { }; continue }
if (clock.page == Size.Zero) { withFrameNanos { }; continue }
val f = MarkFrame(clock.page, Offset.Zero)
if (clock.at == Offset.Unspecified) clock.at = Offset(clock.page.width * 0.64f, clock.page.height * 0.42f)
if (Motion.scale == 0f) {
@@ -108,8 +108,13 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
clock.wall = 0f
return@LaunchedEffect
}
withFrameMillis { now ->
val dt = if (last < 0) 0f else min(50f, (now - last) / Motion.scale)
withFrameNanos { nanos ->
val scale = Motion.scale
if (scale == 0f) return@withFrameNanos
val settled = clock.intro >= END && clock.ball >= IMPACT + REVEAL_MS && !clock.poked
if (settled && last >= 0 && !IdleFrames.due(nanos)) return@withFrameNanos
val now = nanos / 1_000_000L
val dt = if (last < 0) 0f else min(50f, (now - last).toFloat()) / scale.coerceAtLeast(0.01f)
last = now
clock.intro += dt
clock.wall += dt
@@ -117,34 +122,41 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
val before = clock.ball
clock.ball += dt
var x = clock.at.x + vx * dt / 1000f
var y = clock.at.y + vy * dt / 1000f
var x = clock.at.x
var y = clock.at.y
val hw = f.ball
val hh = f.ball
if (x - hw < 0f) { x = hw; vx = abs(vx) }
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
if (y - hh < 0f) { y = hh; vy = abs(vy) }
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
keepOff?.inflate(clearance)?.let { r ->
val nearX = x.coerceIn(r.left, r.right)
val nearY = y.coerceIn(r.top, r.bottom)
val gapX = x - nearX
val gapY = y - nearY
val gap = hypot(gapX, gapY)
if (gap in 0.0001f..f.ball) {
val nx = gapX / gap
val ny = gapY / gap
x = nearX + nx * f.ball
y = nearY + ny * f.ball
val into = vx * nx + vy * ny
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
} else if (gap <= 0.0001f) {
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
var left = dt
do {
val step = min(50f, left)
left -= step
x += vx * step / 1000f
y += vy * step / 1000f
if (x - hw < 0f) { x = hw; vx = abs(vx) }
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
if (y - hh < 0f) { y = hh; vy = abs(vy) }
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
keepOff?.inflate(clearance)?.let { r ->
val nearX = x.coerceIn(r.left, r.right)
val nearY = y.coerceIn(r.top, r.bottom)
val gapX = x - nearX
val gapY = y - nearY
val gap = hypot(gapX, gapY)
if (gap in 0.0001f..f.ball) {
val nx = gapX / gap
val ny = gapY / gap
x = nearX + nx * f.ball
y = nearY + ny * f.ball
val into = vx * nx + vy * ny
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
} else if (gap <= 0.0001f) {
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
}
}
}
} while (left > 0f)
clock.at = Offset(x, y)
if (before < IMPACT && clock.ball >= IMPACT) {
@@ -333,7 +333,7 @@ class DrawerActions(
val onInputSelection: (com.droiddeck.launcher.input.InputRole?) -> Unit = {},
val onGestureSettings: () -> Unit = {},
val touchActive: String = "",
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
val directHoldBehavior: String = MOUSE_BEHAVIOR_NONE,
val onDirectHoldBehavior: (String) -> Unit = {},
val onFexPreset: (String) -> Unit,
val onUpscaler: (Int) -> Unit = {},
@@ -82,7 +82,18 @@ import kotlinx.coroutines.withContext
private const val WALL_MIN_GAMES = 4
private const val WALL_DISTINCT = 40
private const val DRIFT_STEP_NS = 15_000_000L
private const val IDLE_FRAME_NS = 30_000_000L
internal object IdleFrames {
private var shown = 0L
fun due(nanos: Long): Boolean {
if (nanos == shown) return true
if (nanos - shown < IDLE_FRAME_NS) return false
shown = nanos
return true
}
}
@Composable
internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
@@ -281,7 +292,7 @@ internal fun TiltedWall(
var shown = 0L
while (true) withFrameNanos { now ->
if (shown == 0L) shown = now
else if (now - shown >= DRIFT_STEP_NS) {
else if (IdleFrames.due(now)) {
drift.floatValue = ((drift.floatValue + (now - shown) / (period.value * 1_000_000.0 * Motion.scale)) % 1.0).toFloat()
shown = now
}
+17 -7
View File
@@ -5,7 +5,6 @@
use std::collections::{HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;
@@ -18,6 +17,7 @@ use super::net;
use super::zip::{self, Entry};
use crate::amazon::install::check::{free_bytes, space_problem};
use crate::amazon::install::{Events, ReplaceGate, Stop};
use crate::grow_write::{holes_supported, is_cancel, GrowFront};
use crate::fetch_core::{distinct_host_count, run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
pub const LEDGER: &str = ".droiddeck-ea-files";
@@ -37,6 +37,7 @@ struct Split {
file: Mutex<Option<File>>,
received: Vec<AtomicU64>,
left: AtomicUsize,
front: GrowFront,
}
#[derive(Clone, Copy)]
@@ -483,9 +484,16 @@ impl Placer<'_> {
let old = split.received[part].swap(0, Ordering::Relaxed);
self.in_flight.fetch_sub(old, Ordering::Relaxed);
}
handle
.write_all_at(data, start + offset)
.map_err(|e| SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path))))?;
split
.front
.write_all_at(handle, start + offset, data, self.stop)
.map_err(|e| {
if is_cancel(&e) {
SinkError::Retry(format!("{}: cancelled", job.path))
} else {
SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path)))
}
})?;
drop(file);
split.received[part].fetch_add(data.len() as u64, Ordering::Relaxed);
self.in_flight.fetch_add(data.len() as u64, Ordering::Relaxed);
@@ -698,6 +706,7 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
let host = origin(&req.url);
let works = works(&remote, req.part_bytes);
let holes = holes_supported(&req.game_dir);
let splits: Vec<Option<Split>> = remote
.iter()
.enumerate()
@@ -711,6 +720,7 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
file: Mutex::new(None),
received: (0..parts).map(|_| AtomicU64::new(0)).collect(),
left: AtomicUsize::new(parts),
front: GrowFront::new(holes),
}
})
})
@@ -797,13 +807,13 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
return Err(Stop::Failed(message));
}
if !placed_all {
if cancel.load(Ordering::SeqCst) {
return Err(Stop::Cancelled);
}
if let Some(error) = outcome.as_ref().and_then(|o| o.error.clone()) {
ev.log(&format!("download failed: {error}"));
return Err(Stop::Failed("A file failed to download".into()));
}
if cancel.load(Ordering::SeqCst) {
return Err(Stop::Cancelled);
}
return Err(Stop::Failed("The download ended before every file was written".into()));
}
@@ -21,7 +21,14 @@ fn rejects_third_party_managed_install_before_manifest_parsing() {
}
}
fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>) -> String {
#[derive(Default)]
struct Misses {
seen: AtomicUsize,
cancel_at: usize,
cancel: Arc<AtomicBool>,
}
fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>, misses: Arc<Misses>) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let files = Arc::new(files);
@@ -30,13 +37,14 @@ fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>) -> String {
let Ok(stream) = stream else { continue };
let files = Arc::clone(&files);
let hits = Arc::clone(&hits);
std::thread::spawn(move || answer(stream, &files, &hits));
let misses = Arc::clone(&misses);
std::thread::spawn(move || answer(stream, &files, &hits, &misses));
}
});
format!("http://{addr}")
}
fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &AtomicUsize) {
fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &AtomicUsize, misses: &Misses) {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut first = String::new();
if reader.read_line(&mut first).is_err() {
@@ -54,7 +62,13 @@ fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &Atomic
hits.fetch_add(1, Ordering::Relaxed);
let (status, body) = match files.get(&path) {
Some(b) => ("200 OK", b.clone()),
None => ("404 Not Found", Vec::new()),
None => {
if misses.seen.fetch_add(1, Ordering::SeqCst) + 1 == misses.cancel_at {
std::thread::sleep(std::time::Duration::from_millis(300));
misses.cancel.store(true, Ordering::SeqCst);
}
("404 Not Found", Vec::new())
}
};
let head = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
let _ = stream.write_all(head.as_bytes());
@@ -106,6 +120,10 @@ fn pattern(seed: u8, len: usize) -> Vec<u8> {
}
fn fixture() -> Fixture {
fixture_missing(false, Arc::new(Misses::default()))
}
fn fixture_missing(last_chunk: bool, misses: Arc<Misses>) -> Fixture {
let mut c1 = chunk(1, 4096);
let mut c2 = chunk(2, 2048);
let mut c3 = chunk(3, 1000);
@@ -168,10 +186,13 @@ fn fixture() -> Fixture {
let mut served = HashMap::new();
served.insert("/Builds/x/test.manifest".to_string(), manifest_bytes);
for (info, data) in [(&c1, &d1), (&c2, &d2), (&c3, &d3)] {
if last_chunk && info.guid == c3.guid {
continue;
}
served.insert(format!("/Builds/x/{}", parsed.chunk_path(info)), encode(data, true));
}
let hits = Arc::new(AtomicUsize::new(0));
let base = serve(served, Arc::clone(&hits));
let base = serve(served, Arc::clone(&hits), misses);
Fixture {
base,
hits,
@@ -273,6 +294,40 @@ fn a_cancelled_run_reports_cancel() {
let _ = fs::remove_dir_all(&game);
}
fn kept_c(fx: &Fixture, game: &Path) -> bool {
let c = &fx.expected[1].1;
let partial = game.join(staging::DIR_NAME).join(staging::partial_name("b/c.bin", c.len() as u64, Some(Sha1::digest(c).into())));
partial.is_file() && staging::list_path(&partial).is_file()
}
#[test]
fn a_chunk_that_cannot_be_fetched_fails_and_keeps_written_parts() {
let misses = Arc::new(Misses::default());
let fx = fixture_missing(true, Arc::clone(&misses));
let game = temp_game("fetch-fail");
let cancel = AtomicBool::new(false);
let err = run(&request(&fx, &game), &cancel, &Recorder::default()).unwrap_err();
assert!(matches!(&err, Stop::Failed(m) if m.starts_with("Download failed: ")), "{err:?}");
assert_eq!(misses.seen.load(Ordering::SeqCst), crate::fetch_core::MAX_ITEM_ATTEMPTS as usize);
assert!(kept_c(&fx, &game));
let _ = fs::remove_dir_all(&game);
}
#[test]
fn a_cancel_during_the_last_fetch_attempt_reports_cancel_and_keeps_written_parts() {
let cancel = Arc::new(AtomicBool::new(false));
let last = crate::fetch_core::MAX_ITEM_ATTEMPTS as usize;
let misses = Arc::new(Misses { seen: AtomicUsize::new(0), cancel_at: last, cancel: Arc::clone(&cancel) });
let fx = fixture_missing(true, Arc::clone(&misses));
let game = temp_game("fetch-cancel");
let events = Recorder::default();
assert_eq!(run(&request(&fx, &game), &cancel, &events).unwrap_err(), Stop::Cancelled);
assert_eq!(misses.seen.load(Ordering::SeqCst), last);
assert!(events.logs.lock().unwrap().iter().any(|l| l.contains(&format!("failed after {last} attempts"))));
assert!(kept_c(&fx, &game));
let _ = fs::remove_dir_all(&game);
}
fn place_partial(fx: &Fixture, game: &Path, data: &[u8], list: &str) -> PathBuf {
let stage = staging::recover(game).unwrap();
let a = &fx.expected[0].1;
@@ -8,6 +8,7 @@ use std::time::{Duration, Instant};
use sha1::{Digest, Sha1};
use super::cache;
use crate::grow_write::{holes_supported, is_cancel, GrowFront};
use super::schedule::{PlanPart, Schedule, NONE};
use super::{staging, Events, Stop};
use crate::epic::chunk;
@@ -80,6 +81,7 @@ struct Coord {
struct Engine<'a> {
input: &'a EngineInput<'a>,
slots: Vec<Mutex<Slot>>,
fronts: Vec<GrowFront>,
coord: Mutex<Coord>,
wake: Condvar,
admitted: AtomicUsize,
@@ -95,6 +97,17 @@ struct Engine<'a> {
total_bytes: u64,
}
enum Halt {
Cancelled,
Failed(String),
}
impl From<String> for Halt {
fn from(message: String) -> Self {
Halt::Failed(message)
}
}
enum Source<'d> {
Memory(&'d [u8]),
Cache(PathBuf),
@@ -112,6 +125,13 @@ impl<'a> Engine<'a> {
message
}
fn sink_error(&self, halt: Halt) -> SinkError {
match halt {
Halt::Cancelled => SinkError::Retry("cancelled".into()),
Halt::Failed(message) => SinkError::Fatal(self.fail(message)),
}
}
fn cache_path(&self, producer: usize) -> PathBuf {
let p = &self.input.schedule.producers[producer];
let info = &self.input.manifest.chunks[p.chunk as usize];
@@ -158,7 +178,7 @@ impl<'a> Engine<'a> {
self.input.schedule.producers[fetch[at] as usize].anchor as usize + 1
}
fn write_use(&self, u: usize, source: &Source<'_>) -> Result<(), String> {
fn write_use(&self, u: usize, source: &Source<'_>) -> Result<(), Halt> {
let schedule = &self.input.schedule;
let f = schedule.use_file[u] as usize;
let j = u - schedule.file_start[f] as usize;
@@ -175,16 +195,22 @@ impl<'a> Engine<'a> {
let start = part.chunk_offset as usize;
let end = start + part.size as usize;
if end > data.len() {
return Err(format!("A chunk is too short for {}", file.path));
return Err(format!("A chunk is too short for {}", file.path).into());
}
let piece = &data[start..end];
let handle = self.slots[f].lock().expect("slot lock").file.clone();
let Some(handle) = handle else {
return Err(format!("internal: {} is not open", file.path));
return Err(format!("internal: {} is not open", file.path).into());
};
handle
.write_all_at(piece, part.file_offset)
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))?;
self.fronts[f]
.write_all_at(&handle, part.file_offset, piece, self.stop)
.map_err(|e| {
if is_cancel(&e) {
Halt::Cancelled
} else {
Halt::Failed(format!("Could not assemble or atomically replace {}: {e}", file.path))
}
})?;
self.written.fetch_add(piece.len() as u64, Ordering::Relaxed);
let complete = {
@@ -343,14 +369,18 @@ impl<'a> Engine<'a> {
}
};
let Some(f) = candidate else { continue };
if let Err(e) = self.admit(f) {
self.fail(e);
return;
match self.admit(f) {
Ok(()) => {}
Err(Halt::Cancelled) => return,
Err(Halt::Failed(e)) => {
self.fail(e);
return;
}
}
}
}
fn admit(&self, f: usize) -> Result<(), String> {
fn admit(&self, f: usize) -> Result<(), Halt> {
self.open_stage(f)?;
let schedule = &self.input.schedule;
let file = &self.input.files[f];
@@ -415,7 +445,7 @@ impl<'a> Engine<'a> {
out
};
for u in claims {
self.write_use(u, &Source::Memory(&data)).map_err(|e| SinkError::Fatal(self.fail(e)))?;
self.write_use(u, &Source::Memory(&data)).map_err(|h| self.sink_error(h))?;
}
Ok(0)
}
@@ -446,8 +476,10 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
cached[i] = true;
}
}
let holes = holes_supported(&input.stage_dir);
let engine = Engine {
input,
fronts: input.files.iter().map(|_| GrowFront::new(holes)).collect(),
slots: input
.files
.iter()
@@ -532,7 +564,7 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
}
ready
};
let outcome = std::thread::scope(|scope| {
let (outcome, cancelled) = std::thread::scope(|scope| {
let admitter = std::thread::Builder::new()
.name("epic-admit".into())
.spawn_scoped(scope, || {
@@ -541,7 +573,7 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
});
if let Err(e) = admitter {
engine.fail(format!("could not start the install thread: {e}"));
return None;
return (None, false);
}
let outcome = if items.is_empty() {
None
@@ -552,11 +584,9 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
let mut c = engine.coord.lock().expect("coord lock");
c.fetch_done = true;
}
if outcome.as_ref().is_some_and(|o| !o.ok()) {
stop.store(true, Ordering::SeqCst);
}
let cancelled = settle(outcome.as_ref().is_some_and(|o| !o.ok()), stop);
engine.wake.notify_all();
outcome
(outcome, cancelled)
});
let failure = engine.failure.lock().expect("failure lock").take().filter(|m| !m.is_empty());
@@ -593,16 +623,35 @@ fetches={} refetches={} peak_cache_mib={} hosts={}",
hosts.join(","),
));
ending(failure, complete, fetch_error, cancelled, stop.load(Ordering::SeqCst))?;
Ok(Stats { bytes_written: written, files_written: input.files.len() })
}
fn settle(fetch_failed: bool, stop: &AtomicBool) -> bool {
let cancelled = stop.load(Ordering::SeqCst);
if fetch_failed {
stop.store(true, Ordering::SeqCst);
}
cancelled
}
fn ending(
failure: Option<String>,
complete: bool,
fetch_error: Option<String>,
cancelled: bool,
stopped: bool,
) -> Result<(), Stop> {
if let Some(message) = failure {
return Err(Stop::Failed(message));
}
if complete {
return Ok(Stats { bytes_written: written, files_written: input.files.len() });
return Ok(());
}
if let Some(message) = fetch_error {
if let Some(message) = fetch_error.filter(|_| !cancelled) {
return Err(Stop::Failed(format!("Download failed: {}", tidy_fetch_error(&message))));
}
if stop.load(Ordering::SeqCst) {
if stopped {
return Err(Stop::Cancelled);
}
Err(Stop::Failed("The download ended before every file was written".into()))
@@ -704,4 +753,37 @@ mod tests {
assert_eq!(fs::read_to_string(staging::list_path(&kept)).unwrap(), "10\n20\n");
let _ = fs::remove_dir_all(&dir);
}
fn end(fetch_error: Option<&str>, stop: &AtomicBool) -> Result<(), Stop> {
let cancelled = settle(fetch_error.is_some(), stop);
ending(None, false, fetch_error.map(str::to_string), cancelled, stop.load(Ordering::SeqCst))
}
#[test]
fn a_cancel_during_the_last_fetch_attempt_ends_as_cancelled() {
let stop = AtomicBool::new(true);
assert!(matches!(end(Some("timed out"), &stop), Err(Stop::Cancelled)));
assert!(matches!(end(None, &stop), Err(Stop::Cancelled)));
}
#[test]
fn a_fetch_failure_without_a_cancel_ends_as_failed() {
let stop = AtomicBool::new(false);
match end(Some("timed out"), &stop) {
Err(Stop::Failed(message)) => assert!(message.starts_with("Download failed: ")),
_ => panic!("a fetch failure must be reported"),
}
assert!(stop.load(Ordering::SeqCst));
let idle = AtomicBool::new(false);
assert!(matches!(end(None, &idle), Err(Stop::Failed(_))));
}
#[test]
fn a_write_failure_or_a_finished_install_wins_over_a_cancel() {
assert!(matches!(
ending(Some("disk full".into()), false, None, true, true),
Err(Stop::Failed(message)) if message == "disk full"
));
assert!(ending(None, true, Some("late".into()), true, true).is_ok());
}
}
+293
View File
@@ -0,0 +1,293 @@
use std::fs::{self, File, OpenOptions};
use std::io;
use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt};
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
pub const FILL_STEP: usize = 4 * 1024 * 1024;
pub const DIRECT_GAP: u64 = 4 * 1024 * 1024;
const PROBE_GAP: u64 = 1024 * 1024;
static PROBE_SEQ: AtomicU64 = AtomicU64::new(0);
const PROBE_PREFIX: &str = ".droiddeck-hole-probe-";
pub fn is_cancel(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::Interrupted
}
pub fn holes_supported(dir: &Path) -> bool {
let probe = dir.join(format!(
"{PROBE_PREFIX}{}-{}",
std::process::id(),
PROBE_SEQ.fetch_add(1, Ordering::Relaxed)
));
let Ok(file) = OpenOptions::new()
.write(true)
.create_new(true)
.custom_flags(libc::O_NOFOLLOW)
.open(&probe)
else {
return true;
};
let written = file.write_all_at(&[0u8], PROBE_GAP - 1);
drop(file);
let measured = written.and_then(|_| fs::symlink_metadata(&probe));
let _ = fs::remove_file(&probe);
measured
.map(|meta| meta.blocks().saturating_mul(512) < PROBE_GAP)
.unwrap_or(true)
}
pub struct GrowFront {
holes: bool,
size: AtomicU64,
known: AtomicBool,
fill: Mutex<()>,
}
impl GrowFront {
pub fn new(holes: bool) -> Self {
GrowFront {
holes,
size: AtomicU64::new(0),
known: AtomicBool::new(false),
fill: Mutex::new(()),
}
}
pub fn reset(&self) {
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
self.known.store(false, Ordering::Release);
self.size.store(0, Ordering::Release);
}
pub fn write_all_at(
&self,
file: &File,
offset: u64,
data: &[u8],
cancel: &AtomicBool,
) -> io::Result<()> {
let end = offset.saturating_add(data.len() as u64);
if self.holes
|| (self.known.load(Ordering::Acquire) && end <= self.size.load(Ordering::Acquire))
{
return file.write_all_at(data, offset);
}
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
let mut size = self.current(file)?;
if offset > size.saturating_add(DIRECT_GAP) {
self.fill_to(file, &mut size, offset - DIRECT_GAP, cancel)?;
}
if let Err(err) = file.write_all_at(data, offset) {
self.known.store(false, Ordering::Release);
return Err(err);
}
self.publish(size.max(end));
Ok(())
}
pub fn extend_to(&self, file: &File, len: u64, cancel: &AtomicBool) -> io::Result<()> {
if self.holes {
return file.set_len(len);
}
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
let mut size = self.current(file)?;
if size < len {
self.fill_to(file, &mut size, len, cancel)?;
}
Ok(())
}
fn current(&self, file: &File) -> io::Result<u64> {
if self.known.load(Ordering::Acquire) {
Ok(self.size.load(Ordering::Acquire))
} else {
Ok(file.metadata()?.len())
}
}
fn fill_to(
&self,
file: &File,
size: &mut u64,
target: u64,
cancel: &AtomicBool,
) -> io::Result<()> {
let zeros = vec![0u8; FILL_STEP];
while *size < target {
if cancel.load(Ordering::Relaxed) {
self.publish(*size);
return Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
}
let step = ((target - *size) as usize).min(FILL_STEP);
if let Err(err) = file.write_all_at(&zeros[..step], *size) {
self.known.store(false, Ordering::Release);
return Err(err);
}
*size += step as u64;
self.publish(*size);
}
Ok(())
}
fn publish(&self, size: u64) {
self.size.store(size, Ordering::Release);
self.known.store(true, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
"grow-write-{tag}-{}-{}",
std::process::id(),
PROBE_SEQ.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&dir).unwrap();
dir
}
fn open(path: &Path) -> File {
OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(path)
.unwrap()
}
#[test]
fn far_write_fills_the_gap_in_bounded_steps_and_keeps_data() {
let dir = temp_dir("far");
let path = dir.join("f.bin");
let file = open(&path);
let front = GrowFront::new(false);
let cancel = AtomicBool::new(false);
front.write_all_at(&file, 0, b"head", &cancel).unwrap();
let far = 3 * FILL_STEP as u64 + 123;
front.write_all_at(&file, far, b"tail", &cancel).unwrap();
front.write_all_at(&file, 100, b"mid", &cancel).unwrap();
let bytes = fs::read(&path).unwrap();
assert_eq!(bytes.len() as u64, far + 4);
assert_eq!(&bytes[0..4], b"head");
assert_eq!(&bytes[100..103], b"mid");
assert_eq!(&bytes[far as usize..], b"tail");
assert!(bytes[103..far as usize].iter().all(|b| *b == 0));
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn cancel_stops_a_gap_fill_between_steps() {
let dir = temp_dir("cancel");
let path = dir.join("f.bin");
let file = open(&path);
let front = GrowFront::new(false);
let cancel = AtomicBool::new(true);
let err = front
.write_all_at(&file, 8 * FILL_STEP as u64, b"x", &cancel)
.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::Interrupted);
assert_eq!(fs::metadata(&path).unwrap().len(), 0);
cancel.store(false, Ordering::Relaxed);
front.write_all_at(&file, 10, b"ok", &cancel).unwrap();
assert_eq!(&fs::read(&path).unwrap()[10..], b"ok");
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn concurrent_writers_never_lose_data_to_the_fill() {
let dir = temp_dir("race");
let path = dir.join("f.bin");
let file = Arc::new(open(&path));
let front = Arc::new(GrowFront::new(false));
let piece = 64 * 1024u64;
let count = 256u64;
let mut order: Vec<u64> = (0..count).collect();
order.reverse();
let lanes: Vec<Vec<u64>> = (0..4)
.map(|lane| order.iter().copied().filter(|i| i % 4 == lane).collect())
.collect();
let handles: Vec<_> = lanes
.into_iter()
.map(|lane| {
let file = Arc::clone(&file);
let front = Arc::clone(&front);
std::thread::spawn(move || {
let cancel = AtomicBool::new(false);
for i in lane {
let data = vec![(i % 251) as u8 + 1; piece as usize];
front.write_all_at(&file, i * piece, &data, &cancel).unwrap();
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
let bytes = fs::read(&path).unwrap();
assert_eq!(bytes.len() as u64, piece * count);
for i in 0..count {
let start = (i * piece) as usize;
assert!(bytes[start..start + piece as usize]
.iter()
.all(|b| *b == (i % 251) as u8 + 1));
}
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn extend_to_grows_in_steps_and_never_shrinks() {
let dir = temp_dir("extend");
let path = dir.join("f.bin");
let file = open(&path);
let front = GrowFront::new(false);
let cancel = AtomicBool::new(false);
front.write_all_at(&file, 0, b"data", &cancel).unwrap();
let len = 2 * FILL_STEP as u64 + 7;
front.extend_to(&file, len, &cancel).unwrap();
front.extend_to(&file, 2, &cancel).unwrap();
let bytes = fs::read(&path).unwrap();
assert_eq!(bytes.len() as u64, len);
assert_eq!(&bytes[0..4], b"data");
assert!(bytes[4..].iter().all(|b| *b == 0));
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn hole_capable_storage_writes_directly() {
let dir = temp_dir("holes");
let path = dir.join("f.bin");
let file = open(&path);
let front = GrowFront::new(true);
let cancel = AtomicBool::new(true);
front
.write_all_at(&file, 8 * FILL_STEP as u64, b"x", &cancel)
.unwrap();
assert_eq!(fs::metadata(&path).unwrap().len(), 8 * FILL_STEP as u64 + 1);
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn probe_leaves_nothing_behind() {
let dir = temp_dir("probe");
let other = dir.join(format!("{PROBE_PREFIX}game-file"));
fs::write(&other, b"kept").unwrap();
let _ = holes_supported(&dir);
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
assert_eq!(fs::read(&other).unwrap(), b"kept");
fs::remove_file(&other).unwrap();
fs::remove_dir(&dir).unwrap();
}
}
+1
View File
@@ -9,6 +9,7 @@ pub mod epic;
pub mod fetch_core;
pub mod fetch_tuning;
pub mod gog;
pub mod grow_write;
pub mod md5_small;
pub mod priority;
pub mod steam;
@@ -9,6 +9,7 @@
//! read back and checked before anything is fetched.
use crate::fetch_core::{run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
use crate::grow_write::{holes_supported, GrowFront};
use crate::steam::cdn;
use crate::steam::content_manifest::{ChunkData, ContentManifest};
use crate::steam::depot_chunk::{process_depot_chunk, steam_adler_hash};
@@ -110,6 +111,7 @@ struct FileSlot {
size: u64,
path: PathBuf,
mode: u32,
front: GrowFront,
}
struct DepotFiles {
@@ -155,17 +157,23 @@ impl DepotFiles {
}
}
fn write(&self, file_idx: usize, offset: u64, data: &[u8]) -> Result<(), String> {
fn write(
&self,
file_idx: usize,
offset: u64,
data: &[u8],
cancel: &AtomicBool,
) -> Result<(), String> {
let file = self.acquire(file_idx)?;
pwrite_all_at(&file, offset, data).map_err(|err| {
let slot = &self.slots[file_idx];
slot.front.write_all_at(&file, offset, data, cancel).map_err(|err| {
format!(
"write '{}' at {offset}: {err}",
self.slots[file_idx].path.display()
)
})?;
let slot = &self.slots[file_idx];
if slot.remaining.fetch_sub(1, Ordering::AcqRel) == 1 {
finalize(&file, slot)?;
finalize(&file, slot, cancel)?;
drop(file);
self.release(file_idx);
} else if self.open_count.load(Ordering::Relaxed) > MAX_OPEN_FILES {
@@ -176,7 +184,7 @@ impl DepotFiles {
}
/// Files with nothing left to fetch (zero chunks, or every chunk already correct on disk).
fn finalize_untouched(&self, idx: usize) -> Result<(), String> {
fn finalize_untouched(&self, idx: usize, cancel: &AtomicBool) -> Result<(), String> {
let slot = &self.slots[idx];
make_parent_dirs(&self.root, &slot.path)?;
check_file_target(&self.root, &slot.path)?;
@@ -188,6 +196,11 @@ impl DepotFiles {
.map_err(|err| format!("open '{}': {err}", slot.path.display()))?;
set_file_mode(&file, &slot.path, slot.mode)?;
let current = file.metadata().map(|m| m.len()).unwrap_or(u64::MAX);
if current < slot.size {
slot.front
.extend_to(&file, slot.size, cancel)
.map_err(|err| format!("extend '{}': {err}", slot.path.display()))?;
}
if current != slot.size {
file.set_len(slot.size)
.map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?;
@@ -196,7 +209,10 @@ impl DepotFiles {
}
}
fn finalize(file: &File, slot: &FileSlot) -> Result<(), String> {
fn finalize(file: &File, slot: &FileSlot, cancel: &AtomicBool) -> Result<(), String> {
slot.front
.extend_to(file, slot.size, cancel)
.map_err(|err| format!("extend '{}': {err}", slot.path.display()))?;
file.set_len(slot.size)
.map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?;
file.sync_all()
@@ -207,6 +223,7 @@ struct ChunkSink<'a> {
chunks: &'a [UniqueChunk],
files: &'a DepotFiles,
depot_key: &'a [u8],
cancel: &'a AtomicBool,
}
impl FetchSink for ChunkSink<'_> {
@@ -225,7 +242,12 @@ impl FetchSink for ChunkSink<'_> {
let mut credited = 0u64;
for target in &chunk.targets {
self.files
.write(target.file_idx as usize, target.offset, &processed.data)
.write(
target.file_idx as usize,
target.offset,
&processed.data,
self.cancel,
)
.map_err(SinkError::Fatal)?;
credited += processed.data.len() as u64;
}
@@ -276,6 +298,7 @@ fn prepare(
}
};
let holes = holes_supported(&root);
let mut slots = Vec::with_capacity(manifest.files.len());
let mut existing = Vec::with_capacity(manifest.files.len());
for file in &manifest.files {
@@ -297,6 +320,7 @@ fn prepare(
} else {
0o644
},
front: GrowFront::new(holes),
});
}
@@ -354,7 +378,10 @@ fn prepare(
continue;
}
let mut remaining = 0usize;
for (chunk_idx, chunk) in file.chunks.iter().enumerate() {
let mut by_offset: Vec<usize> = (0..file.chunks.len()).collect();
by_offset.sort_by_key(|&idx| file.chunks[idx].offset);
for chunk_idx in by_offset {
let chunk = &file.chunks[chunk_idx];
if verified[file_idx].get(chunk_idx).copied().unwrap_or(false) {
bytes_verified += chunk.cb_original as u64;
continue;
@@ -393,7 +420,13 @@ fn prepare(
if is_regular(file.flags, &file.linktarget)
&& files.slots[idx].remaining.load(Ordering::Relaxed) == 0
{
if let Err(err) = files.finalize_untouched(idx) {
if let Err(err) = files.finalize_untouched(idx, cancel) {
if cancel.load(Ordering::Relaxed) {
return Err(DepotWriteOutcome {
cancelled: true,
..Default::default()
});
}
return Err(DepotWriteOutcome::fail(err));
}
}
@@ -449,6 +482,7 @@ pub fn write_depot(
chunks: &chunks,
files: &files,
depot_key: request.depot_key,
cancel,
};
let depot_id = manifest.metadata.depot_id;
let done_before = AtomicU64::new(bytes_verified);
@@ -676,12 +710,6 @@ fn set_file_mode(_file: &File, _path: &Path, _mode: u32) -> Result<(), String> {
Ok(())
}
#[cfg(unix)]
fn pwrite_all_at(file: &File, offset: u64, data: &[u8]) -> std::io::Result<()> {
use std::os::unix::fs::FileExt;
file.write_all_at(data, offset)
}
#[cfg(unix)]
fn pread_exact_at(file: &File, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
use std::os::unix::fs::FileExt;
@@ -766,6 +794,7 @@ mod tests {
size: 10,
path: path.clone(),
mode: 0o644,
front: GrowFront::new(true),
}];
let root = fs::canonicalize(&dir).unwrap();
let flags = verify_existing(&manifest, &slots, &[10], &root, 2, &AtomicBool::new(false));
@@ -808,6 +837,44 @@ mod tests {
}
}
#[test]
fn queues_each_files_chunks_in_offset_order() {
let dir = std::env::temp_dir().join(format!(
"droiddeck_steam_order_{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let key = [5u8; 32];
let manifest = ContentManifest {
files: vec![FileMapping {
filename: "big.pak".into(),
size: 15,
chunks: vec![chunk(b"three", 10), chunk(b"first", 0), chunk(b"other", 5)],
..Default::default()
}],
..Default::default()
};
let request = DepotWriteRequest {
manifest: &manifest,
depot_key: &key,
servers: &[],
target_dir: &dir,
ca_bundle_path: "",
max_workers: 1,
process_workers: 1,
};
let prepared = prepare(&request, &AtomicBool::new(false)).unwrap();
let offsets: Vec<u64> = prepared
.chunks
.iter()
.map(|c| c.targets[0].offset)
.collect();
assert_eq!(offsets, vec![0, 5, 10]);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn writes_in_place_dedupes_chunks_and_resumes_from_disk() {
let dir = std::env::temp_dir().join(format!(
@@ -867,6 +934,7 @@ mod tests {
chunks: &prepared.chunks,
files: &prepared.files,
depot_key: &key,
cancel: &cancel,
};
let item = |id: u64| FetchItem {
id,
@@ -886,6 +954,7 @@ mod tests {
chunks: &wrong,
files: &prepared.files,
depot_key: &key,
cancel: &cancel,
};
assert!(matches!(
wrong_sink.process(&item(0), encrypted_chunk(&key, b"HELLO")),
@@ -145,4 +145,15 @@ class AddedGamesCandidatesTest {
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
assertEquals("My Game [Repack]", AddedGames.scan(app).single().name)
}
@Test fun linksAndFoldersNamedLikeAnExeAreNotCandidates() {
val elsewhere = tmp.newFolder("Elsewhere")
exe(elsewhere, "Other.exe")
val game = tmp.newFolder("Linked")
exe(game, "bin/Linked.exe")
File(game, "Folder.exe").mkdirs()
java.nio.file.Files.createSymbolicLink(File(game, "other").toPath(), elsewhere.toPath())
java.nio.file.Files.createSymbolicLink(File(game, "Alias.exe").toPath(), File(elsewhere, "Other.exe").toPath())
assertEquals(listOf("bin/Linked.exe"), names(game))
}
}
@@ -0,0 +1,213 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.util.Collections
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
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 AddedGamesSessionListingTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@After fun restore() {
AddedGamesPublisher.now = false
AddedGamesPublisher.live = SteamLiveShortcuts::sync
SessionState.running = false
SessionState.stopRequested = false
SessionState.sessionId = null
SessionState.phase = SessionPhase.IDLE
}
private val stale = """[{"name":"Old","exe":"/root/Games/Old/Old.exe","folder":"/root/Games/Old","dir":"/root/Games/Old","appid":2147483649,"seen":0}]"""
private fun gamesFolder(vararg names: String): File {
val games = tmp.newFolder("PC")
for (n in names) File(games, "$n/$n.exe").apply { parentFile!!.mkdirs() }.writeText("game")
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
return games
}
private fun session(phase: SessionPhase) {
SessionState.sessionId = "session-test"
SessionState.stopRequested = false
SessionState.phase = phase
SessionState.running = true
}
private fun until(what: String, check: () -> Boolean) {
val end = System.currentTimeMillis() + 30_000
while (!check()) {
assertTrue(what, System.currentTimeMillis() < end)
Thread.sleep(20)
}
}
private fun scanLock(): Any =
AddedGames::class.java.getDeclaredField("scanning").apply { isAccessible = true }.get(null)!!
private fun refreshes() = Thread.getAllStackTraces().keys.filter { it.name == "added-games-refresh" }
@Test fun aSessionStartsFromTheLastListingWhileTheLibraryScanHoldsTheLock() {
gamesFolder("Alpha")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val done = CountDownLatch(1)
var returned: File? = null
var seen = ""
synchronized(scanLock()) {
Thread {
returned = AddedGamesPublisher.sessionListing(app)
seen = listing.readText()
done.countDown()
}.start()
assertTrue("the session start waited for the library scan", done.await(5, TimeUnit.SECONDS))
}
assertEquals(listing.path, returned!!.path)
assertEquals(stale, seen)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
val fresh = listing.readText()
assertTrue(fresh.contains("\"Alpha\""))
assertFalse(fresh.contains("\"Old\""))
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
}
@Test fun aFirstSessionScansBeforeStarting() {
gamesFolder("Alpha")
AddedGamesPublisher.now = false
val listing = AddedGames.listingFile(app)
listing.delete()
assertEquals(listing.path, AddedGamesPublisher.sessionListing(app).path)
assertTrue(listing.readText().contains("\"Alpha\""))
assertTrue(refreshes().isEmpty())
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
}
@Test fun aListingThatCannotBeReplacedKeepsTheOldOne() {
val listing = AddedGames.listingFile(app).apply { parentFile?.mkdirs() }
listing.writeText("[]")
val blocked = File(listing.parentFile, listing.name + ".part").apply { mkdirs() }
gamesFolder("Alpha")
AddedGames.writeListing(app, AddedGames.scan(app))
assertEquals("[]", listing.readText())
assertFalse(blocked.exists())
}
@Test fun anUnreadableListingIsRescannedBeforeStarting() {
gamesFolder("Alpha")
AddedGamesPublisher.now = false
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText("[{\"name\":") }
AddedGamesPublisher.sessionListing(app)
assertTrue(listing.readText().contains("\"Alpha\""))
assertTrue(refreshes().isEmpty())
}
@Test fun aGameRemovedWhileTheClientStartsIsNotAddedToIt() {
val games = gamesFolder("Alpha", "Beta")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val delivered = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
session(SessionPhase.STARTING_STEAM)
AddedGamesPublisher.sessionListing(app)
until("the refresh did not write the listing") { listing.readText().contains("\"Beta\"") }
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, true)
SessionState.phase = SessionPhase.READY
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf("Alpha"), delivered.toList())
}
@Test fun aDeliveryTheClientRefusesIsRetriedUntilItIsTaken() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val attempts = Collections.synchronizedList(ArrayList<List<String>>())
AddedGamesPublisher.live = { _, found, include -> attempts.add(found.filter(include).map { it.name }); attempts.size > 1 }
session(SessionPhase.READY)
AddedGamesPublisher.sessionListing(app)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf(listOf("Alpha"), listOf("Alpha")), attempts.toList())
}
@Test fun anEndedSessionStopsTheRetries() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val attempts = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, _ -> attempts.addAll(found.map { it.name }); SessionState.running = false; false }
session(SessionPhase.READY)
AddedGamesPublisher.sessionListing(app)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf("Alpha"), attempts.toList())
}
@Test fun aDeliveryQueuedForAnEndedSessionIsNotSentToTheNextOne() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val delivered = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
session(SessionPhase.READY)
val first = CountDownLatch(1)
val firstHeld = CountDownLatch(1)
val second = CountDownLatch(1)
val secondHeld = CountDownLatch(1)
AddedGamesPublisher.later(app) { firstHeld.countDown(); first.await() }
try {
assertTrue(firstHeld.await(30, TimeUnit.SECONDS))
AddedGamesPublisher.sessionListing(app)
val refresh = refreshes().single()
until("the refresh did not wait for its scan") { refresh.state == Thread.State.WAITING }
AddedGamesPublisher.later(app) { secondHeld.countDown(); second.await() }
first.countDown()
assertTrue(secondHeld.await(30, TimeUnit.SECONDS))
until("the refresh did not queue its delivery") {
refresh.state == Thread.State.WAITING && refresh.stackTrace.any { it.methodName == "deliver" }
}
SessionState.sessionId = "session-next"
} finally {
first.countDown()
second.countDown()
}
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertTrue(delivered.isEmpty())
}
@Test fun theRefreshWaitsForEarlierPublicationsBeforeWriting() {
gamesFolder("Alpha")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val hold = CountDownLatch(1)
val holding = CountDownLatch(1)
AddedGamesPublisher.later(app) { holding.countDown(); hold.await() }
try {
assertTrue(holding.await(30, TimeUnit.SECONDS))
AddedGamesPublisher.sessionListing(app)
val refresh = refreshes().single()
until("the refresh neither finished nor waited") { refresh.state == Thread.State.WAITING || !refresh.isAlive }
assertTrue("the refresh wrote while an earlier publication was running", refresh.isAlive)
assertEquals(stale, listing.readText())
} finally {
hold.countDown()
}
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertTrue(listing.readText().contains("\"Alpha\""))
}
}
@@ -29,7 +29,7 @@ class DirectTouchHoldTest {
override fun move(pointerId: Int, x: Float, y: Float) { touches += "move $pointerId at $x,$y" }
override fun up(pointerId: Int, x: Float, y: Float) { touches += "up $pointerId at $x,$y" }
override fun cancel() { touches += "cancel" }
}).also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
}).also { it.configure(TouchGestureConfig(longPressDelay = 500, directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)) }
@Test fun holdClicksRightWithoutTouchingTheGame() {
touch(MotionEvent.ACTION_DOWN)
@@ -87,18 +87,49 @@ class DirectTouchHoldTest {
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 44.0,30.0"), touches)
}
@Test fun stillHoldClicksRightWithTheDefaultConfig() {
@Test fun stillHoldStaysHeldWithTheDefaultConfig() {
hold.configure(TouchGestureConfig())
touch(MotionEvent.ACTION_DOWN)
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
advance(2000)
touch(MotionEvent.ACTION_MOVE)
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
touch(MotionEvent.ACTION_UP)
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
assertTrue(buttons.isEmpty())
}
@Test fun aSavedRightClickChoiceIsKept() {
val saved = TouchGestureConfig.fromJson(
TouchGestureConfig(directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK).toJson())
assertEquals(TouchGestureConfig.MOUSE_BEHAVIOR_CLICK, saved.directHoldBehavior)
hold.configure(saved)
touch(MotionEvent.ACTION_DOWN)
advance(2000)
touch(MotionEvent.ACTION_UP)
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
assertTrue(touches.isEmpty())
}
@Test fun aHeldTouchLiftsAtOnce() {
hold.configure(TouchGestureConfig())
touch(MotionEvent.ACTION_DOWN)
advance(80)
touch(MotionEvent.ACTION_UP)
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
}
@Test fun aShortTapStaysPressedLongEnoughToBeSeen() {
hold.configure(TouchGestureConfig())
touch(MotionEvent.ACTION_DOWN)
advance(10)
touch(MotionEvent.ACTION_UP)
advance(39)
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
advance(1)
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
}
@Test fun longPressFollowsTheConfiguredDelay() {
hold.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 800))
hold.configure(TouchGestureConfig(longPressDelay = 800, directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
touch(MotionEvent.ACTION_DOWN)
advance(700)
assertTrue(buttons.isEmpty())
@@ -152,7 +152,8 @@ class SessionGestureRoutingTest {
@Test fun pausingCancelsPendingHoldsInBothTouchModes() {
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) {
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E",
directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
val now = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
@@ -167,7 +168,8 @@ class SessionGestureRoutingTest {
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) {
keys.clear()
directButtons.clear()
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E",
directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
val now = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
@@ -36,7 +36,43 @@ class GameEnvironmentStoreTest {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.remove("logs")
.remove("gameDebugLogsEnabled")
.remove("gameCpus")
.commit()
listOf("game-environment.json.new", "game-cores.new").forEach { File(guest.parentFile, it).delete() }
}
@Test fun gameCoresChangedInSettingsReachTheGuestAtOnce() {
val live = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-cores")
val all = com.droiddeck.launcher.core.CpuCores.all
SessionPrefs.setGameCpus(context, all.last().toString())
assertEquals("${all.last()}\n", live.readText())
SessionPrefs.setGameCpus(context, com.droiddeck.launcher.core.CpuCores.format(all.toSet()))
assertEquals("\n", live.readText())
}
@Config(sdk = [34])
@Test fun gameCoresStillReachTheGuestWhenTheRestOfTheEnvironmentCannotBeWritten() {
val dir = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck")
val last = com.droiddeck.launcher.core.CpuCores.all.last()
assertTrue(File(dir, "game-environment.json.new").mkdirs())
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putString("gameCpus", last.toString()).commit()
assertTrue(runCatching { GameEnvironmentStore.publish(context) }.isFailure)
assertEquals("$last\n", File(dir, "game-cores").readText())
}
@Test fun gameCoresThatCannotBeWrittenLeaveNoOlderValueForTheGuest() {
val dir = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck")
val all = com.droiddeck.launcher.core.CpuCores.all
SessionPrefs.setGameCpus(context, all.last().toString())
assertTrue(File(dir, "game-cores.new").mkdirs())
SessionPrefs.setGameCpus(context, all.first().toString())
assertFalse(File(dir, "game-cores").exists())
}
@Test fun gameDebugLogsAreOffByDefault() {
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamLiveShortcutsSyncTest {
@Test fun everyGameKnownOrAddedIsDelivered() {
assertTrue(SteamLiveShortcuts.synced("""{"added":2,"missed":0}"""))
assertTrue(SteamLiveShortcuts.synced("""{"added":0,"missed":0}"""))
}
@Test fun aGameTheClientRefusedIsNotDelivered() {
assertFalse(SteamLiveShortcuts.synced("""{"added":1,"missed":1}"""))
assertFalse(SteamLiveShortcuts.synced("""{"added":0,"missed":3}"""))
}
@Test fun noAnswerIsNotDelivered() {
assertFalse(SteamLiveShortcuts.synced(null))
assertFalse(SteamLiveShortcuts.synced("1"))
}
}
@@ -188,6 +188,34 @@ class DownloadQueueRemovalTest {
assertFalse(folder.exists())
}
@Test fun uninstallStopsARunningDownloadThenRemovesTheGame() {
val running = CountDownLatch(1)
val cancels = AtomicInteger()
val entry = DownloadEntry(Store.GOG, "uninstall-while-running", "Running")
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
running.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(10)
while (!handle.isCancelled && System.nanoTime() < until) Thread.sleep(10)
return null
}
override fun cancel(deleteFiles: Boolean) { cancels.incrementAndGet() }
}
}
assertTrue(running.await(5, TimeUnit.SECONDS))
val folder = File(app.filesDir, "uninstall-while-running").apply { mkdirs() }
File(folder, "game.bin").writeText("x")
val game = InstalledStoreGame(StoreGameSidecar(Store.GOG, "uninstall-while-running", "Running", exe = "game.bin"), folder)
assertEquals(entry.key, game.key)
val done = CountDownLatch(1)
StoresState.uninstall(app, game) { done.countDown() }
assertTrue(idleUntil { done.count == 0L })
assertEquals(1, cancels.get())
assertTrue(DownloadQueue.entry(entry.key)?.state.let { it == null || it == DownloadState.CANCELLED })
assertFalse(folder.exists())
}
private fun blockDiscards(): CountDownLatch {
val release = CountDownLatch(1)
StoreInstalls.beforeDiscard = { release.await(5, TimeUnit.SECONDS) }
@@ -0,0 +1,19 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.assertEquals
import org.junit.Test
class IdleFramesTest {
@Test
fun idleLoopsDrawThirtyFramesASecondAndShareEachOne() {
val start = 5_000_000_000L
val frame = 8_333_333L
val drawn = (0 until 120).count { IdleFrames.due(start + it * frame) }
assertEquals(30, drawn)
val later = start + 1_000_000_000L
assertEquals(listOf(true, true, true), List(3) { IdleFrames.due(later) })
assertEquals(listOf(false, false), List(2) { IdleFrames.due(later + frame) })
assertEquals(listOf(true, true), List(2) { IdleFrames.due(later + 4 * frame) })
}
}
+6 -4
View File
@@ -12,7 +12,8 @@ EA games install, update and start without the EA app. The research behind it is
| Queries | `app/src/main/resources/ea/graphql/*.gql` | EA's own query texts, byte for byte. The gateway matches persisted queries by SHA-256, so these files must not be reformatted (`-text` in `.gitattributes`). |
| Downloads | Rust `src/ea/` in `libdroiddeckstores.so`, `EaInstaller.kt` | A build is one ZIP on EA's CDN. The engine reads its central directory with ranged reads, keeps files whose size and CRC match, and streams every other entry through inflate into place. `.droiddeck-ea-files` records what it placed, so a resume or update does not re-hash those files; files a new build drops are removed. |
| Updates | `EaUpdates` in `EaBackend.kt` | The game page compares the installed version with the offer's live `gameVersion` (every 30 minutes at most). Update runs the same install, which only fetches changed files. |
| Launch, guest | `droiddeck-store-launch` (`prepare_ea`) | Creates the prefix, reads the machine as Wine reports it (`wmic`, `vol`, `hostname`; cached in `pfx/.droiddeck-ea-hw.json`), writes EA app presence keys and the game's `Install Dir` keys in both registry views, runs the build's Touchup once per installed build, then asks the app for the session and writes any licence files. |
| Launch, guest | `droiddeck-store-launch` (`prepare_ea`) | Creates the prefix, reads the machine as Wine reports it (`wmic`, `vol`, `hostname`, CPUID from a 32-bit and a 64-bit probe; cached in `pfx/.droiddeck-ea-hw.json` until the Proton version or its FEX libraries change; a probe that times out, fails or misses a value keeps the older complete cache), writes EA app presence keys and the game's `Install Dir` keys in both registry views, runs the build's Touchup once per installed build, then asks the app for the session and writes any licence files. |
| Launch, Steam copy | `prepare_steam_ea` in `droiddeck-store-launch`, the Proton wrapper | Steam starts its EA titles with `steam2ea://`, which only the EA app handles, and the EA app does not install here. When the prefix has no EA app, the hook reads the game's `__Installer/installerdata.xml` and its offers (`__Installer/LOC/Origin.OFR.*.dat`), runs `prepare_ea` with a `steam` request (the app answers with the launch environment instead of a sidecar file), and writes `droiddeck-ea-steam.bat` in the game's compatdata. The wrapper runs that launcher in place of the link. Writing the EA app presence keys also satisfies the install script, so Steam stops running the EA app installer. |
| Launch, app | `EaLaunch.kt`, `EaOoa.kt`, `EaLsx.kt` | Answers `ea-prepare`: starts the LSX endpoint on `127.0.0.1:3216`, mints the short-lived opaque token, writes `.droiddeck-ea-env` (read once and deleted by the launcher `.bat`), and for games with a `Core` folder requests an online-activation licence for the machine hash. |
| LSX | `EaLsx.kt` | The local endpoint EA's SDK talks to instead of the EA app: challenge, AES session key, config, profile, settings, game info, auth codes for the game's own client ids, licences with Denuvo tokens, entitlements. Friends, presence and the overlay answer empty. |
@@ -20,12 +21,13 @@ EA games install, update and start without the EA app. The research behind it is
The licence names a hash of the machine the game's activation layer computes itself. The hash
version follows the activation library's product version (`Core/activation.dll` or `awc.dll`):
5.x → 4, 4.7.6+ → 3, 4.7.x → 2, 4.x → 1. Versions 2 and 3 also need CPUID leaf 1 ECX, which Wine's
WMI does not expose, so those use `00000000` unless the probe learns it.
5.x → 4, 4.7.6+ → 3, 4.7.x → 2, 4.x → 1. Versions 2 and 3 also hash CPUID leaf 1 ECX, which FEX
reports differently to 32-bit (WOW64) and 64-bit (ARM64EC) processes when their AVX support differs,
so the game is sent the CPUID its own exe's bitness sees. A cache from before the 64-bit probe has
only the 32-bit values, and every game gets those until a probe with Proton found succeeds.
## Not done yet
- Cloud saves (`cloudsync.juno.ea.com`).
- Steam copies of EA games still install the EA app (#2036).
- Pre-DiP games (no `installerdata.xml`) fall back to the exe picker.
- Javelin anti-cheat games do not run under Proton.
+6 -1
View File
@@ -29,6 +29,11 @@ echo "$(date +%H:%M:%S) $verb $EXE ($VERSION, uid $(id -u), DISPLAY ${DISPLAY:-u
# Keep Steam's game identity, DroidDeck's input/display/driver/sync settings and its game environment (the names
# ../proton lists in DROIDDECK_BIONIC_KEEP); drop the rest of the glibc guest's environment.
KEEP=" ${DROIDDECK_BIONIC_KEEP:-} "
# The built-in DirectAudio driver reads DroidDeck's AUDIO_DIRECT_* settings (the microphone switch among them) under
# the BANNER_ names droiddeck-proton gives them for Proton.
for v in $(env | sed -n 's/^\(AUDIO_DIRECT_[A-Za-z0-9_]*\)=.*/\1/p'); do
eval "export BANNER_$v=\"\$$v\""
done
for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
case "$KEEP" in *" $v "*) continue ;; esac
case "$v" in
@@ -36,7 +41,7 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
ANDROID_*|BOOTCLASSPATH|DEX2OATBOOTCLASSPATH|SYSTEMSERVERCLASSPATH|EXTERNAL_STORAGE|ASEC_MOUNTPOINT) ;;
FAKE_*|SDL_*|DD_WIDTH|DD_HEIGHT|DD_VK_DRIVER|WINEDLLOVERRIDES) ;;
DISPLAY|GAMESCOPE_WAYLAND_DISPLAY|FEX_*) ;;
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS) ;;
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS|BANNER_AUDIO_DIRECT_*) ;;
mesa_glthread|vblank_mode|ZINK_*|GALLIUM_HUD|GALLIUM_THREAD) ;;
DD_SYNC|DD_FSYNC_FIRST|DD_SYNC_FALLBACK|PROTON_NO_ESYNC|PROTON_NO_FSYNC|PROTON_NO_NTSYNC|WINEESYNC) ;;
PROTON_USE_D7VK) ;;
@@ -324,6 +324,16 @@ def cloud_on(sidecar):
def exited(argv, code=0):
found = find_store_game(argv)
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if found is None and launch_dir and compat_data and steam_ea_link(argv):
try:
game = str(json.loads((Path(compat_data) / STEAM_EA_STATE).read_text()).get("id") or "")
except (OSError, ValueError, AttributeError):
game = ""
if game:
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": game}, timeout=1.0)
log("steam ea %s exited" % game)
return 0
if found is not None and launch_dir and str(found[1].get("store")) == "rockstar":
ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": str(found[1].get("id"))}, timeout=1.0)
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH")
@@ -1248,39 +1258,69 @@ def wmi_value(text):
CPUID_LEAVES = (0, 1, 0x80000002, 0x80000003, 0x80000004)
def cpuid_exe():
"""A 32-bit console program that writes the raw CPUID leaves an x86 game sees under the emulator."""
def cpuid_exe(wide=False):
"""A console program that writes the raw CPUID leaves an x86 game sees under the emulator: 32-bit, or 64-bit when wide."""
import struct
base, rva = 0x400000, 0x1000
buf, written = base + rva + 0x180, base + rva + 0x1D0
iat = base + rva + 0x138
code = b"\x53\x57\xbf" + struct.pack("<I", buf)
rva = 0x1000
if wide:
base, thunk, optional, names, dll, buf, written = 0x140000000, 8, 0xF0, (0x168, 0x178, 0x184), 0x192, 0x1A0, 0x1F0
else:
base, thunk, optional, names, dll, buf, written = 0x400000, 4, 0xE0, (0x148, 0x158, 0x164), 0x172, 0x180, 0x1D0
ilt, iat = 0x128, 0x128 + 4 * thunk
code = bytearray()
def rip(op, target):
code.extend(op + struct.pack("<i", target - len(code) - len(op) - 4))
if wide:
code += b"\x53\x57\x48\x83\xec\x38"
rip(b"\x48\x8d\x3d", buf)
else:
code += b"\x53\x57\xbf" + struct.pack("<I", base + rva + buf)
for leaf in CPUID_LEAVES:
code += b"\xb8" + struct.pack("<I", leaf) + b"\x31\xc9\x0f\xa2\x89\x07\x89\x5f\x04\x89\x4f\x08\x89\x57\x0c\x83\xc7\x10"
code += b"\x6a\xf5\xff\x15" + struct.pack("<I", iat)
code += b"\x6a\x00\x68" + struct.pack("<I", written) + b"\x6a\x50\x68" + struct.pack("<I", buf) + b"\x50\xff\x15" + struct.pack("<I", iat + 4)
code += b"\x6a\x00\xff\x15" + struct.pack("<I", iat + 8)
code += b"\xb8" + struct.pack("<I", leaf) + b"\x31\xc9\x0f\xa2\x89\x07\x89\x5f\x04\x89\x4f\x08\x89\x57\x0c"
code += b"\x48\x83\xc7\x10" if wide else b"\x83\xc7\x10"
if wide:
code += b"\xb9\xf5\xff\xff\xff"
rip(b"\xff\x15", iat)
code += b"\x48\x89\xc1"
rip(b"\x48\x8d\x15", buf)
code += b"\x41\xb8\x50\x00\x00\x00"
rip(b"\x4c\x8d\x0d", written)
code += b"\x48\xc7\x44\x24\x20\x00\x00\x00\x00"
rip(b"\xff\x15", iat + 8)
code += b"\x31\xc9"
rip(b"\xff\x15", iat + 16)
else:
at = base + rva
code += b"\x6a\xf5\xff\x15" + struct.pack("<I", at + iat)
code += b"\x6a\x00\x68" + struct.pack("<I", at + written) + b"\x6a\x50\x68" + struct.pack("<I", at + buf)
code += b"\x50\xff\x15" + struct.pack("<I", at + iat + 4) + b"\x6a\x00\xff\x15" + struct.pack("<I", at + iat + 8)
section = bytearray(0x200)
section[:len(code)] = code
names = [(0x148, b"GetStdHandle"), (0x158, b"WriteFile"), (0x164, b"ExitProcess")]
struct.pack_into("<IIIII", section, 0x100, rva + 0x128, 0, 0, rva + 0x172, rva + 0x138)
for i, (at, name) in enumerate(names):
struct.pack_into("<I", section, 0x128 + 4 * i, rva + at)
struct.pack_into("<I", section, 0x138 + 4 * i, rva + at)
struct.pack_into("<IIIII", section, 0x100, rva + ilt, 0, 0, rva + dll, rva + iat)
entry = "<Q" if wide else "<I"
for i, (at, name) in enumerate(zip(names, (b"GetStdHandle", b"WriteFile", b"ExitProcess"))):
struct.pack_into(entry, section, ilt + thunk * i, rva + at)
struct.pack_into(entry, section, iat + thunk * i, rva + at)
section[at + 2:at + 2 + len(name)] = name
section[0x172:0x172 + 12] = b"KERNEL32.dll"
section[dll:dll + 12] = b"KERNEL32.dll"
header = bytearray(0x200)
header[0:2] = b"MZ"
struct.pack_into("<I", header, 0x3C, 0x40)
header[0x40:0x44] = b"PE\0\0"
struct.pack_into("<HHIIIHH", header, 0x44, 0x14C, 1, 0, 0, 0, 0xE0, 0x0103)
opt = struct.pack("<HBBIIIIIIIIIHHHHHHIIIIHHIIIIII", 0x10B, 0, 0, 0x200, 0, 0, rva, rva, rva, base, 0x1000, 0x200,
4, 0, 0, 0, 4, 0, 0, 0x2000, 0x200, 0, 3, 0, 0x100000, 0x1000, 0x100000, 0x1000, 0, 16)
struct.pack_into("<HHIIIHH", header, 0x44, 0x8664 if wide else 0x14C, 1, 0, 0, 0, optional, 0x0023 if wide else 0x0103)
if wide:
opt = struct.pack("<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", 0x20B, 0, 0, 0x200, 0, 0, rva, rva, base, 0x1000, 0x200,
5, 2, 0, 0, 5, 2, 0, 0x2000, 0x200, 0, 3, 0, 0x100000, 0x1000, 0x100000, 0x1000, 0, 16)
else:
opt = struct.pack("<HBBIIIIIIIIIHHHHHHIIIIHHIIIIII", 0x10B, 0, 0, 0x200, 0, 0, rva, rva, rva, base, 0x1000, 0x200,
4, 0, 0, 0, 4, 0, 0, 0x2000, 0x200, 0, 3, 0, 0x100000, 0x1000, 0x100000, 0x1000, 0, 16)
dirs = bytearray(128)
struct.pack_into("<II", dirs, 8, rva + 0x100, 40)
struct.pack_into("<II", dirs, 96, rva + 0x138, 16)
header[0x58:0x58 + 0xE0] = opt + bytes(dirs)
header[0x138:0x138 + 40] = struct.pack("<8sIIIIIIHHI", b".text", 0x1000, rva, 0x200, 0x200, 0, 0, 0, 0, 0xE0000060)
struct.pack_into("<II", dirs, 96, rva + iat, 4 * thunk)
header[0x58:0x58 + optional] = opt + bytes(dirs)
header[0x58 + optional:0x58 + optional + 40] = struct.pack("<8sIIIIIIHHI", b".text", 0x1000, rva, 0x200, 0x200, 0, 0, 0, 0, 0xE0000060)
return bytes(header) + bytes(section)
@@ -1332,24 +1372,65 @@ def cpuid_values(raw):
"cpuEcx": "%08x" % regs[1][2], "cpuBrand": brand}
EA_PROBE_FIELDS = ("boardManufacturer", "biosManufacturer", "osInstallDate", "osSerial", "volumeSerial", "hostname",
"cpuVendor", "cpuEax", "cpuEdx", "cpuEcx")
EA_CPU_FIELDS = ("cpuVendor", "cpuEax", "cpuEdx", "cpuEcx")
EA_PROBE_FIELDS = ("boardManufacturer", "biosManufacturer", "osInstallDate", "osSerial", "volumeSerial",
"hostname") + EA_CPU_FIELDS
def probe_complete(values):
return all(str(values.get(key) or "").strip() for key in EA_PROBE_FIELDS)
EA_CPU64 = "cpu64"
EA_RUNTIME = "runtime"
EA_RUNTIME_FILES = ("version", "files/lib/wine/aarch64-windows/libarm64ecfex.dll", "files/lib/wine/aarch64-windows/libwow64fex.dll")
def probe_complete(values, fields=EA_PROBE_FIELDS):
return all(str(values.get(key) or "").strip() for key in fields)
def runtime_stamp(proton):
if not proton or not Path(proton).is_file():
return ""
root = Path(proton).parent
parts = []
for name in EA_RUNTIME_FILES:
try:
parts.append(name + " " + hashlib.sha256((root / name).read_bytes()).hexdigest())
except OSError:
parts.append(name + " -")
return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest()
def read_cpuid(path):
try:
return cpuid_values(path.read_bytes())
except OSError:
return {}
def ea_game_hardware(values, folder, sidecar):
chosen = {key: value for key, value in values.items() if key not in (EA_CPU64, EA_RUNTIME)}
wide = values.get(EA_CPU64)
exe = find_case(folder, str(sidecar.get("exe") or ""))
if isinstance(wide, dict) and exe is not None and exe.is_file():
pe = runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-wine-pe"))
if pe["pe_machine"](str(exe)) == 0x8664:
chosen.update(wide)
return chosen
def ea_hardware(compat_data, proton, timeout=240):
pfx = Path(compat_data) / "pfx"
cache = pfx / EA_HARDWARE
runtime = runtime_stamp(proton)
stale = {}
try:
cached = json.loads(cache.read_text())
if isinstance(cached, dict) and probe_complete(cached):
return cached, "cached"
if not runtime or cached.get(EA_RUNTIME) == runtime:
return cached, "cached"
stale = cached
except (OSError, ValueError):
pass
if not proton or not Path(proton).is_file():
if not runtime:
return {}, "no-proton"
values = {}
with tempfile.TemporaryDirectory(prefix="droiddeck-ea-") as tmp:
@@ -1359,17 +1440,18 @@ def ea_hardware(compat_data, proton, timeout=240):
lines.append('wmic path %s get %s > "%s"' % (cls, prop, windows_path(str(folder / (key + ".txt")))))
lines.append('vol C: > "%s"' % windows_path(str(folder / "volume.txt")))
lines.append('hostname > "%s"' % windows_path(str(folder / "hostname.txt")))
(folder / "cpuid.exe").write_bytes(cpuid_exe())
lines.append('"%s" > "%s"' % (windows_path(str(folder / "cpuid.exe")), windows_path(str(folder / "cpuid.bin"))))
for name, wide in (("cpuid", False), ("cpuid64", True)):
(folder / (name + ".exe")).write_bytes(cpuid_exe(wide))
lines.append('"%s" > "%s"' % (windows_path(str(folder / (name + ".exe"))), windows_path(str(folder / (name + ".bin")))))
bat = folder / "probe.bat"
bat.write_bytes(("\r\n".join(lines) + "\r\n").encode())
try:
subprocess.run([proton, "run", "cmd.exe", "/d", "/c", windows_path(str(bat))], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
except subprocess.TimeoutExpired:
return {}, "timeout"
return stale, "timeout"
except OSError:
return {}, "failed"
return stale, "failed"
for key, _, _ in EA_WMI:
try:
values[key] = wmi_value(decode_output((folder / (key + ".txt")).read_bytes()))
@@ -1384,17 +1466,18 @@ def ea_hardware(compat_data, proton, timeout=240):
values["hostname"] = decode_output((folder / "hostname.txt").read_bytes()).strip().splitlines()[0].strip()
except (OSError, IndexError):
values["hostname"] = ""
try:
values.update(cpuid_values((folder / "cpuid.bin").read_bytes()))
except OSError:
pass
if probe_complete(values):
values.update(read_cpuid(folder / "cpuid.bin"))
wide = read_cpuid(folder / "cpuid64.bin")
if wide:
values[EA_CPU64] = wide
if probe_complete(values) and probe_complete(values.get(EA_CPU64, {}), EA_CPU_FIELDS):
values[EA_RUNTIME] = runtime
try:
cache.write_text(json.dumps(values))
except OSError:
pass
return values, "probed"
return values, "incomplete"
return stale or values, "incomplete"
def ea_registry_entries(folder, sidecar):
@@ -1552,7 +1635,7 @@ def write_licenses(compat_data, licenses):
return written
def prepare_ea(folder, sidecar, compat_data, launch_dir):
def prepare_ea(folder, sidecar, compat_data, launch_dir, steam=None):
game = str(sidecar.get("id"))
proton = os.environ.get("DD_STORE_PROTON", "")
made = create_prefix(compat_data, proton)
@@ -1561,16 +1644,150 @@ def prepare_ea(folder, sidecar, compat_data, launch_dir):
hardware, probe = ea_hardware(compat_data, proton) if ready else ({}, "no-prefix")
answer = None
if launch_dir:
answer = ask(Path(launch_dir) / "stores", {"op": "ea-prepare", "store": "ea", "id": game, "hardware": hardware}, timeout=40.0)
request = {"op": "ea-prepare", "store": "ea", "id": game, "hardware": ea_game_hardware(hardware, folder, sidecar)}
if steam is not None:
request["steam"] = steam
answer = ask(Path(launch_dir) / "stores", request, timeout=40.0)
sidecar = sidecar_at(Path(folder)) or sidecar
log("ea %s prefix=%s stub=%s hardware=%s registry=%s touchup=%s" % (
game, made, stub, probe, ea_registry(folder, sidecar, compat_data, proton), ea_touchup(folder, sidecar, compat_data, proton)))
if answer is None:
log("ea %s session=no reason=%s" % (game, "timeout" if launch_dir else "no-channel"))
return
return None
written = write_licenses(compat_data, answer.get("licenses"))
log("ea %s session=%s reason=%s lsx=%s licence=%s files=%d" % (
game, "yes" if answer.get("ok") else "no", answer.get("reason", ""), answer.get("lsx"), answer.get("license", ""), written))
return answer
STEAM_EA_LINK = re.compile(r"(?i)^steam2ea://launchgame/([0-9]+)")
STEAM_EA_LAUNCHER = "droiddeck-ea-steam.bat"
STEAM_EA_ENV = ".droiddeck-ea-steam-env"
STEAM_EA_STATE = ".droiddeck-ea-steam.json"
STEAM_EA_CLIENT = "drive_c/Program Files/Electronic Arts/EA Desktop/EA Desktop/EADesktop.exe"
STEAM_EA_OFFER = re.compile(r"^(Origin\.OFR\.[0-9]+\.[0-9]+)\.dat$", re.IGNORECASE)
REPLACED = 13
def steam_ea_link(argv):
for raw in argv:
if STEAM_EA_LINK.match(raw.strip().strip('"')):
return raw
return None
def ea_manifest(folder):
path = find_case(folder, "__Installer/installerdata.xml")
if path is None or not path.is_file():
return None
import xml.etree.ElementTree as ET
try:
text = decode_output(path.read_bytes()).lstrip("\ufeff")
root = ET.fromstring(re.sub(r"^\s*<\?xml[^>]*\?>", "", text))
except (OSError, ET.ParseError):
return None
contents = [e.text.strip() for e in root.iter("contentID") if e.text and e.text.strip()]
launchers = []
for runtime in root.iter("runtime"):
for launcher in runtime.iter("launcher"):
path_text = (launcher.findtext("filePath") or "").strip()
if path_text:
launchers.append((path_text, (launcher.findtext("parameters") or "").strip(), (launcher.findtext("trial") or "0").strip() == "1"))
launcher = next((l for l in launchers if not l[2]), launchers[0] if launchers else None)
version = root.find("buildMetaData/gameVersion")
titles = {e.get("locale"): (e.text or "").strip() for e in root.iter("gameTitle") if e.get("locale")}
exe = None
if launcher is not None:
relative = re.sub(r"^\[[^\]]*\]", "", launcher[0]).replace("{installLocation}", "").lstrip("\\/")
exe = find_case(folder, relative)
return {
"contentIds": contents,
"exe": exe if exe is not None and exe.is_file() else None,
"parameters": launcher[1] if launcher else "",
"version": version.get("version", "") if version is not None else "",
"title": titles.get("en_US") or next(iter(titles.values()), "") or Path(folder).name,
}
def steam_ea_offers(folder):
loc = find_case(folder, "__Installer/LOC")
try:
names = sorted(p.name for p in loc.iterdir()) if loc is not None and loc.is_dir() else []
except OSError:
names = []
return [m.group(1) for m in map(STEAM_EA_OFFER.match, names) if m]
def batch_text(value):
return value.replace("%", "%%").replace('"', "")
def batch_arguments(value):
return re.sub(r"[\x00-\x1f]+", " ", value).replace("%", "%%")
def steam_ea_launcher(folder, exe, parameters, compat_data):
env = windows_path(str(Path(compat_data) / STEAM_EA_ENV))
lines = [
"@echo off",
"setlocal",
"rem Written by DroidDeck: starts Steam's copy of an EA game without the EA app.",
'cd /d "%s"' % batch_text(windows_path(str(exe.parent))),
'if not exist "%s" goto run' % batch_text(env),
'for /f "usebackq tokens=1,* delims==" %%%%a in ("%s") do set "%%%%a=%%%%b"' % batch_text(env),
'del "%s"' % batch_text(env),
":run",
'if exist "%s" start "" "%s"' % (EA_STUB, EA_STUB),
'"%s"%s %%*' % (batch_text(windows_path(str(exe))), " " + batch_arguments(parameters) if parameters else ""),
'set "DD_RC=%errorlevel%"',
"taskkill /f /im Origin.exe >nul 2>&1",
"exit /b %DD_RC%",
]
return "\r\n".join(lines) + "\r\n"
def prepare_steam_ea(argv, compat_data, launch_dir):
"""Steam's copies of EA games start through the EA app, which does not install here: start the game itself."""
folder = Path(os.environ.get("STEAM_COMPAT_INSTALL_PATH") or os.getcwd())
if not compat_data:
log("steam ea: no prefix, left to the EA app")
return 0
if (Path(compat_data) / "pfx" / STEAM_EA_CLIENT).is_file():
log("steam ea: the EA app is installed in this prefix, left to it")
return 0
manifest = ea_manifest(folder)
offers = steam_ea_offers(folder)
if manifest is None or manifest["exe"] is None or not manifest["contentIds"] or not offers:
log("steam ea: %s has no EA manifest, launcher or offer, left to the EA app" % folder)
return 0
if not launch_dir:
log("steam ea: no channel to DroidDeck, left to the EA app")
return 0
exe = manifest["exe"]
relative = str(exe.relative_to(folder))
sidecar = {"store": "ea", "id": offers[0], "title": manifest["title"], "exe": relative,
"extra": {"contentIds": ",".join(manifest["contentIds"]), "displayName": manifest["title"], "locale": "en_US"}}
steam = {"folder": str(folder), "offers": offers, "contentIds": manifest["contentIds"], "title": manifest["title"],
"version": manifest["version"], "locale": "en_US", "exe": relative}
answer = prepare_ea(folder, sidecar, compat_data, launch_dir, steam)
env = answer.get("env") if answer and answer.get("ok") else None
if not isinstance(env, dict):
log("steam ea: no EA session (%s), left to the EA app" % ((answer or {}).get("reason") or "no answer"))
return 0
data = Path(compat_data)
try:
secret = data / (STEAM_EA_ENV + ".tmp")
secret.write_bytes("".join("%s=%s\r\n" % (k, v) for k, v in env.items()
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", str(k)) and "\n" not in str(v)).encode())
os.chmod(secret, 0o600)
os.replace(secret, data / STEAM_EA_ENV)
(data / STEAM_EA_LAUNCHER).write_bytes(steam_ea_launcher(folder, exe, manifest["parameters"], compat_data).encode())
(data / STEAM_EA_STATE).write_text(json.dumps({"id": str(answer.get("id") or offers[0])}))
except OSError as error:
log("steam ea: launcher not written (%s), left to the EA app" % type(error).__name__)
return 0
log("steam ea: %s starts %s directly as %s" % (manifest["title"], exe.name, answer.get("id") or offers[0]))
return REPLACED
def gog_support_actions(folder):
@@ -1705,6 +1922,8 @@ def main(argv):
return RAN if subprocess.call(command) == 0 else RAN_FAILED
found = find_store_game(argv)
if found is None:
if steam_ea_link(argv):
return prepare_steam_ea(argv, os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/"), os.environ.get("DD_LAUNCH_DIR", ""))
return 0
folder, sidecar = found
store, game = str(sidecar.get("store")), str(sidecar.get("id"))
@@ -79,6 +79,10 @@ dd_store_launch() {
/usr/local/bin/droiddeck-store-launch "$@"
rc=$?
[ $rc -eq 10 ] && DD_STORE_EXIT=1
if [ $rc -eq 13 ]; then
DD_STORE_EXIT=1
DD_STORE_REPLACE="${STEAM_COMPAT_DATA_PATH%/}/droiddeck-ea-steam.bat"
fi
[ $rc -eq 11 ] && exit 0
[ $rc -eq 12 ] && exit 1
return 0
@@ -88,6 +92,13 @@ dd_run() {
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "${verb:-}"; then
set -- /usr/local/bin/droiddeck-steamvr-game "$@"
fi
if [ -n "${DD_STORE_REPLACE:-}" ]; then
local arg replaced=()
for arg in "$@"; do
case ${arg,,} in steam2ea://*) replaced+=("$DD_STORE_REPLACE") ;; *) replaced+=("$arg") ;; esac
done
set -- "${replaced[@]}"
fi
if [ -n "${DD_STORE_EXIT:-}" ]; then
trap : INT TERM HUP
"$@"
@@ -227,6 +238,14 @@ dd_components() {
DD_GAME_CPUS_SETUP = """
dd_game_cpus() {
local live=/root/.config/droiddeck/game-cores cpus rest=
if [ -f "$live" ] && { IFS= read -r cpus && ! IFS= read -r rest; } <"$live" 2>/dev/null && [ -z "$rest" ] && [ "$(wc -c <"$live" 2>/dev/null)" = "$((${#cpus} + 1))" ]; then
[[ -z $cpus || $cpus =~ ^[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*$ ]] || cpus=${DD_GAME_CPUS:-}
if [ -z "$cpus" ] && [ -n "${DD_CLIENT_CPUS:-}" ]; then
cpus=$(nproc --all 2>/dev/null) && cpus=0-$((cpus - 1)) || cpus=
fi
if [ -n "$cpus" ]; then export DD_GAME_CPUS=$cpus; else unset DD_GAME_CPUS; fi
fi
[ -n "${DD_GAME_CPUS:-}" ] || return 0
command -v taskset >/dev/null 2>&1 || return 0
DD_TASKSET="taskset -c $DD_GAME_CPUS"
+8
View File
@@ -65,6 +65,14 @@ class ToolArguments(unittest.TestCase):
def test_wine_keeps_the_guest_root(self):
self.assertIn('DROIDDECK_GUEST_ROOT) ;;', LAUNCH.read_text())
def test_directaudio_settings_reach_the_built_in_driver(self):
text = LAUNCH.read_text()
block = text[text.index('KEEP="'):text.index('export PATH=/system/bin')]
script = block + 'env | grep -E "AUDIO_DIRECT_|^OTHER=" | sort\n'
env = {'PATH': os.environ['PATH'], 'DROIDDECK_BIONIC_KEEP': 'PATH', 'AUDIO_DIRECT_MIC': '1', 'AUDIO_DIRECT_MS': '60', 'OTHER': 'x'}
result = subprocess.run(['sh', '-c', script], env=env, text=True, capture_output=True, check=True)
self.assertEqual(['BANNER_AUDIO_DIRECT_MIC=1', 'BANNER_AUDIO_DIRECT_MS=60'], result.stdout.split())
class SessionLogs(unittest.TestCase):
SESSION = '/data/user/0/com.droiddeck.launcher/files/logs/2026-11-22-09-steam'
+67
View File
@@ -0,0 +1,67 @@
import os
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
class LiveGameCpusTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
base = Path(self.temp.name)
self.live = base / "game-cores"
tools = base / "tools"
tools.mkdir()
for name, body in (("taskset", "exit 0"), ("nproc", "echo 8")):
tool = tools / name
tool.write_text("#!/bin/sh\n" + body + "\n")
tool.chmod(0o755)
self.path = str(tools) + os.pathsep + os.environ.get("PATH", "")
def run_setup(self, live=None, **extra):
if live is not None:
self.live.write_bytes(live.encode())
setup = COMPAT["DD_GAME_CPUS_SETUP"].replace("/root/.config/droiddeck/game-cores", str(self.live))
script = setup + '\ndd_game_cpus\necho "taskset=${DD_TASKSET:-}"\necho "cpus=${DD_GAME_CPUS-unset}"\n'
env = {key: value for key, value in os.environ.items() if not key.startswith("DD_")}
env.update(PATH=self.path, **extra)
result = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, check=True)
return result.stdout.splitlines()
def test_a_change_made_during_the_session_wins_over_the_session_value(self):
self.assertEqual(self.run_setup("6,7\n", DD_GAME_CPUS="3,4,5,6,7"),
["taskset=taskset -c 6,7", "cpus=6,7"])
def test_every_core_chosen_during_the_session_drops_the_session_pin(self):
self.assertEqual(self.run_setup("\n", DD_GAME_CPUS="3,4,5,6,7"), ["taskset=", "cpus=unset"])
def test_every_core_with_a_pinned_client_still_frees_the_game_from_the_client_cores(self):
self.assertEqual(self.run_setup("\n", DD_GAME_CPUS="0-7", DD_CLIENT_CPUS="0"),
["taskset=taskset -c 0-7", "cpus=0-7"])
def test_without_the_live_file_the_session_value_is_used(self):
self.assertEqual(self.run_setup(DD_GAME_CPUS="3,4,5,6,7"),
["taskset=taskset -c 3,4,5,6,7", "cpus=3,4,5,6,7"])
self.assertEqual(self.run_setup(), ["taskset=", "cpus=unset"])
def test_a_file_caught_mid_write_keeps_the_session_value(self):
for partial in ("", "6,7", "6"):
self.assertEqual(self.run_setup(partial, DD_GAME_CPUS="4,5"), ["taskset=taskset -c 4,5", "cpus=4,5"], partial)
def test_an_unreadable_value_keeps_the_session_value(self):
for bad in ("3;rm\n", "6-\n", "-3\n", "3,,4\n", "3,\n", "3\n4\n", "3\n4", "\n3\n", "3\0,4\n", "\0\n"):
self.assertEqual(self.run_setup(bad, DD_GAME_CPUS="4,5"), ["taskset=taskset -c 4,5", "cpus=4,5"], bad)
def test_the_file_is_found_whatever_home_the_client_runs_with(self):
self.assertEqual(self.run_setup("6,7\n", DD_GAME_CPUS="3,4,5,6,7", HOME="/root/.droiddeck-x64"),
["taskset=taskset -c 6,7", "cpus=6,7"])
self.assertIn("live=/root/.config/droiddeck/game-cores ", COMPAT["DD_GAME_CPUS_SETUP"])
if __name__ == "__main__":
unittest.main()
+127
View File
@@ -452,6 +452,133 @@ class Launchers(unittest.TestCase):
self.assertEqual(-2, rc)
def test_a_steam_ea_link_is_swapped_for_droiddecks_launcher_and_reports_its_exit(self):
with tempfile.TemporaryDirectory() as root:
hook = Path(root) / 'hook'
record = Path(root) / 'ran'
hook.write_text('#!/bin/sh\necho "$@" >> "%s"\n' % record)
hook.chmod(0o755)
setup = compat.DD_STORE_SETUP.replace('/usr/local/bin/droiddeck-store-launch', str(hook)).replace(
'[ -x %s ] || return 0' % hook, '[ -x %s ] || return 0; verb=waitforexitandrun' % hook)
setup = setup.replace(' %s "$@"\n rc=$?' % hook, ' %s "$@"\n rc=13' % hook)
script = setup + '\nverb=waitforexitandrun\ndd_store_launch steam2ea://launchgame/1237970 -dev\nDD_STORE_ARGS=(steam2ea://launchgame/1237970 -dev)\ndd_run %s proton waitforexitandrun Steam2EA://launchgame/1237970 -dev\n' % hook
done = subprocess.run(['bash', '-c', script], env=dict(os.environ, STEAM_COMPAT_DATA_PATH=root + '/'), timeout=20)
self.assertEqual(0, done.returncode)
lines = record.read_text().splitlines()
self.assertEqual('proton waitforexitandrun %s/droiddeck-ea-steam.bat -dev' % root, lines[1])
self.assertEqual('--exited --code 0 steam2ea://launchgame/1237970 -dev', lines[2])
MANIFEST = """<?xml version='1.0' encoding='utf-8'?>
<DiPManifest version="4.0">
<buildMetaData><gameVersion version="1.0.1.3" /></buildMetaData>
<contentIDs><contentID>1039093</contentID></contentIDs>
<runtime>
<launcher uid="1-2"><filePath>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Respawn\\Titanfall2\\Install Dir]Titanfall2.exe</filePath><parameters /><trial>0</trial></launcher>
<launcher uid="2-2"><filePath>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Respawn\\Titanfall2\\Install Dir]Titanfall2_trial.exe</filePath><parameters /><trial>1</trial></launcher>
</runtime>
<gameTitles><gameTitle locale="en_US">Titanfall 2</gameTitle></gameTitles>
</DiPManifest>
"""
class SteamEa(unittest.TestCase):
def steam_copy(self, root):
folder = Path(root) / 'steamapps/common/Titanfall2'
(folder / '__Installer/LOC').mkdir(parents=True)
(folder / '__Installer/installerdata.xml').write_bytes(b'\xff\xfe' + MANIFEST.encode('utf-16-le'))
(folder / '__Installer/LOC/Origin.OFR.50.0001456.dat').write_text('')
(folder / '__Installer/LOC/Origin.OFR.50.0001452.dat').write_text('')
(folder / 'Titanfall2.exe').write_text('')
(folder / 'Titanfall2_trial.exe').write_text('')
data = Path(root) / 'compatdata/1237970'
(data / 'pfx').mkdir(parents=True)
return folder, data
def test_the_manifest_names_the_full_game_its_content_and_version(self):
with tempfile.TemporaryDirectory() as root:
folder, _ = self.steam_copy(root)
manifest = store.ea_manifest(folder)
self.assertEqual(folder / 'Titanfall2.exe', manifest['exe'])
self.assertEqual(['1039093'], manifest['contentIds'])
self.assertEqual('1.0.1.3', manifest['version'])
self.assertEqual('Titanfall 2', manifest['title'])
self.assertEqual(['Origin.OFR.50.0001452', 'Origin.OFR.50.0001456'], store.steam_ea_offers(folder))
def test_a_steam_ea_launch_gets_a_session_and_a_launcher_that_reads_it_once(self):
with tempfile.TemporaryDirectory() as root:
folder, data = self.steam_copy(root)
asked = []
answer = {'ok': True, 'id': 'Origin.OFR.50.0001452', 'env': {'EALsxPort': '3216', 'ContentId': '1039093'}}
prepare = lambda *a: asked.append(a) or answer
env = {'STEAM_COMPAT_INSTALL_PATH': str(folder), 'STEAM_COMPAT_DATA_PATH': str(data), 'DD_LAUNCH_DIR': str(Path(root) / 'session')}
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea', side_effect=prepare):
self.assertEqual(store.REPLACED, store.main(['steam2ea://launchgame/1237970?platform=steam&theme=tf2']))
steam = asked[0][4]
self.assertEqual(['Origin.OFR.50.0001452', 'Origin.OFR.50.0001456'], steam['offers'])
self.assertEqual(['1039093'], steam['contentIds'])
self.assertEqual('Titanfall2.exe', steam['exe'])
self.assertEqual(b'EALsxPort=3216\r\nContentId=1039093\r\n', (data / store.STEAM_EA_ENV).read_bytes())
bat = (data / store.STEAM_EA_LAUNCHER).read_text()
envfile = store.windows_path(str(data / store.STEAM_EA_ENV))
self.assertIn('cd /d "%s"' % store.windows_path(str(folder)), bat)
self.assertIn('for /f "usebackq tokens=1,* delims==" %%%%a in ("%s") do set "%%%%a=%%%%b"' % envfile, bat)
self.assertIn('del "%s"' % envfile, bat)
self.assertIn('"%s" %%*' % store.windows_path(str(folder / 'Titanfall2.exe')), bat)
self.assertEqual({'id': 'Origin.OFR.50.0001452'}, json.loads((data / store.STEAM_EA_STATE).read_text()))
asked.clear()
record = lambda channel, request, timeout=5.0, claim=False: asked.append(request)
with patch.dict(os.environ, env), patch.object(store, 'ask', side_effect=record):
self.assertEqual(0, store.main(['--exited', 'steam2ea://launchgame/1237970']))
self.assertEqual([{'op': 'ea-exited', 'store': 'ea', 'id': 'Origin.OFR.50.0001452'}], asked)
def test_a_steam_copy_is_sent_the_cpuid_of_its_exes_bitness(self):
narrow = dict({key: 'x' for key in store.EA_PROBE_FIELDS}, cpuEcx='82d8230f')
values = dict(narrow, cpu64={'cpuEcx': 'bed8330f'}, runtime='stamp')
for image, expected in ((store.cpuid_exe(True), dict(narrow, cpuEcx='bed8330f')), (store.cpuid_exe(), narrow)):
with tempfile.TemporaryDirectory() as root:
folder, data = self.steam_copy(root)
(folder / 'Titanfall2.exe').write_bytes(image)
asked = []
def fake_ask(channel, request, timeout=5.0, claim=False):
asked.append(request)
return {'ok': True, 'id': 'Origin.OFR.50.0001452', 'env': {'EALsxPort': '3216'}}
env = {'STEAM_COMPAT_INSTALL_PATH': str(folder), 'STEAM_COMPAT_DATA_PATH': str(data),
'DD_LAUNCH_DIR': str(Path(root) / 'session'), 'DD_STORE_PROTON': ''}
with patch.dict(os.environ, env), patch.object(store, 'ask', side_effect=fake_ask), \
patch.object(store, 'create_prefix', return_value='present'), \
patch.object(store, 'install_origin_stub', return_value='ready'), \
patch.object(store, 'ea_hardware', return_value=(values, 'cached')), \
patch.object(store, 'ea_registry', return_value='ready'), \
patch.object(store, 'ea_touchup', return_value='none'):
self.assertEqual(store.REPLACED, store.main(['steam2ea://launchgame/1237970']))
self.assertEqual('ea-prepare', asked[0]['op'])
self.assertEqual('Titanfall2.exe', asked[0]['steam']['exe'])
self.assertEqual(expected, asked[0]['hardware'])
def test_the_manifests_launch_parameters_keep_their_quotes(self):
with tempfile.TemporaryDirectory() as root:
folder, data = self.steam_copy(root)
bat = store.steam_ea_launcher(folder, folder / 'Titanfall2.exe', '-config "game profile.cfg" -rate 50%', str(data))
self.assertIn('Titanfall2.exe" -config "game profile.cfg" -rate 50%% %*', bat)
def test_steam_keeps_the_link_when_droiddeck_cannot_start_the_game(self):
with tempfile.TemporaryDirectory() as root:
folder, data = self.steam_copy(root)
env = {'STEAM_COMPAT_INSTALL_PATH': str(folder), 'STEAM_COMPAT_DATA_PATH': str(data), 'DD_LAUNCH_DIR': str(Path(root) / 'session')}
link = ['steam2ea://launchgame/1237970']
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea', return_value={'ok': False, 'reason': 'signed-out'}):
self.assertEqual(0, store.main(link))
client = data / 'pfx' / store.STEAM_EA_CLIENT
client.parent.mkdir(parents=True)
client.write_text('')
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea', side_effect=AssertionError('the EA app is installed')):
self.assertEqual(0, store.main(link))
self.assertFalse((data / store.STEAM_EA_LAUNCHER).exists())
if __name__ == '__main__':
unittest.main()
+155
View File
@@ -3,6 +3,8 @@ import importlib.machinery
import importlib.util
import json
from pathlib import Path
import re
import struct
import subprocess
import tempfile
import unittest
@@ -15,6 +17,53 @@ store = importlib.util.module_from_spec(spec)
loader.exec_module(store)
def called_imports(exe):
wide = struct.unpack_from('<H', exe, 0x58)[0] == 0x20B
base = struct.unpack_from('<Q', exe, 0x58 + 24)[0] if wide else struct.unpack_from('<I', exe, 0x58 + 28)[0]
dirs = 0x58 + struct.unpack_from('<H', exe, 0x54)[0] - 128
raw = lambda rva: 0x200 + rva - 0x1000
ilt, _, _, dll, iat = struct.unpack_from('<IIIII', exe, raw(struct.unpack_from('<I', exe, dirs + 8)[0]))
thunk = 8 if wide else 4
slots = {}
for i in range(3):
hint = struct.unpack_from('<Q' if wide else '<I', exe, raw(iat) + thunk * i)[0]
if hint != struct.unpack_from('<Q' if wide else '<I', exe, raw(ilt) + thunk * i)[0]:
return None
slots[iat + thunk * i] = exe[raw(hint) + 2:].split(b'\0')[0]
code = exe[0x200:0x300]
called = []
for at in range(len(code) - 6):
if code[at:at + 2] == b'\xff\x15':
value = struct.unpack_from('<i' if wide else '<I', code, at + 2)[0]
called.append(slots.get(0x1000 + at + 6 + value if wide else value - base))
return exe[raw(dll):].split(b'\0')[0], called
PROBE_NARROW = bytes.fromhex('1600000047656e756e74656c696e654961060a00000805000f23d882fffb8b27436f727465782d4135323000000000000000000000000000000000000000000000000000000000000000000000000000')
PROBE_WIDE = bytearray(PROBE_NARROW)
PROBE_WIDE[16 + 8:16 + 12] = bytes.fromhex('0f33d8be')
def fake_probe(wide):
def run(argv, **kwargs):
bat = Path(argv[-1][2:].replace('\\', '/'))
for line in bat.read_text().splitlines():
found = re.search(r'"?([^"]*)"? > "([^"]*)"$', line)
if not found:
continue
source, out = found.group(1), Path(found.group(2)[2:].replace('\\', '/'))
if source.endswith('cpuid64.exe'):
if wide is not None:
out.write_bytes(wide)
elif source.endswith('cpuid.exe'):
out.write_bytes(PROBE_NARROW)
elif source.startswith('vol'):
out.write_text(' Volume Serial Number is 1A2B-3C4D\r\n')
else:
out.write_text('Header\r\nvalue\r\n')
return run
class EaHook(unittest.TestCase):
def test_wmi_output_reads_the_value_under_the_header(self):
text = 'Manufacturer \r\r\nThe Wine Project \r\r\n\r\r\n'
@@ -101,6 +150,112 @@ class EaHook(unittest.TestCase):
self.assertEqual(struct.unpack_from('<H', exe, 0x58 + 68)[0], 3)
self.assertIn(b'KERNEL32.dll', exe)
self.assertEqual(len(exe), 0x400)
self.assertEqual(called_imports(exe), (b'KERNEL32.dll', [b'GetStdHandle', b'WriteFile', b'ExitProcess']))
def test_cpuid_probe_has_a_64_bit_form_that_writes_the_same_leaves(self):
exe = store.cpuid_exe(True)
self.assertEqual(exe[:2], b'MZ')
self.assertEqual(struct.unpack_from('<H', exe, 0x44)[0], 0x8664)
self.assertEqual(struct.unpack_from('<H', exe, 0x58)[0], 0x20B)
self.assertEqual(struct.unpack_from('<H', exe, 0x58 + 68)[0], 3)
self.assertEqual(len(exe), 0x400)
self.assertEqual(called_imports(exe), (b'KERNEL32.dll', [b'GetStdHandle', b'WriteFile', b'ExitProcess']))
code = exe[0x200:0x300]
self.assertEqual(code.count(b'\x0f\xa2'), len(store.CPUID_LEAVES))
loads = {}
for at in range(len(code) - 7):
if code[at:at + 3] in (b'\x48\x8d\x3d', b'\x48\x8d\x15', b'\x4c\x8d\x0d'):
loads[code[at:at + 3]] = at + 7 + struct.unpack_from('<i', code, at + 3)[0]
self.assertEqual(loads[b'\x48\x8d\x3d'], loads[b'\x48\x8d\x15'])
self.assertGreaterEqual(loads[b'\x4c\x8d\x0d'], loads[b'\x48\x8d\x15'] + 16 * len(store.CPUID_LEAVES))
self.assertLessEqual(loads[b'\x4c\x8d\x0d'] + 4, 0x200)
self.assertFalse(any(exe[0x200 + loads[b'\x48\x8d\x15']:0x200 + loads[b'\x4c\x8d\x0d'] + 4]))
self.assertEqual(store.cpuid_exe(False), store.cpuid_exe())
def test_each_game_is_sent_the_cpuid_of_its_own_bitness(self):
narrow = {'cpuVendor': 'GenuineIntel', 'cpuEax': '000A0661', 'cpuEdx': '278BFBFF', 'cpuEcx': '82d8230f', 'cpuBrand': 'Cortex-A520'}
probe = dict({key: 'x' for key in store.EA_PROBE_FIELDS}, **narrow)
values = dict(probe, cpu64=dict(narrow, cpuEcx='bed8330f'), runtime='stamp')
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
(folder / 'Game64.exe').write_bytes(store.cpuid_exe(True))
(folder / 'bin').mkdir()
(folder / 'bin/Game32.exe').write_bytes(store.cpuid_exe())
self.assertEqual(store.ea_game_hardware(values, folder, {'exe': 'game64.exe'}), dict(probe, cpuEcx='bed8330f'))
self.assertEqual(store.ea_game_hardware(values, folder, {'exe': 'bin/Game32.exe'}), probe)
self.assertEqual(store.ea_game_hardware(values, folder, {'exe': 'Missing.exe'}), probe)
self.assertEqual(store.ea_game_hardware(values, folder, {}), probe)
self.assertEqual(store.ea_game_hardware(probe, folder, {'exe': 'Game64.exe'}), probe)
def test_a_probe_from_another_proton_or_fex_build_is_taken_again(self):
with tempfile.TemporaryDirectory() as tmp:
proton = Path(tmp) / 'tool/proton'
fex = proton.parent / 'files/lib/wine/aarch64-windows/libwow64fex.dll'
fex.parent.mkdir(parents=True)
proton.write_text('')
(proton.parent / 'version').write_text('1 experimental-11.0')
fex.write_bytes(b'fex 1')
runtime = store.runtime_stamp(str(proton))
self.assertTrue(runtime)
self.assertEqual(store.runtime_stamp(str(proton)), runtime)
self.assertEqual(store.runtime_stamp(''), '')
compat = Path(tmp) / 'compat'
(compat / 'pfx').mkdir(parents=True)
cached = dict({key: 'x' for key in store.EA_PROBE_FIELDS}, runtime=runtime)
(compat / 'pfx' / store.EA_HARDWARE).write_text(json.dumps(cached))
with patch.object(store.subprocess, 'run', side_effect=AssertionError('probed again')):
self.assertEqual(store.ea_hardware(str(compat), str(proton)), (cached, 'cached'))
self.assertEqual(store.ea_hardware(str(compat), ''), (cached, 'cached'))
fex.write_bytes(b'fex 2')
self.assertNotEqual(store.runtime_stamp(str(proton)), runtime)
with patch.object(store.subprocess, 'run', side_effect=OSError) as run:
self.assertEqual(store.ea_hardware(str(compat), str(proton)), (cached, 'failed'))
run.assert_called_once()
(proton.parent / 'version').write_text('2 experimental-11.0')
self.assertNotEqual(store.runtime_stamp(str(proton)), runtime)
def test_the_probe_records_both_bitnesses_and_the_runtime(self):
with tempfile.TemporaryDirectory() as tmp:
proton = Path(tmp) / 'tool/proton'
proton.parent.mkdir()
proton.write_text('')
compat = Path(tmp) / 'compat'
(compat / 'pfx').mkdir(parents=True)
with patch.object(store.subprocess, 'run', side_effect=fake_probe(bytes(PROBE_WIDE))):
values, how = store.ea_hardware(str(compat), str(proton))
self.assertEqual(how, 'probed')
self.assertEqual(values['cpuEcx'], '82d8230f')
self.assertEqual(values['cpu64']['cpuEcx'], 'bed8330f')
self.assertEqual(values['volumeSerial'], '1a2b3c4d')
self.assertEqual(values['runtime'], store.runtime_stamp(str(proton)))
self.assertEqual(json.loads((compat / 'pfx' / store.EA_HARDWARE).read_text()), values)
def test_a_failed_64_bit_probe_keeps_the_old_cache_and_is_retried(self):
with tempfile.TemporaryDirectory() as tmp:
proton = Path(tmp) / 'tool/proton'
proton.parent.mkdir()
proton.write_text('')
compat = Path(tmp) / 'compat'
(compat / 'pfx').mkdir(parents=True)
cache = compat / 'pfx' / store.EA_HARDWARE
for wide in (None, PROBE_NARROW[:40]):
with patch.object(store.subprocess, 'run', side_effect=fake_probe(wide)):
values, how = store.ea_hardware(str(compat), str(proton))
self.assertEqual(how, 'incomplete')
self.assertEqual(values['cpuEcx'], '82d8230f')
self.assertNotIn('cpu64', values)
self.assertNotIn('runtime', values)
self.assertFalse(cache.exists())
stale = dict({key: 'x' for key in store.EA_PROBE_FIELDS}, cpu64={'cpuEcx': 'bed8330f'}, runtime='old')
cache.write_text(json.dumps(stale))
with patch.object(store.subprocess, 'run', side_effect=fake_probe(None)):
self.assertEqual(store.ea_hardware(str(compat), str(proton)), (stale, 'incomplete'))
self.assertEqual(json.loads(cache.read_text()), stale)
with patch.object(store.subprocess, 'run', side_effect=fake_probe(bytes(PROBE_WIDE))):
values, how = store.ea_hardware(str(compat), str(proton))
self.assertEqual(how, 'probed')
self.assertEqual(values['cpu64']['cpuEcx'], 'bed8330f')
self.assertEqual(json.loads(cache.read_text()), values)
def test_origin_stub_is_a_windowless_program_installed_once(self):
import struct
+2
View File
@@ -11,6 +11,8 @@ Steam on the desktop). The app installs it into `files/linuxfs` and runs it unde
UBWC 5/6 (backported from upstream Mesa) and the KGSL device numbers for WSI (from
[Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)). It also carries Icenowy Zheng's upstream
Zink fix that keeps the Imagination depth/stencil swizzle off colour views (Mesa d55418dae7).
Zink also reclaims the memory a client freed once it has been idle for a second: otherwise only its
next allocation does, and Steam's UI behind a game held 250 MiB more of unswappable GPU memory.
- The runtime's built-in Vulkan driver is DroidDeck's DD-Turnip Linux build (`DD_TURNIP_URL` and
`DD_TURNIP_SHA256` in `base.env`): Ubuntu's Turnip is diverted to `libvulkan_freedreno.so.distrib`
because it lacks the Adreno 8xx fixes. Zink, EGL and llvmpipe stay Ubuntu's.
@@ -0,0 +1,143 @@
Subject: zink: reclaim freed slab entries and cached buffers while the client is idle
zink only reclaims slab entries and expired cached buffers during its next
allocation, and pb_slabs_reclaim stops at the first entries still in use. A
client that frees a lot and then goes idle keeps all of it allocated: Steam's web helper held 500-700 MiB of KGSL memory behind a
fullscreen game after scrolling its library, and released it the moment the
overlay drew a frame. A thread now reclaims once a second after a second
without allocations.
--- a/src/util/pb_slab.h
+++ b/src/util/pb_slab.h
@@ -145,6 +145,9 @@
unsigned
pb_slabs_reclaim(struct pb_slabs *slabs);
+unsigned
+pb_slabs_reclaim_all(struct pb_slabs *slabs);
+
bool
pb_slabs_init(struct pb_slabs *slabs,
unsigned min_order, unsigned max_order,
--- a/src/util/pb_slab.c
+++ b/src/util/pb_slab.c
@@ -231,6 +231,19 @@
return num_reclaims;
}
+/* Like pb_slabs_reclaim, but skips entries that are still in use instead of
+ * stopping at the first ones, so entries freed behind them are reclaimed too.
+ */
+unsigned
+pb_slabs_reclaim_all(struct pb_slabs *slabs)
+{
+ unsigned num_reclaims;
+ simple_mtx_lock(&slabs->mutex);
+ num_reclaims = pb_slabs_reclaim_all_locked(slabs);
+ simple_mtx_unlock(&slabs->mutex);
+ return num_reclaims;
+}
+
/* Initialize the slabs manager.
*
* The minimum and maximum size of slab entries are 2^min_order and
--- a/src/gallium/drivers/zink/zink_types.h
+++ b/src/gallium/drivers/zink/zink_types.h
@@ -1427,6 +1427,12 @@
struct pb_slabs bo_slabs[NUM_SLAB_ALLOCATORS];
unsigned min_alloc_size;
uint32_t next_bo_unique_id;
+ uint32_t alloc_serial;
+ thrd_t reclaim_thread;
+ mtx_t reclaim_lock;
+ cnd_t reclaim_cond;
+ bool reclaim_stop;
+ bool reclaim_running;
} pb;
uint8_t heap_map[ZINK_HEAP_MAX][VK_MAX_MEMORY_TYPES]; // mapping from zink heaps to memory type indices
uint8_t heap_count[ZINK_HEAP_MAX]; // number of memory types per zink heap
--- a/src/gallium/drivers/zink/zink_bo.c
+++ b/src/gallium/drivers/zink/zink_bo.c
@@ -34,6 +34,7 @@
#include "zink_resource.h"
#include "zink_screen.h"
#include "util/u_hash_table.h"
+#include "util/u_thread.h"
#ifdef HAVE_LIBDRM
#define ZINK_USE_DMABUF
@@ -577,6 +578,7 @@
zink_bo_create(struct zink_screen *screen, uint64_t size, unsigned alignment, enum zink_heap heap, enum zink_alloc_flag flags, unsigned mem_type_idx, const void *pNext)
{
struct zink_bo *bo;
+ p_atomic_inc(&screen->pb.alloc_serial);
/* pull in sparse flag */
flags |= zink_alloc_flags_from_heap(heap);
@@ -1390,6 +1392,40 @@
return bo_slab_alloc(priv, mem_type_idx, entry_size, group_index, false);
}
+/* Slab entries and cached buffers a client frees are otherwise only reclaimed by its next
+ * allocation, so a client that goes idle (a browser UI behind a fullscreen game) keeps all of
+ * that memory allocated. On UMA devices it is system RAM that cannot be swapped. */
+static int
+bo_reclaim_thread(void *data)
+{
+ struct zink_screen *screen = data;
+ uint32_t seen = p_atomic_read(&screen->pb.alloc_serial);
+
+ u_thread_setname("zink_reclaim");
+ mtx_lock(&screen->pb.reclaim_lock);
+ while (!screen->pb.reclaim_stop) {
+ struct timespec deadline;
+ timespec_get(&deadline, TIME_UTC);
+ deadline.tv_sec += 1;
+ cnd_timedwait(&screen->pb.reclaim_cond, &screen->pb.reclaim_lock, &deadline);
+ if (screen->pb.reclaim_stop)
+ break;
+ mtx_unlock(&screen->pb.reclaim_lock);
+
+ uint32_t serial = p_atomic_read(&screen->pb.alloc_serial);
+ if (serial == seen) {
+ for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++)
+ pb_slabs_reclaim_all(&screen->pb.bo_slabs[i]);
+ pb_cache_release_all_buffers(&screen->pb.bo_cache);
+ }
+ seen = serial;
+
+ mtx_lock(&screen->pb.reclaim_lock);
+ }
+ mtx_unlock(&screen->pb.reclaim_lock);
+ return 0;
+}
+
bool
zink_bo_init(struct zink_screen *screen)
{
@@ -1425,12 +1461,25 @@
min_slab_order = max_order + 1;
}
screen->pb.min_alloc_size = 1 << screen->pb.bo_slabs[0].min_order;
+
+ mtx_init(&screen->pb.reclaim_lock, mtx_plain);
+ cnd_init(&screen->pb.reclaim_cond);
+ screen->pb.reclaim_running =
+ u_thread_create(&screen->pb.reclaim_thread, bo_reclaim_thread, screen) == thrd_success;
return true;
}
void
zink_bo_deinit(struct zink_screen *screen)
{
+ if (screen->pb.reclaim_running) {
+ mtx_lock(&screen->pb.reclaim_lock);
+ screen->pb.reclaim_stop = true;
+ cnd_signal(&screen->pb.reclaim_cond);
+ mtx_unlock(&screen->pb.reclaim_lock);
+ thrd_join(screen->pb.reclaim_thread, NULL);
+ screen->pb.reclaim_running = false;
+ }
for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
if (screen->pb.bo_slabs[i].groups)
pb_slabs_deinit(&screen->pb.bo_slabs[i]);