CC = gcc
CFLAGS = -fstack-protector-all -g -Wall -Wextra -fno-omit-frame-pointer
SRC = $(wildcard *.c)
TGT = $(subst .c,,$(SRC))
BUILD_DIR = build
DUMP_DIR = dump
SETARCH ?= 0

pframe:
	curl -o pframe.tgz  https://dept-info.labri.fr/~thibault/SecuLog/pframe.tgz && \
		tar -xf pframe.tgz &&\
		rm -rf pframe.tgz

.gdbinit:

configure: pframe .gdbinit
	$(shell echo "python import pframe" > .gdbinit) 

$(BUILD_DIR)/%_32: %.c
	$(shell mkdir -p $(BUILD_DIR))
	$(CC) $(CFLAGS) -m32 -no-pie -o $@ $<
	
$(BUILD_DIR)/%_32-pie: %.c
	$(CC) $(CFLAGS) -m32 -pie -o $@ $<

$(BUILD_DIR)/%_64: %.c
	$(shell mkdir -p $(BUILD_DIR))
	$(CC) $(CFLAGS) -m64 -no-pie -o $@ $<

$(BUILD_DIR)/%_64-pie: %.c
	$(CC) $(CFLAGS) -m64 -pie -o $@ $<

build: $(addprefix $(BUILD_DIR)/, $(addsuffix _32, $(TGT))) \
	   $(addprefix $(BUILD_DIR)/, $(addsuffix _32-pie, $(TGT))) \
	   $(addprefix $(BUILD_DIR)/, $(addsuffix _64, $(TGT))) \
	   $(addprefix $(BUILD_DIR)/, $(addsuffix _64-pie, $(TGT))) \


ifeq ($(SETARCH),1)
gdb_command = setarch -R gdb
else
gdb_command = gdb
endif
PHONY: gdb_%
gdb_%: configure $(addprefix $(BUILD_DIR)/, $(subst gdb_,,%))
	PYTHONPATH=${PWD}/pframe${PYTHONPATH:+:${PYTHONPATH}} $(gdb_command) \
		$(addprefix $(BUILD_DIR)/, $(subst gdb_,,$@)) \
        --command=$(subst gdb_,,$@).gdb


PHONY: clean
clean:
	@rm -rf $(BUILD_DIR) pframe .gdbinit
