from pathlib import Path import os import signal 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 #include #include #include #include #include #include static void show(const char *name, int ok) { printf("%s\t%d\n", name, ok); fflush(stdout); } int main(int argc, char **argv) { const char *name = argv[1]; sem_t *sem = sem_open(name, O_CREAT | O_EXCL, 0600, 1); show("create", sem != SEM_FAILED); show("exclusive", sem_open(name, O_CREAT | O_EXCL, 0600, 1) == SEM_FAILED && errno == EEXIST); sem_t *again = sem_open(name, O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1); int value = -1; show("existing", again == sem && sem_getvalue(again, &value) == 0 && value == 1); show("too-large", sem_open("/ddsem-absent", O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1) == SEM_FAILED && errno == EINVAL); show("wait", sem_wait(sem) == 0 && sem_trywait(again) == -1 && errno == EAGAIN); pid_t child = fork(); if (child == 0) { sem_t *other = sem_open(name, 0); _exit(other != SEM_FAILED && sem_post(other) == 0 && sem_close(other) == 0 ? 0 : 1); } int status = 0; waitpid(child, &status, 0); show("shared", WIFEXITED(status) && WEXITSTATUS(status) == 0 && sem_trywait(sem) == 0); show("close", sem_close(again) == 0 && sem_post(sem) == 0 && sem_close(sem) == 0 && sem_close(sem) == -1 && errno == EINVAL); show("unlink", sem_unlink(name) == 0); show("gone", sem_open(name, 0) == SEM_FAILED && errno == ENOENT); return 0; } """ KEEP = r""" #include #include int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; } """ FORKER = r""" #include #include #include #include #include #include #include #include #include static const char *name; static _Atomic int done; static _Atomic int parked_word; static _Atomic pid_t parked_tid; // the host's futex call: 202 on x86-64, where qemu-user runs, 98 on aarch64 static int blocked_futex(const char *path, unsigned long *addr) { unsigned long nr = 0; FILE *f = fopen(path, "r"); int got = f && fscanf(f, "%lu %lx", &nr, addr) == 2; if (f) fclose(f); return got && (nr == 202 || nr == 98); } static void *park(void *arg) { parked_tid = (pid_t)syscall(SYS_gettid); while (!parked_word) syscall(SYS_futex, &parked_word, 0 /* FUTEX_WAIT */, 0, NULL, NULL, 0); return arg; } // How far qemu-user moved the guest in the host's address space (its guest_base; 0 natively): a // thread parked on a futex this program knows shows that futex's host address in its syscall file, // which qemu-user passes through unlike /proc/self/maps. static long guest_base(void) { char path[96]; unsigned long addr = 0; while (!parked_tid) usleep(1000); snprintf(path, sizeof(path), "/proc/%d/task/%d/syscall", (int)getpid(), (int)parked_tid); for (int i = 0; i < 5000; i++) { if (blocked_futex(path, &addr) && addr) return (long)(addr - (unsigned long)&parked_word); usleep(1000); } return -1; } // A child that hangs in qemu-user itself: a fork while another thread is inside the emulator's // own locks (its mmap() handling) can leave the child waiting on a futex in qemu's memory, which no // guest lock is. The child's blocking call shows the host's address; under qemu-user this // program's /proc/self/maps lists the guest's mappings only, and a futex outside all of them, once // moved back by the guest base, is the emulator's. Natively every futex is in the process's own // mappings: never counted. Seen on x86 runners; there is no emulator on a device. static int stuck_in_emulator(pid_t pid, long base) { char path[64], line[512]; unsigned long addr = 0; snprintf(path, sizeof(path), "/proc/%d/syscall", (int)pid); if (base < 0 || !blocked_futex(path, &addr)) return 0; addr -= (unsigned long)base; FILE *f = fopen("/proc/self/maps", "r"); if (!f) return 0; int guest = 0; while (!guest && fgets(line, sizeof(line), f)) { unsigned long start, end; if (sscanf(line, "%lx-%lx", &start, &end) == 2 && addr >= start && addr < end) guest = 1; } fclose(f); return !guest; } static void *churn(void *arg) { while (!done) { sem_t *sem = sem_open(name, O_CREAT, 0600, 0); if (sem != SEM_FAILED) sem_close(sem); } return arg; } int main(int argc, char **argv) { name = argv[1]; pthread_t parked, thread; if (pthread_create(&parked, NULL, park, NULL) != 0) return 1; long base = guest_base(); printf("base\t%ld\n", base); if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1; int finished = 0, emulator = 0; for (int i = 0; i < 200; i++) { pid_t pid = fork(); if (pid < 0) break; if (pid == 0) { sem_t *sem = sem_open(name, O_CREAT, 0600, 0); _exit(sem == SEM_FAILED || sem_close(sem) != 0); } int status = 0, stalled = 0; pid_t r; for (int waited = 0; (r = waitpid(pid, &status, WNOHANG)) == 0; waited++) { if (waited == 1000) { // 10 s stalled = stuck_in_emulator(pid, base); kill(pid, SIGKILL); } usleep(10000); } if (r != pid) continue; if (stalled) emulator++; else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++; } done = 1; pthread_join(thread, NULL); parked_word = 1; syscall(SYS_futex, &parked_word, 1 /* FUTEX_WAKE */, 1, NULL, NULL, 0); pthread_join(parked, NULL); sem_unlink(name); printf("finished\t%d\n", finished); printf("emulator\t%d\n", emulator); return 0; } """ CALLS = ("create", "exclusive", "existing", "too-large", "wait", "shared", "close", "unlink", "gone") class NativeHookNamedSemaphoresTest(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", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) cls.shm = tmp / "root/tmp/shm" cls.shm.mkdir(parents=True) @classmethod def tearDownClass(cls): cls.tmp.cleanup() def run_hooked(self, program, *args, timeout=120): hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)} env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} 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) # its own process group, so a timeout also ends a child still blocked once the program is gone proc = subprocess.Popen(cmd + [str(program), *args], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True) try: stdout, stderr = proc.communicate(timeout=timeout) except subprocess.TimeoutExpired: os.killpg(proc.pid, signal.SIGKILL) proc.communicate() raise self.assertEqual(proc.returncode, 0, stderr) return dict(line.split("\t") for line in stdout.splitlines()) def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self): name = f"/ddsem-{os.getpid()}" self.assertEqual({call: "1" for call in CALLS}, self.run_hooked(self.probe, name)) self.assertFalse(Path(f"/dev/shm/sem.{name[1:]}").exists()) self.assertEqual([], list(self.shm.iterdir())) def test_a_child_forked_while_another_thread_opens_a_semaphore_can_open_one(self): source = self.probe.with_name("forker.c") source.write_text(FORKER) forker = self.probe.with_name("forker") subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True) name = f"/ddsem-fork-{os.getpid()}" # left by a run that did not get to sem_unlink(), it would fail the other tests' empty /dev/shm self.addCleanup(lambda: (self.shm / f"sem.{name[1:]}").unlink(missing_ok=True)) # 200 forks under a loaded qemu-user, and 10 s for each child that hangs in the emulator result = self.run_hooked(forker, name, timeout=300) # every child opened one, but for one now and then that hung in qemu-user itself (a fork during # the emulator's own locking), which a native run never has if self.prefix: self.assertNotEqual("-1", result.get("base"), result) else: self.assertEqual("0", result.get("base"), result) emulator = int(result.get("emulator", "0")) self.assertEqual(200, int(result.get("finished", "0")) + emulator, result) self.assertLessEqual(emulator, 0 if not self.prefix else 3, result) def test_a_created_semaphore_keeps_its_name_and_mode(self): name = f"ddsem-kept-{os.getpid()}" source = self.probe.with_name("keep.c") source.write_text(KEEP) keep = self.probe.with_name("keep") subprocess.run([self.cc, "-O1", "-pthread", "-o", str(keep), str(source)], check=True) self.run_hooked(keep, name) made = self.shm / f"sem.{name}" self.addCleanup(made.unlink) umask = os.umask(0) os.umask(umask) self.assertEqual([made.name], [p.name for p in self.shm.iterdir()]) self.assertEqual(0o640 & ~umask, made.stat().st_mode & 0o777) if __name__ == "__main__": unittest.main()