gpt4 book ai didi

c - 了解汇编代码中的减法和乘法

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:22 26 4
gpt4 key购买 nike

有人能解释一下反汇编代码中的这些步骤会做什么吗?我有一个大概的想法,但我仍然很困惑。我知道前两条指令设置堆栈并且 eax 将是一个返回值,但仅此而已。

我正在寻找的是以下步骤的目的:

push %ebp - base stack frame pointer
mov %esp, %ebp - stack pointer
sub $0x10, %esp - subtracts 16 from ?
mov 0x8(%ebp), %eax - ?
imul 0xc(%ebp), %eax - multiply 12 and ?
mov %eax, -0x4(%ebp) - ?
mov -0x4(%ebp), %eax - puts -0x4(%ebp) not sure what that would be , into eax making it the return value?
leave
ret

最佳答案

; Standard prolog: stack frame setup
push ebp ; save the old frame pointer
mov ebp, esp ; set the frame pointer to the current top of the stack
sub esp, 0x10 ; make space for 16 bytes of local variables
; Do the stuff
mov eax, [ebp+8] ; copy the first parameter in eax
imul eax, [ebp+0xc] ; multiply eax with the second parameter
mov [ebp-4], eax ; move the result to the first local variable
mov eax, [ebp-4] ; move it back to eax (?) => set it as return value
; Standard cdecl epilog - clean up locals & return
leave ; restore the old frame pointer
; same as: mov esp, ebp
; pop ebp
ret ; return

(很抱歉将其更改为 Intel 符号,但 AT&T 语法对我来说看起来像一团乱七八糟的东西,尤其是取消引用和偏移量的可怕符号1)

要理解这一点,请绕过这张方便的图表,了解堆栈在函数序言之后的 x86 上的 cdecl 函数调用中的正常情况:

x86 stack frame scheme

请记住括号中的表达式是指针取消引用操作。

本质上,这是一个(相当幼稚的)翻译

int multiply(int a, int b) {
// \ \ &b == ebp+12
// \ &a == ebp+8
int c = a*b;
// \ \ multiplication performed in eax
// \ &c == ebp-4
return c;
// \ return value left in eax
}

(使用 cdecl 调用约定,调用者负责从堆栈中清除参数)

这可能是由禁用优化的编译器生成的。一个更紧凑的版本是:

mov eax, [esp+4]
imul eax, [esp+8]
ret

(因为一切都可以在没有局部变量的情况下完成,所以甚至不需要设置堆栈框架)


编辑

刚刚检查过,您的代码与 gcc 在 -O0 处生成的代码完全匹配,而我的代码与在 -O3 处生成的代码几乎相同。


注意事项

  1. 备案:当你看到

    displacement(%register, %offset_register, multiplier)

    (除了 %register 之外的每个组件都是可选的)在 AT&T 语法中它的实际含义

    [register + displacement + offset_register*multiplier]

    其中括号的意思是“获取存储在这里的值”。

    此外,几乎所有参数都在 AT&T 语法中交换(在 Intel 语法中,目标操作数在左侧,即 mov 读起来像一个赋值 - mov ebp, esp => ebp = esp).

关于c - 了解汇编代码中的减法和乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681077/

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