将 x86 程序集跳转表转换为 C

标签 c assembly x86 switch-statement jump-table

我有这个 x86 汇编代码,我正在尝试将它转换为 C:

.GLOBAL calculate
calculate:
    pushl %ebp
    movl %esp,%ebp
    movl 12(%ebp),%eax
    movl 8(%ebp),%ecx
    cmpl $2,%ecx
    ja done
    jmp *operations(,%ecx,4)
operation1:
    imull %eax,%eax
    jmp done
operation2:
    negl %eax
    jmp done
operation3:
    addl $0x80,%eax
done:
    leave
    ret
operations:
    .long operation1, operation2, operation3

我的问题是关于 jmp *operations(,%ecs,4) 行。我认为这是一个 switch 语句,我知道它在内存中是如何工作的,但它如何转换为 C?难道我不必知道这些位置的堆栈上有什么才能为其编写开关吗?

这是我的:

int calculate(int a, int b)
{
    if (2 > a)
    {
        return b;
    }
    switch(a) {
        case /* ? */:
            b = (b * b);
            break;
        case /* ? */:
            b = (b * -1);
            break;
        case /* ? */:
            b = (b + 128);
            break;
    }
    return b;
}

最佳答案

%ecx == 0 -> operations(,%ecx,4) == operations+0 and operation1 is there  
%ecx == 1 -> operations(,%ecx,4) == operations+4 and operation2 is there  
%ecx == 2 -> operations(,%ecx,4) == operations+8 and operation3 is there

因此,代码应该是

int calculate(int a, int b)
{
    if ((unsigned int)a > 2) /* ja is a comparation instruction for unsigned integers */
    {
        return b;
    }
    switch(a) {
        case 0:
            b = (b * b);
            break;
        case 1:
            b = (b * -1);
            break;
        case 2:
            b = (b + 128);
            break;
    }
    return b;
}

关于将 x86 程序集跳转表转换为 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32448590/

相关文章:

assembly - Switch Case 汇编语言

程序集弹出空堆栈

paging - 为什么使用 PAE 地址空间从 32 位增加到 36 位

c - 在c中增加 union 数据

c - 隐藏终端,C + GTK

c - 程序说明

assembly - 使用 MIPS 汇编中的逻辑移位乘以 2 的幂

c - 披萨代码不起作用 | Cinnamon 上的 C 编程

assembly - x86 中 0 值的奇偶校验标志

node.js - 是否可以在 32 位环境上运行 Edge.js?