CXX      ?= g++
CC       ?= gcc
CXXFLAGS ?= -Wall -O2 -fPIC
CFLAGS   ?= -Wall -O2
LDFLAGS  ?= -shared
CPPJOULES_LIB ?= -lCPP_Joules

SRC_DIR         := src
PRELOAD_DIR     := $(SRC_DIR)/preload
TESTS_DIR       := $(SRC_DIR)/tests
BUILD_DIR       := build
BUILD_TESTS_DIR := $(BUILD_DIR)/tests
AFL_DIR         := AFLPlusPlus

PRELOAD_SRC       := $(PRELOAD_DIR)/energy_preload.cpp
PRELOAD_BASE      := $(BUILD_DIR)/energy.so
PRELOAD_AFL       := $(BUILD_DIR)/energy_afl.so
PRELOAD_PRINT     := $(BUILD_DIR)/energy_print.so
PRELOAD_PRINT_AFL := $(BUILD_DIR)/energy_print_afl.so

NPROC := $(shell nproc 2>/dev/null || echo 1)

# =============================================================================
# THE STUDY SET
# =============================================================================
#
# Four targets, named once. harfbuzz, jsoncpp, libjpeg-turbo, libxml2 and zlib
# were dropped from the build on 2026-08-26; scripts/build/build_*.sh and their
# prepare_seeds_*.sh are still on disk, so bringing one back is a matter of
# adding its name here and its binary to BINARIES.
#
# BINARIES is separate because the harness name is not the target name
# (brotli -> brotli_decode_fuzzer, quickjs -> quickjs_eval_fuzzer). Keep the two
# lists in the same order.
# STUDY_TARGETS is the set the ablation reports on. CANDIDATE_TARGETS are built
# and seeded the same way but are not yet part of a published sweep -- they are
# here so `make targets`, `make seeds`, `make freeze` and `make verify` cover
# them without a second pipeline. Promoting one is moving its name up a line.
#
# WHY harfbuzz. libarchive's corpus made its cells bimodal: a generated bzip2
# bomb (12,782 B -> 50 MB, 218x the corpus median, ~290 ms per exec under a
# 700 ms timeout) held 28 of 100 cells on one queue entry for ~4 h. harfbuzz was
# screened with the same timing test -- no seed above 25x its median -- and it
# has no decompression stage at all, so the failure mode cannot occur even from
# a mutated input.
STUDY_TARGETS     := libarchive sqlite3 brotli quickjs
CANDIDATE_TARGETS := harfbuzz

TARGETS  := $(STUDY_TARGETS) $(CANDIDATE_TARGETS)
BINARIES := libarchive_fuzzer sqlite3_fuzzer brotli_decode_fuzzer quickjs_eval_fuzzer \
            harfbuzz_fuzzer

comma := ,
space := $(subst ,, )
TARGETS_CSV := $(subst $(space),$(comma),$(TARGETS))

# The LLVM this tree is built against: the newest llvm-config at or above 17,
# stated rather than left to AFL++. AFL++ picks the newest llvm-config on PATH
# with no floor, and this machine still carries llvm-config-11 and -14 — either
# would silently produce a tree whose TTI cost pass cannot be built, because
# AFLPlusPlus/instrumentation/afl-llvm-tti-cost-optimised-pass.cc requires 17+.
# Override with `make LLVM_CONFIG=llvm-config-N` to pin a specific one.
LLVM_CONFIG ?= $(shell for v in 21 20 19 18 17; do \
                 command -v llvm-config-$$v >/dev/null 2>&1 && { echo llvm-config-$$v; break; }; \
               done)

# =============================================================================
# TOP-LEVEL TARGETS
# =============================================================================

# Prerequisites of a single goal are UNORDERED under -j, and this build has hard
# ordering: AFL++ must exist before any target is compiled (buildlib.sh picks
# $(AFL_DIR)/afl-clang-fast), the _tti binaries need the pass that same build
# produces, and freezing seeds needs the binaries to run afl-cmin against. Top-
# level parallelism buys nothing anyway — every build script already runs its own
# compile with -j internally.
.NOTPARALLEL:

.PHONY: all
all: local_afl preload_all targets targets_tti

