diff --git a/ch3-coop/user/Makefile b/ch3-coop/user/Makefile index f2746fc..367e9f2 100644 --- a/ch3-coop/user/Makefile +++ b/ch3-coop/user/Makefile @@ -3,10 +3,6 @@ TARGET := riscv64gc-unknown-none-elf 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}) - APP_DIR := src/bin TARGET_DIR := target/$(TARGET)/$(MODE) APPS := $(wildcard $(APP_DIR)/*.rs) @@ -16,8 +12,7 @@ BINS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%.bin, $(APPS)) # 编译elf文件 build_elf: clean - CARGO_BUILD_RUSTFLAGS="$(RUST_FLAGS)" \ - cargo build --$(MODE) --target=$(TARGET) + @python3 build.py # 把每个elf文件去掉无关代码 diff --git a/ch3-coop/user/build.py b/ch3-coop/user/build.py new file mode 100644 index 0000000..08661bd --- /dev/null +++ b/ch3-coop/user/build.py @@ -0,0 +1,39 @@ +import os + +base_address = 0x80400000 # 第一个应用的起始地址 +step = 0x20000 # 每个应用的大小 +linker = "src/linker.ld" # 自定义链接脚本 + +RUST_FLAGS = f"-Clink-arg=-T{linker} " # 使用我们自己的链接脚本 +RUST_FLAGS += "-Cforce-frame-pointers=yes " # 强制编译器生成帧指针 +TARGET = "riscv64gc-unknown-none-elf" + +app_id = 0 +apps: list[str] = os.listdir("src/bin") +apps.sort() +for app_file in apps: + app_name = app_file.split(".")[0] + + lines = [] # 修改了base_address linker.ld + lines_before = [] # 最原本的linker.ld的文本, 最下面会恢复 + + # 读出原本文件 + with open(linker, "r") as f: + for line in f.readlines(): + lines_before.append(line) # 保存原本的文本 + line = line.replace(hex(base_address), hex(base_address+step*app_id)) # 替换的文本 + lines.append(line) + with open(linker, "w+") as f: + f.writelines(lines) + + # 逐个编译 + cmd = f"CARGO_BUILD_RUSTFLAGS='{RUST_FLAGS}' cargo build --bin {app_name} --release --target={TARGET}" + print(cmd) + os.system(cmd) + + print(f"[build.py] application {app_name} start with address {hex(base_address+step*app_id)}") + + # 恢复 + with open(linker, "w+") as f: + f.writelines(lines_before) + app_id += 1 \ No newline at end of file diff --git a/ch3-coop/user/src/linker.ld b/ch3-coop/user/src/linker.ld index ae6752b..9d48923 100644 --- a/ch3-coop/user/src/linker.ld +++ b/ch3-coop/user/src/linker.ld @@ -1,7 +1,6 @@ OUTPUT_ARCH(riscv) ENTRY(_start) -/*设置用户程序链接的基础起始位置为0x80400000*/ BASE_ADDRESS = 0x80400000; SECTIONS