##
# Makefile for XGUARD (main branch)
#
# Author:
#  - Adam 'pi3' Zabrocki (http://pi3.com.pl)
##

P_OUTPUT = output
P_PWD ?= $(shell pwd)
P_KVER ?= $(shell uname -r)
P_BOOTUP_SCRIPT ?= scripts/bootup/xguard-bootup.sh
TARGET := xguard
LDFLAGS_$(TARGET).o += -T $(src)/.module.order.def
OBJCOPY := objcopy
RUST_TARGET := aarch64-unknown-none
RUST_LIB := src/rust/target/$(RUST_TARGET)/release/librust_x_guard.a
RUST_X_GUARD_OBJ := src/rust/rust_x_guard.o
EL2_OBJ := $(obj)/hyp/kvm_nvhe.o
RUST_CMD_FILE := src/rust/.$(notdir $(RUST_X_GUARD_OBJ)).cmd

ifneq ($(KERNELRELEASE),)
    KERNEL := /lib/modules/$(KERNELRELEASE)/build
    clean-files := hyp/hyp.lds hyp/hyp-reloc.S
else
    KERNEL := /lib/modules/$(P_KVER)/build
endif

#
# Use DEBUG=on for debug build.
#
ifeq ($(DEBUG), on)
ccflags-m := -ggdb -DP_XGUARD_DEBUG_BUILD -finstrument-functions
ccflags-y := ${ccflags-m}
$(TARGET)-objs += src/modules/print_log/p_xguard_debug_log.o
export CARGO_PROFILE_RELEASE_DEBUG = true
endif

obj-m += $(TARGET).o
$(TARGET)-objs += src/modules/comm_channel/p_comm_channel.o \
            src/rust/rust_x_guard.o \
            src/x_guard_main.o \
	    hyp/kvm_nvhe.o

all: xguard-build

# Rust 构建规则
$(RUST_X_GUARD_OBJ):
	cd $(obj)/src/rust && ./build_rust.sh $(KERNEL)

$(EL2_OBJ): FORCE
	$(MAKE) $(build)=$(obj)/hyp $(EL2_OBJ)

xguard-build: $(RUST_X_GUARD_OBJ) $(EL2_OBJ)
	$(MAKE) -C $(KERNEL) M=$(P_PWD) modules EXTRA_CFLAGS="-Wno-error=unused-function -Wno-error=unused-variable"
	mkdir -p $(P_OUTPUT)
	cp $(P_PWD)/$(TARGET).ko $(P_OUTPUT)

install-module: all
	$(MAKE) -C $(KERNEL) M=$(P_PWD) modules_install

install: install-module
	depmod $(KERNELRELEASE)
	$(P_PWD)/$(P_BOOTUP_SCRIPT) install

uninstall:
	$(P_PWD)/$(P_BOOTUP_SCRIPT) uninstall

clean: xguard-clean rust-clean

xguard-clean:
	$(MAKE) -C $(KERNEL) M=$(P_PWD) clean
	$(RM) Module.markers modules.order
	$(RM) $(P_PWD)/src/modules/kmod/client/kmod/Module.markers
	$(RM) $(P_PWD)/src/modules/kmod/client/kmod/modules.order
	$(RM) -rf $(P_OUTPUT)
	#$(RM) $(RUST_CMD_FILE)

rust-clean:
	cd src/rust && cargo clean
	$(RM) $(RUST_X_GUARD_OBJ)

.PHONY: clean uninstall install install-module all xguard-build xguard-clean rust-clean
