TARGET := riscv64gc-unknown-none-elf
KERNEL_ENTRY := 0x80200000
MODE := release
KERNEL_ELF := target/$(TARGET)/$(MODE)/os
KERNEL_BIN := $(KERNEL_ELF).bin
SYMBOL_MAP := target/system.map
QEMU_CMD_PATH := ../../tools/qemu-system-riscv64
QEMU_PID = $(shell ps aux | grep "[q]emu-system' | awk '{print $$2}")
OBJDUMP := rust-objdump --arch-name=riscv64
OBJCOPY := rust-objcopy --binary-architecture=riscv64

RUST_FLAGS := -Clink-arg=-Tsrc/linker.ld  # 使用我们自己的链接脚本
RUST_FLAGS += -Cforce-frame-pointers=yes  # 强制编译器生成帧指针
RUST_FLAGS:=$(strip ${RUST_FLAGS})

# 编译elf文件
build_elf: clean
	CARGO_BUILD_RUSTFLAGS="$(RUST_FLAGS)" \
 	cargo build --$(MODE) --target=$(TARGET)

# 导出一个符号表, 供我们查看
$(SYMBOL_MAP):build_elf
	nm $(KERNEL_ELF) | sort > $(SYMBOL_MAP)

# 丢弃内核可执行elf文件中的元数据得到内核镜像
$(KERNEL_BIN): build_elf
	@$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@


debug:build_elf $(KERNEL_BIN) $(SYMBOL_MAP)
	$(QEMU_CMD_PATH) \
		-machine virt \
		-display none \
		-daemonize \
		-bios ../../bootloader/rustsbi-qemu.bin \
		-device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY) \
		-s -S

run:build_elf $(KERNEL_BIN) $(SYMBOL_MAP) kill
	$(QEMU_CMD_PATH) \
		-machine virt \
		-nographic \
		-bios ../../bootloader/rustsbi-qemu.bin \
		-device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY)

clean:
	rm -rf ./target* && rm -rf ./src/link_app.S

kill:
	-kill -9 $(QEMU_PID)

