diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index 446996a06e..9bc0558ff0 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -542,7 +542,35 @@ static int zr_start(void) { return 0; } -static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec"))); +static pthread_key_t zr_key; +static int zr_key_ready; +static pthread_mutex_t zr_key_lock = PTHREAD_MUTEX_INITIALIZER; +static unsigned char zr_idle; + +static void zr_key_make(void) { + if (__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) return; + pthread_mutex_lock(&zr_key_lock); + if (!__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) { + pthread_key_t key; + if (pthread_key_create(&key, NULL) == 0) { + if (pthread_getspecific(key) == NULL) { + zr_key = key; + __atomic_store_n(&zr_key_ready, 1, __ATOMIC_RELEASE); + } else { + pthread_key_delete(key); + } + } + } + pthread_mutex_unlock(&zr_key_lock); +} + +static void zr_key_child(void) { + pthread_mutex_init(&zr_key_lock, NULL); +} + +static volatile unsigned char *zr_selector(void) { + return __atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE) ? (volatile unsigned char *)pthread_getspecific(zr_key) : NULL; +} int prctl(int option, ...) { va_list ap; @@ -552,16 +580,32 @@ int prctl(int option, ...) { unsigned long arg4 = va_arg(ap, unsigned long); unsigned long arg5 = va_arg(ap, unsigned long); va_end(ap); - volatile unsigned char *dispatch = zr_dispatch; + int arming = option == PR_SET_SYSCALL_USER_DISPATCH && arg2; + if (arming) { + zr_key_make(); + if (!__atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE)) { + errno = EAGAIN; + return -1; + } + } + volatile unsigned char *dispatch = zr_selector(); unsigned char selector = dispatch != NULL ? *dispatch : 0; if (selector) *dispatch = 0; + if (arming && pthread_setspecific(zr_key, dispatch != NULL ? (void *)dispatch : (void *)&zr_idle) != 0) { + if (selector) *dispatch = selector; + errno = ENOMEM; + return -1; + } long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5); + int failed = (unsigned long)result > -4096UL; + if (arming) pthread_setspecific(zr_key, failed ? (void *)dispatch : (void *)arg5); if (selector) *dispatch = selector; - if ((unsigned long)result > -4096UL) { + int ready = __atomic_load_n(&zr_key_ready, __ATOMIC_ACQUIRE); + if (failed) { errno = (int)-result; return -1; } - if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL; + if (option == PR_SET_SYSCALL_USER_DISPATCH && !arg2 && ready) pthread_setspecific(zr_key, NULL); return (int)result; } @@ -569,7 +613,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) { (void)sig; (void)context; if (info == NULL || info->si_code != SI_USER) return; - volatile unsigned char *dispatch = zr_dispatch; + volatile unsigned char *dispatch = zr_selector(); unsigned char selector = dispatch != NULL ? *dispatch : 0; if (selector) *dispatch = 0; int saved = errno; @@ -598,6 +642,7 @@ static void zr_paths(void) { } __attribute__((constructor)) static void zr_init(void) { + pthread_atfork(NULL, NULL, zr_key_child); zr_paths(); int fd = zr_open(zr_ctl); if (fd < 0) return; diff --git a/tools/tests/test_zram_preload.py b/tools/tests/test_zram_preload.py index 3d6b7d6126..cc798afaa5 100644 --- a/tools/tests/test_zram_preload.py +++ b/tools/tests/test_zram_preload.py @@ -555,6 +555,79 @@ def swap_total_kb(): return 0 +CROSS_THREAD = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef PR_SET_SYSCALL_USER_DISPATCH +#define PR_SET_SYSCALL_USER_DISPATCH 59 +#endif + +extern void *__libc_malloc(size_t); +extern void *__libc_calloc(size_t, size_t); +extern void *__libc_realloc(void *, size_t); + +static int watching; +static pid_t victim; +static int allocations; + +static void count(void) { + if (__atomic_load_n(&watching, __ATOMIC_ACQUIRE) && gettid() == __atomic_load_n(&victim, __ATOMIC_RELAXED)) __atomic_add_fetch(&allocations, 1, __ATOMIC_RELAXED); +} + +void *malloc(size_t n) { count(); return __libc_malloc(n); } +void *calloc(size_t a, size_t b) { count(); return __libc_calloc(a, b); } +void *realloc(void *p, size_t n) { count(); return __libc_realloc(p, n); } + +static void *idle(void *arg) { + (void)arg; + sigset_t none; + sigemptyset(&none); + __atomic_store_n(&victim, gettid(), __ATOMIC_RELAXED); + __atomic_store_n(&watching, 1, __ATOMIC_RELEASE); + sigsuspend(&none); + __atomic_store_n(&watching, 0, __ATOMIC_RELEASE); + return NULL; +} + +int main(int argc, char **argv) { + sigset_t urg; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + pthread_sigmask(SIG_BLOCK, &urg, NULL); + void *lib = dlopen(argv[1], RTLD_LAZY); + if (lib == NULL) { puts(dlerror()); return 1; } + int (*control)(int, ...) = (int (*)(int, ...))dlsym(lib, "prctl"); + volatile char selector = 0; + if (argc > 2) { + pthread_key_t key, last = 0; + while (pthread_key_create(&key, NULL) == 0) last = key; + int r = control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector); + printf("refused %d %s\n", r, r != 0 && errno == EAGAIN ? "again" : "other"); + pthread_key_delete(last); + printf("retried %d\n", control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector)); + return 0; + } + if (control(PR_SET_SYSCALL_USER_DISPATCH, 1, 0, 0, &selector) != 0) { puts("nodispatch"); return 0; } + pthread_t thread; + pthread_create(&thread, NULL, idle, NULL); + while (!__atomic_load_n(&watching, __ATOMIC_ACQUIRE)) usleep(1000); + if (write(2, "signal\n", 7) != 7) return 1; + kill(getpid(), SIGURG); + pthread_join(thread, NULL); + printf("allocations %d\n", allocations); + return 0; +} +""" + @unittest.skipUnless(shutil.which("cc"), "needs a C compiler") class ZramPreloadTest(unittest.TestCase): @classmethod @@ -773,6 +846,39 @@ class ZramPreloadTest(unittest.TestCase): self.assertEqual([1], out["trimmed"], out) self.assertEqual([1], out["named"], out) + def test_a_signal_on_another_thread_allocates_nothing_after_dispatch_was_armed(self): + source = self.dir / "crossthread.c" + program = self.dir / "crossthread" + source.write_text(CROSS_THREAD) + subprocess.run(["cc", "-O2", "-pthread", "-o", str(program), str(source), "-ldl"], check=True) + environment = dict(os.environ, GLIBC_TUNABLES="glibc.rtld.optional_static_tls=0", LD_DEBUG="bindings") + for name in ("LD_PRELOAD", "LD_BIND_NOW"): + environment.pop(name, None) + result = subprocess.run([str(program), str(self.lib)], env=environment, capture_output=True, text=True, timeout=60) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + if result.stdout.strip() == "nodispatch": + self.skipTest("kernel lacks syscall user dispatch") + self.assertEqual("allocations 0", result.stdout.strip()) + after = result.stderr.split("signal\n", 1)[1] + self.assertNotIn("pthread_getspecific", after) + refused = subprocess.run([str(program), str(self.lib), "exhaust"], env=environment, capture_output=True, + text=True, timeout=60) + self.assertEqual("refused -1 again\nretried 0", refused.stdout.strip()) + + def test_loads_at_runtime_without_spare_static_tls(self): + loader = self.dir / "loader" + source = self.dir / "loader.c" + source.write_text("#include \n#include \n" + "int main(int c, char **v) { (void)c; void *h = dlopen(v[1], RTLD_NOW);" + " puts(h ? \"loaded\" : dlerror()); return h == NULL; }\n") + subprocess.run(["cc", "-O2", "-o", str(loader), str(source), "-ldl"], check=True) + environment = dict(os.environ, GLIBC_TUNABLES="glibc.rtld.optional_static_tls=0") + environment.pop("LD_PRELOAD", None) + result = subprocess.run([str(loader), str(self.lib)], env=environment, capture_output=True, text=True, + timeout=60) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + self.assertEqual("loaded", result.stdout.strip()) + if __name__ == "__main__": unittest.main()