diff --git a/Makefile b/Makefile index 1d785a24..f2169360 100644 --- a/Makefile +++ b/Makefile @@ -68,9 +68,12 @@ DEBUG_OPT_FLAGS += \ -O0 \ -g3 \ -fno-omit-frame-pointer \ - $(SANITIZE) + $(SANITIZE) \ + -DDEBUG -ifdef RELEASE +ifeq ($(NDEBUG),1) +OPT_FLAGS := -O3 -DNDEBUG $(COMMON_OPT_FLAGS) +else ifdef RELEASE OPT_FLAGS := -O3 $(COMMON_OPT_FLAGS) else OPT_FLAGS ?= $(DEBUG_OPT_FLAGS) $(COMMON_OPT_FLAGS) @@ -126,6 +129,9 @@ override CXXFLAGS += \ -std=c++20 \ -MMD \ -MP +# preload.so must not inherit the global CPPFLAGS: _FILE_OFFSET_BITS=64 +# would hide its unsuffixed open/openat/fopen/creat interposers. +PRELOAD_CPPFLAGS ?= override INC_FLAGS := \ -Isrc \ -Ivendored \ @@ -175,7 +181,7 @@ all: libfuse $(BUILDDIR)/mergerfs $(BUILDDIR)/fsck.mergerfs $(BUILDDIR)/mergerfs .PHONY: help help: - @echo "usage: make ARG\n" + @echo "usage: make ARG" @echo "USE_XATTR=0 - build program without xattrs functionality" @echo "STATIC=1 - build static binary" @echo "LTO=1 - build with link time optimization" @@ -233,7 +239,7 @@ $(BUILDDIR)/.test_objs/%.cpp.o: tests/%.cpp | $(BUILDDIR)/stamp $(CXX) $(CXXFLAGS) $(TESTS_FLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) -c $< -o $@ $(BUILDDIR)/preload.so: $(BUILDDIR)/stamp tools/preload.c - $(CC) -shared -fPIC $(CFLAGS) -o $@ tools/preload.c + $(CC) -shared -fPIC $(PRELOAD_CPPFLAGS) $(CFLAGS) -o $@ tools/preload.c preload: $(BUILDDIR)/preload.so @@ -369,9 +375,15 @@ endef .PHONY: release release-all .PHONY: release-amd64 release-arm64 release-armhf release-riscv64 -.PHONY: release-sample release-static release-tarball release-installer +.PHONY: release-sample release-static release-tarball +# Invalidate profile-dependent products, not packages in build/pkgs. release: - $(MAKE) RELEASE=1 CPPFLAGS="$(CPPFLAGS) -DNDEBUG" all + $(RM) -rf $(BUILDDIR)/.objs $(BUILDDIR)/.test_objs $(BUILDDIR)/stamp + $(RM) -f $(BUILDDIR)/mergerfs $(BUILDDIR)/fsck.mergerfs \ + $(BUILDDIR)/mergerfs.collect-info $(BUILDDIR)/tests \ + $(BUILDDIR)/preload.so + $(MAKE) -C vendored/libfuse clean + $(MAKE) RELEASE=1 PRELOAD_CPPFLAGS=-DNDEBUG CPPFLAGS="$(CPPFLAGS) -DNDEBUG" all preload release-all: $(call build_release,"all") release-sample: @@ -389,8 +401,6 @@ release-static: $(call build_release,"static") release-tarball: $(call build_release,"tarball") -release-installer: - $(call build_release,"installer") container: $(eval GITREF ?= $(shell git describe --exact-match --tags HEAD 2>/dev/null || git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD)) diff --git a/buildtools/build-release b/buildtools/build-release index 241aeece..8a445964 100755 --- a/buildtools/build-release +++ b/buildtools/build-release @@ -18,7 +18,7 @@ def build(git_repo, '--force-rm'] if os.path.exists(git_repo): git_repo = os.path.realpath(git_repo) - args += ['-v',f'{git_repo}:/tmp/mergerfs.git:ro:z'] + args += ['-v',f'{git_repo}:/tmp/mergerfs.git:ro,z'] args += ['--build-arg=GIT_REPO=file:///tmp/mergerfs.git'] else: args += [f'--build-arg=GIT_REPO={git_repo}'] diff --git a/mergerfs.spec b/mergerfs.spec index e558283f..89ac59e4 100644 --- a/mergerfs.spec +++ b/mergerfs.spec @@ -26,7 +26,7 @@ management of files across numerous commodity storage devices. It is similar to mhddfs, unionfs, and aufs. %build -make %{?_smp_mflags} CFLAGS="%{optflags}" CXXFLAGS="%{optflags}" LDFLAGS="%{__global_ldflags}" +make %{?_smp_mflags} release CFLAGS="%{optflags}" CXXFLAGS="%{optflags}" LDFLAGS="%{__global_ldflags}" %install make install PREFIX=%{_prefix} DESTDIR=%{buildroot} diff --git a/mkdocs/docs/setup/build.md b/mkdocs/docs/setup/build.md index 56b77a43..5f5bbb07 100644 --- a/mkdocs/docs/setup/build.md +++ b/mkdocs/docs/setup/build.md @@ -84,9 +84,22 @@ $ gmake install # as root ``` $ make help -usage: make - -make USE_XATTR=0 - build program without xattrs functionality -make STATIC=1 - build static binary -make LTO=1 - build with link time optimization +usage: make ARG +USE_XATTR=0 - build program without xattrs functionality +STATIC=1 - build static binary +LTO=1 - build with link time optimization +SANITIZE=1 - build with sanitizers (address,undefined,leak) +SANITIZE=list - build with custom sanitizers (comma separated) +CLEANUP=1 - cleanup images between release build process +PKGDIR=/dir/ - location for release build pkgs +GITREF=gitref - gitref to use for release builds ``` + +A plain `make` builds the debug profile (`-O0 -g3`, assertions +enabled). `make release` builds the binaries and `preload.so` with +`-O3` and assertions disabled. It rebuilds the objects, binaries and +vendored libfuse so debug objects cannot end up in the release build. +It leaves packages and reports in `build/pkgs/` (or your `PKGDIR`) +alone. `make clean` still removes the entire `build/` directory. +`make NDEBUG=1` selects the same release flags without cleaning; the +static package builds use it together with `LTO=1 STATIC=1`. diff --git a/tests/TEST_release_metadata b/tests/TEST_release_metadata new file mode 100755 index 00000000..35c5c72f --- /dev/null +++ b/tests/TEST_release_metadata @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +BUILD_RELEASE = ROOT / "buildtools" / "build-release" + + +class ReleaseMetadataTests(unittest.TestCase): + def setUp(self): + tmpdir = os.environ.get("TMPDIR") + tmp = tempfile.TemporaryDirectory( + prefix="mergerfs-release-metadata-", dir=tmpdir + ) + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.home = self.root / "home" + self.home.mkdir() + + def base_env(self): + env = os.environ.copy() + for key in list(env): + if key.startswith("GIT_"): + del env[key] + env.update( + { + "HOME": str(self.home), + "XDG_CONFIG_HOME": str(self.home / ".config"), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_AUTHOR_NAME": "Release Test", + "GIT_AUTHOR_EMAIL": "release@example.invalid", + "GIT_COMMITTER_NAME": "Release Test", + "GIT_COMMITTER_EMAIL": "release@example.invalid", + "LC_ALL": "C", + } + ) + return env + + def run_command(self, args, cwd, env=None, timeout=30): + return subprocess.run( + [str(arg) for arg in args], cwd=str(cwd), + env=env or self.base_env(), stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, timeout=timeout, + ) + + def run_driver(self, fail_target="", missing_podman=False, branch="test"): + work = self.root / "driver" + containers = work / "buildtools" / "containerfiles" + containers.mkdir(parents=True) + for name in ("debian-bad", "debian-good"): + (containers / name).write_text("# test fixture\n", encoding="ascii") + + repo = work / "repo" + repo.mkdir() + fake_bin = work / "bin" + fake_bin.mkdir() + podman_log = work / "podman-args.jsonl" + podman = fake_bin / "podman" + podman.write_text( + """#!/usr/bin/env python3 +import json +import os +import sys + +with open(os.environ["PODMAN_LOG"], "a", encoding="ascii") as stream: + stream.write(json.dumps(sys.argv[1:]) + "\\n") +target = sys.argv[sys.argv.index("-f") + 1] +if os.path.basename(target) == os.environ.get("PODMAN_FAIL_TARGET"): + raise SystemExit(19) +raise SystemExit(0) +""", + encoding="ascii", + ) + podman.chmod(0o755) + + packages = work / "pkgs" + env = self.base_env() + if missing_podman: + env["PATH"] = str(work / "missing-bin") + else: + env["PATH"] = str(fake_bin) + os.pathsep + env.get("PATH", "") + env["PODMAN_LOG"] = str(podman_log) + env["PODMAN_FAIL_TARGET"] = fail_target + driver_args = [ + sys.executable, + BUILD_RELEASE, + "--target=all", + "--git-repo={}".format(repo), + "--pkgdirpath={}".format(packages), + ] + if branch is not None: + driver_args.append("--branch={}".format(branch)) + rv = self.run_command(driver_args, cwd=work, env=env) + calls = [] + if podman_log.exists(): + calls = [ + json.loads(line) + for line in podman_log.read_text(encoding="ascii").splitlines() + ] + report_path = packages / "build-report.txt" + report = "" + if report_path.exists(): + report = report_path.read_text(encoding="ascii") + return rv, calls, report.splitlines() + + def assert_driver_report(self, lines, bad_status): + self.assertEqual(len(lines), 2) + pattern = r"^debian-bad: branch=test; timestamp=\d+; rv={};$" + self.assertRegex(lines[0], pattern.format(bad_status)) + self.assertRegex( + lines[1], r"^debian-good: branch=test; timestamp=\d+; rv=success;$") + + def assert_local_volume_syntax(self, calls): + volumes = [ + arg for call in calls for arg in call + if arg.endswith(":/tmp/mergerfs.git:ro,z") + ] + self.assertEqual(len(volumes), 2) + + def test_driver_success(self): + rv, calls, report = self.run_driver() + self.assertEqual( + rv.returncode, 0, msg=rv.stdout + rv.stderr + ) + self.assertEqual(len(calls), 2) + self.assert_driver_report(report, "success") + self.assert_local_volume_syntax(calls) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/TEST_release_pkg_preservation b/tests/TEST_release_pkg_preservation new file mode 100755 index 00000000..f9d25f66 --- /dev/null +++ b/tests/TEST_release_pkg_preservation @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 + +"""make release preserves packages and rebuilds the release profile. + +Copies the repository Makefile over a minimal scratch fixture tree +(one tiny source, a stub vendored libfuse following the repo's +BUILDDIR conventions) and drives the real plain and release targets. +The fixture binary prints "debug" or "release" chosen by #ifdef +NDEBUG, so the profile flip is observed from the built executable; +packages staged like an earlier build leaves them (default build/pkgs, +a custom PKGDIR under build, one outside build) must survive +byte-for-byte. +""" + +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] + +SENTINELS = ( + "build/pkgs/mergerfs_1.0.0_amd64.deb", + "build/pkgs/build-report.txt", + "build/pkgs-custom/mergerfs_1.0.0_amd64.deb", + "pkgdir-elsewhere/mergerfs_1.0.0_amd64.deb", +) + +FIXTURE_CPP = ( + "#include \n" + "int\n" + "main()\n" + "{\n" + "#ifdef NDEBUG\n" + " std::puts(\"release\");\n" + "#else\n" + " std::puts(\"debug\");\n" + "#endif\n" + " return 0;\n" + "}\n" +) + +LIBFUSE_MAKEFILE = ( + "BUILDDIR := build\n" + "ARCHIVE := $(BUILDDIR)/libfuse.a\n" + ".PHONY: all clean\n" + "all: $(ARCHIVE)\n" + "$(ARCHIVE):\n" + "\tmkdir -p $(BUILDDIR)\n" + "\tar rcs $@\n" + "clean:\n" + "\trm -rf $(BUILDDIR)\n" +) + + +class ReleasePkgPreservationTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.mkdtemp(prefix="mergerfs-release-pkg-") + self.addCleanup(shutil.rmtree, tmp, ignore_errors=True) + self.fixture = Path(tmp) / "tree" + (self.fixture / "src").mkdir(parents=True) + (self.fixture / "vendored" / "libfuse").mkdir(parents=True) + (self.fixture / "tools").mkdir() + shutil.copy(ROOT / "Makefile", self.fixture / "Makefile") + self.write("src/version.hpp", + '#define MERGERFS_VERSION "0.0.0-fixture"\n') + self.write("src/fixture.cpp", FIXTURE_CPP) + self.write("tools/preload.c", + "void mergerfs_fixture_preload(void)\n{\n}\n") + self.write("vendored/libfuse/Makefile", LIBFUSE_MAKEFILE) + for rel in SENTINELS: + path = self.fixture / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes((rel + "\n").encode("ascii") * 8) + self.run_make() + + def write(self, relpath, content): + path = self.fixture / relpath + path.write_text(content, encoding="ascii") + return path + + def run_make(self, *args): + env = os.environ.copy() + for key in ("MAKEFLAGS", "MFLAGS", "CC", "CXX", "CFLAGS", + "CXXFLAGS", "CPPFLAGS", "LDFLAGS", "NDEBUG", + "RELEASE", "LTO", "STATIC", "SANITIZE", "PKGDIR"): + env.pop(key, None) + make = shutil.which("gmake") or "make" + proc = subprocess.run([make, "-C", str(self.fixture)] + list(args), + env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, timeout=50) + self.assertEqual(proc.returncode, 0, + msg="make {} failed:\n{}".format( + " ".join(args) or "(default)", proc.stdout)) + + def run_binary(self, relpath): + proc = subprocess.run([str(self.fixture / relpath)], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, timeout=10) + self.assertEqual(proc.returncode, 0, msg=proc.stdout) + return proc.stdout.strip() + + def test_release_preserves_packages_and_flips_profile(self): + self.assertEqual(self.run_binary("build/mergerfs"), "debug") + sentinels = {rel: (self.fixture / rel).read_bytes() + for rel in SENTINELS} + + self.run_make("release") + + for rel in SENTINELS: + self.assertEqual((self.fixture / rel).read_bytes(), + sentinels[rel], + msg="make release changed {}".format(rel)) + self.assertEqual(self.run_binary("build/mergerfs"), "release", + msg="make release did not rebuild with NDEBUG") + self.assertTrue((self.fixture / "build/preload.so").exists(), + "make release did not build preload.so") + + +if __name__ == "__main__": + unittest.main() diff --git a/vendored/libfuse/Makefile b/vendored/libfuse/Makefile index c22eaa4a..094f4590 100644 --- a/vendored/libfuse/Makefile +++ b/vendored/libfuse/Makefile @@ -49,9 +49,12 @@ DEBUG_OPT_FLAGS += \ -O0 \ -g3 \ -fno-omit-frame-pointer \ - $(SANITIZE) + $(SANITIZE) \ + -DDEBUG -ifdef RELEASE +ifeq ($(NDEBUG),1) +OPT_FLAGS := -O3 -DNDEBUG $(COMMON_OPT_FLAGS) +else ifdef RELEASE OPT_FLAGS := -O3 $(COMMON_OPT_FLAGS) else OPT_FLAGS ?= $(DEBUG_OPT_FLAGS) $(COMMON_OPT_FLAGS)