Compare commits

..
Author SHA1 Message Date
The412Banner d811d87b7a fix(session): stop clock and memory sampling while the session is suspended
A suspended session froze the guest, but the app kept sampling clocks every
2 s and memory every 10 s. On ROMs that refuse some of the clock files, every
clock tick also raised five SELinux denials, which filled most of app.log.
Both loggers now skip their samples while the session is suspended and pick
up again after resume.
2026-11-29 13:42:33 +00:00
14 changed files with 116 additions and 355 deletions

No files matched your search

@@ -8,13 +8,17 @@ import android.os.Build
import android.os.PowerManager
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.session.SessionState
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class ClockLogComponent(private val logFile: File) : SessionPart() {
class ClockLogComponent(
private val logFile: File,
private val paused: () -> Boolean = { SessionState.suspended },
) : SessionPart() {
@Volatile private var running = false
private var stopped = false
private var thread: Thread? = null
@@ -55,26 +59,28 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
limitLines(steps, ceiling, GpuLimits.first(minSources)).forEach { w.write(it + "\n") }
w.flush()
while (running && logFile.length() < MAX_BYTES) {
val line = StringBuilder(time.format(Date()))
for (p in policies) {
val cur = firstNumber(File(p, "scaling_cur_freq").path)
val max = firstNumber(File(p, "scaling_max_freq").path)
val hw = firstNumber(File(p, "cpuinfo_max_freq").path)
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
}
if (ceiling == null) ceiling = ceilingSource(maxSources)?.also { w.write("gpu ceiling from: $it\n") }
line.append(gpuField(gpu, ceiling, steps?.mhz?.last()))
if (power != null && Build.VERSION.SDK_INT >= 29) {
line.append(" | thermal ${power.currentThermalStatus}")
if (Build.VERSION.SDK_INT >= 30) {
val h = power.getThermalHeadroom(10)
if (!h.isNaN()) line.append(String.format(Locale.US, " headroom %.2f", h))
if (!paused()) {
val line = StringBuilder(time.format(Date()))
for (p in policies) {
val cur = firstNumber(File(p, "scaling_cur_freq").path)
val max = firstNumber(File(p, "scaling_max_freq").path)
val hw = firstNumber(File(p, "cpuinfo_max_freq").path)
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
}
if (ceiling == null) ceiling = ceilingSource(maxSources)?.also { w.write("gpu ceiling from: $it\n") }
line.append(gpuField(gpu, ceiling, steps?.mhz?.last()))
if (power != null && Build.VERSION.SDK_INT >= 29) {
line.append(" | thermal ${power.currentThermalStatus}")
if (Build.VERSION.SDK_INT >= 30) {
val h = power.getThermalHeadroom(10)
if (!h.isNaN()) line.append(String.format(Locale.US, " headroom %.2f", h))
}
}
batteryTenths()?.let { line.append(String.format(Locale.US, " | battery %.1f C", it / 10.0)) }
w.write(line.append('\n').toString())
w.flush()
}
batteryTenths()?.let { line.append(String.format(Locale.US, " | battery %.1f C", it / 10.0)) }
w.write(line.append('\n').toString())
w.flush()
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}
@@ -104,7 +104,9 @@ object MemoryLog {
if (thread != null) return
thread = Thread({
while (!Thread.currentThread().isInterrupted) {
runCatching { MemoryReadout.device()?.let { android.util.Log.i(TAG, line(it, MemoryReadout.split())) } }
if (!SessionState.suspended) {
runCatching { MemoryReadout.device()?.let { android.util.Log.i(TAG, line(it, MemoryReadout.split())) } }
}
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}, "memory-log").apply { isDaemon = true; start() }
@@ -57,17 +57,12 @@ import com.droiddeck.launcher.stores.StoresState
/** What the Library pretends while a developer previews it. Nothing here is saved: a restart always comes back to [OFF]. */
internal enum class LibraryPreview { OFF, NOTHING_INSTALLED, SIGNED_OUT, SAMPLE }
/** How many games the Steam home pretends are installed. Nothing here is saved. */
internal enum class SteamHomePreview(val games: Int) { OFF(-1), NONE(0), FEW(3), MANY(12) }
internal enum class DrawerPreview { STEAM, DESKTOP, GAME }
/** Developer tools' preview states: screens that are otherwise hard to reach, shown without changing anything real. */
internal object DevPreview {
var library by mutableStateOf(LibraryPreview.OFF)
var drawer by mutableStateOf<DrawerPreview?>(null)
var steamHome by mutableStateOf(SteamHomePreview.OFF)
var openSteam by mutableStateOf(false)
/** The UI zoo sheet: where previews are picked, one at a time, only when asked for. */
var zoo by mutableStateOf(false)
/** Opt-in: a preview button where its state lives (the Library's toolbar), for switching states without the zoo. */
@@ -92,41 +87,6 @@ internal fun sampleOwned(store: Store): List<CatalogItem> =
internal fun sampleInstalled(owned: Map<Store, List<CatalogItem>>): Set<String> =
owned.values.flatMap { items -> items.take(SAMPLE_INSTALLED).map { it.key } }.toSet()
/** The Steam home's games while a developer previews it: this many invented titles, no art, nothing installed. */
internal fun sampleSteamHomeGames(count: Int): List<com.droiddeck.launcher.frontend.Library.SteamGame> = listOf(
"Portal 2", "Hades", "Celeste", "Stardew Valley", "Hollow Knight", "Balatro",
"Dead Cells", "Terraria", "Vampire Survivors", "Slay the Spire", "Cuphead", "Inscryption",
).take(count).mapIndexed { i, name ->
com.droiddeck.launcher.frontend.Library.SteamGame(1000 + i, name, art = null, library = "steam", lastPlayed = 1_700_000_000_000L - i * 86_400_000L)
}
/** The pill a previewed Steam home shows, so the fake state is never mistaken for the real one. */
@Composable
internal fun SteamHomePreviewPill(modifier: Modifier = Modifier) {
val preview = DevPreview.steamHome
if (preview == SteamHomePreview.OFF) return
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val label = stringResource(
when (preview) {
SteamHomePreview.NONE -> R.string.dev_preview_steam_none
SteamHomePreview.FEW -> R.string.dev_preview_steam_few
else -> R.string.dev_preview_steam_many
},
)
val end = stringResource(R.string.dev_preview_end)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = modifier.background(colors.surface, CircleShape).border(1.dp, pal.signal, CircleShape)
.clickable(role = Role.Button, onClickLabel = end) { DevPreview.steamHome = SteamHomePreview.OFF }
.padding(start = 14.dp, end = 10.dp, top = 8.dp, bottom = 8.dp).testTag("dev-preview-steam-end"),
) {
Icon(Icons.Outlined.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp))
Text(stringResource(R.string.dev_preview_banner, label), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Icon(Icons.Filled.Close, end, tint = colors.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
}
/** The pill a previewed Library shows, so the fake state is never mistaken for the real one. */
@Composable
internal fun LibraryPreviewPill(modifier: Modifier = Modifier) {
@@ -255,17 +215,6 @@ internal fun UiZooSheet() {
DrawerPreview.GAME to R.string.session_title_game,
)) ActionRow(stringResource(label), null, show, onClick = { close(); DevPreview.drawer = mode }, modifier = Modifier.testTag("zoo-drawer-${mode.name.lowercase()}"))
}
SettingsGroup(stringResource(R.string.dev_preview_steam_home)) {
for ((mode, label) in listOf(
SteamHomePreview.NONE to R.string.dev_preview_steam_none,
SteamHomePreview.FEW to R.string.dev_preview_steam_few,
SteamHomePreview.MANY to R.string.dev_preview_steam_many,
)) ActionRow(
stringResource(label), null, show,
onClick = { close(); DevPreview.steamHome = mode; DevPreview.openSteam = true },
modifier = Modifier.testTag("zoo-steam-${mode.name.lowercase()}"),
)
}
SettingsGroup(stringResource(R.string.dev_preview_library)) {
for ((mode, label) in listOf(
LibraryPreview.NOTHING_INSTALLED to R.string.dev_preview_library_nothing_installed,
@@ -272,10 +272,7 @@ private fun Content(
return
}
if (selected == "steam") {
Box(modifier) {
SteamHome(s, a, Modifier.fillMaxSize())
SteamHomePreviewPill(Modifier.align(androidx.compose.ui.Alignment.BottomCenter).padding(bottom = 20.dp))
}
SteamHome(s, a, modifier)
return
}
if (selected == "store") {
@@ -658,11 +658,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
LaunchedEffect(SetupTabs.openSection) {
if (SetupTabs.openSection != null && (railSelection != "setup" || s.pageKey != null)) showRailPage("setup", true)
}
LaunchedEffect(DevPreview.openSteam) {
if (!DevPreview.openSteam) return@LaunchedEffect
DevPreview.openSteam = false
showRailPage("steam", true)
}
LaunchedEffect(DevPreview.openLibrary) {
if (!DevPreview.openLibrary) return@LaunchedEffect
DevPreview.openLibrary = false
@@ -113,8 +113,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
}
val owned = remember(ownedAll, concealed) { ownedAll.filter { it.first.toLong() !in concealed } }
val featured = remember(featuredAll, concealed) { featuredAll.filter { it.appId.toLong() !in concealed } }
val previewing = DevPreview.steamHome
val games = remember(s.steamGames, previewing, LibraryHidden.keys, LibraryHidden.steam) { (if (previewing == SteamHomePreview.OFF) s.steamGames else sampleSteamHomeGames(previewing.games)).filterNot { LibraryHidden.isHidden(hideKey(it), it) }.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
val games = remember(s.steamGames, LibraryHidden.keys, LibraryHidden.steam) { s.steamGames.filterNot { LibraryHidden.isHidden(hideKey(it), it) }.sortedWith(compareByDescending<Library.SteamGame> { it.lastPlayed }.thenBy { it.gameId }) }
val narrow = LocalNarrowPane.current
var words by remember { mutableStateOf<Rect?>(null) }
val mode = com.droiddeck.launcher.session.SessionService.MODE_STEAM
@@ -164,12 +163,12 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
games.isEmpty() -> EmptyLibrary(
avoid = words,
wall = if (owned.isEmpty() && featured.isEmpty()) null else { { CapsuleWall(emptyList(), owned = owned, featured = featured) } },
) { Box(Modifier.fillMaxSize().graphicsLayer { scaleX = 1.06f; scaleY = 1.06f }) { WallFade(bottomWhenTall = true) } }
) { Box(Modifier.fillMaxSize().graphicsLayer { scaleX = 1.06f; scaleY = 1.06f }) { WallFade() } }
games.size < WALL_MIN_GAMES -> CapsuleFan(games)
else -> CapsuleWall(games, owned = owned, featured = featured)
}
},
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade(bottomWhenTall = true) },
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
words = {
val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
@@ -233,35 +232,19 @@ internal fun Modifier.overhang(by: androidx.compose.ui.unit.Dp = 4.dp): Modifier
}
@Composable
internal fun WallFade(modifier: Modifier = Modifier.fillMaxSize().overhang(), bottomWhenTall: Boolean = false) {
internal fun WallFade(modifier: Modifier = Modifier.fillMaxSize().overhang()) {
val colors = MaterialTheme.colorScheme
BoxWithConstraints(modifier) {
if (bottomWhenTall && maxHeight > maxWidth) {
// The words sit at the bottom of a tall page, so the art stays clear above them and darkens only behind them.
Box(
Modifier.fillMaxSize().background(
Brush.verticalGradient(
0f to colors.background.copy(alpha = 0.12f),
0.5f to colors.background.copy(alpha = 0.18f),
0.72f to colors.background.copy(alpha = 0.72f),
1f to colors.background.copy(alpha = 0.94f),
),
),
)
} else {
Box(
Modifier.fillMaxSize().background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.86f),
0.34f to colors.background.copy(alpha = 0.6f),
0.68f to colors.background.copy(alpha = 0.14f),
1f to colors.background.copy(alpha = 0.04f),
),
),
)
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
}
}
Box(
modifier.background(
Brush.horizontalGradient(
0f to colors.background.copy(alpha = 0.86f),
0.34f to colors.background.copy(alpha = 0.6f),
0.68f to colors.background.copy(alpha = 0.14f),
1f to colors.background.copy(alpha = 0.04f),
),
),
)
Box(modifier.background(Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f))))
}
@Composable
@@ -404,45 +387,31 @@ private fun CapsuleFan(games: List<Library.SteamGame>) {
transition.animateFloat(0f, 1f, infiniteRepeatable(tween(ms, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "float")
}
val still = Motion.scale == 0f
val landscape = listOf(
val slots = listOf(
FanSlot(0.54f, 0.14f, 0.62f, -9f),
FanSlot(0.70f, 0.24f, 0.56f, 5f),
FanSlot(0.40f, 0.30f, 0.50f, -17f),
)
// A tall page sizes the cards from its width, so they fit any aspect; heights are fractions of the width.
val portrait = listOf(
FanSlot(0.27f, 0.11f, 0.70f, -9f),
FanSlot(0.55f, 0.19f, 0.64f, 5f),
FanSlot(0.04f, 0.26f, 0.56f, -17f),
)
BoxWithConstraints(
Modifier.fillMaxSize().drawBehind {
drawRect(
Brush.radialGradient(
listOf(pal.signal.copy(alpha = 0.14f), Color.Transparent),
center = if (size.height > size.width) Offset(size.width * 0.55f, size.height * 0.28f) else Offset(size.width * 0.68f, size.height * 0.45f),
radius = if (size.height > size.width) size.width * 0.9f else size.height * 0.6f,
center = Offset(size.width * 0.68f, size.height * 0.45f), radius = size.height * 0.6f,
),
)
},
) {
val radius = with(density) { 14.dp.toPx() }
val tall = maxHeight > maxWidth
val slots = if (tall) portrait else landscape
for (i in games.indices.reversed()) {
val slot = slots[i]
val h = if (tall) maxWidth * slot.height else maxHeight * slot.height
val x = if (tall) {
// The lean and the float swing the corners out by about h/2 * sin(angle).
val swing = h * kotlin.math.sin(Math.toRadians(kotlin.math.abs(slot.lean) + 2.0)).toFloat() / 2f
(maxWidth * slot.x).coerceIn(swing, (maxWidth - h * 2f / 3f - swing).coerceAtLeast(swing))
} else maxWidth * slot.x
val h = maxHeight * slot.height
val v: State<Float> = floats[i]
val look = WallCapsule(artBrush(hueOf(games[i].name)), games[i].art)
val art = look.art?.let { rememberCapsuleArt(it, with(density) { Size((h * 2f / 3f).toPx(), h.toPx()) }, radius) }
Spacer(
Modifier
.offset(x = x, y = maxHeight * slot.y)
.offset(x = maxWidth * slot.x, y = maxHeight * slot.y)
.size(h * 2f / 3f, h)
.graphicsLayer {
val t = if (still) 0f else v.value
-4
View File
@@ -4376,10 +4376,6 @@
<string name="dev_ui_zoo_open">Open</string>
<string name="dev_ui_zoo_show">Show</string>
<string name="dev_ui_zoo_note">Previews change nothing real: nothing is installed, removed or signed out, and the menu\'s switches save nothing. A Library preview stays until you end it from its pill or restart.</string>
<string name="dev_preview_steam_home">Steam home</string>
<string name="dev_preview_steam_none">No games installed</string>
<string name="dev_preview_steam_few">3 games installed</string>
<string name="dev_preview_steam_many">12 games installed</string>
<string name="dev_preview_library">Library</string>
<string name="dev_preview_library_nothing_installed">Nothing installed</string>
<string name="dev_preview_library_signed_out">Signed out of every store</string>
@@ -4,6 +4,7 @@ import android.content.Intent
import android.os.BatteryManager
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
@@ -13,6 +14,7 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.util.concurrent.atomic.AtomicBoolean
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
@@ -36,6 +38,23 @@ class ClockLogComponentTest {
assertTrue(log.readText(), log.readText().contains("| battery 42.3 C"))
}
@Test fun aSuspendedSessionTakesNoSamplesUntilItResumes() {
val context = RuntimeEnvironment.getApplication()
context.sendStickyBroadcast(Intent(Intent.ACTION_BATTERY_CHANGED).putExtra(BatteryManager.EXTRA_TEMPERATURE, 412))
val log = tmp.newFile("suspended-clocks.log")
val suspended = AtomicBoolean(true)
clocks = ClockLogComponent(log) { suspended.get() }.also { it.attach(context); it.start() }
val headerDeadline = System.currentTimeMillis() + 5_000
while (!log.readText().contains("gpu floor:") && System.currentTimeMillis() < headerDeadline) Thread.sleep(20)
assertTrue(log.readText(), log.readText().contains("gpu floor:"))
Thread.sleep(500)
assertFalse(log.readText(), log.readText().contains("| battery"))
suspended.set(false)
val resumedDeadline = System.currentTimeMillis() + 5_000
while (!log.readText().contains("| battery 41.2 C") && System.currentTimeMillis() < resumedDeadline) Thread.sleep(20)
assertTrue(log.readText(), log.readText().contains("| battery 41.2 C"))
}
@Test fun stoppedComponentCannotStartFromAnEarlierSnapshot() {
val context = RuntimeEnvironment.getApplication()
val log = tmp.newFile("stopped-clocks.log")
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.session
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLog
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class MemoryLogTest {
@Before fun clear() {
MemoryLog.stop()
ShadowLog.clear()
}
@After fun reset() {
MemoryLog.stop()
SessionState.suspended = false
}
@Test fun aRunningSessionLogsMemory() {
SessionState.suspended = false
MemoryLog.start()
val deadline = System.currentTimeMillis() + 5_000
while (ShadowLog.getLogsForTag("Memory").isEmpty() && System.currentTimeMillis() < deadline) Thread.sleep(20)
assertTrue(ShadowLog.getLogsForTag("Memory").isNotEmpty())
}
@Test fun aSuspendedSessionLogsNoMemory() {
SessionState.suspended = true
MemoryLog.start()
Thread.sleep(1_500)
assertTrue(ShadowLog.getLogsForTag("Memory").map { it.msg }.toString(), ShadowLog.getLogsForTag("Memory").isEmpty())
}
}
@@ -1099,7 +1099,6 @@ def newest_foreign_backup(backups):
def restore_compatible_system_dlls(prefix, proton, env=None):
restored = []
game = (env or {}).get("STEAM_COMPAT_INSTALL_PATH")
for folder, name, path, source, machines, builtins, backups in prefix_system_dlls(prefix, proton, env):
if not path.is_symlink() or not path.is_file():
continue
@@ -1112,7 +1111,7 @@ def restore_compatible_system_dlls(prefix, proton, env=None):
if backup is None or backup.is_symlink() or not backup.is_file():
continue
machine = pe_machine(backup)
if machine is None or not PE["machine_compatible"](backup, machines, machine, builtins, name, game):
if machine is None or not PE["machine_compatible"](backup, machines, machine, builtins, name):
continue
try:
os.replace(backup, path)
@@ -1124,12 +1123,11 @@ def restore_compatible_system_dlls(prefix, proton, env=None):
def repair_foreign_system_dlls(prefix, proton, env=None):
repaired = []
game = (env or {}).get("STEAM_COMPAT_INSTALL_PATH")
for folder, name, path, source, machines, builtins, backups in prefix_system_dlls(prefix, proton, env):
if path.is_symlink() or not path.is_file():
continue
machine = pe_machine(path)
if machine is None or PE["machine_compatible"](path, machines, machine, builtins, game=game):
if machine is None or PE["machine_compatible"](path, machines, machine, builtins):
continue
link = path.parent / (name + ".dd-new")
backup = path.parent / (name + FOREIGN_SUFFIX)
@@ -479,7 +479,7 @@ def save_state(compat, state):
os.replace(temp, compat / STATE)
def foreign_component(rel, path, machines, dist=None, game=None):
def foreign_component(rel, path, machines, dist=None):
parts = Path(rel).parts
folder = parts[2] if len(parts) > 2 and parts[:2] == ("drive_c", "windows") else None
if not machines or folder not in PE_MACHINES or not rel.lower().endswith(".dll"):
@@ -487,7 +487,7 @@ def foreign_component(rel, path, machines, dist=None, game=None):
machine = pe_machine(path)
libdir, compatible = machines[folder]
builtins = dist / libdir if dist else None
return machine is not None and not machine_compatible(path, compatible, machine, builtins, game=game)
return machine is not None and not machine_compatible(path, compatible, machine, builtins)
def pending_for(app_id, pending=PENDING):
@@ -549,7 +549,6 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
placed_stems = set()
machines = PE["proton_pe_machines"](proton, env) if proton else None
dist = Path(proton).parent / "files/lib/wine" if proton else None
game = (env or {}).get("STEAM_COMPAT_INSTALL_PATH")
saved_overrides = state.get("overrides") if isinstance(state.get("overrides"), dict) else {}
saved_requires = state.get("requires") if isinstance(state.get("requires"), dict) else {}
recorded = [c for c in state.get("components", []) if isinstance(c, str) and valid_id(c)]
@@ -589,7 +588,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
kept_requires[cid] = list(requires)
values += [(cid, value) for value in registry]
for rel, src in files:
foreign = foreign_component(rel, src, machines, dist, game)
foreign = foreign_component(rel, src, machines, dist)
if foreign:
skipped.add(Path(rel).stem.lower())
changed = False
@@ -610,10 +609,9 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
path = existing(pfx / rel)
saved = compat / BACKUP / rel
if saved.is_file():
if foreign_component(rel, saved, machines, dist, game):
if foreign_component(rel, saved, machines, dist):
if path is not None and not path.is_symlink():
path.unlink()
keep[rel] = cid
continue
target = path or (pfx / rel)
os.replace(saved, target)
@@ -1,12 +1,8 @@
#!/usr/bin/python3
import mmap
import os
import re
from pathlib import Path
VC_RUNTIME = re.compile(r"(msvc[pr]\d.*|vcruntime\d.*|vcomp\d*|vcamp\d.*|vccorlib\d.*|concrt\d.*|mfcm?\d.*)\.dll",
re.IGNORECASE)
PE_MACHINES = {
"system32": ("aarch64-windows", frozenset((0xAA64, 0xA641))),
"syswow64": ("i386-windows", frozenset((0x14C,))),
@@ -83,8 +79,8 @@ def pe_has_arm64ec_metadata(path):
def pe_imports(path):
try:
with open(path, "rb") as source:
image = mmap.mmap(source.fileno(), 0, access=mmap.ACCESS_READ)
except (OSError, ValueError):
image = source.read()
except OSError:
return None
try:
if image[:2] != b"MZ":
@@ -141,13 +137,9 @@ def pe_imports(path):
return names
except (IndexError, ValueError):
return None
finally:
image.close()
PROGRAM_IMPORTS = {}
GAME_IMPORTS = {}
GAME_DEPTH = 4
def program_imports(builtins):
@@ -174,42 +166,13 @@ def program_imports(builtins):
return PROGRAM_IMPORTS[key]
def game_imports(folder):
key = str(folder)
if key not in GAME_IMPORTS:
arm64, arm64ec = set(), set()
root = os.path.realpath(folder)
for top, dirs, files in os.walk(root):
if os.path.relpath(top, root).count(os.sep) >= GAME_DEPTH:
dirs[:] = []
for entry in files:
if not entry.lower().endswith((".exe", ".dll")):
continue
path = os.path.join(top, entry)
machine = pe_machine(path)
if machine == 0xAA64:
found = arm64
elif machine == 0x8664 and pe_has_arm64ec_metadata(path):
found = arm64ec
else:
continue
found |= pe_imports(path) or set()
GAME_IMPORTS[key] = (frozenset(arm64), frozenset(arm64ec))
return GAME_IMPORTS[key]
def machine_compatible(path, machines, machine=None, builtins=None, name=None, game=None):
def machine_compatible(path, machines, machine=None, builtins=None, name=None):
machine = pe_machine(path) if machine is None else machine
if machine == 0x8664 and 0xA641 in machines:
if pe_has_arm64ec_metadata(path):
return True
imported = program_imports(builtins) if builtins is not None else None
name = (name or Path(path).name).lower()
if game:
arm64, arm64ec = game_imports(game)
if name in arm64 or (name in arm64ec and VC_RUNTIME.fullmatch(name)):
return False
return imported is not None and name not in imported
return imported is not None and (name or Path(path).name).lower() not in imported
if machine == 0x8664 and pe_has_arm64ec_metadata(path):
return False
return machine in machines
-118
View File
@@ -3499,22 +3499,6 @@ def program_image(machine, imports):
return bytes(image)
def arm64ec_program_image(imports):
image = bytearray(program_image(0x8664, imports))
directory = 68 + 20 + 112 + 10 * 8
image[directory:directory + 4] = (0x1100).to_bytes(4, "little")
image[directory + 4:directory + 8] = (0xD0).to_bytes(4, "little")
image[0x300:0x304] = (0xD0).to_bytes(4, "little")
image[0x3C8:0x3D0] = (0x10000000).to_bytes(8, "little")
return bytes(image)
def arm64x_program_image(imports):
image = bytearray(arm64ec_program_image(imports))
image[68:70] = (0xAA64).to_bytes(2, "little")
return bytes(image)
def bytes_path(folder, data):
path = folder / "image.exe"
path.write_bytes(data)
@@ -3589,108 +3573,6 @@ class ForeignSystemDllTest(unittest.TestCase):
self.assertFalse((windows / "system32" / name).is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
def arm64ec_game(self, tmp, shipping):
game = Path(tmp) / "common/Game"
binaries = game / "Game/Binaries/Win64"
binaries.mkdir(parents=True)
(game / "Game.exe").write_bytes(program_image(0x8664, ["kernel32.dll"]))
(binaries / "Game-Win64-Shipping.exe").write_bytes(shipping)
(binaries / "plugin.dll").write_bytes(program_image(0x8664, ["concrt140.dll"]))
return {"STEAM_COMPAT_INSTALL_PATH": str(game)}
def visual_cpp_prefix(self, tmp):
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
for name in ("vcruntime140.dll", "msvcp140.dll", "concrt140.dll", "vulkan-1.dll", "d3dcompiler_47.dll"):
(builtins / name).write_bytes(program_image(0xAA64, []))
(windows / "system32" / name.upper()).write_bytes(pe_image(0x8664))
return proton, compat, windows
def test_x64_runtime_an_arm64ec_game_image_imports_is_replaced_by_the_builtin(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.visual_cpp_prefix(tmp)
env = self.arm64ec_game(tmp, arm64ec_program_image(["VCRUNTIME140.dll", "MSVCP140.dll", "vulkan-1.dll"]))
fixed = MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env)
self.assertEqual(["system32/MSVCP140.DLL (machine 0x8664)", "system32/VCRUNTIME140.DLL (machine 0x8664)"], fixed)
for name in ("CONCRT140.DLL", "VULKAN-1.DLL"):
self.assertFalse((windows / "system32" / name).is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton), env))
self.assertEqual([], MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env))
restored = MODULE["restore_compatible_system_dlls"](str(compat), str(proton))
self.assertEqual(2, len(restored))
self.assertFalse((windows / "system32/VCRUNTIME140.DLL").is_symlink())
def test_x64_runtime_stays_for_x64_games_and_launches_without_a_game_folder(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.visual_cpp_prefix(tmp)
env = self.arm64ec_game(tmp, program_image(0x8664, ["VCRUNTIME140.dll", "MSVCP140.dll"]))
self.assertEqual([], MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env))
self.assertEqual([], MODULE["repair_foreign_system_dlls"](str(compat), str(proton), {}))
self.assertEqual([], MODULE["repair_foreign_system_dlls"](
str(compat), str(proton), {"STEAM_COMPAT_INSTALL_PATH": str(Path(tmp) / "missing")}))
for name in ("VCRUNTIME140.DLL", "MSVCP140.DLL"):
self.assertFalse((windows / "system32" / name).is_symlink())
def arm64_game(self, tmp, exe_imports, plugin_imports=()):
game = Path(tmp) / "common/Game"
binaries = game / "BinArm64"
binaries.mkdir(parents=True)
(game / "Game.exe").write_bytes(program_image(0x8664, ["kernel32.dll"]))
(binaries / "Game.arm64.exe").write_bytes(program_image(0xAA64, exe_imports))
(binaries / "plugin.dll").write_bytes(arm64x_program_image(list(plugin_imports)))
return {"STEAM_COMPAT_INSTALL_PATH": str(game)}
def test_x64_dlls_an_arm64_game_image_imports_are_replaced_by_the_builtins(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.visual_cpp_prefix(tmp)
env = self.arm64_game(tmp, ["MSVCP140.dll", "D3DCOMPILER_47.dll"], ["VCRUNTIME140.dll"])
fixed = MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env)
self.assertEqual(["system32/D3DCOMPILER_47.DLL (machine 0x8664)", "system32/MSVCP140.DLL (machine 0x8664)",
"system32/VCRUNTIME140.DLL (machine 0x8664)"], fixed)
for name in ("D3DCOMPILER_47.DLL", "MSVCP140.DLL", "VCRUNTIME140.DLL"):
self.assertTrue((windows / "system32" / name).is_symlink())
self.assertEqual(0xAA64, MODULE["pe_machine"](windows / "system32" / name))
for name in ("CONCRT140.DLL", "VULKAN-1.DLL"):
self.assertFalse((windows / "system32" / name).is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton), env))
self.assertEqual([], MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env))
self.assertEqual(3, len(MODULE["restore_compatible_system_dlls"](str(compat), str(proton))))
self.assertFalse((windows / "system32/D3DCOMPILER_47.DLL").is_symlink())
def test_x64_dlls_an_arm64_game_does_not_import_stay(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.visual_cpp_prefix(tmp)
env = self.arm64_game(tmp, ["kernel32.dll"], ["user32.dll"])
self.assertEqual([], MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env))
for name in ("D3DCOMPILER_47.DLL", "MSVCP140.DLL", "VCRUNTIME140.DLL"):
self.assertFalse((windows / "system32" / name).is_symlink())
def test_non_runtime_dlls_stay_for_x64_and_arm64ec_games(self):
for shipping in (program_image(0x8664, ["MSVCP140.dll", "D3DCOMPILER_47.dll"]),
arm64ec_program_image(["D3DCOMPILER_47.dll"])):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.visual_cpp_prefix(tmp)
env = self.arm64ec_game(tmp, shipping)
self.assertEqual([], MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env))
for name in ("D3DCOMPILER_47.DLL", "MSVCP140.DLL"):
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
def test_arm64ec_images_below_the_scanned_depth_are_ignored(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.visual_cpp_prefix(tmp)
game = Path(tmp) / "common/Deep"
deep = game.joinpath(*("d%d" % level for level in range(MODULE["PE"]["GAME_DEPTH"] + 2)))
deep.mkdir(parents=True)
(deep / "tool.exe").write_bytes(arm64ec_program_image(["VCRUNTIME140.dll"]))
env = {"STEAM_COMPAT_INSTALL_PATH": str(game)}
self.assertEqual([], MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env))
(deep.parent / "tool.exe").write_bytes(arm64ec_program_image(["VCRUNTIME140.dll"]))
MODULE["PE"]["GAME_IMPORTS"].clear()
self.assertEqual(["system32/VCRUNTIME140.DLL (machine 0x8664)"],
MODULE["repair_foreign_system_dlls"](str(compat), str(proton), env))
def test_repaired_dll_proton_programs_do_not_import_gets_its_native_copy_back(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
-52
View File
@@ -6,8 +6,6 @@ import unittest
from pathlib import Path
from unittest import mock
from tools.tests.test_game_environment import arm64ec_program_image, program_image
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
MODULE = runpy.run_path(str(BIN / "droiddeck-wincomponents"))
GAME_ENV = runpy.run_path(str(BIN / "droiddeck-game-env"))
@@ -171,56 +169,6 @@ class WinComponentsTest(unittest.TestCase):
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/msvcp140.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vcruntime140.dll"), 0x8664)
def test_x64_runtime_an_arm64ec_game_imports_is_not_placed(self):
proton = self.proton()
game = Path(self.tmp.name) / "common/Game/Game/Binaries/Win64"
game.mkdir(parents=True)
(game / "Game-Win64-Shippingarm64ec.exe").write_bytes(arm64ec_program_image(["MSVCP140.dll", "VCRUNTIME140.dll"]))
names = ["concrt140", "msvcp140", "vcruntime140"]
self.component("vc", names, {"system32/%s.dll" % name: self.pe_image(0x8664) for name in names})
self.pick("vc")
env = {"STEAM_COMPAT_INSTALL_PATH": str(game.parents[2])}
for _ in range(2):
placed, _ = self.apply(proton, env)
self.assertEqual(placed, ["concrt140"])
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/concrt140.dll"), 0x8664)
self.assertFalse((self.pfx / "system32/msvcp140.dll").exists())
self.assertFalse((self.pfx / "system32/vcruntime140.dll").exists())
def arm64_game(self, imports):
game = Path(self.tmp.name) / "common/Game/BinArm64"
game.mkdir(parents=True)
(game / "Game.arm64.exe").write_bytes(program_image(0xAA64, imports))
return {"STEAM_COMPAT_INSTALL_PATH": str(game.parent)}
def test_x64_dlls_an_arm64_game_imports_are_not_placed(self):
proton = self.proton()
env = self.arm64_game(["MSVCP140.dll", "D3DCOMPILER_47.dll"])
names = ["concrt140", "d3dcompiler_47", "msvcp140", "vcruntime140"]
self.component("vc", names, {"system32/%s.dll" % name: self.pe_image(0x8664) for name in names})
self.pick("vc")
for _ in range(2):
placed, _ = self.apply(proton, env)
self.assertEqual(placed, ["concrt140", "vcruntime140"])
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vcruntime140.dll"), 0x8664)
self.assertFalse((self.pfx / "system32/msvcp140.dll").exists())
self.assertFalse((self.pfx / "system32/d3dcompiler_47.dll").exists())
def test_saved_original_stays_tracked_while_a_game_defers_its_restoration(self):
proton = self.proton()
original = self.pe_image(0x8664) + b"original"
self.pfx.joinpath("system32").mkdir(parents=True)
self.pfx.joinpath("system32/msvcp140.dll").write_bytes(original)
self.component("vc", ["msvcp140"], {"system32/msvcp140.dll": self.pe_image(0x8664)})
self.pick("vc")
self.apply(proton)
self.assertNotEqual(original, (self.pfx / "system32/msvcp140.dll").read_bytes())
self.pick()
self.apply(proton, self.arm64_game(["MSVCP140.dll"]))
self.assertFalse((self.pfx / "system32/msvcp140.dll").exists())
self.apply(proton)
self.assertEqual(original, (self.pfx / "system32/msvcp140.dll").read_bytes())
def test_deselected_component_restores_the_saved_x64_dll(self):
proton = self.proton()
self.pfx.joinpath("system32").mkdir(parents=True)