# Adjust the following variable according to the target firmware
HPILO_VER_MAJOR ?= 4
HPILO_VER_MINOR ?= 250

ARM_OBJDUMP ?= arm-none-eabi-objdump
ARM_GCC ?= arm-none-eabi-gcc

HPILO_VER := $(shell printf "0x%d%06d" $(HPILO_VER_MAJOR) $(HPILO_VER_MINOR))
STAGE2_NAME := stage2_ilo$(HPILO_VER_MAJOR)_$(HPILO_VER_MINOR)

CPPFLAGS += -DHPILO_VER=$(HPILO_VER)

WARNINGS := -Wall -Wextra
WARNINGS += -Wno-unused-parameter
WARNINGS += -Wno-unused-variable
WARNINGS += -Wno-unused-function
WARNINGS += -Werror

all: $(STAGE2_NAME).bin

clean:
	$(RM) ./*.bin ./*.o ./.*.d

%.bin: %.linked.o
	@# Error if relocations exists
	if $(ARM_OBJDUMP) -r $< | grep -i shcode ; then \
		echo "Fatal error: relocations exist!" ; \
		$(ARM_OBJDUMP) -r $< ; \
		false ; \
	fi
	arm-none-eabi-objcopy -j .shcode -O binary $< $@
	chmod -x $@
	stat -c '%s %n' $@

%.linked.o: %.o
	@# Link files
	arm-none-eabi-ld -nostdlib -O1 -T stage2.lds -shared -Bsymbolic -as-needed -no-undefined -warn-common -fatal-warnings $^ -o $@

# r4 is used to hold thread-local structures. According to ARM doc, it is the
# Thread Register (TR), which usually is r9. gcc allows specifying it with
# -mpic-register=r4
$(STAGE2_NAME).o: stage2.c
	$(ARM_GCC) $(WARNINGS) $(CPPFLAGS) -Wp,-MT,$@ -Wp,-MD,$(dir $@).$(notdir $@).d \
		-O2 -c -fPIC -nostdlib -ffreestanding -mpic-register=r4 $< -o $@

-include .*.d

dump: $(STAGE2_NAME).bin
	$(ARM_OBJDUMP) -D -bbinary -marm $<

dumplinked: $(STAGE2_NAME).linked.o
	$(ARM_OBJDUMP) -s $<

dumplinkedd: $(STAGE2_NAME).linked.o
	$(ARM_OBJDUMP) -dr $<

.PHONY: all clean dump dumplinked dumplinkedd
.PRECIOUS: %.linked.o %.o
