# Makefile
#
# Copyright (C) 2025-2026 by Robert Cousins.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# $Id: Makefile,v 2.2 2026/11/05 17:05:49 rec Exp $
#
# File:    Makefile
# Author:  Robert Cousins
# Purpose: Builds the static and shared libraries, the tests, the example and
#          the benchmark, runs the tests, installs and uninstalls, builds the
#          LaTeX manual, and rolls the release tarball.
# Depends: GNU make (gmake on FreeBSD), a C99 compiler, install(1).
#          pdflatex and makeindex for the manual target only; the tarball ships
#          the PDF, so a user without LaTeX never needs them.
# Note:    Targets:
#            all            - libraries, tests, example, benchmark (the default)
#            lib            - static and shared libraries (also: library)
#            test, check    - build and run every test; fails if any test fails
#            sanitize-test  - the tests under -fsanitize=address,undefined
#            tsan-test      - test_threads under -fsanitize=thread
#            bench          - run the benchmark (also: benchmark builds it)
#            man            - check the man page with mandoc, if present
#            manual         - build manual.pdf
#            docs           - man and manual
#            install, uninstall - honour PREFIX, DESTDIR and the *DIR variables
#            dist           - build the release tarball (also: release)
#            clean, distclean
#
#          CC, COPT, CWARN, CFLAGS, LDFLAGS can be set on the command line.
#          -fPIC and -std are kept separate from CFLAGS so that "make CFLAGS=-g"
#          still links a shared library.  sanitize-test uses COPT for the same
#          reason.  There is no configure step; the uname block below is all
#          of the platform configuration the package needs.
#
# Versions:
#   2.0.0  2025-11-19  Robert Cousins  Stateful iterators release.
#   2.1.0  2026-11-04  Robert Cousins  Added DESTDIR, uninstall, man page and
#                                      manual installation, sanitizer targets
#                                      and the new tests.  Tests link the
#                                      static archive, so they need no
#                                      LD_LIBRARY_PATH.  Removed -Werror from
#                                      the default flags, since it breaks
#                                      builds on newer compilers (make
#                                      WERROR=-Werror restores it).  clean no
#                                      longer deletes release tarballs.  Ships
#                                      and installs LICENSE and TUNING.md.

# Library name and version
LIBNAME = patricia
VERSION = 2.1.0
SOVERSION = 2

# Toolchain
CC ?= cc
AR ?= ar
ARFLAGS = rcs
INSTALL ?= install
CSTD = -std=c99
CWARN = -Wall -Wextra -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -pedantic
COPT = -O2
WERROR =
CFLAGS ?=
LDFLAGS ?=
ALL_CFLAGS = $(CSTD) $(CWARN) $(WERROR) $(COPT) -fPIC $(CFLAGS)

# Platform: FreeBSD's ports tree keeps man pages under PREFIX/man
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),FreeBSD)
    DEFAULT_MANROOT = $(PREFIX)/man
else
    DEFAULT_MANROOT = $(PREFIX)/share/man
endif

# Installation directories
PREFIX = /usr/local
LIBDIR = $(PREFIX)/lib
INCDIR = $(PREFIX)/include
MANROOT = $(DEFAULT_MANROOT)
MANDIR = $(MANROOT)/man3
DOCDIR = $(PREFIX)/share/doc/lib$(LIBNAME)

# Library files
LIB_STATIC = lib$(LIBNAME).a
LIB_SHARED = lib$(LIBNAME).so.$(VERSION)
LIB_SONAME = lib$(LIBNAME).so.$(SOVERSION)
LIB_LINK = lib$(LIBNAME).so

LIB_SOURCES = patricia.c
LIB_OBJECTS = $(LIB_SOURCES:.c=.o)
LIB_HEADERS = patricia.h

# Programs linked only with the static library
TEST_PROGS = test_patricia test_regress test_oracle test_threads test_oom
PROGS = $(TEST_PROGS) example benchmark

# Names the man page can also be reached by
MAN_LINKS = patricia_create patricia_destroy patricia_insert patricia_update \
            patricia_get_or_insert patricia_get_or_insert_with patricia_lookup \
            patricia_delete patricia_contains patricia_size patricia_clear \
            patricia_foreach patricia_foreach_prefix patricia_first patricia_last \
            patricia_next patricia_prev patricia_find_gte patricia_find_gt \
            patricia_find_lte patricia_find_lt patricia_iter_create \
            patricia_iter_create_reverse patricia_iter_destroy patricia_iter_next \
            patricia_iter_prev patricia_iter_seek patricia_iter_delete \
            patricia_iter_update patricia_iter_key patricia_iter_value \
            patricia_iter_valid patricia_iter_reset patricia_get_stats \
            patricia_insert_int patricia_lookup_int patricia_update_int \
            patricia_delete_int

