此代码将字符串(位于ebp+arg_0
)的每个字符与不同的常量(ASCII字符)(如“I”,“o”和“S”)进行比较。我想,基于其他代码部分,这段代码最初用C语言编写。
这个比较代码部分看起来非常低效。我的问题,你认为这段代码在C中看起来怎么样?最初使用了什么代码构造?到目前为止我的想法
是的,它是挑战的一部分,我已经有了旗帜/解决方案,不用担心。只是想更好地理解代码。
这不是一个for循环。因为我没有看到任何向上跳跃和停止状态。
正确。
它不是整个/ case / switch代码构造
它不可能,它比较数组的不同索引。
我最好的猜测是,这是很多连续的if / elses。你能帮我吗?
看起来可能是这段代码:
void f(const char* arg_0) {
if(arg_0[4] == 'I' && arg_0[5] == 'o' && arg_0[6] == 'S') {
printf("Gratz man :)");
exit(0); //noreturn, hence your control flow ends here in the assembly
}
puts("Wrong password"); // Or `printf("Wrong password\n");` which gets optimized to `puts`
// leave, retn
}
This is how gcc compiles it without optimizations:
.LC0:
.string "Gratz man :)"
.LC1:
.string "Wrong password"
f(char const*):
push ebp
mov ebp, esp
sub esp, 8
mov eax, DWORD PTR [ebp+8]
add eax, 4
movzx eax, BYTE PTR [eax]
cmp al, 73
jne .L2
mov eax, DWORD PTR [ebp+8]
add eax, 5
movzx eax, BYTE PTR [eax]
cmp al, 111
jne .L2
mov eax, DWORD PTR [ebp+8]
add eax, 6
movzx eax, BYTE PTR [eax]
cmp al, 83
jne .L2
sub esp, 12
push OFFSET FLAT:.LC0
call printf
add esp, 16
sub esp, 12
push 0
call exit
.L2:
sub esp, 12
push OFFSET FLAT:.LC1
call puts
add esp, 16
nop
leave
ret
看起来与您的反汇编代码非常相似。
这个比较代码部分看起来非常低效
看起来它是在没有优化的情况下编译的。启用优化后,gcc compiled the code to:
.LC0:
.string "Gratz man :)"
.LC1:
.string "Wrong password"
f(char const*):
sub esp, 12
mov eax, DWORD PTR [esp+16]
cmp BYTE PTR [eax+4], 73
jne .L2
cmp BYTE PTR [eax+5], 111
je .L5
.L2:
mov DWORD PTR [esp+16], OFFSET FLAT:.LC1
add esp, 12
jmp puts
.L5:
cmp BYTE PTR [eax+6], 83
jne .L2
sub esp, 12
push OFFSET FLAT:.LC0
call printf
mov DWORD PTR [esp], 0
call exit
不知道为什么gcc决定再次跳下来而不是直线jne
s。此外,ret
消失了,你的printf
得到尾调用优化,即jmp printf
而不是call printf
,然后是ret
。
第一个参数(arg_0
)是指向给定密码字符串的指针,例如const char *arg_0
。该指针(第一个字符的地址)被加载到eax
寄存器(mov eax, [ebp+arg_0]
)中,然后添加当前字符的索引以将其推进到该索引(add eax, 4
等)。然后将该地址的单个字节加载到eax
(movzx eax, byte ptr [eax]
)中。
然后将该字节/字符与正确的字符/字符进行比较(cmp eax, 'I'
等)。如果结果不为零(即,如果它们不相等),则程序跳转到“密码错误”分支(jnz
- 如果不为零则跳转),否则它继续进行下一次比较(并最终成功)。
因此,最接近的直接C等价物将是:
void check(const char *arg_0) {
// presumably comparisons 0-3 are omitted
if (arg_0[4] != 'I') goto fail;
if (arg_0[5] != 'o') goto fail;
if (arg_0[6] != 'S') goto fail;
printf("Gratz man :)");
exit(0);
fail:
puts("Wrong password");
}
(当然,实际的C代码不太可能像这样,因为goto fail
排列不典型。)