mergerfs/tests/TEST_preload_fopen_modes

104 lines
3.1 KiB
Text
Raw Normal View History

2026-11-25 12:59:47 -05:00
#!/usr/bin/env python3
"""Check both stream interposers on ordinary files without requiring FUSE."""
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
# The executable exports the virtual fullpath lookup. Only the fopen under
# test sees the alternate path; verification is done by the Python parent.
DRIVER = r'''
#define _GNU_SOURCE
#include <sys/xattr.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
static const char *g_BACKING;
ssize_t
fgetxattr(int fd_, const char *name_, void *out_, size_t size_)
{
(void)fd_;
if((g_BACKING == NULL) || (strcmp(name_,"user.mergerfs.fullpath") != 0))
{
errno = ENODATA;
return -1;
}
size_t len = strlen(g_BACKING);
if(size_ < len)
{
errno = ERANGE;
return -1;
}
memcpy(out_,g_BACKING,len);
return (ssize_t)len;
}
int
main(int argc_, char **argv_)
{
FILE *stream;
if(argc_ != 4)
return 1;
g_BACKING = argv_[3];
stream = (strcmp(argv_[1],"fopen") == 0) ? fopen("view",argv_[2]) : fopen64("view",argv_[2]);
g_BACKING = NULL;
if(stream == NULL)
return 1;
if(fputc('X',stream) == EOF)
return 1;
return (fclose(stream) != 0);
}
'''
def main():
cc = shutil.which("cc")
if not sys.platform.startswith("linux") or not cc:
print("requires Linux and a C compiler")
return 77
root = Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory(prefix="mergerfs-fopen-") as tmp:
work = Path(tmp)
so = work / "preload.so"
src = work / "driver.c"
src.write_text(DRIVER, encoding="ascii")
subprocess.run([cc, "-shared", "-fPIC", "-O2", root / "tools/preload.c",
"-o", so, "-ldl"], check=True)
exe = work / "driver"
subprocess.run([cc, "-O2", "-rdynamic", src, "-o", exe], check=True)
view, backing = work / "view", work / "backing"
for spelling in ("fopen", "fopen64"):
# r+ is the positive interposition control. The others must not
# touch the second pathname, even if it is absent or exclusive.
for mode, seed, original, want_view, want_backing in (
("r+", b"abc", b"def", b"abc", b"Xef"),
("w", b"abc", b"def", b"X", b"def"),
("a+", b"abc", None, b"abcX", None),
("wx", None, b"def", b"X", b"def")):
for path, data in ((view, seed), (backing, original)):
if data is not None:
path.write_bytes(data)
elif path.exists():
path.unlink()
subprocess.run([exe, spelling, mode, backing], cwd=work, check=True,
env={**os.environ, "LD_PRELOAD": str(so)})
if (view.read_bytes() != want_view or
(backing.read_bytes() if backing.exists() else None) != want_backing):
sys.exit(f"{spelling}({mode}): incorrect view or backing file after write")
return 0
if __name__ == "__main__":
sys.exit(main())