# syd's fuzz/Makefile
# Copyright (c) 2023, 2024 Ali Polatel <alip@chesswob.org>
# SPDX-License-Identifier: GPL-3.0

# User variables
# Target, e.g: --target=aarch64-unknown-linux-musl
TARGET=

ARCH=$(shell uname -m)
LIBC=$(shell readlink /lib/ld-linux* | grep -q musl && echo musl || echo gnu)

# Common tools
RM= rm
FIND= find
RSYNC = rsync
GIT = git
INSTALL= install
PREFIX= /usr/local
BINDIR= bin
DOCDIR= $(HOME)/src/sydbox.exherbo.org
CARGO= cargo
PKG_CONFIG= pkg-config

# Environment variables necessary to link libseccomp statically.
export LIBSECCOMP_LINK_TYPE= static
export LIBSECCOMP_LIB_PATH= $(shell $(PKG_CONFIG) --variable=libdir libseccomp || echo /usr/lib)

export RUST_BACKTRACE=1

# Cargo flags
CARGOFLAGS= -j$(shell nproc) -v

TARGETS=\
	target/debug/canonicalize \
	target/debug/config \
	target/debug/wildmatch

all: $(TARGETS)
	$(MAKE) -B target/debug/canonicalize
	$(MAKE) -B target/debug/config
	$(MAKE) -B target/debug/wildmatch
	@echo 'Run one of the following to start the fuzzing campaign'
	@echo '- make fuzz_conf'
	@echo '- make fuzz_path'
	@echo '- make fuzz_wild'

fuzz_conf: target/debug/config
	$(CARGO) afl fuzz -i in/config -o out/config -atext -D $<
fuzz_elf: target/debug/elf
	$(CARGO) afl fuzz -i in/elf -o out/elf -D $<
fuzz_path: target/debug/canonicalize
	$(CARGO) afl fuzz -i in/canonicalize -o out/canonicalize -D $<
fuzz_wild: target/debug/wildmatch
	$(CARGO) afl fuzz -i in/wildmatch -o out/wildmatch -D $<

target/debug/canonicalize: src/canonicalize.rs
	@echo Using libseccomp library from $(LIBSECCOMP_LIB_PATH)
	$(CARGO) fmt
	$(CARGO) clippy $(CARGOFLAGS)
	$(CARGO) afl build $(CARGOFLAGS)
target/debug/config: src/config.rs
	@echo Using libseccomp library from $(LIBSECCOMP_LIB_PATH)
	$(CARGO) fmt
	$(CARGO) clippy $(CARGOFLAGS)
	$(CARGO) afl build $(CARGOFLAGS)
target/debug/elf: src/elf.rs
	@echo Using libseccomp library from $(LIBSECCOMP_LIB_PATH)
	$(CARGO) fmt
	$(CARGO) clippy $(CARGOFLAGS)
	$(CARGO) afl build $(CARGOFLAGS)
target/debug/wildmatch: src/wildmatch.rs
	@echo Using libseccomp library from $(LIBSECCOMP_LIB_PATH)
	$(CARGO) fmt
	$(CARGO) clippy $(CARGOFLAGS)
	$(CARGO) afl build $(CARGOFLAGS)

.PHONY: all fuzz_conf fuzz_path fuzz_wild
