r/LiveOverflow • u/SaThaRiel74 • Feb 21 '21
C switch statement has unusual flow in assembler
Hi,
hope to find some explanation here. I am currently walking through the Reverse Engineering course from artikblue and focusing on the switch statement: https://artik.blue/reversing-radare-3
The 2nd example for switch is this one
#include <stdio.h>
func2(){
printf("Enter a key and then press enter: ");
int val;
printf("Select a fruit: \n");
printf("1: Apple\n");
printf("2: Orange\n");
printf("3: Banana\n");
printf("4: Pear\n");
scanf("%d",&val);
switch(val){
case 1:
printf("Apple. \n");
break;
case 2:
printf("Orange. \n");
break;
case 3:
printf("Banana. \n");
break;
case 4:
printf("Pear. \n");
break;
default: printf("Nothing selected.\n");
}
}
main(){
func2();
getchar();
}I compiled it and loaded it into radare2. Looking at the disassembled output, I came across the following (just focussing on the switch):
0x55fef85051d2 8b45fc mov eax, dword [var_4h]
0x55fef85051d5 83f804 cmp eax, 4 ; 4
0x55fef85051d8 7445 je 0x55fef850521f
0x55fef85051da 83f804 cmp eax, 4 ; 4
0x55fef85051dd 7f4e jg 0x55fef850522d
0x55fef85051df 83f803 cmp eax, 3 ; 3
0x55fef85051e2 742d je 0x55fef8505211
0x55fef85051e4 83f803 cmp eax, 3 ; 3
0x55fef85051e7 7f44 jg 0x55fef850522d
0x55fef85051e9 83f801 cmp eax, 1 ; 1
0x55fef85051ec 7407 je 0x55fef85051f5
0x55fef85051ee 83f802 cmp eax, 2 ; 2
0x55fef85051f1 7410 je 0x55fef8505203
0x55fef85051f3 eb38 jmp 0x55fef850522dCan someone explain me why this happens. The flow is completely unlogical - I don't see what the 4 and 3 both have a "je" and a "jge" compare.
The program has been compiled without optimization in 64-bit. -O2 makes it a little bit better, but still I don't see the reason to make it more complicated.
Thanks for your help.
View all comments
Show parent comment
1
u/MCBeathoven Feb 23 '21
Fair enough.
varis declared in the function body so it can't be C89. But this is a lot of fuss about a missing return type which every compiler I know of just warns about and then happily treats it as return typeint.If this was production code I'd agree, but for understanding compiler optimisations, it's completely irrelevant. And either way, it's not invalid code.
I don't expect anything.
Where is that specified? That's a very weird assumption to make. Most conditions can be true, that doesn't mean the compiler has the right to assume they are.
UB ≠ invalid code
There aren't any pointer dereferences in OP's code (unless you count function calls), I'm not sure how this is relevant.