Rust内联汇编模板语法 [英] Rust inline assembly template syntax

查看:396
本文介绍了Rust内联汇编模板语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在test.s中具有以下代码:

call $8 + $8

运行nasm test.s成功编译.我希望以下等效的Rust代码能够成功编译,但不会成功.

Running nasm test.s compiles successfully. I'd expect the following equivalent Rust code to compile successfully, but it doesn't.

test.rs中:

#![feature(asm)]
fn main() {
    unsafe {
        asm! (
            "call $0 + $0"
            :
            : "i" (8)
            : "memory"
            : "volatile"
        )
    }
}

rustc test.rs的输出:

test.rs:4:9: 10:11 error: <inline asm>:1:12: error: invalid token in expression
        call $8 + $8
                  ^

推荐答案

这对我有用:

#![feature(asm)]
fn main() {
    unsafe {
        asm!( "call ${0:c} + ${0:c}"
            :
            : "i"(8)
            : "memory"
            : "volatile"
        )
    }
}

以下是LLVM参考中的相关文档.通过查看objdump的输出,我们可以验证是否已发出内联程序集:

Here's the relevant documentation in the LLVM reference. By looking at the output of objdump, we can verify that our inline assembly has been emitted:

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 

更新:以下是直接从内联程序集中调用函数的示例:

UPDATE: Here's an example of directly calling a function from inline assembly:

#![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.

But you should never ever do such a thing, unless you have a very good and compelling argument to do so (for example, because you're writing a JIT). I had to spend an hour debugging a mysterious segfault until I realized that I also had to put alignstack in the options section.

您已被警告.

这篇关于Rust内联汇编模板语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