1SUBDIR_ROOTS := .
2DIRS := . $(shell find $(SUBDIR_ROOTS) -type d)
3GARBAGE_PATTERNS := *.o *.s~ *.s *.S~ *.c~ *.h~ kernel
4GARBAGE := $(foreach DIR,$(DIRS),$(addprefix $(DIR)/,$(GARBAGE_PATTERNS)))
5
6DIR_LIB=libs
7lib_patterns := *.a
8LIB_FILES := $(foreach DIR,$(DIR_LIB),$(addprefix $(DIR)/,$(lib_patterns)))
9
10
11# 控制操作系统使用的中断控制器 _INTR_8259A_ _INTR_APIC_
12PIC := _INTR_APIC_
13CFLAGS = $(GLOBAL_CFLAGS) -D $(PIC) -I $(shell pwd) -I $(shell pwd)/include -I $(shell pwd)/arch/x86_64/include
14
15export ASFLAGS := --64
16
17LD_LIST := head.o
18
19
20kernel_subdirs := common driver process debug filesystem time arch exception mm smp sched syscall ktest libs ipc
21
22
23
24head.o: head.S
25	$(CC) -E head.S > _head.s # 预处理
26	as $(ASFLAGS) -o head.o _head.s
27
28
29main.o: main.c
30# -fno-builtin: 不使用C语言内建函数
31# The -m64 option sets int to 32bits and long and pointer to 64 bits and generates code for AMD’s x86-64 architecture.
32	$(CC) $(CFLAGS) -c main.c  -o main.o
33
34kernel_rust:
35	rustup default nightly
36	cargo +nightly build --release --target ./arch/x86_64/x86_64-unknown-none.json
37
38all: kernel
39
40	@echo "Linking kernel..."
41	ld -b elf64-x86-64 -z muldefs -o kernel head.o main.o $(shell find . -name "*.o") ../target/x86_64-unknown-none/release/libdragonos_kernel.a -T link.lds
42# 生成kallsyms
43	current_dir=$(pwd)
44
45	@dbg='debug';for x in $$dbg; do \
46		cd $$x;\
47		$(MAKE) generate_kallsyms kernel_root_path="$(shell pwd)";\
48		cd ..;\
49		if [ "$$?" != "0" ]; then\
50            exit $$?;\
51        fi;\
52	done
53
54
55# 重新链接
56	@echo "Re-Linking kernel..."
57	@echo $(shell find . -name "*.o")
58	ld -b elf64-x86-64 -z muldefs -o kernel head.o main.o $(shell find . -name "*.o") ../target/x86_64-unknown-none/release/libdragonos_kernel.a ./debug/kallsyms.o  -T link.lds
59	@echo "Generating kernel ELF file..."
60# 生成内核文件
61	objcopy -I elf64-x86-64 -O elf64-x86-64 -R ".comment" -R ".eh_frame" kernel ../../bin/kernel/kernel.elf
62	@echo "Kernel Build Done."
63
64ECHO:
65	@echo "$@"
66
67$(kernel_subdirs): ECHO
68
69	$(MAKE) -C $@ all CFLAGS="$(CFLAGS)" ASFLAGS="$(ASFLAGS)" PIC="$(PIC)" kernel_root_path="$(shell pwd)"
70
71kernel: head.o main.o $(kernel_subdirs) kernel_rust
72
73
74
75clean:
76	cargo clean
77	rm -rf $(GARBAGE)
78	@list='$(kernel_subdirs)'; for subdir in $$list; do \
79		echo "Clean in dir: $$subdir";\
80		cd $$subdir && $(MAKE) clean;\
81		cd .. ;\
82	done