# CC = gcc
CFLAGS = -g -zexecstack
SFLASG = 
SRC = $(wildcard *.c) $(wildcard *.s)
TGT = $(subst .c,,$(subst. .S,,$(SRC)))
BUILD_DIR = build
DUMP_DIR = dump


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)/%: %.c
	$(shell mkdir -p $(BUILD_DIR))
	$(CC) $(CFLAGS) -o $@ $<

$(BUILD_DIR)/%: %.S
	$(shell mkdir -p $(BUILD_DIR))
	$(CC) -g $< -o $@ -static -nostdlib

build: $(addprefix $(BUILD_DIR)/, $(TGT))

PHONY: gdb_shellcode
gdb_shellcode: build/shellcode configure
	PYTHONPATH=${PWD}/pframe${PYTHONPATH:+:${PYTHONPATH}} \
		   setarch -R gdb ./$(BUILD_DIR)/shellcode

PHONY: gdb_anodin
gdb_anodin: build/anodin configure
	PYTHONPATH=${PWD}/pframe${PYTHONPATH:+:${PYTHONPATH}} \
		   setarch -R gdb ./$(BUILD_DIR)/anodin

PHONY: gdb_exploit
gdb_exploit: build/exploit build/anodin configure
ifeq ($(A_ADDR),)
	$(error A_ADDR must be defined, launch make gdb_anodin then run)
endif
	echo '$(A_ADDR)' | ./$(BUILD_DIR)/exploit > hack.txt
	PYTHONPATH=${PWD}/pframe${PYTHONPATH:+:${PYTHONPATH}} \
			   setarch -R gdb ./$(BUILD_DIR)/anodin --command=anodin.gdb
	rm hack.txt

PHONY: opcode
opcode: build/shellcode
	readelf -x .text build/shellcode | sed -e '$$ d' -e '1,2 d' \
		| awk -F ' ' '{$$1=$$6=""; print $$0}' \
		| tr -d '[ \n]' \
		| sed 's/../0x&,/g' > opcode.txt

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