Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement in assembly

Tags:

c

x86

assembly

I'm trying to understand how switch statement works in assembly and I have the following program :

int main (int argc, char **argv)
{
    int     x = argc > 1 ? atoi(argv[1]) : 2;
    int     y;

    switch (x) {
        case 0:
            y = 0;
            break;
        case 1:
            y = 1;
            break;
        case 2:
            y = 2;
            break;
        case 3:
            y = 3;
            // this case "drops through"
        case 4:
            y = 4;
            break;
        default:
            y = -1;
            break;
        }

    return 0;
}

In assembly it looks like :

0x804842f <main+19>     cmpl   $0x1,(%eax)
0x8048432 <main+22>     jle    0x804844a <main+46>                                                                                          
0x8048434 <main+24>     mov    0x4(%eax),%eax
0x8048437 <main+27>     add    $0x4,%eax
0x804843a <main+30>     mov    (%eax),%eax
0x804843c <main+32>     sub    $0xc,%esp
0x804843f <main+35>     push   %eax
0x8048440 <main+36>     call   0x8048310 <atoi@plt>
0x8048445 <main+41>     add    $0x10,%esp
0x8048448 <main+44>     jmp    0x804844f <main+51>
0x804844a <main+46>     mov    $0x2,%eax
0x804844f <main+51>     mov    %eax,-0xc(%ebp)
0x8048452 <main+54>     cmpl   $0x4,-0xc(%ebp)
0x8048456 <main+58>     ja     0x8048492 <main+118>
0x8048458 <main+60>     mov    -0xc(%ebp),%eax
0x804845b <main+63>     shl    $0x2,%eax
0x804845e <main+66>     add    $0x8048540,%eax       

My first question is why there is ja instruction in <main+58>, instead of jg, as we are using signed integers. And second question is why there is a shift by 2 bits in <main+63>and not any other value.

like image 257
Mr.SrJenea Avatar asked Aug 06 '26 21:08

Mr.SrJenea


1 Answers

The ja is a trick to fold the two signed checks into a single unsigned check. That effectively does if (x > 4 || x < 0), so the only things passed through are 0-4 as expected.

The shift by 2 bits is scaling for the pointer size. You have cut off the next part of the disassembly where I am pretty sure you would see an indirect jump through a table. That table holds pointers of size 4 (on your architecture) so the index should be scaled by 4, which is a shift of 2 bits.

like image 139
Jester Avatar answered Aug 08 '26 10:08

Jester