# libFuzzer targets for the untrusted parsers.
#
#   make            build all three
#   make run        build, then run each for 20000 iterations on the seeds
#   make run-smoke  a larger fixed budget for CI
#   make run-long   the same, for 10 minutes each
#
# The targets use AddressSanitizer and UndefinedBehaviorSanitizer. A crash or a
# sanitizer report is a real defect in a parser that reads files from a card.

CLANG ?= clang
SAN := -fsanitize=fuzzer,address,undefined -fno-omit-frame-pointer -g -O1
CPPFLAGS := -DRT_HOST_BUILD=1 -DRT_SKIP_SANITY=1 \
            -I../src -I../src/core -I../src/platform
LDLIBS := -lm -lpthread

CORE := ../src/core/llm.c ../src/core/model_lib.c ../src/core/moe.c \
        ../src/core/tokenizer.c ../src/rt_core.c ../src/rt_manifest.c \
        ../src/rt_envelope.c
PLAT := ../host/dot_s8_host.c ../host/rt_platform_posix.c

TARGETS := fuzz_manifest fuzz_m8 fuzz_tokenizer
SEEDS := seeds
# libFuzzer writes new units into the first corpus directory. Keep that
# separate from the curated seeds so a campaign does not turn `seeds/` into
# hundreds of generated files. `corpus/` is gitignored.
CORPUS := corpus

.PHONY: all run run-smoke run-long clean

all: $(TARGETS)

$(CORPUS):
	mkdir -p $(CORPUS)/manifest $(CORPUS)/m8 $(CORPUS)/tokenizer

fuzz_manifest: fuzz_manifest.c $(CORE) $(PLAT)
	$(CLANG) $(SAN) $(CPPFLAGS) -o $@ $^ $(LDLIBS)

fuzz_m8: fuzz_m8.c $(CORE) $(PLAT)
	$(CLANG) $(SAN) $(CPPFLAGS) -o $@ $^ $(LDLIBS)

fuzz_tokenizer: fuzz_tokenizer.c ../src/core/tokenizer.c
	$(CLANG) $(SAN) $(CPPFLAGS) -o $@ $^ $(LDLIBS)

run: all $(CORPUS)
	./fuzz_manifest -runs=20000 -print_final_stats=1 $(CORPUS)/manifest $(SEEDS)/manifest
	./fuzz_m8 -runs=20000 -max_len=524288 -print_final_stats=1 $(CORPUS)/m8 $(SEEDS)/m8
	./fuzz_tokenizer -runs=20000 -print_final_stats=1 $(CORPUS)/tokenizer $(SEEDS)/tokenizer

# CI budget: a fixed number of runs, not a wall-clock window, so the result is
# reproducible and a slow runner does not silently shrink coverage.
run-smoke: all $(CORPUS)
	./fuzz_manifest -runs=30000 -print_final_stats=1 $(CORPUS)/manifest $(SEEDS)/manifest
	./fuzz_m8 -runs=30000 -max_len=524288 -print_final_stats=1 $(CORPUS)/m8 $(SEEDS)/m8
	./fuzz_tokenizer -runs=30000 -print_final_stats=1 $(CORPUS)/tokenizer $(SEEDS)/tokenizer

run-long: all $(CORPUS)
	./fuzz_manifest -max_total_time=600 $(CORPUS)/manifest $(SEEDS)/manifest
	./fuzz_m8 -max_total_time=600 -max_len=524288 $(CORPUS)/m8 $(SEEDS)/m8
	./fuzz_tokenizer -max_total_time=600 $(CORPUS)/tokenizer $(SEEDS)/tokenizer

clean:
	rm -f $(TARGETS)
	rm -rf crash-* leak-* timeout-* oom-*
