diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index d449c8a753..7b2273d227 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -11,6 +11,7 @@ import sys import tempfile import termios import threading +import time import unittest from pathlib import Path @@ -1241,6 +1242,31 @@ int main(void) { } """ +# A worker's program that says whether it has the hook's pidfd of its parent (kept at 900) and exits +# with 9 at once. Built with NOFDS, it first takes every free descriptor (/proc then cannot be read). +EXIT9 = r""" +#include +#include +#include +#include +#include + +int main(void) { + char target[64]; + ssize_t n = readlink("/proc/self/fd/900", target, sizeof(target) - 1); + target[n > 0 ? n : 0] = 0; + printf("pidfd\t%d\n", strcmp(target, "anon_inode:[pidfd]") == 0); +#ifdef NOFDS + struct rlimit lim = {512, 512}; // below the hook's kept fds, which stay open + setrlimit(RLIMIT_NOFILE, &lim); + while (open("/dev/null", O_RDONLY) >= 0) {} + printf("nofds\t%d\n", open("/proc/self/stat", O_RDONLY) < 0); +#endif + fflush(stdout); + return 9; +} +""" + # An unlisted program that execs the next one, as env and shell wrappers do WRAP = r""" #include @@ -2001,31 +2027,81 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual("6", result.get("other"), out.stdout) self.assertEqual("-1", result.get("again"), out.stdout) - def start_worker_exit(self, name, parent, state): + def start_worker_exit(self, name, parent, state, nofds=False, child_start=1 << 62): # A worker's program that exits with 9 at once, its entry (slot 0) given parent and state, as - # the parent's check of a gone worker leaves it while it holds it (TAKEN). Returns the run and - # the table. + # the parent's check of a gone worker leaves it while it holds it (TAKEN). With nofds it first + # takes every free descriptor, so that /proc cannot be read when it exits. A child_start before + # the parent's start leaves it without the parent's pidfd. Returns the run and the table. tmp = Path(self.tmp.name) probe = tmp / name - (tmp / (name + ".c")).write_text("int main(void) { return 9; }\n") + (tmp / (name + ".c")).write_text(("#define NOFDS 1\n" if nofds else "") + EXIT9) subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / (name + ".c"))], check=True) table = os.memfd_create("ddh-test-table", 0) self.addCleanup(os.close, table) os.ftruncate(table, 64 + 1024 * 64) os.pwrite(table, struct.pack("