From 3f3ed3923be5e04e10d6b509c6cb31a2741a53f1 Mon Sep 17 00:00:00 2001 From: TideGear Date: Fri, 16 Oct 2026 10:30:21 -0700 Subject: [PATCH] fix: hold XInput rumble until the game changes it, instead of stopping after a second (#938) --- app/src/main/cpp/fakeinput_steam.cpp | 32 +++--- .../launcher/session/RumbleComponent.kt | 92 +++++++++++++--- .../launcher/session/RumbleComponentTest.kt | 69 ++++++++++-- .../session/SessionLogShareZipTest.kt | 9 +- tools/linuxfs/preload/inputudev.c | 20 ++++ tools/linuxfs/preload/netif.c | 3 + tools/tests/test_winebus_rumble_preload.py | 101 ++++++++++++++++++ 7 files changed, 283 insertions(+), 43 deletions(-) create mode 100644 tools/tests/test_winebus_rumble_preload.py diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp index d1864a277e..71022649c6 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -371,6 +371,17 @@ send_vibration(int strong, int weak, uint16_t duration_ms, uint16_t slot) { syscall(SYS_close, sock); } +// Must match RumbleComponent.HOLD_MS: play until the slot's next effect or stop. +static constexpr uint16_t RUMBLE_HOLD_MS = 0xffff; + +__attribute__((visibility("hidden"))) static void send_ff_effect(const struct ff_effect &effect, uint16_t slot) { + uint16_t duration = effect.replay.length ? effect.replay.length : RUMBLE_HOLD_MS; + if (effect.type == FF_RUMBLE) + send_vibration(effect.u.rumble.strong_magnitude, effect.u.rumble.weak_magnitude, duration, slot); + else if (effect.type == FF_PERIODIC) + send_vibration(effect.u.periodic.magnitude, effect.u.periodic.magnitude, duration, slot); +} + __attribute__((visibility("hidden"))) static void check_ff_event(const struct input_event *ev, uint16_t slot) { if (ev->type != EV_FF) @@ -381,15 +392,7 @@ check_ff_event(const struct input_event *ev, uint16_t slot) { auto it = ff_effects().find(id); if (it == ff_effects().end()) return; - - uint16_t duration = it->second.replay.length; - if (it->second.type == FF_RUMBLE) { - send_vibration(it->second.u.rumble.strong_magnitude, - it->second.u.rumble.weak_magnitude, duration, slot); - } else if (it->second.type == FF_PERIODIC) { - send_vibration(it->second.u.periodic.magnitude, - it->second.u.periodic.magnitude, duration, slot); - } + send_ff_effect(it->second, slot); } else { send_vibration(0, 0, 0, slot); } @@ -3469,16 +3472,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { if (effect->id == -1) effect->id = next_ff_id++; ff_effects()[effect->id] = *effect; - - uint16_t duration = effect->replay.length; - uint16_t slot = static_cast(event_number); - if (effect->type == FF_RUMBLE) { - send_vibration(effect->u.rumble.strong_magnitude, - effect->u.rumble.weak_magnitude, duration, slot); - } else if (effect->type == FF_PERIODIC) { - send_vibration(effect->u.periodic.magnitude, effect->u.periodic.magnitude, - duration, slot); - } + send_ff_effect(*effect, static_cast(event_number)); return 0; } else if (type == 0x45 && number == 0x81) { int id = (intptr_t)argp; diff --git a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt index 8c69891d84..d363177eb0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt @@ -4,6 +4,9 @@ import android.net.LocalServerSocket import android.content.SharedPreferences import android.os.Build import android.os.CombinedVibration +import android.os.Handler +import android.os.HandlerThread +import android.os.Looper import android.os.SystemClock import android.os.VibrationEffect import android.os.Vibrator @@ -21,15 +24,18 @@ class RumbleComponent : SessionPart() { @Volatile private var server: LocalServerSocket? = null private var phone: Motors? = null private val playing = HashMap() - private val sent = HashMap() + private val effects = HashMap() private val controllers = HashMap() private var preferences: SharedPreferences? = null private var enabled = false + private var motorThread: HandlerThread? = null + private var handler: Handler? = null private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == null || key == "rumble") refreshEnabled() } internal var controllerMotors: (Int) -> Motors? = ::lookupController + internal var motorLooper: Looper? = null @Synchronized private fun refreshEnabled() { enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true @@ -42,6 +48,7 @@ class RumbleComponent : SessionPart() { val vibrator = if (Build.VERSION.SDK_INT >= 31) ctx.getSystemService(VibratorManager::class.java)?.defaultVibrator else @Suppress("DEPRECATION") ctx.getSystemService(Vibrator::class.java) phone = vibrator?.takeIf { it.hasVibrator() }?.let { PhoneMotors(it) } + handler = Handler(motorLooper ?: HandlerThread("rumble-motors").also { motorThread = it; it.start() }.looper) preferences = ControllerPrefs.prefs(ctx).also { it.registerOnSharedPreferenceChangeListener(preferenceListener) } refreshEnabled() server = s @@ -66,6 +73,9 @@ class RumbleComponent : SessionPart() { preferences = null enabled = false cancelAll() + handler = null + motorThread?.quitSafely() + motorThread = null phone = null controllers.clear() val s = server @@ -81,24 +91,39 @@ class RumbleComponent : SessionPart() { val previous = playing[slot] if (target !== previous) { previous?.cancel() - sent.remove(slot) + forget(slot) if (target == null) playing.remove(slot) else playing[slot] = target target?.let { Log.i(TAG, "rumble: slot $slot playing on ${it.name}") } } if (target == null) return - if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); sent.remove(slot); return } + if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); forget(slot); return } + val handler = handler ?: return + val effect = effects.getOrPut(slot) { Effect(slot) } + effect.want(strong, weak, ms) val now = SystemClock.uptimeMillis() - val last = sent[slot] - if (last != null && (now - last.at < MIN_GAP_MS || (last.strong == strong && last.weak == weak && now < last.until))) return - val duration = ms.toLong().coerceIn(1L, 5000L) + if (effect.playing(now)) return + handler.removeCallbacks(effect) + val wait = effect.at + MIN_GAP_MS - now + if (wait > 0) handler.postDelayed(effect, wait) else play(effect) + } + + @Synchronized private fun play(effect: Effect) { + val target = playing[effect.slot] + if (target == null || effects[effect.slot] !== effect) return + val duration = if (effect.hold) HOLD_EFFECT_MS else effect.ms.toLong().coerceIn(1L, 5000L) try { - target.play(strong, weak, duration) - sent[slot] = Sent(strong, weak, now, now + duration) + target.play(effect.strong, effect.weak, duration) + effect.played(SystemClock.uptimeMillis(), duration) + if (effect.hold) handler?.postDelayed(effect, KEEPALIVE_MS) } catch (e: Exception) { Log.w(TAG, "rumble: ${target.name}: $e") } } + private fun forget(slot: Int) { + effects.remove(slot)?.let { handler?.removeCallbacks(it) } + } + private fun target(slot: Int): Motors? { val id = PadBridge.controllerForSlot(slot) if (id == PadBridge.NO_CONTROLLER) return phone @@ -109,10 +134,36 @@ class RumbleComponent : SessionPart() { private fun cancelAll() { playing.values.toSet().forEach { it.cancel() } playing.clear() - sent.clear() + effects.values.forEach { handler?.removeCallbacks(it) } + effects.clear() } - private data class Sent(val strong: Int, val weak: Int, val at: Long, val until: Long) + private inner class Effect(val slot: Int) : Runnable { + var strong = 0 + var weak = 0 + var ms = 0 + var at = -MIN_GAP_MS + private var playedStrong = 0 + private var playedWeak = 0 + private var playedMs = 0 + private var until = 0L + val hold get() = ms == HOLD_MS + + fun want(strong: Int, weak: Int, ms: Int) { this.strong = strong; this.weak = weak; this.ms = ms } + + fun playing(now: Long) = playedMs != 0 && playedStrong == strong && playedWeak == weak && playedMs == ms && + (hold || now < until) + + fun played(now: Long, duration: Long) { + playedStrong = strong + playedWeak = weak + playedMs = ms + at = now + until = now + duration + } + + override fun run() = play(this) + } internal interface Motors { val name: String @@ -137,20 +188,35 @@ class RumbleComponent : SessionPart() { any = true } if (ids.size >= 2) { add(ids[0], strong); add(ids[1], weak) } else add(ids[0], max(strong, weak)) - if (any) manager.vibrate(combined.combine()) else manager.cancel() + if (any) manager.vibrate(combined.combine()) else cancel() + } + + // Some vendors' input-device vibrator HALs (Samsung's) don't halt a Bluetooth pad's running + // effect on cancel(), but a new effect always replaces it. + override fun cancel() { + val supersede = CombinedVibration.startParallel() + ids.forEach { supersede.addVibrator(it, VibrationEffect.createOneShot(1L, 1)) } + manager.vibrate(supersede.combine()) + manager.cancel() } - override fun cancel() = manager.cancel() } private class LegacyPadMotors(override val name: String, private val vibrator: Vibrator) : Motors { override fun play(strong: Int, weak: Int, ms: Long) = vibrator.vibrate(oneShot(vibrator, max(strong, weak), ms)) - override fun cancel() = vibrator.cancel() + override fun cancel() { + vibrator.vibrate(VibrationEffect.createOneShot(1L, 1)) + vibrator.cancel() + } } companion object { private const val TAG = "SessionService" const val NAME = "droiddeck-rumble" const val MIN_GAP_MS = 50L + // Must match RUMBLE_HOLD_MS in fakeinput_steam.cpp. + const val HOLD_MS = 0xFFFF + const val HOLD_EFFECT_MS = 2000L + const val KEEPALIVE_MS = 1500L private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect { val amplitude = if (vibrator.hasAmplitudeControl()) (strength * 255L / 65535L).toInt().coerceIn(1, 255) diff --git a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt index b388c1a53f..9a1e2d55ed 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/RumbleComponentTest.kt @@ -35,7 +35,7 @@ class RumbleComponentTest { vibrator = if (Build.VERSION.SDK_INT >= 31) context.getSystemService(VibratorManager::class.java).defaultVibrator else context.getSystemService(Vibrator::class.java) shadowOf(vibrator).setHasVibrator(true) - rumble = RumbleComponent().also { it.attach(context); it.start() } + rumble = RumbleComponent().also { it.motorLooper = Looper.getMainLooper(); it.attach(context); it.start() } } @After fun stopListener() { rumble.stop() } @@ -78,24 +78,73 @@ class RumbleComponentTest { assertFalse("the phone buzzed as well", shadowOf(vibrator).isVibrating) } - @Test fun repeatedAndRapidEffectsDoNotRestartTheMotors() { + @Test fun repeatedAndRapidEffectsDoNotRestartTheMotorsButTheLatestStillLands() { val pad = FakeMotors() rumble.controllerMotors = { pad } activeController(PAD_ID) repeat(5) { effect(strong = 40000, weak = 1000) } effect(strong = 20000, weak = 1000) + effect(strong = 30000, weak = 1000) assertEquals("a stream of packets restarted the motor each time", 1, pad.played.size) - shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofMillis(RumbleComponent.MIN_GAP_MS)) - effect(strong = 40000, weak = 1000) - assertEquals("the same strength, still playing, was started again", 1, pad.played.size) - effect(strong = 20000, weak = 1000) - assertEquals(Triple(20000, 1000, 5000L), pad.played.last()) + idle(RumbleComponent.MIN_GAP_MS) + assertEquals("the last change inside the gap was lost", + listOf(Triple(40000, 1000, 5000L), Triple(30000, 1000, 5000L)), pad.played) + effect(strong = 30000, weak = 1000) + assertEquals("the same strength, still playing, was started again", 2, pad.played.size) effect(strong = 0, weak = 0) assertFalse(pad.vibrating) effect(strong = 20000, weak = 1000) assertTrue("an effect right after a stop was dropped", pad.vibrating) } + @Test fun aHeldEffectKeepsTheMotorsRunningUntilTheGameStopsIt() { + val pad = FakeMotors() + rumble.controllerMotors = { pad } + activeController(PAD_ID) + effect(strong = 40000, weak = 20000, ms = RumbleComponent.HOLD_MS) + assertEquals(listOf(Triple(40000, 20000, RumbleComponent.HOLD_EFFECT_MS)), pad.played) + idle(RumbleComponent.KEEPALIVE_MS * 4 + 100) + assertEquals("the held effect was not re-armed before it ran out", 5, pad.played.size) + effect(strong = 40000, weak = 20000, ms = RumbleComponent.HOLD_MS) + assertEquals("a repeat of the held strength restarted the motors", 5, pad.played.size) + effect(strong = 0, weak = 0) + assertFalse(pad.vibrating) + idle(RumbleComponent.KEEPALIVE_MS * 4 + 100) + assertEquals("the keepalive restarted the motors after a stop", 5, pad.played.size) + assertFalse(pad.vibrating) + } + + @Test fun aHeldEffectFollowsTheGamesNewStrength() { + val pad = FakeMotors() + rumble.controllerMotors = { pad } + activeController(PAD_ID) + effect(strong = 40000, weak = 0, ms = RumbleComponent.HOLD_MS) + effect(strong = 10000, weak = 0, ms = RumbleComponent.HOLD_MS) + idle(RumbleComponent.KEEPALIVE_MS * 2) + assertTrue(pad.played.drop(1).isNotEmpty()) + assertTrue("the keepalive replayed an old strength", pad.played.drop(1).all { it.first == 10000 }) + } + + @Test fun aTimedEffectIsNotRearmed() { + val pad = FakeMotors() + rumble.controllerMotors = { pad } + activeController(PAD_ID) + effect(strong = 40000, weak = 0, ms = 300) + idle(RumbleComponent.KEEPALIVE_MS * 3) + assertEquals(listOf(Triple(40000, 0, 300L)), pad.played) + } + + @Test fun disablingStopsTheKeepalive() { + val pad = FakeMotors() + rumble.controllerMotors = { pad } + activeController(PAD_ID) + effect(ms = RumbleComponent.HOLD_MS) + ControllerPrefs.setRumble(context, false) + idle(RumbleComponent.KEEPALIVE_MS * 3) + assertEquals(1, pad.played.size) + assertFalse(pad.vibrating) + } + @Test fun aControllerWithoutMotorsFallsBackToThePhone() { rumble.controllerMotors = { null } activeController(PAD_ID) @@ -163,12 +212,14 @@ class RumbleComponentTest { (slots as java.util.concurrent.atomic.AtomicIntegerArray).set(slot, id) } - private fun effect(strong: Int = 65535, weak: Int = 65535, slot: Int = 0) { + private fun effect(strong: Int = 65535, weak: Int = 65535, slot: Int = 0, ms: Int = 5000) { val int = Int::class.javaPrimitiveType RumbleComponent::class.java.getDeclaredMethod("buzz", int, int, int, int) - .apply { isAccessible = true }.invoke(rumble, strong, weak, 5000, slot) + .apply { isAccessible = true }.invoke(rumble, strong, weak, ms, slot) } + private fun idle(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(java.time.Duration.ofMillis(ms)) + private class FakeMotors : RumbleComponent.Motors { override val name = "fake pad" val played = mutableListOf>() diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt index 6ee341bc89..95893adde6 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt @@ -2,6 +2,9 @@ package com.droiddeck.launcher.session import com.droiddeck.launcher.runtime.LinuxRuntime import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale import java.util.zip.ZipFile import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -27,13 +30,15 @@ class SessionLogShareZipTest { "Authorization: Bearer abc.def.ghi\n" + "kept: EResult 5, app 1086940, steamapps/common/Game\n" ) - File(logs, "stores").apply { mkdirs() }.resolve("stores-2026-10-08.log").writeText("epic: f_token=zzzzzzzz12 window 32\n") + // StoreLogFiles.prune, started by App.onCreate, deletes a stores log named for a day over a week old. + val storesLog = "stores-" + SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date()) + ".log" + File(logs, "stores").apply { mkdirs() }.resolve(storesLog).writeText("epic: f_token=zzzzzzzz12 window 32\n") File(logs, SessionPaths.TOOLS_DIR).apply { mkdirs() }.resolve("flatpak-install.log").writeText("== install\nCookie: steamLoginSecure=76561198000000000%7C%7Ceyabc\n") val zip = SessionLogShare.zipFolder(app, session)!! assertTrue(zip.path.startsWith(File(app.cacheDir, "share").path)) val text = ZipFile(zip).use { z -> z.entries().toList().associate { e -> e.name to z.getInputStream(e).bufferedReader().readText() } } - assertTrue(text.keys.containsAll(listOf("2026-10-08-01-steam/session.log", "stores/stores-2026-10-08.log", "tools/flatpak-install.log"))) + assertTrue(text.keys.containsAll(listOf("2026-10-08-01-steam/session.log", "stores/$storesLog", "tools/flatpak-install.log"))) val all = text.values.joinToString("\n") for (secret in listOf("0a1b2c3d4e5f", "deadbeefcafe", "abcdef123456", "someone@example.com", "AUTHCODE123", "abc.def.ghi", "zzzzzzzz12", "eyabc")) { assertFalse("$secret survived", all.contains(secret)) diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index 2de0ef908e..4960c382da 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -5,10 +5,12 @@ #define _GNU_SOURCE #include #include +#include #include #include #include #include +#include #include #include @@ -176,6 +178,24 @@ static int caller_is_winebus(void *caller) { return strstr(info.dli_fname, "winebus.so") != NULL; } +/* Wine's HID haptics give every XInput rumble a 1000 ms cutoff and xinput only writes on a change, + * but XInput motors hold their speed until the next XInputSetState; evdev's length 0 holds until + * stopped. Only this library, preloaded first, sees winebus as the caller. The length is put back + * because winebus compares its copy with the next state to decide whether to upload again. */ +__attribute__((visibility("hidden"))) int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, + unsigned long request, void *arg, void *caller, + int *rc) { + struct ff_effect *effect = arg; + __u16 length; + + if (request != EVIOCSFF || effect == NULL || effect->type != FF_RUMBLE || !caller_is_winebus(caller)) return 0; + length = effect->replay.length; + effect->replay.length = 0; + *rc = real(fd, request, arg); + effect->replay.length = length; + return 1; +} + char *realpath(const char *path, char *resolved) { static char *(*real_realpath)(const char *, char *); void *caller = __builtin_return_address(0); diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index bcd12e924f..3cadddf85b 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -406,6 +406,8 @@ int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long void *arg, int *rc) __attribute__((visibility("hidden"))); int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); +int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, + void *arg, void *caller, int *rc) __attribute__((visibility("hidden"))); int ioctl(int fd, unsigned long request, ...) { typedef int (*ioctl_fn)(int, unsigned long, void *); @@ -419,6 +421,7 @@ int ioctl(int fd, unsigned long request, ...) { if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc; if (bl_drm_gem_close(fd, request, arg, &rc)) return rc; if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl"); + if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc; if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg); bl_kgsl_chip_id_fixup(request, arg, rc); if (arg == NULL || !is_link_query(request)) return rc; diff --git a/tools/tests/test_winebus_rumble_preload.py b/tools/tests/test_winebus_rumble_preload.py new file mode 100644 index 0000000000..82e3b01120 --- /dev/null +++ b/tools/tests/test_winebus_rumble_preload.py @@ -0,0 +1,101 @@ +from pathlib import Path +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +# Stands in for libfakeinput.so, which ld.so.preload lists after libblsession.so. +SHIM = r""" +#include +#include +#include + +int ioctl(int fd, unsigned long request, ...) { + va_list ap; + va_start(ap, request); + struct ff_effect *effect = va_arg(ap, struct ff_effect *); + va_end(ap); + if (request == EVIOCSFF) printf("shim type %u length %u\n", effect->type, effect->replay.length); + return 0; +} +""" + +UPLOAD = r""" +#include +#include +#include +#include + +void upload(unsigned short type, unsigned short length) { + struct ff_effect effect; + memset(&effect, 0, sizeof(effect)); + effect.id = -1; + effect.type = type; + effect.replay.length = length; + ioctl(3, EVIOCSFF, &effect); + printf("caller length %u\n", effect.replay.length); +} +""" + +PROGRAM = r""" +#include +#include +#include + +void upload(unsigned short type, unsigned short length); + +int main(int argc, char **argv) { + void *winebus = dlopen(argv[1], RTLD_NOW); + void (*from_winebus)(unsigned short, unsigned short) = (void (*)(unsigned short, unsigned short))dlsym(winebus, "upload"); + if (argv[2][0] == 'w') from_winebus(argv[3][0] == 'r' ? FF_RUMBLE : FF_PERIODIC, 1000); + else upload(FF_RUMBLE, 1000); + fflush(stdout); + return 0; +} +""" + + +@unittest.skipUnless(sys.platform == "linux" and shutil.which("cc"), "needs Linux and cc") +class WinebusRumblePreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dir = Path(tempfile.mkdtemp()) + build = cls.dir / "build" + build.mkdir() + for name, text in (("shim.c", SHIM), ("upload.c", UPLOAD), ("program.c", PROGRAM)): + (build / name).write_text(text) + cls.lib = cls.dir / "libblsession.so" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib), + *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) + cls.shim = cls.dir / "libshim.so" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.shim), str(build / "shim.c")], check=True) + cls.winebus = cls.dir / "winebus.so" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "upload.c")], check=True) + cls.program = cls.dir / "program" + subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "upload.c"), "-ldl"], + check=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.dir, True) + + def upload(self, caller, kind="rumble"): + env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.lib, self.shim)) + result = subprocess.run([str(self.program), str(self.winebus), caller, kind], env=env, + capture_output=True, text=True, timeout=10, check=True) + return result.stdout.splitlines() + + def test_winebus_rumble_reaches_the_shim_held_and_comes_back_unchanged(self): + self.assertEqual(self.upload("winebus"), ["shim type %d length 0" % 0x50, "caller length 1000"]) + + def test_other_callers_and_effects_keep_their_length(self): + self.assertEqual(self.upload("program"), ["shim type %d length 1000" % 0x50, "caller length 1000"]) + self.assertEqual(self.upload("winebus", "periodic"), ["shim type %d length 1000" % 0x51, "caller length 1000"]) + + +if __name__ == "__main__": + unittest.main()