Compare commits

..
Author SHA1 Message Date
kalac2232 2ab642bf4e fix(session): Handle invalid filenames when trimming page cache
Walk files with NIO and skip unreadable entries. Keep page-cache trimming from interrupting session startup.
2026-12-05 23:34:33 -05:00
Kurt Himebauch cad55fc2b9 Keep adaptive sticks visible at rest
Separate adaptive stick capture from idle visibility and keep dock touch capture bounded.
2026-12-05 23:33:11 -05:00
15 changed files with 144 additions and 163 deletions

No files matched your search

@@ -156,7 +156,13 @@ object InputLibraries {
update(context) { library ->
library.copy(layouts = library.layouts.map { layout ->
if (layout.id != layoutId || !layout.editable) layout
else layout.copy(elements = layout.elements.map { if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = on) else it })
else {
fun updateSticks(elements: List<InputSurfaceElement>) = elements.map {
if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = it.hideStickAtRest, adaptiveCapture = on)
else it
}
layout.copy(elements = updateSticks(layout.elements), rotated = updateSticks(layout.rotated))
}
})
}
}.onSuccess { ControllerPrefs.setAdaptiveSticks(context, on) }.isSuccess
@@ -328,7 +334,8 @@ object InputLibraries {
for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown)
.put("adaptiveCapture", e.adaptiveCapture))
}
private fun decodeElements(array: JSONArray) = array.objects(64).map { e ->
@@ -336,7 +343,8 @@ object InputLibraries {
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false),
if (e.isNull("adaptiveCapture")) null else e.optBoolean("adaptiveCapture", false))
}
internal fun encode(library: InputLibrary): String {
@@ -32,7 +32,7 @@ data class SavedInputLayout(
fun withQuickButton(button: InputCommand, shown: Boolean) =
copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button))
fun derived(id: String, name: String) = copy(id = id, name = name, origin = origin ?: this.id)
val adaptiveSticks get() = elements.filter { it.kind == InputElementKind.STICK }.takeIf { editable && it.isNotEmpty() }?.all { it.floating && it.hideWhenIdle }
val adaptiveSticks get() = elements.filter { it.kind == InputElementKind.STICK }.takeIf { editable && it.isNotEmpty() }?.all { it.adaptiveStick }
fun supports(role: InputRole) = screen.supports(role) && when (template) {
InputLayoutTemplate.OVERLAY -> role == InputRole.PRIMARY
InputLayoutTemplate.DECK, InputLayoutTemplate.TRACKPAD -> role == InputRole.SECONDARY
@@ -37,7 +37,12 @@ data class InputSurfaceElement(
val buttonShape: InputButtonShape = InputButtonShape.ROUNDED,
val showLabel: Boolean = true,
val alwaysShown: Boolean = false,
val adaptiveCapture: Boolean? = null,
) {
// Old layouts encoded Adaptive sticks as Floating + Hide when idle.
val adaptiveStick get() = kind == InputElementKind.STICK && floating && (adaptiveCapture ?: hideWhenIdle)
val hideStickAtRest get() = hideWhenIdle && (adaptiveCapture != null || !adaptiveStick)
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
fun bounded() = copy(x = x.coerceIn(0f, 0.97f), y = y.coerceIn(0f, 0.97f),
@@ -188,7 +188,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton)
}.map { c ->
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, adaptiveCapture = if (c.stick >= 0) settings.adaptiveSticks else null,
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded()
}.toMutableList()
if (settings.keyboardButton) result += keyboard()
@@ -37,8 +37,10 @@ object OnScreenLayout {
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
val placed = placeElements(context, saved, width, height, safe, buttonsOnly, dock, rearButtons, trackpads)
// Below the game a stick covers nothing, so it keeps its base in view instead of appearing only under the thumb.
return if (dock == null) placed else placed.map { if (it.kind == InputElementKind.STICK) it.copy(hideWhenIdle = false) else it }
// Docked sticks stay visible and only pick up touches inside their own bounds.
return if (dock == null) placed else placed.map {
if (it.kind == InputElementKind.STICK) it.copy(hideWhenIdle = false, adaptiveCapture = false) else it
}
}
private fun placeElements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
@@ -2,10 +2,16 @@ package com.droiddeck.launcher.session
import android.util.Log
import java.io.File
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
internal object PageCacheTrim {
private const val TAG = "PageCacheTrim"
private const val MIN_FILE_BYTES = 8L shl 20
internal const val MIN_FILE_BYTES = 8L shl 20
private const val POLL_MS = 3000L
private const val RESCAN_MS = 120_000L
@@ -37,7 +43,7 @@ internal object PageCacheTrim {
if (mem != null && shouldTrim(mem, baseline)) {
val now = System.currentTimeMillis()
if (now - scanned > RESCAN_MS) {
files = roots().flatMap { root -> root.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.filter { it.isFile && it.length() >= MIN_FILE_BYTES }.toList() }
files = roots().flatMap { root -> bigFiles(root) }
scanned = now
}
val began = System.nanoTime()
@@ -56,6 +62,34 @@ internal object PageCacheTrim {
}, "page-cache-trim").apply { isDaemon = true }.start()
}
// java.io's directory listing hands raw entry names to JNI NewStringUTF, which aborts the
// process on names that are not valid UTF-8; NIO decodes them with replacement instead.
// Without FOLLOW_LINKS, symlinked directories are never descended into, like the old onEnter,
// except that a starting directory that is itself a link has to be resolved first; a link
// whose target has vanished yields an empty result instead of an error.
internal fun bigFiles(root: File): List<File> {
val out = ArrayList<File>()
val start = root.toPath()
val real = if (Files.isSymbolicLink(start)) {
try {
start.toRealPath()
} catch (_: IOException) {
return out
}
} else start
Files.walkFileTree(real, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (attrs.isRegularFile && attrs.size() >= MIN_FILE_BYTES) out.add(file.toFile())
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, error: IOException): FileVisitResult = FileVisitResult.CONTINUE
override fun postVisitDirectory(dir: Path, error: IOException?): FileVisitResult = FileVisitResult.CONTINUE
})
return out
}
private fun drop(file: File) {
PageCacheNative.fadviseDontNeed(file.path)
}
@@ -67,8 +67,18 @@ internal fun InputElementProperties(element: InputSurfaceElement, action: InputA
}
if (element.kind == InputElementKind.STICK) {
val host = rememberMenuHost()
ToggleRow(host, "element-floating", stringResource(R.string.input_floating_stick), null, element.floating) { onChange(element.copy(floating = it)) }
ToggleRow(host, "element-hide-idle", stringResource(R.string.input_hide_idle), null, element.hideWhenIdle) { onChange(element.copy(hideWhenIdle = it)) }
val adaptive = element.adaptiveCapture ?: element.adaptiveStick
ToggleRow(host, "element-floating", stringResource(R.string.input_floating_stick), null, element.floating) {
onChange(element.copy(floating = it, hideWhenIdle = element.hideStickAtRest, adaptiveCapture = adaptive))
}
if (element.floating) {
ToggleRow(host, "element-adaptive-capture", stringResource(R.string.input_adaptive_capture), null, element.adaptiveStick) {
onChange(element.copy(hideWhenIdle = element.hideStickAtRest, adaptiveCapture = it))
}
}
ToggleRow(host, "element-hide-idle", stringResource(R.string.input_hide_idle), null, element.hideStickAtRest) {
onChange(element.copy(hideWhenIdle = it, adaptiveCapture = adaptive))
}
}
val host = rememberMenuHost()
if ((element.kind == InputElementKind.BUTTON || element.kind == InputElementKind.TRIGGER) && element.icon == 0 && element.image.isEmpty() ||
@@ -236,11 +236,11 @@ class InputSurfaceView(
super.dispatchDraw(canvas)
}
}
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) }
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || it.adaptiveStick) }
for (element in customLayout) {
val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } }
canvas.addView(when (element.kind) {
InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null)
InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideStickAtRest && pad != null)
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel,
stock = element.id == "legacy:${element.control.id}", source = source)
InputElementKind.DPAD -> DirectionPad(context, element, source)
@@ -641,7 +641,7 @@ class InputSurfaceView(
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
val adaptive get() = adaptive(element)
val adaptive get() = element.adaptiveStick
fun reach() = min(width, height) * if (classic(element)) CLASSIC_REACH else PANEL_REACH
@@ -859,8 +859,6 @@ class InputSurfaceView(
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
private fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating && element.hideWhenIdle
private fun classic(element: InputSurfaceElement) = (element.id == "legacy:${element.control.id}" || element.id == "builtin:keyboard") &&
(element.buttonShape == InputButtonShape.CIRCLE || element.buttonShape == InputButtonShape.PILL)
@@ -74,6 +74,7 @@
<string name="input_keep_shared">Keep shared</string>
<string name="input_independent_copy">Independent copy</string>
<string name="input_floating_stick">Start stick at touch position</string>
<string name="input_adaptive_capture">Adaptive touch area</string>
<string name="input_hide_idle">Hide stick when not in use</string>
<string name="input_tools">Tools</string>
<string name="input_quick_auto">Auto (%1$s)</string>
@@ -467,6 +467,7 @@ class InputLibraryTest {
val enabled = InputLibraries.read(context)
val changed = enabled.layouts.single { it.id == overlay.id }
assertEquals(true, changed.adaptiveSticks)
assertTrue(changed.elements.filter { it.kind == InputElementKind.STICK }.all { !it.hideStickAtRest && it.adaptiveCapture == true })
assertTrue(ControllerPrefs.read(context).adaptiveSticks)
assertEquals(overlay.elements.filter { it.kind != InputElementKind.STICK }, changed.elements.filter { it.kind != InputElementKind.STICK })
assertEquals(library.layouts.filter { it.id != overlay.id }, enabled.layouts.filter { it.id != overlay.id })
@@ -336,6 +336,20 @@ class OnScreenLayoutTest {
}
}
@Test fun dockedSticksStayVisibleWithoutExpandingTheirTouchArea() {
val custom = InputSurfaceElement(InputControl.LS, .2f, .2f, .2f, .3f,
id = "custom-stick", hideWhenIdle = true, adaptiveCapture = true)
val layout = SavedInputLayout("custom", "Custom", listOf(custom), aspect = 1.5f)
val overlay = OnScreenLayout.elements(context, layout, 1200, 800, Rect()).single()
assertTrue(overlay.adaptiveStick)
assertTrue(overlay.hideStickAtRest)
val docked = OnScreenLayout.elements(context, layout, 1200, 800, Rect(),
dock = OnScreenLayout.Dock(false, false)).single()
assertFalse(docked.adaptiveStick)
assertFalse(docked.hideStickAtRest)
assertTrue(docked.floating)
}
@Test fun dockedControlsStayInsideTheSafeAreaAtTheDefaultSizeWithoutAControllerKit() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
ControllerPrefs.setSize(context, 100)
@@ -5,6 +5,8 @@ import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.nio.file.Files
import java.nio.file.Path
class PageCacheTrimTest {
private val meminfo = "MemFree: 1048576 kB\nActive(file): 2097152 kB\nInactive(file): 1048576 kB\n"
@@ -15,4 +17,31 @@ class PageCacheTrimTest {
@Test fun skipsSmallBuildUp() = assertFalse(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(2000 * 1024, 1200 * 1024), 1000 * 1024))
@Test fun skipsWhenPlentyFree() = assertFalse(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(6000 * 1024, 5000 * 1024), 1000 * 1024))
@Test fun lowFreeAcceptsSmallerBuildUp() = assertTrue(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(500 * 1024, 1200 * 1024), 1000 * 1024))
@Test fun bigFilesSkipLinksButEnterALinkedRoot() {
fun big(dir: Path, name: String): Path = Files.createFile(dir.resolve(name)).also {
java.io.RandomAccessFile(it.toFile(), "rw").use { it.setLength(PageCacheTrim.MIN_FILE_BYTES + 1) }
}
val base = Files.createTempDirectory("dd-trim")
try {
val root = Files.createDirectories(base.resolve("root"))
val outside = Files.createDirectories(base.resolve("outside"))
val big = big(root, "big.bin")
big(Files.createDirectories(root.resolve("sub")), "nested.bin")
Files.createFile(root.resolve("small.bin"))
big(outside, "outside.bin")
Files.createSymbolicLink(root.resolve("linked-dir"), outside)
Files.createSymbolicLink(root.resolve("linked-file"), big)
val rootLink = Files.createSymbolicLink(base.resolve("root-link"), root)
val expected = listOf("big.bin", "nested.bin")
assertEquals(expected, PageCacheTrim.bigFiles(root.toFile()).map { it.name }.sorted())
assertEquals(expected, PageCacheTrim.bigFiles(rootLink.toFile()).map { it.name }.sorted())
val dangling = Files.createSymbolicLink(base.resolve("dangling"), base.resolve("gone"))
assertTrue(PageCacheTrim.bigFiles(dangling.toFile()).isEmpty())
} finally {
base.toFile().deleteRecursively()
}
}
}
@@ -1,6 +1,9 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
@@ -18,6 +21,7 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class])
@@ -355,6 +359,28 @@ class InputSurfaceTouchTest {
touch(MotionEvent.ACTION_UP, 1 to (490f to 170f))
}
@Test @GraphicsMode(GraphicsMode.Mode.NATIVE)
fun adaptiveSticksDrawAtRestUnlessExplicitlyHidden() {
val legacy = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true)
fun idlePixel(e: InputSurfaceElement): Int {
show(e)
val target = element(view, e.id)
val bitmap = Bitmap.createBitmap(target.width, target.height, Bitmap.Config.ARGB_8888)
return try {
target.draw(Canvas(bitmap))
bitmap.getPixel(target.width / 2, target.height / 2)
} finally {
bitmap.recycle()
}
}
assertTrue(Color.alpha(idlePixel(legacy)) > 0)
val visible = legacy.copy(adaptiveCapture = true, hideWhenIdle = false)
assertTrue(Color.alpha(idlePixel(visible)) > 0)
assertTrue(view.takesTouchAt(10f, 300f))
assertEquals(0, Color.alpha(idlePixel(visible.copy(hideWhenIdle = true))))
assertTrue(view.takesTouchAt(10f, 300f))
}
@Test fun adaptiveSticksCaptureAroundThemAndTheLeftOneToTheEdge() {
val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true)
val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, hideWhenIdle = true)
-53
View File
@@ -8,7 +8,6 @@
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
@@ -548,55 +547,3 @@ EXPORT uid_t getuid(void)
}
return (uid_t)raw_getuid();
}
static bool read_at(int fd, void *buf, size_t n, off_t at)
{
return pread(fd, buf, n, at) == (ssize_t)n;
}
static void load_needed_of(const char *path)
{
Elf64_Ehdr e;
Elf64_Phdr ph[32];
Elf64_Dyn dyn[128];
uint64_t strtab = 0, strsz = 0, needed[32];
size_t n_dyn = 0, n_needed = 0;
off_t names_at = -1;
char *names = NULL;
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return;
if (!read_at(fd, &e, sizeof e, 0) || memcmp(e.e_ident, ELFMAG, SELFMAG) || e.e_ident[EI_CLASS] != ELFCLASS64 ||
e.e_phentsize != sizeof *ph || e.e_phnum > 32 || !read_at(fd, ph, e.e_phnum * sizeof *ph, (off_t)e.e_phoff))
goto out;
for (int i = 0; i < e.e_phnum; i++) {
if (ph[i].p_type != PT_DYNAMIC) continue;
n_dyn = ph[i].p_filesz / sizeof *dyn;
if (n_dyn > 128) n_dyn = 128;
if (!read_at(fd, dyn, n_dyn * sizeof *dyn, (off_t)ph[i].p_offset)) goto out;
break;
}
for (size_t i = 0; i < n_dyn && dyn[i].d_tag != DT_NULL; i++) {
if (dyn[i].d_tag == DT_STRTAB) strtab = dyn[i].d_un.d_ptr;
else if (dyn[i].d_tag == DT_STRSZ) strsz = dyn[i].d_un.d_val;
else if (dyn[i].d_tag == DT_NEEDED && n_needed < 32) needed[n_needed++] = dyn[i].d_un.d_val;
}
for (int i = 0; i < e.e_phnum; i++)
if (ph[i].p_type == PT_LOAD && strtab >= ph[i].p_vaddr && strtab - ph[i].p_vaddr + strsz <= ph[i].p_filesz)
names_at = (off_t)(ph[i].p_offset + strtab - ph[i].p_vaddr);
if (names_at < 0 || !strsz || strsz > (16u << 20) || !(names = malloc(strsz + 1)) ||
!read_at(fd, names, strsz, names_at))
goto out;
names[strsz] = 0;
for (size_t i = 0; i < n_needed; i++)
if (needed[i] < strsz && !dlopen(names + needed[i], RTLD_NOW))
say("steamshm: %s, needed by %s, did not load: %s\n", names + needed[i], path, dlerror());
out:
free(names);
close(fd);
}
__attribute__((constructor)) static void link_steamclient_needs_before_it(void)
{
const char *path = getenv("WINESTEAMCLIENTPATH64");
if (path && *path) load_needed_of(path);
}
@@ -1,94 +0,0 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
STEAMSHM = Path(__file__).resolve().parents[1] / "bionic-runtime/steamshm.c"
SOURCES = {
"libsystemxml.so": ("int xml_copy(void) { return 1; }\n", []),
"libvendor.so": ("int xml_copy(void);\nint vendor_xml_copy(void) { return xml_copy(); }\n", ["systemxml"]),
"libframework.so": ("int framework(void) { return 0; }\n", ["vendor"]),
"libsteam.so": ("int xml_copy(void) { return 2; }\nint CreateInterface(void) { return 0; }\n", ["framework"]),
}
LOADER_PRELUDE = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <elf.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define say(...) fprintf(stderr, __VA_ARGS__)
"""
def steamclient_loader():
source = STEAMSHM.read_text()
return LOADER_PRELUDE + source[source.index("static bool read_at("):]
PROGRAM = r"""
#include <dlfcn.h>
#include <stdio.h>
int main(void) {
if (!dlopen("libsteam.so", RTLD_NOW)) { puts(dlerror()); return 1; }
void *vendor = dlopen("libvendor.so", RTLD_NOW | RTLD_NOLOAD);
int (*copy)(void) = vendor ? (int (*)(void))dlsym(vendor, "vendor_xml_copy") : 0;
if (!copy) return 1;
printf("%d\n", copy());
return 0;
}
"""
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
class SteamClientNeedsTest(unittest.TestCase):
def setUp(self):
self.dir = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.dir, True)
for name, (code, needs) in SOURCES.items():
src = self.dir / (name + ".c")
src.write_text(code)
subprocess.run(["cc", "-shared", "-fPIC", "-o", str(self.dir / name), str(src), "-L", str(self.dir),
"-Wl,--no-as-needed", *("-l" + n for n in needs)], check=True)
(self.dir / "main.c").write_text(PROGRAM)
subprocess.run(["cc", "-o", str(self.dir / "main"), str(self.dir / "main.c"), "-ldl"], check=True)
loader = self.dir / "loader.c"
loader.write_text(steamclient_loader())
self.preload = self.dir / "libsteamshm.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-fvisibility=hidden",
str(loader), "-ldl", "-o", str(self.preload)], check=True)
def vendor_binding(self, preload=True, steam=None):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "WINESTEAMCLIENTPATH64")}
env["LD_LIBRARY_PATH"] = str(self.dir)
if steam:
env["WINESTEAMCLIENTPATH64"] = steam
if preload:
env["LD_PRELOAD"] = str(self.preload)
run = subprocess.run([str(self.dir / "main")], env=env, capture_output=True, text=True, check=True)
return run.stdout.strip()
def test_without_the_preload_a_framework_library_binds_to_steams_copy(self):
self.assertEqual(self.vendor_binding(preload=False), "2")
def test_the_libraries_steam_needs_link_to_their_own_copy_first(self):
self.assertEqual(self.vendor_binding(steam=str(self.dir / "libsteam.so")), "1")
def test_without_a_steam_library_path_nothing_is_loaded_early(self):
self.assertEqual(self.vendor_binding(), "2")
def test_a_missing_or_foreign_steam_library_is_ignored(self):
self.assertEqual(self.vendor_binding(steam=str(self.dir / "missing.so")), "2")
self.assertEqual(self.vendor_binding(steam=str(self.dir / "main.c")), "2")
if __name__ == "__main__":
unittest.main()