gpt4 book ai didi

c - 这种没有推送寄存器的交换有多安全?

转载 作者:太空狗 更新时间:2023-10-29 14:57:11 24 4
gpt4 key购买 nike

我是 Assembly 的新手,下面的代码应该通过两个不同的函数交换两个整数:首先使用 swap_c然后使用 swap_asm .

但是,我怀疑我是否需要push (我的意思是保存)汇编代码和pop之前的寄存器的每个值他们稍后(就在返回 main 之前)。换句话说,如果我返回不同的寄存器内容,CPU 会生我的气吗(不是像 ebpesp 这样的关键内容;但是,只是 eaxebxecxedx )运行后swap_asm功能?取消对 assembly 部分中行的注释是否更好?

这段代码对我来说运行正常,我设法减少了 27 行汇编 C代码减少到 7 条 assembly 线。

p.s.: 系统为 Windows 10,VS-2013 Express。

main.c部分

#include <stdio.h>

extern void swap_asm(int *x, int *y);

void swap_c(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}

int main(int argc, char *argv[]) {
int x = 3, y = 5;
printf("before swap => x = %d y = %d\n\n", x, y);

swap_c(&x, &y);
printf("after swap_c => x = %d y = %d\n\n", x, y);

swap_asm(&x, &y);
printf("after swap_asm => x = %d y = %d\n\n", x, y);

getchar();
return (0);
}

assembly.asm部分

 .686
.model flat, c
.stack 100h
.data

.code
swap_asm proc
; push eax
; push ebx
; push ecx
; push edx
mov eax, [esp] + 4 ; get address of "x" stored in stack into eax
mov ebx, [esp] + 8 ; get address of "y" stored in stack into ebx
mov ecx, [eax] ; get value of "x" from address stored in [eax] into ecx
mov edx, [ebx] ; get value of "y" from address stored in [ebx] into edx
mov [eax], edx ; store value in edx into address stored in [eax]
mov [ebx], ecx ; store value in ecx into address stored in [ebx]
; pop edx
; pop ecx
; pop ebx
; pop eax
ret
swap_asm endp
end

最佳答案

通常,这取决于您正在使用的系统的调用约定。 调用约定 指定如何调用函数。通常,它说明将参数放在哪里以及被调用函数必须保留哪些寄存器。

在具有 cdecl 调用约定(这是您可能使用的调用约定)的 i386 Windows 上,您可以自由地覆盖 eaxecxedx 寄存器。 ebx 寄存器必须保留。虽然您的代码似乎可以工作,但当一个函数开始依赖于 ebx 被保留时,它神秘地失败了,所以最好保存和恢复它。

关于c - 这种没有推送寄存器的交换有多安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35397944/

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