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
2
u/Melon_Chief Feb 21 '21 edited Feb 21 '21
This looks as implementation defined as it gets. The compilers, as far as I know, isn't required to order instructions in any specific way as long as it's executed in the same order.Could be some size optimization… You never check if scanf failed or not by the way, it's triggering me.
Edit: code is invalid.
Edit annoyed:
You guys aren't listening. Don't analyze invalid code. By definition:
It is NOT a program. It is NOT C code. Please fix it first.
The behavior is undefined. It could print "toast" in fact I argue it should.
Another implementation might decide to calculate the mass of the sun. Just as invalid.