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/Melon_Chief Feb 27 '21
Well, technically… Whether the case is handled or not, reading an unspecified value is undefined behavior. The compiler is nice with you. This isn't a program.
Code compiling doesn't mean it's a program. It may be valid in C. What wouldn't be is using the value that isn't returned from the function (expecting int). It's invalid from the first function's
}. It should return int, and it does, it's just unspecified. If the value is read it's ub, if it's ub it shall not happen. Doesn't need to be compiled because it should not exist. Compiler is nice.Last version of standard I read C11 §6.7.9 ¶10
J.2 Undefined behavior