mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Merge remote-tracking branch 'origin/main' into frozen-session-disk-spill
This commit is contained in:
commit
088e9994a0
104 files changed
+15184
-317
No files matched your search
@@ -0,0 +1,223 @@
|
||||
import json
|
||||
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"), run_name="steam_compatibility")
|
||||
SETUP = COMPAT["DD_ANTICHEAT_SETUP"]
|
||||
|
||||
|
||||
class AntiCheatRoutingTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.steam = self.root / "Steam"
|
||||
self.common = self.steam / "steamapps" / "common"
|
||||
self.tools = self.steam / "compatibilitytools.d"
|
||||
self.game = self.common / "Some Game"
|
||||
self.game.mkdir(parents=True)
|
||||
self.tools.mkdir(parents=True)
|
||||
self.record = self.root / "record.json"
|
||||
self.fex = self.root / "droiddeck-fex"
|
||||
self.fex.write_text("#!/bin/bash\nif [ \"$1\" = update ]; then echo \"$1\" >> \"$DD_RECORD.update\"; "
|
||||
"[ -n \"${DD_UPDATED_PATCHES:-}\" ] && printf '%s\\n' \"$DD_UPDATED_PATCHES\" > \"$DD_PATCHES\"; exit 0; fi\n"
|
||||
"python3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], "
|
||||
"\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, "
|
||||
"open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n")
|
||||
self.fex.chmod(0o755)
|
||||
self.patches = self.root / "fex-patches"
|
||||
self.patches.write_text("openat2-enosys-fallback\nfixed-guest-memory-above-host-address-limit\n")
|
||||
|
||||
def tool(self, name, x86_64=True):
|
||||
tool = self.tools / name
|
||||
(tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True)
|
||||
if not x86_64:
|
||||
(tool / "files" / "bin-arm64").mkdir()
|
||||
(tool / "proton").write_text("#!/bin/sh\n")
|
||||
(tool / "proton").chmod(0o755)
|
||||
return tool
|
||||
|
||||
def runtime(self, name, library):
|
||||
folder = self.common / name / "v2" / "lib64"
|
||||
folder.mkdir(parents=True)
|
||||
(folder / library).write_text("")
|
||||
return self.common / name
|
||||
|
||||
def file(self, relative):
|
||||
path = self.game / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("{}")
|
||||
|
||||
def launch(self, verb="waitforexitandrun", extra=None):
|
||||
script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)).replace(
|
||||
"/usr/local/share/fex-emu/.droiddeck-patches", str(self.patches)) + (
|
||||
"dd_game_cpus() { :; }\n"
|
||||
"verb=$1; shift\n"
|
||||
"dd_anticheat \"$@\"\n"
|
||||
"echo stayed\n")
|
||||
env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record), "DD_PATCHES": str(self.patches),
|
||||
"STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)}
|
||||
env.update(extra or {})
|
||||
result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")],
|
||||
env=env, capture_output=True, text=True, timeout=30)
|
||||
routed = json.loads(self.record.read_text()) if self.record.exists() else None
|
||||
return result, routed
|
||||
|
||||
def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
newest = self.tool("DroidDeck-Proton-11.0-10-x86_64")
|
||||
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
|
||||
runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertNotIn("stayed", result.stdout)
|
||||
self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")])
|
||||
self.assertEqual(routed["eac"], str(runtime))
|
||||
self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr)
|
||||
|
||||
def test_battleye_sets_its_own_runtime(self):
|
||||
self.file("BattlEye/BEClient_x64.so")
|
||||
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so")
|
||||
_, routed = self.launch()
|
||||
self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None))
|
||||
|
||||
def test_a_runtime_already_set_with_files_is_kept(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
own = self.root / "own-eac"
|
||||
(own / "v2").mkdir(parents=True)
|
||||
(own / "v2" / "easyanticheat_x64.so").write_text("")
|
||||
_, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)})
|
||||
self.assertEqual(routed["eac"], str(own))
|
||||
|
||||
def test_games_without_anti_cheat_files_stay_on_arm64(self):
|
||||
self.file("Data/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertEqual(result.stderr, "")
|
||||
|
||||
def test_without_an_x86_64_build_the_launch_stays_on_arm64(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr)
|
||||
|
||||
def test_without_the_runtime_files_the_launch_stays_on_arm64(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
(self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True)
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("its Proton runtime is not installed", result.stderr)
|
||||
|
||||
def test_the_user_can_turn_routing_off(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
|
||||
def test_a_tool_the_user_chose_is_kept(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
for chosen in ("GE-Proton11-15-aarch64", "DroidDeck-Bionic-14.1-r85", "proton_experimental"):
|
||||
result, routed = self.launch(extra={"DD_AC_TOOL": chosen})
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertIn("%s was chosen for this game, so it runs as chosen" % chosen, result.stderr)
|
||||
|
||||
def test_droiddeck_proton_builds_still_route(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
newest = self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
for own in ("DroidDeck-Proton 11-14.1", "DroidDeck-Proton-11-14.2"):
|
||||
self.record.unlink(missing_ok=True)
|
||||
result, routed = self.launch(extra={"DD_AC_TOOL": own})
|
||||
self.assertEqual(routed["argv"][1], str(newest / "proton"))
|
||||
|
||||
def test_a_fex_build_without_high_guest_memory_stays_on_arm64(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
for patches in ("openat2-enosys-fallback\n", None):
|
||||
if patches is None:
|
||||
self.patches.unlink()
|
||||
else:
|
||||
self.patches.write_text(patches)
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertIn("the installed FEX build cannot run anti-cheat", result.stderr)
|
||||
|
||||
def test_an_older_fex_build_is_updated_before_routing(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
self.patches.unlink()
|
||||
result, routed = self.launch(extra={"DD_UPDATED_PATCHES": "fixed-guest-memory-above-host-address-limit"})
|
||||
self.assertEqual(routed["argv"][1], str(tool / "proton"))
|
||||
self.assertNotIn("cannot run anti-cheat", result.stderr)
|
||||
self.assertTrue((self.root / "record.json.update").exists())
|
||||
|
||||
def test_games_without_anti_cheat_files_do_not_update_fex(self):
|
||||
self.file("Data/Settings.json")
|
||||
self.launch()
|
||||
self.assertFalse((self.root / "record.json.update").exists())
|
||||
|
||||
def test_choices_are_kept_the_same_with_an_older_fex_build(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
self.patches.unlink()
|
||||
result, routed = self.launch(extra={"DD_AC_TOOL": "GE-Proton11-15-aarch64"})
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("GE-Proton11-15-aarch64 was chosen for this game, so it runs as chosen", result.stderr)
|
||||
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
|
||||
self.assertIsNone(routed)
|
||||
self.assertEqual(result.stderr, "")
|
||||
|
||||
def test_the_fex_build_lists_its_patches(self):
|
||||
build = (BIN.parents[4] / "fex" / "build-in-arch.sh").read_text()
|
||||
self.assertIn("> out/usr/local/share/fex-emu/.droiddeck-patches", build)
|
||||
names = {p.stem.split("-", 1)[1] for p in (BIN.parents[4] / "fex" / "patches").glob("*.patch")}
|
||||
self.assertIn("fixed-guest-memory-above-host-address-limit", names)
|
||||
|
||||
def test_adopted_tools_pass_their_own_folder_name(self):
|
||||
wrapper = COMPAT["extra_wrapper_sh"]("proton")
|
||||
self.assertIn('DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"', wrapper)
|
||||
self.assertNotIn("DD_AC_TOOL=", COMPAT["LAUNCHER_SH"])
|
||||
|
||||
def test_other_verbs_are_left_alone(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch(verb="getcompatpath")
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
|
||||
def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self):
|
||||
launcher = COMPAT["LAUNCHER_SH"]
|
||||
self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"'))
|
||||
wrapper = COMPAT["extra_wrapper_sh"]("proton")
|
||||
self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback="))
|
||||
self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"'))
|
||||
self.assertIn('! dd_x86_64_proton "$d"', wrapper)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,38 @@
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
NATIVE = ROOT / "app/src/main/cpp/waylandcomp/src"
|
||||
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
|
||||
|
||||
|
||||
class BottomMirrorCompositionTest(unittest.TestCase):
|
||||
def test_mirror_requests_composition_until_its_last_consumer_leaves(self):
|
||||
panel = (APP / "ui/BottomMirrorPage.kt").read_text()
|
||||
self.assertIn("actions.holdComposed(true)", panel)
|
||||
self.assertIn("onDispose { actions.holdComposed(false) }", panel)
|
||||
activity = (APP / "SessionActivity.kt").read_text()
|
||||
hold = activity.split("private fun holdComposedOutput(", 1)[1].split("private fun zeroCopyActive", 1)[0]
|
||||
self.assertIn("if (held == wasHeld) return", hold)
|
||||
self.assertIn("nativeSetMirrorCapture(held)", hold)
|
||||
self.assertIn("if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy", hold)
|
||||
self.assertIn("CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy", activity)
|
||||
self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())", activity)
|
||||
self.assertIn("nativeSetZeroCopy(composedOutputFree())", hold)
|
||||
self.assertNotIn("SessionPrefs.set", hold)
|
||||
|
||||
def test_compositor_selects_readable_surface_without_dropping_unimportable_hdr(self):
|
||||
jni = (NATIVE / "waylandcomp_jni.c").read_text()
|
||||
self.assertIn("droiddeck_host_mirror_capture(on ? 1 : 0);", jni)
|
||||
host = (NATIVE / "droiddeck_ext.c").read_text()
|
||||
self.assertIn("case HOST_MIRROR_CAPTURE:\n droiddeck_set_mirror_capture(m->a);", host)
|
||||
compositor = (NATIVE / "compositor.c").read_text()
|
||||
self.assertIn("if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {\n hdr_route = 2;", compositor)
|
||||
self.assertIn("g_zero_copy && !g_mirror_capture && (!framegen || fg_layer)", compositor)
|
||||
self.assertIn("if (un && g_zero_copy)", compositor)
|
||||
self.assertIn("if (g_zero_copy && droiddeck_color_hdr_open()) note_hdr_unimported", compositor)
|
||||
self.assertNotIn("if (g_mirror_capture) ls = NULL", compositor)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1235,6 +1235,29 @@ class LaunchTest(FexTestCase):
|
||||
self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files"))
|
||||
self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350")
|
||||
|
||||
def test_an_adopted_proton_keeps_the_runtime_of_its_original_manifest(self):
|
||||
proton = self.proton("4183110")
|
||||
folder = proton.parent
|
||||
os.rename(folder / "toolmanifest.vdf", folder / "toolmanifest.vdf.droiddeck-orig")
|
||||
self.write(folder / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/droiddeck-proton-wrap %verb%"\n}\n')
|
||||
self.assertEqual(FEX["required_runtime"](str(proton)), "4183110")
|
||||
os.unlink(folder / "toolmanifest.vdf.droiddeck-orig")
|
||||
self.assertEqual(FEX["required_runtime"](str(proton)), "1628350")
|
||||
|
||||
def test_proton_action_keeps_the_prefix_and_runs_under_fex(self):
|
||||
self.fex_tool()
|
||||
self.runtime()
|
||||
proton = self.proton("1628350")
|
||||
prefix = str(self.tmp / "compatdata" / "730")
|
||||
env = {"STEAM_COMPAT_DATA_PATH": prefix}
|
||||
with mock.patch.dict(os.environ, env, clear=False), mock.patch("os.execve") as emulated:
|
||||
self.quiet(FEX["main"], ["proton", str(proton), "waitforexitandrun", "game.exe"])
|
||||
command, guest = emulated.call_args[0][1], emulated.call_args[0][2]
|
||||
self.assertEqual(command[1:], [str(proton), "waitforexitandrun", "game.exe"])
|
||||
self.assertEqual(guest["STEAM_COMPAT_DATA_PATH"], prefix)
|
||||
self.assertNotEqual(FEX["guest_environment"]({"portable": True}, env)["STEAM_COMPAT_DATA_PATH"], prefix)
|
||||
self.assertEqual(FEX["main"](["proton", str(proton)]), 2)
|
||||
|
||||
def test_native_programs_run_directly(self):
|
||||
program = self.write(self.tmp / "native", elf(183), 0o755)
|
||||
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
|
||||
|
||||
@@ -15,6 +15,8 @@ VALVE_11 = {"name": COMPAT["TOOL_11"], "display": "Proton 11.0 ARM64", "dir": CO
|
||||
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
|
||||
GE10 = {"name": "GE-Proton10-3", "display": "GE-Proton10-3", "dir": "GE-Proton10-3", "valve": False}
|
||||
NEWER = {"name": "DroidDeck-Proton-11-12.1", "display": "DroidDeck-Proton 11-12.1", "dir": "DroidDeck-Proton 11-12.1", "valve": False}
|
||||
X86 = {"name": "DroidDeck-Proton-11-14.2-x86_64", "display": "DroidDeck-Proton 11-14.2 x86-64", "dir": "DroidDeck-Proton 11-14.2 x86-64",
|
||||
"valve": False, "x86_64": True}
|
||||
|
||||
|
||||
def config_text(entries):
|
||||
@@ -204,6 +206,50 @@ class DroidDeckProtonDefaultTest(unittest.TestCase):
|
||||
self.assertEqual(newest, "b")
|
||||
self.assertEqual(gone, {OLD["name"]})
|
||||
|
||||
def test_an_x86_64_build_never_becomes_the_automatic_default(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL)], [VALVE, NEW, X86], ["42"])
|
||||
self.assertEqual((default, mapping["0"]), (NEW["name"], NEW["name"]))
|
||||
default, mapping, _ = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, X86])
|
||||
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
|
||||
|
||||
def test_an_automatic_x86_64_default_moves_back_to_arm64(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, NEW, X86])
|
||||
self.assertEqual((default, mapping, state["source"]), (NEW["name"], {"0": NEW["name"]}, "update"))
|
||||
default, mapping, _ = self.run_default(
|
||||
{"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, X86])
|
||||
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
|
||||
|
||||
def test_an_x86_64_default_the_user_picked_is_kept(self):
|
||||
for source in ("app", "steam"):
|
||||
default, mapping, _ = self.run_default(
|
||||
{"default": X86["name"], "written": X86["name"], "source": source}, [("0", X86["name"])], [VALVE, NEW, X86])
|
||||
self.assertEqual((default, mapping), (X86["name"], {"0": X86["name"]}))
|
||||
|
||||
def test_a_request_for_the_automatic_x86_64_default_keeps_it(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": X86["name"], "written": X86["name"], "source": "update", "applied": 1}, [("0", X86["name"])],
|
||||
[VALVE, NEW, X86], request={"seq": 2, "name": X86["name"]})
|
||||
self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app"))
|
||||
default, mapping, state = self.run_default(state, [("0", X86["name"])], [VALVE, NEW, X86],
|
||||
request={"seq": 2, "name": X86["name"]})
|
||||
self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app"))
|
||||
|
||||
def test_x86_64_layouts_are_marked_in_the_catalog(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tools = Path(tmp) / "compatibilitytools.d"
|
||||
for entry, arm in (("DroidDeck-Proton 11-14.2 x86-64", False), ("DroidDeck-Proton 11-14.2", True)):
|
||||
(tools / entry / "files" / "lib" / "wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True)
|
||||
if arm:
|
||||
(tools / entry / "files" / "bin-arm64").mkdir()
|
||||
(tools / entry / COMPAT["EXTRA_WRAPPER"]).write_text("")
|
||||
catalog = {t["dir"]: t for t in COMPAT["tool_catalog"](tmp) if not t["valve"]}
|
||||
self.assertTrue(catalog["DroidDeck-Proton 11-14.2 x86-64"].get("x86_64"))
|
||||
self.assertNotIn("x86_64", catalog["DroidDeck-Proton 11-14.2"])
|
||||
newest, _ = COMPAT["own_proton_moves"]({}, list(catalog.values()))
|
||||
self.assertEqual(newest, catalog["DroidDeck-Proton 11-14.2"]["name"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -117,6 +117,28 @@ class FexInstallTest(unittest.TestCase):
|
||||
self.assertEqual("old thunk\n", (self.root / "usr/local" / side / name).read_text())
|
||||
self.assertEqual("stale\n", (self.root / "usr/local" / side / "libwayland-client-thunk.so").read_text())
|
||||
|
||||
def test_a_build_without_a_patch_list_drops_the_old_one(self):
|
||||
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
|
||||
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
|
||||
self.assertEqual("OK", self.install(installed_loads=True)[0])
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
def test_a_failed_install_keeps_the_old_patch_list(self):
|
||||
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
|
||||
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
|
||||
self.assertEqual("FAILED", self.install(installed_loads=False)[0])
|
||||
self.assertEqual("fixed-guest-memory-above-host-address-limit\n", marker.read_text())
|
||||
|
||||
def test_a_build_with_a_patch_list_installs_it(self):
|
||||
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").write_text("openat2-enosys-fallback\n")
|
||||
shipped = Path(self.temp.name) / "pkg/usr/local/share/fex-emu"
|
||||
shipped.mkdir(parents=True)
|
||||
(shipped / ".droiddeck-patches").write_text("fixed-guest-memory-above-host-address-limit\n")
|
||||
self.pack()
|
||||
self.assertEqual("OK", self.install(installed_loads=True)[0])
|
||||
self.assertEqual("fixed-guest-memory-above-host-address-limit\n",
|
||||
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").read_text())
|
||||
|
||||
def test_an_archive_that_does_not_match_installs_nothing(self):
|
||||
result, err = self.install(installed_loads=True, sha="0" * 64)
|
||||
self.assertEqual("FAILED", result)
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATCH = REPO / "tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch"
|
||||
EMULATED = "Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles"
|
||||
|
||||
HOST_MOUNTS = """/dev/block/dm-28 / ext4 ro,seclabel,relatime,discard 0 0
|
||||
tmpfs /dev tmpfs rw,seclabel,nosuid,relatime,size=5791196k,nr_inodes=1447799,mode=755 0 0
|
||||
proc /proc proc rw,relatime,gid=3009,hidepid=invisible 0 0
|
||||
sysfs /sys sysfs rw,seclabel,relatime 0 0
|
||||
/dev/fuse /mnt/user/0/emulated fuse rw,lazytime,nosuid,nodev,noexec,noatime,user_id=0,group_id=0,allow_other 0 0
|
||||
"""
|
||||
|
||||
HOST_MOUNTINFO = """9838 9837 254:28 / / ro,relatime master:1 - ext4 /dev/block/dm-28 ro,seclabel,discard
|
||||
9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw,gid=3009,hidepid=invisible
|
||||
9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw,hidepid=2,subset=pid
|
||||
9871 9838 0:21 / /sys rw,relatime master:5 - sysfs sysfs rw,seclabel
|
||||
"""
|
||||
|
||||
HARNESS = r"""
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
namespace fextl {
|
||||
using string = std::string;
|
||||
template<typename T> using vector = std::vector<T>;
|
||||
}
|
||||
HELPERS
|
||||
static std::string Filter(const std::string& In, bool MountInfo) {
|
||||
std::string Out;
|
||||
size_t Pos = 0;
|
||||
while (Pos < In.size()) {
|
||||
size_t Eol = In.find('\n', Pos);
|
||||
const size_t LineEnd = Eol == std::string::npos ? In.size() : Eol;
|
||||
Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
|
||||
if (Eol != std::string::npos) {
|
||||
Out += '\n';
|
||||
}
|
||||
Pos = LineEnd + 1;
|
||||
}
|
||||
return Out;
|
||||
}
|
||||
int main(int argc, char** argv) {
|
||||
if (argv[1][0] == 'p') {
|
||||
for (int i = 2; i < argc; ++i) {
|
||||
std::printf("%s\n", IsProcMountTablePath(argv[i]) ? "yes" : "no");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
std::string In;
|
||||
char Buf[4096];
|
||||
size_t Len;
|
||||
while ((Len = std::fread(Buf, 1, sizeof(Buf), stdin)) > 0) {
|
||||
In.append(Buf, Len);
|
||||
}
|
||||
std::fputs(Filter(In, argv[1][0] == 'i').c_str(), stdout);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def added():
|
||||
return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
|
||||
|
||||
def helpers():
|
||||
body = added()
|
||||
start = body.index("static const char* ProcFileOfPid(const char* Path) {")
|
||||
end = body.index("static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {")
|
||||
end = body.index("}", end) + 1
|
||||
return "\n".join(body[start:end])
|
||||
|
||||
|
||||
class FexProcMountTablesTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.binary = None
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
if compiler:
|
||||
source = Path(cls.tmp.name) / "mounts.cpp"
|
||||
source.write_text(HARNESS.replace("HELPERS", helpers()))
|
||||
binary = Path(cls.tmp.name) / "mounts"
|
||||
subprocess.run([compiler, "-std=c++20", "-O1", "-o", str(binary), str(source)], check=True)
|
||||
cls.binary = binary
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_filter(self, mode, text):
|
||||
if not self.binary:
|
||||
self.skipTest("no C++ compiler")
|
||||
return subprocess.run([str(self.binary), mode], input=text, capture_output=True, text=True, check=True).stdout
|
||||
|
||||
def matches(self, *paths):
|
||||
if not self.binary:
|
||||
self.skipTest("no C++ compiler")
|
||||
out = subprocess.run([str(self.binary), "p", *paths], capture_output=True, text=True, check=True).stdout
|
||||
return out.split()
|
||||
|
||||
def test_only_the_emulated_files_change(self):
|
||||
files = re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)
|
||||
self.assertEqual({EMULATED + ".cpp", EMULATED + ".h"}, set(files))
|
||||
|
||||
def test_mount_tables_are_routed_to_the_filter_on_open(self):
|
||||
body = added()
|
||||
self.assertIn(" if (pathname && IsProcMountTablePath(pathname)) {", body)
|
||||
self.assertIn(" return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);", body)
|
||||
|
||||
def test_every_path_form_of_the_mount_tables_matches(self):
|
||||
paths = ["/proc/mounts", "/proc/self/mounts", "/proc/thread-self/mounts", "/proc/self/mountinfo", "/proc/4242/mounts",
|
||||
"/proc/4242/mountinfo", "/proc/4242/task/4243/mountinfo"]
|
||||
self.assertEqual(["yes"] * len(paths), self.matches(*paths))
|
||||
|
||||
def test_other_proc_files_do_not_match(self):
|
||||
paths = ["/proc/self/maps", "/proc/self/status", "/proc/self/mountstats", "/proc/4242/task/mounts", "/proc/self/mounts/x",
|
||||
"/etc/mounts", "/proc/4242x/mounts"]
|
||||
self.assertEqual(["no"] * len(paths), self.matches(*paths))
|
||||
|
||||
def test_only_the_proc_line_of_mounts_changes(self):
|
||||
out = self.run_filter("m", HOST_MOUNTS).splitlines()
|
||||
expected = HOST_MOUNTS.splitlines()
|
||||
expected[2] = "proc /proc proc rw,relatime 0 0"
|
||||
self.assertEqual(expected, out)
|
||||
|
||||
def test_only_proc_super_options_of_mountinfo_change(self):
|
||||
out = self.run_filter("i", HOST_MOUNTINFO).splitlines()
|
||||
expected = HOST_MOUNTINFO.splitlines()
|
||||
expected[1] = "9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw"
|
||||
expected[2] = "9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw"
|
||||
self.assertEqual(expected, out)
|
||||
|
||||
def test_tables_without_proc_pass_through_unchanged(self):
|
||||
text = "".join(line + "\n" for line in HOST_MOUNTS.splitlines() if " proc " not in line)
|
||||
self.assertEqual(text, self.run_filter("m", text))
|
||||
|
||||
def test_malformed_lines_pass_through_unchanged(self):
|
||||
text = "proc /proc proc\nno dash here proc rw\n\nproc\n"
|
||||
self.assertEqual(text, self.run_filter("m", text))
|
||||
self.assertEqual(text, self.run_filter("i", text))
|
||||
|
||||
def test_no_comments_are_added(self):
|
||||
self.assertFalse([line for line in added() if line.strip().startswith(("//", "/*"))])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,14 +8,17 @@ from pathlib import Path
|
||||
|
||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
||||
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
|
||||
EMULATION = FEX / "patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch"
|
||||
MCONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
|
||||
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
|
||||
PROBE = FEX / "probes/signal-register-update.c"
|
||||
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
|
||||
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
|
||||
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
|
||||
|
||||
|
||||
def files():
|
||||
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
|
||||
def files(patch=PATCH):
|
||||
sections = re.split(r"^diff --git a/(\S+) \S+\n", patch.read_text(), flags=re.M)
|
||||
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
|
||||
|
||||
|
||||
@@ -96,6 +99,50 @@ class SignalRegisterUpdateTest(unittest.TestCase):
|
||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
||||
|
||||
|
||||
class ClearedSyscallInfoTest(unittest.TestCase):
|
||||
SOURCE = "ArchHelpers::Context::SavedSyscallInfo(Context)"
|
||||
|
||||
def saved_info(self):
|
||||
lines = [line[1:] for line in files(EMULATION)[MCONTEXT].splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
start = lines.index("template<typename Backup>")
|
||||
end = lines.index("}", start)
|
||||
return "\n".join(lines[start:end + 1])
|
||||
|
||||
def test_register_writeback_reads_the_same_saved_state_as_the_restore(self):
|
||||
frames = files(EMULATION)[FRAMES]
|
||||
self.assertIn("- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;", frames)
|
||||
self.assertIn("+ const uint32_t Spilled = " + self.SOURCE + " & 0xFFFF;", frames)
|
||||
delegator = added(files(EMULATION)[DELEGATOR])
|
||||
self.assertIn("Thread->CurrentFrame->InSyscallInfo = " + self.SOURCE + ";", delegator)
|
||||
self.assertIn("Frame->InSyscallInfo = " + self.SOURCE + ";", delegator)
|
||||
self.assertIn("Frame->InSyscallInfo = Context->InSyscallInfo;", removed(files(EMULATION)[DELEGATOR]))
|
||||
self.assertNotIn("Context->ClearedSyscallInfo :", "\n".join(delegator))
|
||||
|
||||
@unittest.skipUnless(shutil.which("c++") or shutil.which("g++") or shutil.which("clang++"), "needs a C++ compiler")
|
||||
def test_cleared_state_is_preferred_only_when_flagged(self):
|
||||
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
|
||||
source = "\n".join([
|
||||
"#include <cstdint>",
|
||||
"#include <cstdio>",
|
||||
"enum ContextFlags : uint32_t { CONTEXT_FLAG_INJIT = 1U << 0, CONTEXT_FLAG_SYSCALLINFO_CLEARED = 1U << 1 };",
|
||||
"struct Backup { uint16_t InSyscallInfo; uint16_t ClearedSyscallInfo; uint32_t Flags; };",
|
||||
self.saved_info(),
|
||||
"int main() {",
|
||||
" const Backup Thunk {0, 0xFFFF, CONTEXT_FLAG_SYSCALLINFO_CLEARED};",
|
||||
" const Backup Jit {0x0F0F, 0x1234, CONTEXT_FLAG_INJIT};",
|
||||
" const Backup Idle {0, 0x1234, 0};",
|
||||
" std::printf(\"%x %x %x\\n\", SavedSyscallInfo(&Thunk), SavedSyscallInfo(&Jit), SavedSyscallInfo(&Idle));",
|
||||
"}",
|
||||
])
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "saved.cpp"
|
||||
binary = Path(tmp) / "saved"
|
||||
path.write_text(source)
|
||||
subprocess.run([compiler, "-std=c++20", "-Wall", "-Werror", "-o", str(binary), str(path)], check=True)
|
||||
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=60).stdout
|
||||
self.assertEqual(output.split(), ["ffff", "f0f", "0"])
|
||||
|
||||
|
||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
|
||||
class SignalRegisterUpdateProbeTest(unittest.TestCase):
|
||||
@classmethod
|
||||
|
||||
@@ -2664,8 +2664,8 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
|
||||
def test_both_proton_wrappers_call_environment_launcher(self):
|
||||
self.assertIn('dd_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"])
|
||||
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton")
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
|
||||
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["extra_wrapper_sh"]("proton"))
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
|
||||
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
|
||||
self.assertIn('dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
|
||||
|
||||
@@ -2673,9 +2673,11 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
scripts = (COMPAT["launcher_sh"](), COMPAT["extra_wrapper_sh"]("proton"))
|
||||
query = "/root/.local/share/Steam/steamrtarm64/../bin/d3ddriverquery64.exe"
|
||||
probe = "/root/.local/share/Steam/steamapps/compatdata/0"
|
||||
for script in scripts:
|
||||
for script, here in zip(scripts, ("$depot", "$here")):
|
||||
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
|
||||
self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("dd_components "))
|
||||
answered = script.index('case "$verb:${1##*/}:')
|
||||
self.assertLess(answered, script.index('dd_components "%s"' % here))
|
||||
self.assertLess(answered, script.index('dd_anticheat "$@"'))
|
||||
for args, prefix in (([query, "-d3d12"], probe), ([query], probe + "/"),
|
||||
([query.replace("64.exe", ".exe")], probe)):
|
||||
result = subprocess.run(["bash", "-s", "run"] + args, input=script, text=True, capture_output=True,
|
||||
@@ -2744,7 +2746,7 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for name in ("libddsession.so", "libfakeinput.so"):
|
||||
(Path(tmp) / name).write_bytes(b"")
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
|
||||
start = script.index("for fake in ")
|
||||
block = script[start:script.index("\ndone\n", start) + 6].replace("/usr/local/lib/", tmp + "/")
|
||||
for inherited, expected in (
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import errno
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define SIZE 100003
|
||||
|
||||
static unsigned long sum_of(int fd) {
|
||||
unsigned long sum = 0;
|
||||
unsigned char buf[4096];
|
||||
ssize_t n;
|
||||
long total = 0;
|
||||
while ((n = read(fd, buf, sizeof(buf))) > 0) {
|
||||
for (ssize_t i = 0; i < n; i++) sum = sum * 31 + buf[i];
|
||||
total += n;
|
||||
}
|
||||
return total == SIZE ? sum : 0;
|
||||
}
|
||||
|
||||
static int open_by(const char *how, const char *path, int flags) {
|
||||
if (strcmp(how, "open") == 0) return open(path, flags);
|
||||
if (strcmp(how, "openat") == 0) return openat(AT_FDCWD, path, flags);
|
||||
return (int)syscall(SYS_openat, AT_FDCWD, path, flags, 0);
|
||||
}
|
||||
|
||||
static void report(const char *label, int fd, int src) {
|
||||
if (fd < 0) {
|
||||
printf("%s\terr\t%d\n", label, errno);
|
||||
return;
|
||||
}
|
||||
char link[64], target[256];
|
||||
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
|
||||
ssize_t n = readlink(link, target, sizeof(target) - 1);
|
||||
target[n > 0 ? n : 0] = '\0';
|
||||
char *deleted = strstr(target, " (deleted)");
|
||||
if (deleted) *deleted = '\0';
|
||||
struct stat a, b;
|
||||
fstat(fd, &a);
|
||||
fstat(src, &b);
|
||||
unsigned long sum = sum_of(fd);
|
||||
int write_errno = pwrite(fd, "x", 1, 0) < 0 ? errno : 0;
|
||||
int grow_errno = ftruncate(fd, SIZE + 1) < 0 ? errno : 0;
|
||||
printf("%s\tok\t%lu\t%d\t%s\t%d\t%ld\t%o\t%d\t%d\n", label, sum, fcntl(fd, F_GET_SEALS), target,
|
||||
(fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (long)lseek(src, 0, SEEK_CUR), (unsigned)(a.st_mode & 07777),
|
||||
write_errno != 0, grow_errno != 0);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int src = memfd_create("probe-module", MFD_ALLOW_SEALING);
|
||||
unsigned char *data = malloc(SIZE);
|
||||
for (long i = 0; i < SIZE; i++) data[i] = (unsigned char)(i * 7 + 3);
|
||||
if (write(src, data, SIZE) != SIZE) return 3;
|
||||
unsigned long want = 0;
|
||||
for (long i = 0; i < SIZE; i++) want = want * 31 + data[i];
|
||||
printf("want\t%lu\n", want);
|
||||
fcntl(src, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
|
||||
fchmod(src, 0);
|
||||
char path[64];
|
||||
const char *forms[] = {"self", "thread", "pid", "dev"};
|
||||
const char *hows[] = {"open", "openat", "syscall"};
|
||||
for (int f = 0; f < 4; f++) {
|
||||
for (int h = 0; h < 3; h++) {
|
||||
if (f == 0) snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
|
||||
if (f == 1) snprintf(path, sizeof(path), "/proc/thread-self/fd/%d", src);
|
||||
if (f == 2) snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), src);
|
||||
if (f == 3) snprintf(path, sizeof(path), "/dev/fd/%d", src);
|
||||
char label[32];
|
||||
snprintf(label, sizeof(label), "%s-%s", forms[f], hows[h]);
|
||||
report(label, open_by(hows[h], path, O_RDONLY | O_CLOEXEC), src);
|
||||
}
|
||||
}
|
||||
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
|
||||
report("keep-cloexec-off", open(path, O_RDONLY), src);
|
||||
report("write", open(path, O_RDWR), src);
|
||||
int foreign = memfd_create("probe-foreign", 0);
|
||||
fchmod(foreign, 0);
|
||||
pid_t child = fork();
|
||||
if (child < 0) return 6;
|
||||
if (child == 0) {
|
||||
pause();
|
||||
_exit(0);
|
||||
}
|
||||
snprintf(path, sizeof(path), "/proc/%d/fd/%d", (int)child, foreign);
|
||||
report("other-pid", open(path, O_RDONLY), src);
|
||||
kill(child, SIGKILL);
|
||||
waitpid(child, NULL, 0);
|
||||
|
||||
int plain = open(argv[1], O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
|
||||
if (write(plain, "x", 1) != 1) return 4;
|
||||
fchmod(plain, 0);
|
||||
snprintf(path, sizeof(path), "/proc/self/fd/%d", plain);
|
||||
report("plain-file", open(path, O_RDONLY | O_CLOEXEC), plain);
|
||||
|
||||
int open_mfd = memfd_create("probe-open", 0);
|
||||
if (write(open_mfd, data, SIZE) != SIZE) return 5;
|
||||
snprintf(path, sizeof(path), "/proc/self/fd/%d", open_mfd);
|
||||
int again = open(path, O_RDONLY | O_CLOEXEC);
|
||||
struct stat a, b;
|
||||
fstat(again, &a);
|
||||
fstat(open_mfd, &b);
|
||||
printf("readable-memfd\t%d\n", again >= 0 && a.st_ino == b.st_ino);
|
||||
unsigned long long how[3] = {O_RDONLY | O_CLOEXEC, 0, 0};
|
||||
errno = 0;
|
||||
long direct = syscall(437, AT_FDCWD, "/", how, sizeof(how));
|
||||
printf("kernel-openat2\t%d\n", direct >= 0 || errno != ENOSYS);
|
||||
int (*open2)(int, const char *, void *, size_t) = dlsym(RTLD_DEFAULT, "openat2");
|
||||
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
|
||||
if (open2 && argc > 2) {
|
||||
errno = 0;
|
||||
int refused = open2(AT_FDCWD, path, (void *)8, 24);
|
||||
int refused_errno = errno;
|
||||
printf("unreadable-how\t%d\t%d\n", refused, refused_errno);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookMemfdReopenTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
if os.geteuid() == 0:
|
||||
raise unittest.SkipTest("root ignores the file mode that stands in for the refused reopen")
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
cls.root.mkdir()
|
||||
cls.plain = cls.root / "plain"
|
||||
cls.bare = cls.run_probe(False)
|
||||
cls.kernel_openat2 = cls.bare["kernel-openat2"] == ["1"]
|
||||
cls.hooked = cls.run_probe(True, *(["how"] if cls.kernel_openat2 else []))
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
os.chmod(cls.plain, 0o600)
|
||||
cls.tmp.cleanup()
|
||||
|
||||
@classmethod
|
||||
def run_probe(cls, hook, *extra):
|
||||
if cls.plain.exists():
|
||||
os.chmod(cls.plain, 0o600)
|
||||
hook_env = {"DDNATV_ROOT": str(cls.root), "LD_PRELOAD": str(cls.hook)} if hook else {}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
|
||||
if cls.prefix:
|
||||
cmd = list(cls.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(cls.probe), str(cls.plain), *extra], env=env, capture_output=True, text=True, timeout=120)
|
||||
if out.returncode != 0:
|
||||
raise AssertionError(out.stdout + out.stderr)
|
||||
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
|
||||
|
||||
def test_the_refused_reopen_is_the_condition_without_the_hook(self):
|
||||
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-open"])
|
||||
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-syscall"])
|
||||
|
||||
def test_a_refused_read_only_reopen_of_an_own_memfd_gets_its_bytes_and_seals(self):
|
||||
want = self.hooked["want"][0]
|
||||
for form in ("self", "thread", "pid", "dev"):
|
||||
for how in ("open", "openat", "syscall"):
|
||||
with self.subTest(form=form, how=how):
|
||||
status, total, seals, name, cloexec, offset, mode, unwritable, fixed = self.hooked[f"{form}-{how}"]
|
||||
self.assertEqual("ok", status)
|
||||
self.assertEqual(want, total)
|
||||
self.assertEqual(str(0x2 | 0x4 | 0x8), seals)
|
||||
self.assertEqual("1", unwritable)
|
||||
self.assertEqual("1", fixed)
|
||||
self.assertEqual("/memfd:probe-module", name)
|
||||
self.assertEqual("1", cloexec)
|
||||
self.assertEqual("100003", offset)
|
||||
self.assertEqual("0", mode)
|
||||
|
||||
def test_close_on_exec_follows_the_open_flags(self):
|
||||
self.assertEqual("0", self.hooked["keep-cloexec-off"][4])
|
||||
|
||||
def test_an_unreadable_open_how_gets_the_kernel_error(self):
|
||||
if not self.kernel_openat2:
|
||||
self.skipTest("the runner has no openat2")
|
||||
self.assertEqual(["-1", str(errno.EFAULT)], self.hooked["unreadable-how"])
|
||||
|
||||
def test_a_writable_reopen_stays_refused(self):
|
||||
self.assertEqual(["err", str(errno.EACCES)], self.hooked["write"])
|
||||
|
||||
def test_another_process_descriptor_is_not_copied(self):
|
||||
self.assertEqual(["err", str(errno.EACCES)], self.bare["other-pid"])
|
||||
self.assertEqual(["err", str(errno.EACCES)], self.hooked["other-pid"])
|
||||
|
||||
def test_a_refused_regular_file_stays_refused(self):
|
||||
self.assertEqual(["err", str(errno.EACCES)], self.hooked["plain-file"])
|
||||
self.assertEqual(self.bare["plain-file"], self.hooked["plain-file"])
|
||||
|
||||
def test_a_memfd_the_kernel_reopens_is_the_same_file(self):
|
||||
self.assertEqual(["1"], self.hooked["readable-memfd"])
|
||||
self.assertEqual(["1"], self.bare["readable-memfd"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -19,6 +19,13 @@ int main(int argc, char **argv) {
|
||||
for (int i = 1; i < argc; i++) {
|
||||
char buf[4096];
|
||||
ssize_t n;
|
||||
if (strncmp(argv[i], "fill:", 5) == 0 || strncmp(argv[i], "short:", 6) == 0) {
|
||||
size_t size = argv[i][0] == 'f' ? sizeof(buf) : 256;
|
||||
memset(buf, '/', sizeof(buf));
|
||||
n = readlink(strchr(argv[i], ':') + 1, buf, size);
|
||||
printf("%s\t%s\n", argv[i], n > 0 && (size_t)n < size && buf[n] == 0 ? "ends" : "runs on");
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "at:", 3) == 0) {
|
||||
int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY);
|
||||
n = dfd >= 0 ? readlinkat(dfd, "exe", buf, sizeof(buf) - 1) : -1;
|
||||
@@ -57,6 +64,7 @@ class NativeHookProcExeTest(unittest.TestCase):
|
||||
(cls.root / "usr/bin").mkdir(parents=True)
|
||||
cls.kwin = cls.root / "usr/bin/kwin_wayland"
|
||||
shutil.copy(tmp / "sleeper", cls.kwin)
|
||||
(cls.root / "compositor").symlink_to("usr/bin/kwin_wayland")
|
||||
cls.runtime = tmp / "runtime"
|
||||
cls.runtime.mkdir()
|
||||
cls.bound = cls.runtime / "chrome"
|
||||
@@ -151,6 +159,14 @@ class NativeHookProcExeTest(unittest.TestCase):
|
||||
link = f"/proc/{pid}/exe"
|
||||
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link])
|
||||
|
||||
def test_the_own_program_answer_ends_where_the_name_ends(self):
|
||||
key = "fill:/proc/self/exe"
|
||||
self.assertEqual("ends", self.readlink(key)[key])
|
||||
|
||||
def test_a_link_read_into_a_short_buffer_ends_where_its_target_ends(self):
|
||||
key = "short:/compositor"
|
||||
self.assertEqual("ends", self.readlink(key)[key])
|
||||
|
||||
def test_a_loader_without_a_known_program_keeps_the_kernel_link(self):
|
||||
pid = self.start(loader=True)
|
||||
link = f"/proc/{pid}/exe"
|
||||
|
||||
@@ -45,6 +45,38 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
"""
|
||||
|
||||
FORMS = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <sys/stat.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (chdir(argv[1]) != 0) return 2;
|
||||
char buf[PATH_MAX];
|
||||
printf("cwd\t%s\n", getcwd(buf, sizeof(buf)) ? buf : "");
|
||||
ssize_t n = readlink("/proc/self/cwd", buf, sizeof(buf) - 1);
|
||||
printf("proc-cwd\t%.*s\n", n > 0 ? (int)n : 0, buf);
|
||||
n = readlink(argv[2], buf, sizeof(buf) - 1);
|
||||
printf("relative\t%.*s\n", n > 0 ? (int)n : 0, buf);
|
||||
char climbing[PATH_MAX];
|
||||
snprintf(climbing, sizeof(climbing), "../../../../../../../../../../../../etc/alternatives/%s", argv[2]);
|
||||
n = readlinkat(AT_FDCWD, climbing, buf, sizeof(buf) - 1);
|
||||
printf("climbing-at\t%.*s\n", n > 0 ? (int)n : 0, buf);
|
||||
struct stat st;
|
||||
printf("climbing-size\t%ld\n", fstatat(AT_FDCWD, climbing, &st, AT_SYMLINK_NOFOLLOW) == 0 ? (long)st.st_size : -1L);
|
||||
for (int i = 3; i < argc; i++) {
|
||||
char *got = realpath(argv[i], NULL);
|
||||
printf("realpath:%s\t%s\n", argv[i], got ? got : "");
|
||||
free(got);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookReadlinkTest(unittest.TestCase):
|
||||
@classmethod
|
||||
@@ -65,12 +97,20 @@ class NativeHookReadlinkTest(unittest.TestCase):
|
||||
(cls.root / "bin/nano").write_text("")
|
||||
os.symlink(cls.root / "bin/nano", cls.root / "etc/alternatives/editor")
|
||||
os.symlink("/bin/nano", cls.root / "etc/alternatives/guest")
|
||||
(tmp / "forms.c").write_text(FORMS)
|
||||
cls.forms = tmp / "forms"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.forms), str(tmp / "forms.c")], check=True)
|
||||
cls.steam = cls.root / "root/.local/share/Steam"
|
||||
(cls.steam / "steamapps/common/Game").mkdir(parents=True)
|
||||
(cls.steam / "steamapps/common/Game/Game.exe").write_text("")
|
||||
(cls.root / "root/pfx/dosdevices").mkdir(parents=True)
|
||||
os.symlink(cls.steam, cls.root / "root/pfx/dosdevices/s:")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def read(self, link):
|
||||
def run_hooked(self, argv):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
|
||||
if self.prefix:
|
||||
@@ -78,10 +118,16 @@ class NativeHookReadlinkTest(unittest.TestCase):
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.probe), link], env=env, capture_output=True, text=True, timeout=120)
|
||||
out = subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
|
||||
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
|
||||
|
||||
def read(self, link):
|
||||
return self.run_hooked([str(self.probe), link])
|
||||
|
||||
def path_forms(self, cwd, relative_link, *paths):
|
||||
return {key: value[0] for key, value in self.run_hooked([str(self.forms), cwd, relative_link, *paths]).items()}
|
||||
|
||||
def test_a_buffer_sized_from_lstat_gets_the_guest_target(self):
|
||||
result = self.read("/etc/alternatives/editor")
|
||||
self.assertEqual(["9", "/bin/nano"], result["sized"])
|
||||
@@ -101,6 +147,45 @@ class NativeHookReadlinkTest(unittest.TestCase):
|
||||
self.assertEqual(["-1", str(errno.EINVAL)], result["zero"])
|
||||
self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"])
|
||||
|
||||
def test_a_link_named_by_its_real_path_keeps_a_real_target(self):
|
||||
steam = str(self.steam)
|
||||
result = self.read(str(self.root / "root/pfx/dosdevices/s:"))
|
||||
self.assertEqual([str(len(steam)), steam], result["sized"])
|
||||
self.assertEqual([str(len(steam)), steam], result["sized-at"])
|
||||
self.assertEqual([str(len(steam)), steam], result["full"])
|
||||
|
||||
def test_a_link_named_by_its_guest_path_keeps_the_guest_target(self):
|
||||
result = self.read("/root/pfx/dosdevices/s:")
|
||||
self.assertEqual([str(len("/root/.local/share/Steam")), "/root/.local/share/Steam"], result["full"])
|
||||
self.assertEqual(["9", "/bin/nano"], self.read("/etc/alternatives/editor")["sized"])
|
||||
|
||||
def test_a_link_the_hook_wrote_reads_in_the_form_it_is_named_in(self):
|
||||
real = str(self.root / "bin/nano")
|
||||
self.assertEqual([str(len(real)), real], self.read(str(self.root / "etc/alternatives/editor"))["sized"])
|
||||
self.assertEqual(["9", "/bin/nano"], self.read(str(self.root / "etc/alternatives/guest"))["sized"])
|
||||
|
||||
def test_a_game_reached_through_a_drive_link_is_named_like_the_working_directory(self):
|
||||
game = self.steam / "steamapps/common/Game"
|
||||
through_drive = str(self.root / "root/pfx/dosdevices/s:/steamapps/common/Game/Game.exe")
|
||||
result = self.path_forms(str(game), "Game.exe", through_drive, "Game.exe")
|
||||
self.assertEqual(str(game), result["cwd"])
|
||||
self.assertEqual(str(game / "Game.exe"), result[f"realpath:{through_drive}"])
|
||||
self.assertTrue(result[f"realpath:{through_drive}"].startswith(result["cwd"] + "/"))
|
||||
|
||||
def test_the_proc_working_directory_link_matches_getcwd(self):
|
||||
game = str(self.steam / "steamapps/common/Game")
|
||||
result = self.path_forms(game, "Game.exe")
|
||||
self.assertEqual(result["cwd"], result["proc-cwd"])
|
||||
|
||||
def test_guest_and_relative_names_keep_the_guest_form(self):
|
||||
guest_drive = "/root/pfx/dosdevices/s:/steamapps/common/Game/Game.exe"
|
||||
result = self.path_forms(str(self.root / "etc/alternatives"), "editor", guest_drive, "/etc/alternatives/editor")
|
||||
self.assertEqual("/bin/nano", result["relative"])
|
||||
self.assertEqual("/bin/nano", result["climbing-at"])
|
||||
self.assertEqual("9", result["climbing-size"])
|
||||
self.assertEqual("/root/.local/share/Steam/steamapps/common/Game/Game.exe", result[f"realpath:{guest_drive}"])
|
||||
self.assertEqual("/bin/nano", result["realpath:/etc/alternatives/editor"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,81 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/resource.h>
|
||||
|
||||
static void show(const char *name, int ret) {
|
||||
struct rlimit now;
|
||||
if (getrlimit(RLIMIT_RTTIME, &now) != 0) exit(2);
|
||||
printf("%s\t%d\t%lld\t%lld\n", name, ret, (long long)now.rlim_cur, (long long)now.rlim_max);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
struct rlimit zero = {0, 0}, soft_zero = {0, 200000}, usable = {100000, 200000};
|
||||
show("start", 0);
|
||||
show("zero", setrlimit(RLIMIT_RTTIME, &zero));
|
||||
show("soft_zero", setrlimit(RLIMIT_RTTIME, &soft_zero));
|
||||
show("usable", setrlimit(RLIMIT_RTTIME, &usable));
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookRttimeLimitTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
cls.root.mkdir()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def limits(self):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.probe)], env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
|
||||
return {name: (int(ret), int(cur), int(hard))
|
||||
for name, ret, cur, hard in (line.split("\t") for line in out.stdout.splitlines())}
|
||||
|
||||
def test_a_realtime_limit_of_zero_is_reported_set_and_not_applied(self):
|
||||
limits = self.limits()
|
||||
self.assertEqual(0, limits["zero"][0])
|
||||
self.assertEqual(limits["start"][1:], limits["zero"][1:])
|
||||
|
||||
def test_a_soft_realtime_limit_of_zero_is_not_applied(self):
|
||||
limits = self.limits()
|
||||
self.assertEqual(0, limits["soft_zero"][0])
|
||||
self.assertEqual(limits["start"][1:], limits["soft_zero"][1:])
|
||||
|
||||
def test_a_usable_realtime_limit_is_applied(self):
|
||||
self.assertEqual((0, 100000, 200000), self.limits()["usable"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -78,6 +78,7 @@ static int g_loop_stub;
|
||||
static int g_fallback_accept;
|
||||
static int g_fallback_token;
|
||||
static int g_hdr_count;
|
||||
static int g_mirror_count, g_mirror_capture;
|
||||
|
||||
int text_input_host_commit(const char *u, size_t n)
|
||||
{
|
||||
@@ -143,6 +144,7 @@ void toplevel_icon_init(struct wl_display *d) { (void)d; }
|
||||
void single_pixel_init(struct wl_display *d) { (void)d; }
|
||||
void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; }
|
||||
void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; }
|
||||
void droiddeck_set_mirror_capture(int on) { g_mirror_capture = on; g_mirror_count++; }
|
||||
|
||||
struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; }
|
||||
void wl_display_flush_clients(struct wl_display *d) { (void)d; }
|
||||
@@ -216,7 +218,10 @@ int main(void)
|
||||
droiddeck_host_key(29, 0);
|
||||
droiddeck_host_text_commit("later", 5);
|
||||
droiddeck_host_hdr_output(1);
|
||||
droiddeck_host_mirror_capture(1);
|
||||
CHECK(g_mirror_count == 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_mirror_count == 1 && g_mirror_capture == 1);
|
||||
CHECK(g_n == saved);
|
||||
CHECK(g_hdr_count == 1);
|
||||
CHECK(g_fallback_token > 0);
|
||||
@@ -259,7 +264,10 @@ int main(void)
|
||||
droiddeck_host_key(32, 1);
|
||||
droiddeck_host_key(32, 0);
|
||||
droiddeck_host_hdr_output(0);
|
||||
droiddeck_host_mirror_capture(0);
|
||||
CHECK(g_mirror_count == 1);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_mirror_count == 2 && g_mirror_capture == 0);
|
||||
CHECK(g_n == saved + 1);
|
||||
CHECK(g_hdr_count == 2);
|
||||
CHECK(g_fallback_token > 0);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import signal
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -29,6 +30,7 @@ PROGRAM = r"""
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *ctl;
|
||||
@@ -220,6 +222,45 @@ static void *writer(void *arg) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static volatile unsigned char dispatch_selector;
|
||||
static int dispatch_traps, dispatch_done, dispatch_ready;
|
||||
static long dispatch_result = -1;
|
||||
|
||||
static void dispatch_trap(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)info;
|
||||
__atomic_add_fetch(&dispatch_traps, 1, __ATOMIC_RELAXED);
|
||||
#ifdef __x86_64__
|
||||
((ucontext_t *)context)->uc_mcontext.gregs[REG_RAX] = -ENOSYS;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void *dispatch_signaller(void *arg) {
|
||||
(void)arg;
|
||||
sigset_t set;
|
||||
sigemptyset(&set);
|
||||
sigaddset(&set, SIGURG);
|
||||
pthread_sigmask(SIG_BLOCK, &set, NULL);
|
||||
char ack[256], text[32];
|
||||
snprintf(ack, sizeof(ack), "%s.trim.%d", ctl, getpid());
|
||||
unlink(ack);
|
||||
FILE *f = fopen(ctl, "w");
|
||||
if (!f) exit(3);
|
||||
fprintf(f, "2 %ld\n", 1L << 30);
|
||||
fclose(f);
|
||||
while (!__atomic_load_n(&dispatch_ready, __ATOMIC_ACQUIRE)) usleep(1000);
|
||||
kill(getpid(), SIGURG);
|
||||
for (int i = 0; i < 1200 && dispatch_result < 0; i++) {
|
||||
f = fopen(ack, "r");
|
||||
char *line = f ? fgets(text, sizeof(text), f) : NULL;
|
||||
if (f) fclose(f);
|
||||
if (line) dispatch_result = atol(text);
|
||||
else usleep(10000);
|
||||
}
|
||||
__atomic_store_n(&dispatch_done, 1, __ATOMIC_RELEASE);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
ctl = argv[1];
|
||||
size = strtoul(argv[2], NULL, 0) << 20;
|
||||
@@ -391,6 +432,38 @@ int main(int argc, char **argv) {
|
||||
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
|
||||
printf("filtered_trim %ld\n", trim('2', 1L << 30));
|
||||
return 0;
|
||||
} else if (!strcmp(argv[4], "dispatch")) {
|
||||
stop = 1;
|
||||
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
|
||||
struct sigaction trap;
|
||||
memset(&trap, 0, sizeof(trap));
|
||||
trap.sa_sigaction = dispatch_trap;
|
||||
trap.sa_flags = SA_SIGINFO;
|
||||
sigemptyset(&trap.sa_mask);
|
||||
sigaction(SIGSYS, &trap, NULL);
|
||||
errno = 0;
|
||||
printf("prctlerr %d\n", prctl(-1, 0, 0, 0, 0) == -1 && errno == EINVAL);
|
||||
if (prctl(59, 1, (unsigned long)sa.sa_restorer, 16, &dispatch_selector)) {
|
||||
printf("dispatch 0\n");
|
||||
return 0;
|
||||
}
|
||||
printf("dispatch 1\n");
|
||||
fflush(stdout);
|
||||
pthread_t signaller;
|
||||
pthread_create(&signaller, NULL, dispatch_signaller, NULL);
|
||||
dispatch_selector = 1;
|
||||
__atomic_store_n(&dispatch_ready, 1, __ATOMIC_RELEASE);
|
||||
while (!__atomic_load_n(&dispatch_done, __ATOMIC_ACQUIRE)) {
|
||||
}
|
||||
char name[16] = {0};
|
||||
int named = prctl(PR_GET_NAME, name, 0, 0, 0) == 0 && name[0] != 0;
|
||||
dispatch_selector = 0;
|
||||
prctl(59, 0, 0, 0, 0);
|
||||
pthread_join(signaller, NULL);
|
||||
printf("traps %d\n", __atomic_load_n(&dispatch_traps, __ATOMIC_RELAXED));
|
||||
printf("trimmed %d\n", dispatch_result >= 0);
|
||||
printf("named %d\n", named);
|
||||
return 0;
|
||||
} else if (!strcmp(argv[4], "burst")) {
|
||||
send_request('0');
|
||||
usleep(10000);
|
||||
@@ -690,6 +763,16 @@ class ZramPreloadTest(unittest.TestCase):
|
||||
out = self.run_program(None, 48, 0, "burst")
|
||||
self.assertEqual([1], out["burstack"])
|
||||
|
||||
@unittest.skipUnless(platform.machine() == "x86_64", "selector check is x86-64 only")
|
||||
def test_requests_are_served_while_syscall_user_dispatch_blocks(self):
|
||||
out = self.run_program(None, 8, 0, "dispatch")
|
||||
self.assertEqual([1], out["prctlerr"])
|
||||
if out["dispatch"] != [1]:
|
||||
self.skipTest("kernel lacks syscall user dispatch")
|
||||
self.assertEqual([0], out["traps"], out)
|
||||
self.assertEqual([1], out["trimmed"], out)
|
||||
self.assertEqual([1], out["named"], out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user