# One command, correct order, for a fresh checkout on a prepared machine.
# setup_environment is NOT included: it installs system packages with sudo, so
# it stays an explicit, separate step.
#
# seeds -> freeze -> lock is the whole corpus pipeline and each stage is
# idempotent: prepare_seeds_*.sh skips a target whose public.zip exists, freeze
# skips a target already under initial-seeds/ (--force to redo), and the lock is
# rewritten from whatever is there.
#
# `scale_pilot` is deliberately NOT here: it is 30 minutes of campaign per
# target and is only valid on an idle machine. Run it after setup, and only if
# you intend to run tti_hwpc (h*) cells -- tti_path needs no scale.
.PHONY: setup
setup: local_afl preload_all targets targets_tti seeds freeze lock verify
	@echo
	@echo "[+] setup complete. For tti_hwpc (h0/h1, arms H6/H7) THIS NODE needs its"
	@echo "    own per-target cost scale -- on an IDLE machine:  make scale_pilot"

.PHONY: build_all
build_all: local_afl preload_all targets targets_tti

# =============================================================================
# TOOLCHAIN AND AFL++
# =============================================================================

.PHONY: check_llvm
check_llvm:
	@[ -n "$(LLVM_CONFIG)" ] || { \
	  echo "ERROR: no llvm-config >= 17 on PATH."; \
	  echo "       The TTI cost pass needs LLVM 17+. Install one with:"; \
	  echo "         wget https://apt.llvm.org/llvm.sh && chmod +x llvm.sh && sudo ./llvm.sh 17"; \
	  echo "       or point at an existing one: make LLVM_CONFIG=llvm-config-N"; \
	  exit 1; }
	@echo "[llvm] $(LLVM_CONFIG) ($$($(LLVM_CONFIG) --version))"

.PHONY: local_afl afl
local_afl: | check_llvm
	@cd $(AFL_DIR) && make -j$(NPROC) LLVM_CONFIG=$(LLVM_CONFIG) all

afl: local_afl

# The tree's OWN compiler, not PATH's. buildlib.sh compiles every target with
# $(AFL_DIR)/afl-clang-fast so that the pass, the runtime and the afl-fuzz that
# runs the campaign all come from one tree; a system-wide AFL++ on PATH is a
# different build and must not be what gets checked here.
.PHONY: check_afl
check_afl:
	@[ -x "$(AFL_DIR)/afl-clang-fast" ] || { \
	  echo "ERROR: $(AFL_DIR)/afl-clang-fast missing — run 'make local_afl'."; exit 1; }

.PHONY: check_tti_pass
check_tti_pass: check_afl
	@[ -f "$(AFL_DIR)/afl-llvm-tti-cost-optimised-pass.so" ] || { \
	  echo "ERROR: the TTI cost pass is not built — run 'make local_afl'."; \
	  echo "       It needs LLVM 17+; see 'make check_llvm'."; exit 1; }
# STALENESS, not just existence. Editing the pass and running `make targets_tti`
# would otherwise rebuild every _tti binary against the PREVIOUS .so and say
# nothing: T would change meaning between two builds that look identical, and
# the only symptom is numbers that do not reproduce. Measured here: the .so was
# 10 days older than its source after a pass edit, and two _tti binaries had
# already been built from it.
	@src="$(AFL_DIR)/instrumentation/afl-llvm-tti-cost-optimised-pass.cc"; \
	 so="$(AFL_DIR)/afl-llvm-tti-cost-optimised-pass.so"; \
	 if [ -f "$$src" ] && [ "$$src" -nt "$$so" ]; then \
	   echo "ERROR: $$so is OLDER than $$src."; \
	   echo "       The pass was edited but not rebuilt. Run 'make local_afl'"; \
	   echo "       first, then rebuild every _tti binary ('make targets_tti')."; \
	   exit 1; \
	 fi

# =============================================================================
# PRELOAD LIBRARIES
# =============================================================================

.PHONY: preload_all preload preload_afl preload_print preload_print_afl

preload_all: preload preload_afl preload_print preload_print_afl

$(BUILD_DIR) $(BUILD_TESTS_DIR):
	mkdir -p $@

preload: $(PRELOAD_BASE)
$(PRELOAD_BASE): $(PRELOAD_SRC) | $(BUILD_DIR)
	$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $^ $(CPPJOULES_LIB)

preload_afl: $(PRELOAD_AFL)
$(PRELOAD_AFL): $(PRELOAD_SRC) | $(BUILD_DIR)
	$(CXX) $(CXXFLAGS) -DAFL_ENERGY_MAPPING $(LDFLAGS) -o $@ $^ $(CPPJOULES_LIB)