# Distribution files
DIST_FILES = $(LIB_SOURCES) $(LIB_HEADERS) $(TEST_PROGS:=.c) example.c benchmark.c \
             bench.h Makefile LICENSE README.md TUNING.md RELEASE_v$(VERSION).md patricia.3 manual.tex \
             manual.pdf

DIST_DIR = lib$(LIBNAME)-$(VERSION)

.PHONY: all lib library examples tests test check sanitize-test \
        tsan-test run-example bench man manual docs install uninstall dist \
        release clean distclean

# Default target
all: lib $(PROGS)

lib library: $(LIB_STATIC) $(LIB_SHARED)

examples: example
tests: $(TEST_PROGS)

# Build static library
$(LIB_STATIC): $(LIB_OBJECTS)
	$(AR) $(ARFLAGS) $@ $^

# Build shared library
$(LIB_SHARED): $(LIB_OBJECTS)
	$(CC) -shared -Wl,-soname,$(LIB_SONAME) -o $@ $^ $(LDFLAGS)
	ln -sf $(LIB_SHARED) $(LIB_SONAME)
	ln -sf $(LIB_SONAME) $(LIB_LINK)

$(LIB_LINK): $(LIB_SHARED)

# Compile object files
%.o: %.c $(LIB_HEADERS)
	$(CC) $(ALL_CFLAGS) -c $< -o $@

benchmark.o: bench.h

# Programs
test_patricia test_regress test_oracle example benchmark: %: %.o $(LIB_STATIC)
	$(CC) $(ALL_CFLAGS) $(LDFLAGS) -o $@ $< $(LIB_STATIC)

test_threads: test_threads.o $(LIB_STATIC)
	$(CC) $(ALL_CFLAGS) $(LDFLAGS) -pthread -o $@ $< $(LIB_STATIC)

test_threads.o: test_threads.c $(LIB_HEADERS)
	$(CC) $(ALL_CFLAGS) -pthread -c $< -o $@

test_oom: test_oom.o $(LIB_STATIC)
	$(CC) $(ALL_CFLAGS) $(LDFLAGS) -Wl,--wrap=malloc -Wl,--wrap=realloc -o $@ $< $(LIB_STATIC)

# Run tests.  The loop stops at nothing, reports everything, and fails if any
# program failed.
test check: $(TEST_PROGS) example
	@fail=0; \
	for t in $(TEST_PROGS); do \
	    echo "== $$t"; \
	    if [ "$$t" = test_patricia ]; then \
	        ./$$t > $$t.out 2>&1; rc=$$?; tail -4 $$t.out | head -3; rm -f $$t.out; \
	    else \
	        ./$$t > $$t.out 2>&1; rc=$$?; tail -1 $$t.out; rm -f $$t.out; \
	    fi; \
	    [ $$rc -eq 0 ] || { echo "FAILED: $$t (exit $$rc)"; fail=1; }; \
	done; \
	echo "== example"; \
	./example > /dev/null || { echo "FAILED: example"; fail=1; }; \
	if [ $$fail -eq 0 ]; then echo "ALL TESTS PASSED"; else echo "SOME TESTS FAILED"; fi; \
	exit $$fail

# The same suite under ASan and UBSan, with UBSan findings fatal.  The tree is
# cleaned before and after so sanitized objects cannot leak into a later build.
SAN_FLAGS = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer

sanitize-test:
	$(MAKE) clean
	@fail=0; $(MAKE) COPT="$(SAN_FLAGS)" LDFLAGS="-fsanitize=address,undefined" test || fail=1; \
	$(MAKE) clean; exit $$fail

# test_threads under ThreadSanitizer.  On Linux with high ASLR entropy TSan
# refuses to start unless ASLR is off: make tsan-test TSAN_RUN="setarch -R"
TSAN_RUN =

tsan-test:
	$(MAKE) clean
	@fail=0; $(MAKE) COPT="-O1 -g -fsanitize=thread" LDFLAGS="-fsanitize=thread" test_threads || fail=1; \
	if [ $$fail -eq 0 ]; then $(TSAN_RUN) ./test_threads || fail=1; fi; \
	$(MAKE) clean; exit $$fail

