From c0abf31a6b7c316a42f53157903dacb15cf5d837 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:02:08 -0500 Subject: [PATCH] fix(native): start popen() and system() shells with posix_spawn (#3357) --- tools/nativeguest/hook/exec.c | 59 ++++++++---- tools/tests/test_native_hook_popen.py | 129 ++++++++++++++++++++++++++ 2 files changed, 171 insertions(+), 17 deletions(-) create mode 100644 tools/tests/test_native_hook_popen.py diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index b4249eb06c..eb2659f37d 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -1161,6 +1161,7 @@ int system(const char *command) { int status = -1; pid_t pid = start_shell(command, -1, -1, &old, &intr, &quit, 0); + if (pid < 0) status = 127 << 8; // as glibc's system() when the shell could not be started if (pid > 0) { while (waitpid(pid, &status, 0) < 0) { if (errno != EINTR) { @@ -1192,28 +1193,52 @@ static pthread_mutex_t g_popen_lock = PTHREAD_MUTEX_INITIALIZER; static pid_t start_shell(const char *command, int child_fd, int target_fd, const sigset_t *mask, const struct sigaction *intr, const struct sigaction *quit, int close_popen_streams) { - pid_t pid = fork(); - if (pid != 0) return pid; - if (intr) sigaction(SIGINT, intr, NULL); - if (quit) sigaction(SIGQUIT, quit, NULL); - if (mask) sigprocmask(SIG_SETMASK, mask, NULL); + // Through posix_spawn(), as glibc does: its child only makes system calls. A forked child running + // the exec code here would take locks that another thread of a multithreaded caller may have held + // at fork(), and wait for them forever (Steam's popen()s did, and its main loop stalled). + posix_spawn_file_actions_t actions; + posix_spawnattr_t attr; + if (posix_spawn_file_actions_init(&actions) != 0) return -1; + if (posix_spawnattr_init(&attr) != 0) { + posix_spawn_file_actions_destroy(&actions); + return -1; + } + int err = 0; if (child_fd >= 0) { - if (child_fd == target_fd) { - fcntl(target_fd, F_SETFD, 0); - } else if (dup2(child_fd, target_fd) < 0) { - _exit(127); - } + // dup2 onto itself clears FD_CLOEXEC in the child (glibc 2.29 and later) + err = posix_spawn_file_actions_adddup2(&actions, child_fd, target_fd); } // POSIX: the streams of earlier popen() calls are not open in the new shell - if (close_popen_streams) { - for (struct ddnatv_popen *p = g_popen_streams; p; p = p->next) { - int fd = fileno(p->fp); - if (fd >= 0 && fd != target_fd) close(fd); - } + for (struct ddnatv_popen *p = g_popen_streams; !err && close_popen_streams && p; p = p->next) { + int fd = fileno(p->fp); + if (fd >= 0 && fd != target_fd) err = posix_spawn_file_actions_addclose(&actions, fd); } + short flags = 0; + if (!err && mask) { + posix_spawnattr_setsigmask(&attr, mask); + flags |= POSIX_SPAWN_SETSIGMASK; + } + // SIGINT and SIGQUIT as they were before system() ignored them: an exec keeps an ignored signal + // ignored and puts a handled one back to the default + sigset_t defaults; + sigemptyset(&defaults); + if (intr && intr->sa_handler != SIG_IGN) sigaddset(&defaults, SIGINT); + if (quit && quit->sa_handler != SIG_IGN) sigaddset(&defaults, SIGQUIT); + if (!err && (intr || quit)) { + posix_spawnattr_setsigdefault(&attr, &defaults); + flags |= POSIX_SPAWN_SETSIGDEF; + } + if (!err) err = posix_spawnattr_setflags(&attr, flags); + pid_t pid = -1; char *const argv[] = { (char *)"sh", (char *)"-c", (char *)command, NULL }; - ddnatv_execve("/bin/sh", argv, environ, 0); - _exit(127); + if (!err) err = posix_spawn(&pid, "/bin/sh", &actions, &attr, argv, environ); + posix_spawn_file_actions_destroy(&actions); + posix_spawnattr_destroy(&attr); + if (err) { + errno = err; + return -1; + } + return pid; } FILE *popen(const char *command, const char *type) { diff --git a/tools/tests/test_native_hook_popen.py b/tools/tests/test_native_hook_popen.py new file mode 100644 index 0000000000..0293fecbba --- /dev/null +++ b/tools/tests/test_native_hook_popen.py @@ -0,0 +1,129 @@ +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +# The rootfs' /bin/sh for these tests: "sh -c 'echo WORDS'" prints WORDS, "sh -c 'exit N'" exits N. +SHELL = r""" +#include +#include +#include + +int main(int argc, char **argv) { + if (argc < 3 || strcmp(argv[1], "-c") != 0) return 2; + if (strncmp(argv[2], "echo ", 5) == 0) { + puts(argv[2] + 5); + return 0; + } + if (strncmp(argv[2], "exit ", 5) == 0) return atoi(argv[2] + 5); + return 127; +} +""" + +# posix_spawn() of argv[1] -c "exit 3", without the hook: prints the exit status it got +SPAWN_PROBE = r""" +#include +#include +#include + +extern char **environ; + +int main(int argc, char **argv) { + pid_t pid; + char *args[] = {"sh", "-c", "exit 3", NULL}; + int status = 0; + if (posix_spawn(&pid, argv[1], NULL, NULL, args, environ) != 0 || waitpid(pid, &status, 0) != pid) return 1; + printf("%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; +} +""" + +# popen() and system() through the hook (which starts the shell with posix_spawn()) +PROGRAM = r""" +#include +#include +#include +#include + +int main(int argc, char **argv) { + if (strcmp(argv[1], "system") == 0) { + int status = system("exit 3"); + printf("system\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; + } + // a second stream open while the first is read: the shell of the first must not hold it + FILE *other = popen("echo other", "r"); + FILE *f = popen("echo from the shell", "r"); + char line[64] = ""; + if (f && !fgets(line, sizeof(line), f)) line[0] = 0; + line[strcspn(line, "\n")] = 0; + int status = f ? pclose(f) : -1; + if (other) pclose(other); + printf("popen\t%s\n", line); + printf("pclose\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; +} +""" + + +class NativeHookPopenTest(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) + cls.root = tmp / "root" + (cls.root / "bin").mkdir(parents=True) + (tmp / "sh.c").write_text(SHELL) + subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True) + # posix_spawn()'s child execs the shell itself. Under qemu-user that exec works only where the + # kernel runs aarch64 programs (binfmt_misc), which a plain x86 runner does not. + (tmp / "spawn.c").write_text(SPAWN_PROBE) + subprocess.run([cls.cc, "-static", "-O1", "-o", str(tmp / "spawn"), str(tmp / "spawn.c")], check=True) + probe = subprocess.run(list(cls.prefix or []) + [str(tmp / "spawn"), str(cls.root / "bin/sh")], + capture_output=True, text=True, timeout=60) + if probe.stdout.strip() != "3": + cls.tmp.cleanup() + raise unittest.SkipTest("this runner cannot exec an aarch64 program from a posix_spawn() child") + (tmp / "prog.c").write_text(PROGRAM) + cls.program = tmp / "prog" + subprocess.run([cls.cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c")], check=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_program(self, mode): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + # Only what the program needs: other test modules in the same run change os.environ + env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin")} + 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.program), mode], env=env, capture_output=True, text=True, timeout=60) + self.assertEqual(0, out.returncode, out.stderr) + return dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out + + def test_popen_reads_the_shells_output(self): + result, out = self.run_program("popen") + self.assertEqual("from the shell", result.get("popen"), out.stdout + out.stderr) + self.assertEqual("0", result.get("pclose"), out.stdout) + + def test_system_returns_the_shells_status(self): + result, out = self.run_program("system") + self.assertEqual("3", result.get("system"), out.stdout + out.stderr) + + +if __name__ == "__main__": + unittest.main()