preload_print: $(PRELOAD_PRINT)
$(PRELOAD_PRINT): $(PRELOAD_SRC) | $(BUILD_DIR)
	$(CXX) $(CXXFLAGS) -DAFL_FORCE_PRINT $(LDFLAGS) -o $@ $^ $(CPPJOULES_LIB)

preload_print_afl: $(PRELOAD_PRINT_AFL)
$(PRELOAD_PRINT_AFL): $(PRELOAD_SRC) | $(BUILD_DIR)
	$(CXX) $(CXXFLAGS) -DAFL_FORCE_PRINT -DAFL_ENERGY_MAPPING $(LDFLAGS) -o $@ $^ $(CPPJOULES_LIB)

.PHONY: hello
hello: $(BUILD_TESTS_DIR)/hello
$(BUILD_TESTS_DIR)/hello: $(TESTS_DIR)/hello.cpp | $(BUILD_TESTS_DIR)
	$(CXX) $(CXXFLAGS) $(CFLAGS) -o $@ $^

# =============================================================================
# FUZZ TARGET BUILDS
# =============================================================================

.PHONY: targets targets_tti $(TARGETS)

targets: $(TARGETS)

# One rule for all four: the script is always scripts/build/build_<target>.sh.
$(TARGETS): | check_afl
	./scripts/build/build_$@.sh

# The _tti siblings. Built ALONGSIDE the normal binaries, never instead of them:
# c1 runs the normal binary, every TTI cell and the replay run the _tti one.
#
# Not folded into `targets`, because TTI=1 is a per-invocation environment
# setting and mixing it into a rule that also builds normal binaries would make
# which-binary-got-which-flags depend on rule ordering.
targets_tti: | check_tti_pass
	@for t in $(TARGETS); do \
	  echo "[tti] $$t"; \
	  TTI=1 ./scripts/build/build_$$t.sh || exit 1; \
	done

# =============================================================================
# SEED CORPORA
# =============================================================================
#
# Three stages, in this order, and only the first is per-target:
#
#   seeds   fetch/generate the raw corpus  -> targets/<t>/public.zip + MANIFEST
#   freeze  afl-cmin ONCE against the built binary, then never again
#           -> initial-seeds/<t>/minimised/
#   lock    record what was frozen         -> initial-seeds/<t>/corpus.lock
#
# freeze needs the binaries, so it depends on them. It also needs to happen only
# once per corpus: afl-cmin's output depends on the target binary, so re-running
# it after a rebuild changes which seeds get fuzzed and makes campaigns from
# either side of the rebuild incomparable. That is why it skips an already
# frozen target unless FREEZE_ARGS=--force.

.PHONY: seeds freeze lock $(addprefix seeds_,$(TARGETS))

seeds: $(addprefix seeds_,$(TARGETS))

$(addprefix seeds_,$(TARGETS)):
	./scripts/build/prepare_seeds_$(patsubst seeds_%,%,$@).sh

# libarchive2 — libarchive with the generated expansion-grid seeds removed.
# Not a build target: it is the SAME binary and a different corpus, so it has no
# entry in TARGETS. See scripts/build/make_libarchive2.sh for why it is a second
# named corpus rather than an edit to libarchive/.
.PHONY: libarchive2
LIBARCHIVE2_ARGS ?=
libarchive2: | check_afl
	./scripts/build/make_libarchive2.sh --force $(LIBARCHIVE2_ARGS)

FREEZE_ARGS ?=
freeze: | check_afl
	./scripts/build/freeze_initial_seeds.sh --targets $(TARGETS_CSV) $(FREEZE_ARGS)

lock:
	python3 scripts/build/normalise_manifests.py
	python3 scripts/build/write_corpus_lock.py

# =============================================================================
# VERIFY
# =============================================================================
#
# Fails loudly if a binary or a corpus is missing, rather than at hour 3 of a
# campaign.

