gpt4 book ai didi

rust - 如何将 Rust 代码编译为裸机 32 位 x86 (i686) 代码?我应该使用什么编译目标?

转载 作者:行者123 更新时间:2023-12-04 07:31:42 33 4
gpt4 key购买 nike

我想使用cargo/Rust 为x86(又名i686 又名x86_64 32 位模式)编译裸机32 位代码。我需要什么目标?在 official supported target list我找不到任何东西,这是实用的。

最佳答案

不幸的是,Rust 编译器没有为此内置目标定义 [Rust nightly 1.54, June 2021],但您可以提供自定义目标定义:
<项目根>/x86-unknown-bare_metal.json

{
"llvm-target": "i686-unknown-none",
"data-layout": "e-m:e-i32:32-f80:128-n8:16:32-S128-p:32:32",
"arch": "x86",
"target-endian": "little",
"target-pointer-width": "32",
"target-c-int-width": "32",
"os": "none",
"executables": true,
"linker-flavor": "ld.lld",
"linker": "rust-lld",
"panic-strategy": "abort",
"disable-redzone": true,
"features": "+soft-float,+sse"
}
此定义将指针宽度设置为 32,用于编译代码,可以在早期的 x86 引导过程中使用(当您已经处于 32 位保护模式时)。我不是 100% 确定“功能”,因为它们可能取决于您想要做什么/需要什么。 i686指 32 位模式下的 x86_64 和 data-layout is explained here .
此外,您应该添加文件
/.cargo/config.toml
[unstable]
# cross compile core library for custom target
build-std = ["core", "compiler_builtins"]
build-std-features = ["compiler-builtins-mem"]

[build]
# points to file in project root
target = "x86-unknown-bare_metal.json"
现在,您可以使用 cargo build 构建具有 32 位 x86 代码的裸机二进制文件。 .
// disable rust standard library
#![no_std]
// disables Rust runtime init,
#![no_main]

// see https://docs.rust-embedded.org/embedonomicon/smallest-no-std.html
#![feature(lang_items)]

// see https://docs.rust-embedded.org/embedonomicon/smallest-no-std.html
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

use core::panic::PanicInfo;
use core::sync::atomic;
use core::sync::atomic::Ordering;

#[no_mangle]
/// The name **must be** `_start`, otherwise the compiler doesn't output anything
/// to the object file. I don't know why it is like this.
fn _start() -> ! {
loop {}
}

#[inline(never)]
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {
atomic::compiler_fence(Ordering::SeqCst);
}
}
为方便起见,您还应该添加
<项目根>/rust-toolchain.toml
# With this file, another toolchain to the currently selected one will be used, when you execute `cargo build`.
# https://rust-lang.github.io/rustup/overrides.html

[toolchain]
# equals to rust nightly 1.54 as of the release day 2021-05-10
channel = "nightly-2021-05-10"
components = [ "rust-src", "rust-std", "rustc", "cargo" ]

关于rust - 如何将 Rust 代码编译为裸机 32 位 x86 (i686) 代码?我应该使用什么编译目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67902309/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com