diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-open b/tools/linuxfs/overlay/usr/local/bin/droiddeck-open index 45f806297c..bf0aaff7c1 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-open +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-open @@ -370,7 +370,7 @@ def main(argv): what = "steam" elif what == "script" and for_x86(path): what = "x86 script" - elif what in ("script", "elf") and game_folder(path): + elif what in ("script", "elf") and not (mode == "exec" and machine(head(path)) in EMULATED) and game_folder(path): what = "folder" try: cmd, folder = command(path, argv[1:], what, mode == "window", appid) @@ -381,10 +381,11 @@ def main(argv): cmd = placed(cmd, what, mode, os.environ) if mode != "exec" or not sys.stderr.isatty(): say("%s (%s): %s" % (path, what, " ".join(cmd[:4]))) - try: - os.chdir(folder) - except OSError: - pass + if not (mode == "exec" and what in ("elf", "script", "x86 script")): + try: + os.chdir(folder) + except OSError: + pass if mode == "exec": os.execv(cmd[0], cmd) started = time.monotonic() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-script-run b/tools/linuxfs/overlay/usr/local/bin/droiddeck-script-run index 55606d8c5a..3fe50f5d35 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-script-run +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-script-run @@ -16,6 +16,7 @@ run=("${interp[@]}" "./$entry") if [ -x /usr/local/bin/droiddeck-fex ]; then run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$folder" -- "${interp[@]}" "./$entry") fi +if [ "$fex" = off ]; then unset BL_BINFMT; else export BL_BINFMT=1; fi echo "== script $entry in $folder (${interp[*]:-a program}, FEX $fex)" case ${DBUS_SESSION_BUS_ADDRESS:-} in unix:*) "${run[@]}" "$@" ;; diff --git a/tools/linuxfs/preload/binfmt.c b/tools/linuxfs/preload/binfmt.c index 7aee2ee2fa..eb912efe11 100644 --- a/tools/linuxfs/preload/binfmt.c +++ b/tools/linuxfs/preload/binfmt.c @@ -21,11 +21,15 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t #if defined(__aarch64__) || defined(BINFMT_TEST) -static int desktop(void) { - const char *value = getenv("BL_DESKTOP"); +static int flag(const char *name) { + const char *value = getenv(name); return value && value[0] == '1' && value[1] == 0; } +static int handing_off(void) { + return flag("BL_DESKTOP") || flag("BL_BINFMT"); +} + static int foreign(const char *path, int error) { if (!path || !strcmp(path, BINFMT_HANDLER)) return 0; int fd = open(path, O_RDONLY | O_CLOEXEC); @@ -49,7 +53,7 @@ static int foreign(const char *path, int error) { } static int wanted(const char *path, int error) { - return (error == ENOEXEC || error == ENOENT || error == EACCES) && desktop() && foreign(path, error); + return (error == ENOEXEC || error == ENOENT || error == EACCES) && handing_off() && foreign(path, error); } static int lookup(const char *file, char *out, size_t size) { @@ -100,7 +104,7 @@ static int spawn_handler(pid_t *pid, const char *path, const posix_spawn_file_ac } __attribute__((visibility("hidden"))) void bl_binfmt_before(const char *path, char *const argv[], char *const envp[]) { - if (desktop() && foreign(path, ENOEXEC)) hand_off(path, argv, envp); + if (handing_off() && foreign(path, ENOEXEC)) hand_off(path, argv, envp); } __attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error) { @@ -111,18 +115,18 @@ __attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char __attribute__((visibility("hidden"))) void bl_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) { char path[PATH_MAX]; - if (desktop() && lookup(file, path, sizeof path)) bl_binfmt_before(path, argv, envp); + if (handing_off() && lookup(file, path, sizeof path)) bl_binfmt_before(path, argv, envp); } __attribute__((visibility("hidden"))) int bl_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) { char path[PATH_MAX]; - if (desktop() && lookup(file, path, sizeof path)) return bl_binfmt_retry(path, argv, envp, error); + if (handing_off() && lookup(file, path, sizeof path)) return bl_binfmt_retry(path, argv, envp, error); errno = error; return -1; } __attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode) { - if (mode != X_OK || !desktop()) return 0; + if (mode != X_OK || !handing_off()) return 0; int runs = foreign(path, EACCES) != 0; errno = EACCES; return runs; @@ -131,7 +135,7 @@ __attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, i __attribute__((visibility("hidden"))) int bl_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[], spawn_fn real) { - if (desktop() && foreign(path, ENOEXEC)) return spawn_handler(pid, path, fa, attr, argv, envp, real); + if (handing_off() && foreign(path, ENOEXEC)) return spawn_handler(pid, path, fa, attr, argv, envp, real); int error = real(pid, path, fa, attr, argv, envp); return error && wanted(path, error) ? spawn_handler(pid, path, fa, attr, argv, envp, real) : error; } @@ -150,7 +154,7 @@ int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp"); if (!spawn) spawn = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawn"); char path[PATH_MAX]; - if (!desktop() || !lookup(file, path, sizeof path)) return real(pid, file, fa, attr, argv, envp); + if (!handing_off() || !lookup(file, path, sizeof path)) return real(pid, file, fa, attr, argv, envp); return bl_binfmt_spawn(pid, path, fa, attr, argv, envp, spawn); } diff --git a/tools/tests/test_binfmt_preload.py b/tools/tests/test_binfmt_preload.py index 063345edb2..8314d39e40 100644 --- a/tools/tests/test_binfmt_preload.py +++ b/tools/tests/test_binfmt_preload.py @@ -88,14 +88,20 @@ class BinfmtPreloadTest(unittest.TestCase): path.chmod(mode) return path - def run_program(self, how, target, *args, desktop=True): + def environment(self, desktop=True, **extra): env = {"PATH": "%s:/usr/bin:/bin" % self.dir, "LD_PRELOAD": str(self.library), "HANDLER_LOG": str(self.log)} if desktop: env["BL_DESKTOP"] = "1" - done = subprocess.run([str(self.program), how, str(target)] + list(args), env=env, + env.update(extra) + return env + + def handed(self): + return self.log.read_text().splitlines() if self.log.exists() else None + + def run_program(self, how, target, *args, desktop=True, **extra): + done = subprocess.run([str(self.program), how, str(target)] + list(args), env=self.environment(desktop, **extra), stdout=subprocess.PIPE, text=True, timeout=30) - handed = self.log.read_text().splitlines() if self.log.exists() else None - return done.returncode, done.stdout.strip(), handed + return done.returncode, done.stdout.strip(), self.handed() def test_an_x86_program_goes_to_the_handler_before_it_is_executed(self): tool = self.x86() @@ -155,6 +161,76 @@ class BinfmtPreloadTest(unittest.TestCase): self.file("script.sh", b"#!/bin/sh\nexit 5\n") self.assertEqual(self.run_program("spawnp", "script.sh"), (0, "exit 5", None)) + def test_the_hand_off_switch_works_without_the_desktop(self): + tool = self.x86() + for how in ("execve", "execvp"): + self.log.unlink(missing_ok=True) + self.assertEqual(self.run_program(how, tool, "a", desktop=False, BL_BINFMT="1"), (7, "", ["--exec", str(tool), "a"])) + self.log.unlink() + self.assertEqual(self.run_program("spawnp", "tool", "b", desktop=False, BL_BINFMT="1"), (0, "exit 7", ["--exec", str(tool), "b"])) + + def test_only_the_value_one_switches_the_hand_off_on(self): + for value in ("0", "", "11", "yes"): + with self.subTest(value=value): + self.assertEqual(self.run_program("execve", self.x86(), desktop=False, BL_BINFMT=value), (0, "", None)) + + def test_the_desktop_hands_off_whatever_the_switch_says(self): + tool = self.x86() + for value in ("0", ""): + with self.subTest(value=value): + self.log.unlink(missing_ok=True) + self.assertEqual(self.run_program("execve", tool, BL_BINFMT=value), (7, "", ["--exec", str(tool)])) + + def script_child(self, *lines, **extra): + script = self.file("start.sh", ("#!/bin/bash\ncd \"${0%%/*}\"\n%s\n" % "\n".join(lines)).encode()) + done = subprocess.run([str(script)], env=self.environment(**extra), stdout=subprocess.PIPE, text=True, timeout=30) + return done.returncode, done.stdout.strip(), self.handed() + + @unittest.skipUnless(os.path.exists("/bin/bash"), "needs bash") + def test_an_x86_program_a_native_script_runs_goes_to_the_handler(self): + tool = self.x86() + self.assertEqual(self.script_child("./tool one", "echo after $?", desktop=False, BL_BINFMT="1"), + (0, "after 7", ["--exec", "./tool", "one"])) + self.log.unlink() + self.assertEqual(self.script_child("exec ./tool two", desktop=False, BL_BINFMT="1"), (7, "", ["--exec", str(tool), "two"])) + + @unittest.skipUnless(os.path.exists("/bin/bash"), "needs bash") + def test_native_children_of_a_script_run_as_themselves(self): + self.file("child.sh", b"#!/bin/sh\nexit 5\n") + self.assertEqual(self.script_child("./child.sh", "echo $?", desktop=False, BL_BINFMT="1"), (0, "5", None)) + + @unittest.skipUnless(os.path.exists("/bin/bash"), "needs bash") + def test_outside_the_desktop_and_script_runs_a_scripts_children_are_untouched(self): + self.x86() + self.assertEqual(self.script_child("./tool", "echo $?", desktop=False), (0, "0", None)) + + +@unittest.skipUnless(os.path.exists("/bin/bash") and not os.path.exists("/usr/local/bin/droiddeck-fex"), + "needs bash and no droiddeck-fex on this host") +class ScriptRunTest(unittest.TestCase): + def run_app(self, env, fex=None): + tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, tmp, True) + (tmp / "app/files").mkdir(parents=True) + (tmp / "app/entry").write_text("go.sh") + if fex: + (tmp / "app/fex").write_text(fex) + (tmp / "app/files/go.sh").write_text("#!/bin/bash\necho \"${BL_BINFMT-unset} ${BL_DESKTOP-unset}\"\n") + runner = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-script-run" + base = {"PATH": "/usr/bin:/bin", "DBUS_SESSION_BUS_ADDRESS": "unix:path=/nonexistent"} + done = subprocess.run(["/bin/bash", str(runner), str(tmp / "app")], stdout=subprocess.PIPE, text=True, timeout=60, + env=dict(base, **env)) + return done.returncode, done.stdout.strip().splitlines()[-1] + + def test_a_script_run_switches_the_hand_off_on_for_its_children_only(self): + self.assertEqual(self.run_app({}), (0, "1 unset")) + self.assertEqual(self.run_app({"BL_BINFMT": "0", "BL_DESKTOP": "1"}), (0, "1 1")) + self.assertEqual(self.run_app({}, fex="on"), (0, "1 unset")) + + def test_fex_off_keeps_x86_children_away_from_the_hand_off(self): + self.assertEqual(self.run_app({}, fex="off"), (0, "unset unset")) + self.assertEqual(self.run_app({"BL_BINFMT": "1"}, fex="off"), (0, "unset unset")) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_desktop_open.py b/tools/tests/test_desktop_open.py index d9ac36cd9f..a23d855448 100644 --- a/tools/tests/test_desktop_open.py +++ b/tools/tests/test_desktop_open.py @@ -315,6 +315,68 @@ class GameFolderTest(Temp): self.assertRegex(requests[0], "^id=[0-9a-f]{16}\nkind=folder\npath=%s\n$" % script) +class ExecTest(Temp): + def setUp(self): + super().setUp() + self.storage = self.tmp / "storage" + self.write("storage/Download/Game/start.sh", b"#!/bin/sh\n./game.x86_64\n", 0o755) + self.write("storage/Download/Game/game.x86_64", elf(62), 0o755) + self.write("storage/Download/Game/helper.bin", elf(183), 0o755) + self.write("storage/Download/Game/libhelper.so", elf(183)) + self.copied = [] + env = {k: v for k, v in os.environ.items() if k not in ("BL_DESKTOP", "BL_BINFMT", "GAMESCOPE_WAYLAND_DISPLAY")} + for patcher in (mock.patch.dict(OPEN, {"noexec": lambda path: True, "storage_root": lambda folder: str(self.storage), + "copied_in": lambda path: self.copied.append(path) or "/opt/droiddeck-apps/game", + "steam_title": lambda path: None, "notify": lambda *a: None, + "CACHE": str(self.tmp / "cache")}), + mock.patch.dict(os.environ, env, clear=True), + mock.patch.object(OPEN["os"], "chdir"), + mock.patch.object(OPEN["os"], "execv", side_effect=self.execv), + mock.patch.object(OPEN["subprocess"], "call", side_effect=self.call)): + patcher.start() + self.addCleanup(patcher.stop) + self.ran = [] + + def execv(self, program, cmd): + self.ran.append(cmd) + raise SystemExit(0) + + def call(self, cmd, *args, **kwargs): + self.ran.append(cmd) + return 0 + + def open(self, *argv, env=None): + os.environ.update(env or {}) + with contextlib.suppress(SystemExit): + OPEN["main"](list(argv)) + return self.ran[-1] + + def test_an_x86_program_a_running_program_starts_runs_under_fex_where_it_lies(self): + program = str(self.storage / "Download/Game/game.x86_64") + for env in ({}, {"BL_BINFMT": "1"}): + with self.subTest(env=env): + self.assertEqual(self.open("--exec", program, "-x", env=env), [OPEN["FEX"], "run", "--mode", "auto", "--", program, "-x"]) + self.assertEqual(self.copied, []) + + def test_an_in_place_hand_off_keeps_the_callers_working_folder(self): + program = str(self.storage / "Download/Game/game.x86_64") + with mock.patch("os.chdir") as chdir: + self.open("--exec", program, env={"BL_BINFMT": "1"}) + chdir.assert_not_called() + self.open("--exec", str(self.storage / "Download/Game/helper.bin")) + chdir.assert_called_once() + + def test_a_native_program_a_running_program_starts_still_gets_its_folder_copied_in(self): + program = str(self.storage / "Download/Game/helper.bin") + self.assertEqual(self.open("--exec", program, "-y"), [OPEN["SCRIPT_RUN"], "/opt/droiddeck-apps/game", "-y"]) + self.assertEqual(self.copied, [program]) + + def test_opening_an_x86_program_from_the_desktop_still_copies_its_folder_in(self): + program = str(self.storage / "Download/Game/game.x86_64") + self.assertEqual(self.open(program, env={"BL_DESKTOP": "1"}), [OPEN["SCRIPT_RUN"], "/opt/droiddeck-apps/game"]) + self.assertEqual(self.copied, [program]) + + def appinfo(apps): strings = []