from pathlib import Path import os import subprocess import tempfile import unittest PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" PROGRAM = r""" #define _GNU_SOURCE #include #include #include #include #include #include #include #include static int ask(const char *name) { struct robust_list_head *head = NULL; size_t len = 0; errno = 0; long ret = syscall(SYS_get_robust_list, 0, &head, &len); int ok = ret == 0 && head != NULL && len == sizeof(*head) && head->futex_offset < 0; printf("%s %s ret=%ld errno=%d len=%zu\n", name, ok ? "ok" : "failed", ret, errno, len); return ok; } static int leader_gone(void) { char line[256]; FILE *status = fopen("/proc/self/status", "r"); int zombie = 0; while (status && fgets(line, sizeof line, status)) if (!strncmp(line, "State:", 6)) zombie = strchr(line, 'Z') != NULL; if (status) fclose(status); return zombie; } static void *after_leader(void *unused) { (void)unused; for (int i = 0; i < 200 && !leader_gone(); i++) usleep(10000); printf("leader %s\n", leader_gone() ? "zombie" : "alive"); exit(ask("after-leader-exit") ? 0 : 1); } static void *thread(void *unused) { (void)unused; return (void *)(long)ask("thread"); } int main(void) { pthread_t t; void *ok; if (!ask("main")) return 1; pthread_create(&t, NULL, thread, NULL); pthread_join(t, &ok); if (!ok) return 1; pthread_create(&t, NULL, after_leader, NULL); pthread_exit(NULL); } """ class RobustListAfterLeaderExit(unittest.TestCase): @classmethod def setUpClass(cls): cls.tmp = Path(tempfile.mkdtemp()) cls.lib = cls.tmp / "librobust.so" subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib), str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), str(PRELOAD / "clockpause.c"), "-ldl"], check=True) source = cls.tmp / "robust.c" source.write_text(PROGRAM) subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-pthread", "-o", str(cls.tmp / "robust"), str(source)], check=True) def test_every_thread_gets_its_list_after_the_first_thread_exits(self): result = subprocess.run([str(self.tmp / "robust")], capture_output=True, text=True, timeout=30, env=dict(os.environ, LD_PRELOAD=str(self.lib))) self.assertIn("leader zombie", result.stdout) self.assertEqual(0, result.returncode, result.stdout + result.stderr) self.assertIn("after-leader-exit ok", result.stdout) if __name__ == "__main__": unittest.main()