.PHONY: verify
verify:
	@ok=1; \
	for b in $(BINARIES); do \
	  if [ -x "$(BUILD_DIR)/$$b" ]; then echo "  OK    binary  $$b"; \
	  else echo "  FAIL  binary  $$b   (make targets)"; ok=0; fi; \
	done; \
	for b in $(BINARIES); do \
	  t="$(BUILD_DIR)/$${b}_tti"; \
	  if [ ! -x "$$t" ]; then \
	    echo "  FAIL  _tti    $$b   (make targets_tti)"; ok=0; \
	  elif ! strings -a "$$t" 2>/dev/null | grep -q SIG_AFL_TTI_RUNTIME; then \
	    echo "  FAIL  _tti    $$b   built without the TTI runtime (make targets_tti)"; ok=0; \
	  elif [ "$$t" -ot "src/tti/tti_runtime.c" ] || [ "$$t" -ot "src/hwpc/perf_task_counter.c" ]; then \
	    echo "  FAIL  _tti    $$b   older than the runtime (make targets_tti)"; ok=0; \
	  else echo "  OK    _tti    $$b"; fi; \
	done; \
	for t in $(TARGETS); do \
	  z="targets/$$t/public.zip"; \
	  if [ -f "$$z" ]; then \
	    echo "  OK    corpus  $$t ($$(unzip -Z1 $$z 2>/dev/null | wc -l) seeds)"; \
	  else echo "  FAIL  corpus  $$t   (make seeds_$$t)"; ok=0; fi; \
	done; \
	for t in $(TARGETS); do \
	  n=$$(ls "initial-seeds/$$t/minimised" 2>/dev/null | wc -l); \
	  if [ "$$n" -gt 0 ]; then echo "  OK    frozen  $$t ($$n seeds)"; \
	  else echo "  FAIL  frozen  $$t   (make freeze)"; ok=0; fi; \
	done; \
	echo; \
	python3 scripts/build/normalise_manifests.py --check || ok=0; \
	echo; \
	python3 scripts/build/write_corpus_lock.py --check || ok=0; \
	[ "$$ok" = 1 ] || { echo; echo "setup incomplete"; exit 1; }; \
	echo; echo "[+] all $(words $(TARGETS)) targets built (normal + _tti), seeded and locked"

# =============================================================================
# SCALE PILOT  (lambda_0 for tti_hwpc)
# =============================================================================
#
# tti_hwpc schedules on C = T + alpha*lambda0*M and does NOT invent a scale:
# afl-fuzz FATALs without AFL_COST_CONFIG, per target and per platform. This is
# what produces that file.
#
# MEASURED PER NODE. Every machine runs its own 30-minute snapshot and computes
# its own lambda_0, so this is part of each node's procedure and not a value
# shipped to it. The output goes to results/proxy/scale/<target>.yaml, which is
# gitignored -- a node's own measurement must not dirty the tree and block the
# next `git pull`. configs/proxy/ stays the committed reference a node falls
# back to before it has measured anything.
#
# Each pilot is a 30-MINUTE VANILLA CAMPAIGN plus a replay, so `scale_pilot`
# over four targets is roughly 2.5 hours. That is why it is NOT part of `setup`:
# setup is a build step that should run anywhere, and this is a MEASUREMENT that
# is only valid on an idle, quiesced machine -- the same conditions an energy
# cell needs. Run it on each node, deliberately, once that machine is quiet:
#
#     make scale_pilot                      # all four, skipping frozen ones
#     make scale_pilot_sqlite3              # one target
#     PILOT_ARGS="--duration 45m" make scale_pilot_brotli
#
# --skip-existing makes it re-runnable: a target this node has already measured
# is done, not an error. Use the script directly (no --skip-existing) to be told
# loudly instead, and --force to actually replace this node's scale -- which
# makes every h-cell already run on THIS NODE incomparable with the next ones,
# breaking the within-node pairing the analysis rests on.

.PHONY: scale_pilot $(addprefix scale_pilot_,$(TARGETS))

PILOT_ARGS ?=

scale_pilot: $(addprefix scale_pilot_,$(TARGETS))

$(addprefix scale_pilot_,$(TARGETS)): | verify
	./scripts/proxy/run_scale_pilot.sh $(patsubst scale_pilot_%,%,$@) \
	    --skip-existing $(PILOT_ARGS)

# =============================================================================
# ENVIRONMENT SETUP
# =============================================================================

.PHONY: setup_environment
setup_environment:
	./scripts/setup_env.sh

# =============================================================================
# CLEAN
# =============================================================================

.PHONY: clean clean_targets clean_all

# Preload libs + target binaries. Keeps the AFL++ build and the frozen seeds.
clean:
	rm -rf $(BUILD_DIR)

# Only the per-target scratch trees under build/, keeping the fuzzer binaries.
clean_targets:
	rm -rf $(BUILD_DIR)/tmp_*_build

clean_all: clean
	@cd $(AFL_DIR) && make clean || true
