繁体   English   中英

交换寄存器内容的汇编程序

[英]Assembler program to swap contents of registers

我正在尝试做一个真正简单的汇编程序来交换寄存器的内容。 这是我尝试过的:

movq (%rcx), %rax
movq (%rbx), %rdx
movq %rdx, (%rcx)
movq %rax, (%rbx)
ret

它给了我分段错误。

以下是 c 中的工作程序示例:

void swap(int64_t *a, int64_t *b) {
    int64_t c = *a;
    *a = *b;
    *b = c;
}

请参阅: https://en.wikipedia.org/wiki/X86_calling_conventions

您忽略了提及您是为 Microsoft/Win x64 还是为 System V AMD64 ABI [或完全为其他东西] 进行编译。

您正在使用 AT&T asm 语法,所以我假设您需要 SysV 调用约定。 (Since tools like GCC and GAS are more common on Linux / MacOS. But if you're using MinGW w64 on Windows then you'll want the Windows convention.)


您假设参数位于: %rcx%rbx 符合一约定 [尽管它更接近 MS ABI]

对于 System V AMD64 ABI(例如 Linux、BSD、MacOS),前两个参数分别在%rdi%rsi中传递。 而且,不在%rdx%rcx中(用于第三和第四个参数)。

您始终可以使用%rax%rdx作为临时 reg,因为%rax保存 function 返回值,而%rdx是一个 arg reg,因此调用者不会期望它们被保留。

所以你要:

# Non-Windows
movq (%rdi),%rax
movq (%rsi),%rdx
movq %rdx,(%rdi)
movq %rax,(%rsi)
ret

对于 MS 64 位,arg 寄存器为: %rcx, %rdx, %r8, %r9

所以,你会想要:

# Windows
movq (%rcx),%rax
movq (%rdx),%r8
movq %r8,(%rcx)
movq %rax,(%rdx)
ret

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM