#!/usr/bin/env python3 """Mounted ENOMEM regression for func.readdir=cor and func.readdir=seq. The dirents-level failures are covered by TEST_dirents_allocation; this test drives the real daemon, once per policy. A fill that fails partway must be reported as ENOMEM and leave no partial or stale listing cached, so the next read on the SAME handle re-enumerates and serves the exact reference suffix from the requested cookie. Helpers come from the tracked cookie-replay regression via runpy. Only the daemon gets an LD_PRELOAD failing one realloc: old pointer nonnull (not an initial reservation), new size 64KiB (the second 32KiB data quantum of the handle's dirents buffer), on the 'fuse.read' thread, and only while a marker file exists, armed after a clean reference listing and consumed on fire so the recovery fill succeeds. seq is targeted by the same injector because read-thread-count=1 with process-thread-count=-1 runs every request synchronously on 'fuse.read', where seq performs its whole fill and grows the handle buffer in the same 32KiB quanta (its branch scratch buffer is posix_memalign'ed, so it cannot steal the realloc); cor merges into the same buffer there, while its branch scratch buffers grow on 'readdir.cor' workers. Fails (not skips) if the injector never fires or the errno is not ENOMEM. Exit codes: 0 pass, 1 fail, 77 skip. """ import errno import os import runpy import shutil import subprocess import sys import tempfile SKIP = 77 HERE = os.path.dirname(os.path.realpath(__file__)) _cookie = runpy.run_path(os.path.join(HERE, "TEST_readdir_cor_cookie_replay")) (close_dir, fail, first_difference, libc, mergerfs_mount, opendir_or_raise, populate, read_all, read_one, read_listing) = ( _cookie[name] for name in ("close_dir", "fail", "first_difference", "libc", "mergerfs_mount", "opendir_or_raise", "populate", "read_all", "read_one", "read_listing")) # Synchronous read thread: both policies grow the handle's shared # dirents buffer there. seq fills it directly on the request thread; # cor merges into it there, not on the readdir.cor branch workers. OPTIONS_TEMPLATE = ("defaults,use_ino,category.create=mfs,cache.readdir=false," "read-thread-count=1,process-thread-count=-1," "func.readdir={policy}") PRELOAD_C = r""" #define _GNU_SOURCE #include #include #include #include extern void *__libc_realloc(void *,size_t); /* The open directory handle's dirents buffer grows in 32KiB quanta on the synchronous read thread; its 64KiB growth carries a non-NULL old pointer, unlike the opendir-time init reservation. Both policies grow it there: seq fills it directly, cor merges into it. */ #define MERGED_GROWTH ((size_t)(64 * 1024)) void * realloc(void *ptr_,size_t size_) { if((ptr_ != NULL) && (size_ == MERGED_GROWTH)) { const char *marker = getenv("MERGERFS_TEST_COR_ENOMEM_MARKER"); char name[16]; if((marker != NULL) && (pthread_getname_np(pthread_self(),name,sizeof(name)) == 0) && (strcmp(name,"fuse.read") == 0) && (access(marker,F_OK) == 0)) { unlink(marker); return NULL; } } return __libc_realloc(ptr_,size_); } """ def main(): if not sys.platform.startswith("linux"): print("Linux-only cor ENOMEM regression; skipping on " + sys.platform) return SKIP if not hasattr(libc, "__libc_realloc"): print("glibc is required for the daemon allocator hook") return SKIP compiler = shutil.which("cc") or shutil.which("gcc") if compiler is None: print("no C compiler for the preload; skipping") return SKIP tmp_parent = os.path.join(HERE, ".test_tmp") os.makedirs(tmp_parent, exist_ok=True) tmpdir = tempfile.mkdtemp(prefix="mergerfs_cor_enomem_", dir=tmp_parent) preload = os.path.join(tmpdir, "cor_enomem_preload.so") marker = os.path.join(tmpdir, "cor_enomem_armed") preload_env = os.environ.get("LD_PRELOAD") try: src = os.path.join(tmpdir, "cor_enomem_preload.c") with open(src, "w", encoding="ascii") as stream: stream.write(PRELOAD_C) built = subprocess.run( [compiler, "-O2", "-fPIC", "-shared", src, "-o", preload], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) if built.returncode != 0: return fail("preload compilation failed:\n" + built.stdout) os.environ["LD_PRELOAD"] = preload os.environ["MERGERFS_TEST_COR_ENOMEM_MARKER"] = marker try: for policy in ("cor:4", "seq"): rv = injected_run(marker, policy) if rv != 0: return rv return 0 except RuntimeError as exc: if ("binary not found" in str(exc)) or ("fusermount" in str(exc)): print(str(exc), end="") return SKIP return fail(str(exc)) except OSError as exc: return fail("cor ENOMEM regression failed: %s" % exc) finally: if preload_env is None: os.environ.pop("LD_PRELOAD", None) else: os.environ["LD_PRELOAD"] = preload_env os.environ.pop("MERGERFS_TEST_COR_ENOMEM_MARKER", None) shutil.rmtree(tmpdir, ignore_errors=True) def injected_run(marker, policy): options = OPTIONS_TEMPLATE.format(policy=policy) with mergerfs_mount(num_branches=4, options=options) as (mount, branches): dirpath = os.path.join(mount, "dir") populate(branches) truth = read_listing(dirpath) if len(truth) < 4: return fail("reference listing has only %d entries" % len(truth)) if len({entry[0] for entry in truth}) != len(truth): return fail("reference listing contains duplicate names") mid = len(truth) // 2 cookie = truth[mid][3] expected_suffix = truth[(mid + 1):] with open(marker, "w", encoding="ascii"): pass dp = opendir_or_raise(dirpath) try: libc.seekdir(dp, cookie) try: first = read_one(dp) except OSError as exc: if exc.errno != errno.ENOMEM: return fail("injected failure reported errno %s, " "expected ENOMEM" % exc.errno) else: return fail("injector never fired: the seeked readdir " "returned %r" % (first,)) suffix = read_all(dp) finally: close_dir(dp) if suffix != expected_suffix: return fail("after ENOMEM the same handle served a wrong " "suffix: " + first_difference(suffix, expected_suffix)) return 0 if __name__ == "__main__": raise SystemExit(main())