# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2021-2022 , Chunguang Yang <yangchg@chinatelecom.cn>
#
#
bin = elf
exe = flat
bits = 64
ldarch = elf64-x86-64
arch_LDFLAGS = -m elf_x86_64

fcf_protection_full := $(call cc-option, -fcf-protection=full,)
COMMON_CFLAGS += $(fcf_protection_full) -mno-sse -mno-sse2 -mno-red-zone

cflatobjs += lib/x86/setjmp64.o
cflatobjs += lib/x86/intel-iommu.o
cflatobjs += lib/x86/usermode.o
cflatobjs += lib/acpi.o
cflatobjs += lib/pci.o
cflatobjs += lib/pci-edu.o
cflatobjs += lib/alloc.o
cflatobjs += lib/auxinfo.o
cflatobjs += lib/vmalloc.o
cflatobjs += lib/alloc_page.o
cflatobjs += lib/alloc_phys.o
cflatobjs += lib/x86/setup.o
cflatobjs += lib/x86/io.o
cflatobjs += lib/x86/smp.o
cflatobjs += lib/x86/vm.o
cflatobjs += lib/x86/fwcfg.o
cflatobjs += lib/x86/apic.o
cflatobjs += lib/x86/atomic.o
cflatobjs += lib/x86/desc.o
cflatobjs += lib/x86/isr.o
cflatobjs += lib/x86/stack.o
cflatobjs += lib/x86/fault_test.o
cflatobjs += lib/x86/delay.o
cflatobjs += lib/x86/pmu.o

OBJDIRS += lib/x86

$(libcflat): LDFLAGS += $(arch_LDFLAGS)
$(libcflat): CFLAGS += -ffreestanding -I $(SRCDIR)/lib -I lib

cstart.o = $(TEST_DIR)/cstart64.o

COMMON_CFLAGS += -m$(bits)
ifneq ($(WA_DIVIDE),)
COMMON_CFLAGS += -Wa,--divide
endif
COMMON_CFLAGS += -O1

# stack.o relies on frame pointers.
KEEP_FRAME_POINTER := y

FLATLIBS = lib/libcflat.a

# We want to keep intermediate file: %.elf and %.o
.PRECIOUS: %.elf %.o

%.elf: LDFLAGS += $(arch_LDFLAGS)
%.elf: %.o $(FLATLIBS) $(SRCDIR)/x86/flat.lds $(cstart.o)
	$(LD) $(LDFLAGS) -T $(SRCDIR)/x86/flat.lds -o $@ \
		$(filter %.o, $^) $(FLATLIBS)
	@chmod a-x $@

%.flat: %.elf
	$(OBJCOPY) -O elf32-i386 $^ $@
	@chmod a-x $@

tests = $(TEST_DIR)/dummy.$(exe)
tests += $(TEST_DIR)/hygon.$(exe)
tests += $(TEST_DIR)/timer.$(exe)
tests += $(TEST_DIR)/intel_timecost.$(exe)
tests += $(TEST_DIR)/reg_ops.$(exe)
tests += $(TEST_DIR)/intel_nested.$(exe)
tests += $(TEST_DIR)/pmu.$(exe)
tests += $(TEST_DIR)/apic.$(exe)
tests += $(TEST_DIR)/hyperv_integration_test.$(exe)

test_cases: $(tests)

$(TEST_DIR)/%.o: CFLAGS += -std=gnu99 -ffreestanding -I $(SRCDIR)/lib -I $(SRCDIR)/lib/x86 -I lib

arch_clean:
	$(RM) $(TEST_DIR)/*.o $(TEST_DIR)/*.flat $(TEST_DIR)/*.elf \
	$(TEST_DIR)/.*.d lib/x86/.*.d \
	$(TEST_DIR)/efi/*.o $(TEST_DIR)/efi/.*.d \
	$(TEST_DIR)/*.so $(TEST_DIR)/*.efi $(TEST_DIR)/*.debug
