CC = riscv64-linux-gnu-gcc
OBJCOPY = riscv64-linux-gnu-objcopy
EMULATOR = ./amach

ASFLAGS = -march=rv32imac -mabi=ilp32 -nostdlib -s -static -fno-pic -fno-pie -mno-relax
LDFLAGS = -Wl,-Ttext=0x100b0 -Wl,--build-id=none

all: rv32imac_tests.bin rv32imac_syscall_tests.bin rv32imac_tests.elf rv32imac_syscall_tests.elf

rv32imac_tests.elf: rv32imac_tests.s
	$(CC) $(ASFLAGS) $(LDFLAGS) rv32imac_tests.s -o rv32imac_tests.elf

rv32imac_tests.bin: rv32imac_tests.elf
	$(OBJCOPY) -O binary rv32imac_tests.elf rv32imac_tests.bin

rv32imac_syscall_tests.elf: rv32imac_syscall_tests.s
	$(CC) $(ASFLAGS) $(LDFLAGS) rv32imac_syscall_tests.s -o rv32imac_syscall_tests.elf

rv32imac_syscall_tests.bin: rv32imac_syscall_tests.elf
	$(OBJCOPY) -O binary rv32imac_syscall_tests.elf rv32imac_syscall_tests.bin

run: rv32imac_tests.bin rv32imac_syscall_tests.bin rv32imac_tests.elf rv32imac_syscall_tests.elf
	@echo "Running CPU instruction tests (binary)..."
	$(EMULATOR) rv32imac_tests.bin
	@echo "Running CPU instruction tests (ELF)..."
	$(EMULATOR) rv32imac_tests.elf
	@echo "Running syscall tests (binary)..."
	rm -rf test_dir test_link.txt test_output.txt test_output_new.txt
	ln -sf test_output_new.txt test_link.txt
	$(EMULATOR) rv32imac_syscall_tests.bin
	@echo "Running syscall tests (ELF)..."
	rm -rf test_dir test_link.txt test_output.txt test_output_new.txt
	ln -sf test_output_new.txt test_link.txt
	$(EMULATOR) rv32imac_syscall_tests.elf
	@echo "Testing standard ebreak..."
	@echo "115 0 16 0" | awk -f amach.awk 2>&1 | grep -q "Fatal: EBREAK"
	@echo "Testing compressed c.ebreak..."
	@echo "2 144" | awk -f amach.awk 2>&1 | grep -q "Fatal: EBREAK"
	@echo "All tests PASSED!"

clean:
	rm -rf rv32imac_tests.elf rv32imac_tests.bin rv32imac_syscall_tests.elf rv32imac_syscall_tests.bin test_dir test_link.txt test_output.txt test_output_new.txt

.PHONY: all run clean
