Ben*_*nck 5 c x86 assembly 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
Run Code Online (Sandbox Code Playgroud)
我的问题是关于这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;
}
Run Code Online (Sandbox Code Playgroud)
%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
Run Code Online (Sandbox Code Playgroud)
因此,代码应该是
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;
}
Run Code Online (Sandbox Code Playgroud)