# Run example
run-example: example
	./example

# Run benchmark
bench: benchmark
	./benchmark

# Check the man page.  mandoc is absent on some machines, so this is optional.
man:
	@if command -v mandoc >/dev/null 2>&1; then \
	    mandoc -Tlint -Wwarning patricia.3 || true; \
	else \
	    echo "mandoc not found, man page not checked"; \
	fi

# Build the manual: three passes with makeindex after the first
manual: manual.pdf

manual.pdf: manual.tex
	pdflatex -interaction=nonstopmode -halt-on-error manual.tex > /dev/null
	makeindex manual.idx > /dev/null 2>&1
	pdflatex -interaction=nonstopmode -halt-on-error manual.tex > /dev/null
	pdflatex -interaction=nonstopmode -halt-on-error manual.tex > /dev/null

docs: man manual

# Install library, headers, man page and manual
install: lib
	$(INSTALL) -d $(DESTDIR)$(LIBDIR) $(DESTDIR)$(INCDIR) $(DESTDIR)$(MANDIR) $(DESTDIR)$(DOCDIR)
	$(INSTALL) -m 644 $(LIB_STATIC) $(DESTDIR)$(LIBDIR)/
	$(INSTALL) -m 755 $(LIB_SHARED) $(DESTDIR)$(LIBDIR)/
	cd $(DESTDIR)$(LIBDIR) && ln -sf $(LIB_SHARED) $(LIB_SONAME)
	cd $(DESTDIR)$(LIBDIR) && ln -sf $(LIB_SONAME) $(LIB_LINK)
	$(INSTALL) -m 644 $(LIB_HEADERS) $(DESTDIR)$(INCDIR)/
	$(INSTALL) -m 644 patricia.3 $(DESTDIR)$(MANDIR)/
	cd $(DESTDIR)$(MANDIR) && for n in $(MAN_LINKS); do ln -sf patricia.3 $$n.3; done
	$(INSTALL) -m 644 manual.pdf LICENSE README.md TUNING.md RELEASE_v$(VERSION).md $(DESTDIR)$(DOCDIR)/

# Remove what install put there
uninstall:
	rm -f $(DESTDIR)$(LIBDIR)/$(LIB_STATIC) $(DESTDIR)$(LIBDIR)/$(LIB_SHARED)
	rm -f $(DESTDIR)$(LIBDIR)/$(LIB_SONAME) $(DESTDIR)$(LIBDIR)/$(LIB_LINK)
	rm -f $(DESTDIR)$(INCDIR)/patricia.h $(DESTDIR)$(MANDIR)/patricia.3
	cd $(DESTDIR)$(MANDIR) 2>/dev/null && for n in $(MAN_LINKS); do rm -f $$n.3; done || true
	rm -f $(DESTDIR)$(DOCDIR)/manual.pdf $(DESTDIR)$(DOCDIR)/README.md
	rm -f $(DESTDIR)$(DOCDIR)/LICENSE $(DESTDIR)$(DOCDIR)/TUNING.md
	rm -f $(DESTDIR)$(DOCDIR)/RELEASE_v$(VERSION).md
	-rmdir $(DESTDIR)$(DOCDIR) 2>/dev/null

# Create release tarball
dist release: manual.pdf
	rm -rf $(DIST_DIR) $(DIST_DIR).tgz
	mkdir $(DIST_DIR)
	cp -p $(DIST_FILES) $(DIST_DIR)/
	chmod 644 $(DIST_DIR)/*
	tar czf $(DIST_DIR).tgz $(DIST_DIR)
	rm -rf $(DIST_DIR)
	@echo "Created: $(DIST_DIR).tgz"

# Clean build artifacts.  manual.pdf and release tarballs are kept.
clean:
	rm -f $(LIB_OBJECTS) $(PROGS:=.o) $(PROGS) $(TEST_PROGS:=.out)
	rm -f $(LIB_STATIC) $(LIB_SHARED) $(LIB_SONAME) $(LIB_LINK)
	rm -f *.core core
	rm -f manual.aux manual.log manual.toc manual.out manual.idx manual.ilg manual.ind

distclean: clean
	rm -f $(DIST_DIR).tgz
	rm -rf $(DIST_DIR)
