# GNU make / gmake. Native target requires an illumos 64-bit compiler + headers.
CC = gcc
CPPFLAGS = -D__EXTENSIONS__ -D_POSIX_C_SOURCE=200809L -Isrc
CFLAGS = -std=c99 -m64 -O2 -Wall -Wextra -Werror -Wformat=2
LDLIBS = -lkstat -lrt
SOURCES = src/main.c src/core.c src/config.c src/support.c src/illumos.c
TESTFLAGS = -std=c99 -O1 -g -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 -Isrc -Wall -Wextra -Werror -Wformat=2 -pedantic

.PHONY: all native-check test test-sanitize portability clean
all: o6h-memory-guard

native-check:
	@test "`uname -s`" = SunOS || { echo "Native build requires SmartOS/illumos; use make test and make portability here."; exit 1; }

o6h-memory-guard: $(SOURCES) src/guard.h | native-check
	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $(SOURCES) $(LDLIBS)

test-guard: tests/test_guard.c src/core.c src/config.c src/guard.h
	$(CC) $(TESTFLAGS) -o $@ tests/test_guard.c src/core.c src/config.c

test-runtime: tests/test_runtime.c src/main.c src/core.c src/config.c src/guard.h
	$(CC) $(TESTFLAGS) -o $@ tests/test_runtime.c src/core.c src/config.c

test: test-guard test-runtime
	./test-guard
	./test-runtime

test-sanitize:
	$(CC) $(TESTFLAGS) -fsanitize=address,undefined -fno-omit-frame-pointer -o test-sanitize-guard tests/test_guard.c src/core.c src/config.c
	./test-sanitize-guard
	$(CC) $(TESTFLAGS) -fsanitize=address,undefined -fno-omit-frame-pointer -o test-sanitize-runtime tests/test_runtime.c src/core.c src/config.c
	./test-sanitize-runtime

# Local API sketches only: NOT real illumos headers, ABI, linking or runtime validation.
portability:
	$(CC) $(TESTFLAGS) -Itests/api-sketch -fsyntax-only $(SOURCES)
	@for source in $(SOURCES); do $(CC) $(TESTFLAGS) -Itests/api-sketch -fanalyzer -c $$source -o /dev/null || exit 1; done
	sh -n install.sh
	xmllint --nonet --noout smf/o6h-memory-guard.xml

clean:
	rm -f o6h-memory-guard test-guard test-runtime test-sanitize-guard test-sanitize-runtime
