问题描述
我正在尝试为 RaspBerry Pi 编译 Rust 程序。我的印象是起始地址必须是 0x8000
,因此我使用自定义链接器脚本来布置程序以遵循此要求:
SECTIONS
{
.text 0x8000 : {
*(.text)
}
.data : {
*(.data)
}
}
我在架构文件 aarch64-unkNown-none.json
中指定了这一点:
{
"arch": "aarch64","data-layout": "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128","disable-redzone": true,"executables": true,"features": "+strict-align,+neon,+fp-armv8","linker": "rust-lld","linker-flavor": "ld.lld","pre-link-args": {
"ld.lld": [
"-Taarch64-raspi3.ld"
]
},"llvm-target": "aarch64-unkNown-none","max-atomic-width": 128,"panic-strategy": "abort","relocation-model": "static","target-pointer-width": "64","unsupported-abis": [
"stdcall","stdcall-unwind","fastcall","vectorcall","thiscall","thiscall-unwind","win64","sysv64"
]
}
我使用 cargo build -Zbuild-std --features=raspi3 --target=aarch64-unkNown-none.json --release
命令构建。
这是我的main.rs
:
#![cfg_attr(not(test),no_std)]
#![cfg_attr(not(test),no_main)]
#![feature(global_asm)]
#![feature(asm)]
#![feature(naked_functions)]
#[cfg(not(test))]
global_asm!(include_str!("platform/raspi3/start.s"));
mod aarch64;
mod panic;
mod platform;
这是start.s
:
.section .init
.global _start
.equ BASE,0x3f200000 //Base address
.equ GPFSEL2,0x08 //FSEL2 register offset
.equ GPSET0,0x1c //GPSET0 register offset
.equ GPCLR0,0x28 //GPCLR0 register offset
.equ SET_BIT3,0x08 //sets bit three b1000
.equ SET_BIT21,0x200000 //sets bit 21
.equ COUNTER,0xf0000
_start:
ldr x0,=BASE
ldr x1,=SET_BIT3
str x1,[x0,#GPFSEL2]
ldr x1,=SET_BIT21
str x1,#GPSET0]
b _start
当我编译它时,它将起始块放在 0x0 处,如下所示:
0000000000000000 <_start>:
0: d2a7e400 mov x0,#0x3f200000 // #1059061760
4: d2800101 mov x1,#0x8 // #8
8: f9000401 str x1,#8]
c: d2a00401 mov x1,#0x200000 // #2097152
10: f801c001 stur x1,#28]
14: 17fffffb b 0 <_start>
发生这种情况有什么原因吗?
解决方法
当你写作时:
.text 0x8000 : {
*(.text)
}
您告诉链接器通过连接来自每个编译模块 (.text
) 的 0x8000
部分,在地址 .text
处设置可执行 *
部分。
但是,在您的程序集中,_start
函数是在 .section .init
中定义的,在链接描述文件中的任何地方都没有提到。我不确定链接描述文件中未提及的部分究竟会发生什么,但我很确定依赖它是一个坏主意。
您可能希望 .init
部分位于可执行文件 .text
部分的开头:
.text 0x8000 : {
*(.init) /* _start */
*(.text)
}
注意:AFAIK,Rust 不会将所有代码发送到一个大的 .text
部分,但它创建了更小的 .text.name_of_the_thing
部分。您可能希望将它们全部链接在一起,以便:
.text 0x8000 : {
*(.init) /* _start */
*(.text)
*(.text.*)
}