Rust 内联汇编模板语法
Rust inline assembly template syntax
我在test.s
中有以下代码:
call +
运行 nasm test.s
编译成功。我希望以下等效的 Rust 代码能够成功编译,但它没有。
在test.rs
中:
#![feature(asm)]
fn main() {
unsafe {
asm! (
"call [=11=] + [=11=]"
:
: "i" (8)
: "memory"
: "volatile"
)
}
}
rustc test.rs
的输出:
test.rs:4:9: 10:11 error: <inline asm>:1:12: error: invalid token in expression
call +
^
这对我有用:
#![feature(asm)]
fn main() {
unsafe {
asm!( "call ${0:c} + ${0:c}"
:
: "i"(8)
: "memory"
: "volatile"
)
}
}
这是相关的 documentation in the LLVM reference。通过查看 objdump
的输出,我们可以验证我们的内联程序集是否已发出:
0000000000005190 <_ZN4main20hc3048743ecd04f53eaaE>:
5190: e8 7b ae ff ff callq 10 <_ZN10sys_common11thread_info11THREAD_INFO5__KEY20h20efb688859d2c0dRhsE+0x10>
5195: c3 retq
5196: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1)
519d: 00 00 00
更新:下面是直接从内联汇编调用函数的示例:
#![feature(asm)]
fn called_even_if_mangled() {
println!("Just a regular function minding its own business");
}
fn main() {
unsafe {
asm!( "call ${0:c}"
:
: "i"(called_even_if_mangled)
: "memory"
: "volatile", "alignstack"
// Omit "alignstack" and you'll get a segfault because of a
// misaligned SSE load on some initialization code regarding
// stdin.
)
}
}
但是你应该永远不要做这样的事情,除非你有一个非常好的和令人信服的论据来这样做(例如,因为你正在编写一个 JIT)。我不得不花一个小时调试一个神秘的段错误,直到我意识到我还必须将 alignstack
放在选项部分。
您已收到警告。
我在test.s
中有以下代码:
call +
运行 nasm test.s
编译成功。我希望以下等效的 Rust 代码能够成功编译,但它没有。
在test.rs
中:
#![feature(asm)]
fn main() {
unsafe {
asm! (
"call [=11=] + [=11=]"
:
: "i" (8)
: "memory"
: "volatile"
)
}
}
rustc test.rs
的输出:
test.rs:4:9: 10:11 error: <inline asm>:1:12: error: invalid token in expression
call +
^
这对我有用:
#![feature(asm)]
fn main() {
unsafe {
asm!( "call ${0:c} + ${0:c}"
:
: "i"(8)
: "memory"
: "volatile"
)
}
}
这是相关的 documentation in the LLVM reference。通过查看 objdump
的输出,我们可以验证我们的内联程序集是否已发出:
0000000000005190 <_ZN4main20hc3048743ecd04f53eaaE>:
5190: e8 7b ae ff ff callq 10 <_ZN10sys_common11thread_info11THREAD_INFO5__KEY20h20efb688859d2c0dRhsE+0x10>
5195: c3 retq
5196: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1)
519d: 00 00 00
更新:下面是直接从内联汇编调用函数的示例:
#![feature(asm)]
fn called_even_if_mangled() {
println!("Just a regular function minding its own business");
}
fn main() {
unsafe {
asm!( "call ${0:c}"
:
: "i"(called_even_if_mangled)
: "memory"
: "volatile", "alignstack"
// Omit "alignstack" and you'll get a segfault because of a
// misaligned SSE load on some initialization code regarding
// stdin.
)
}
}
但是你应该永远不要做这样的事情,除非你有一个非常好的和令人信服的论据来这样做(例如,因为你正在编写一个 JIT)。我不得不花一个小时调试一个神秘的段错误,直到我意识到我还必须将 alignstack
放在选项部分。
您已收到警告。