Search code examples
cassemblyswitch-statementreverse-engineering

Switch statement assembly code to c


I am having a very hard time reverse engineering a switch statement from assembly code into a C program.

.file 
"switch_prob2-soln.c"
.text
.globl switch_prob
.type switch_prob, @function
switch_prob:
.LFB0:
.cfi_startproc
subq $60, %rsi
cmpq $5, %rsi
ja .L2
jmp *.L7(,%rsi,8)
.section .rodata
.align 8
.align 4
 .L7:
 .quad .L3
 .quad .L2
 .quad .L3
 .quad .L4
 .quad .L5
 .quad .L6
 .text
 .L3:
 leaq 0(,%rdi,8), %rax
 ret
 .L4:
 movq %rdi, %rax
 sarq $3, %rax
 ret
 .L5:
 movq %rdi, %rax
 salq $4, %rax
 subq %rdi, %rax
 movq %rax, %rdi
 .L6:
 imulq %rdi, %rdi
 .L2:
 leaq 75(%rdi), %rax
 ret
 .cfi_endproc
 .LFE0:
 .size switch_prob, .-switch_prob
  .ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
 .section .note.GNU-stack,"",@progbits

Here is the basic C program that I have:

long switch_prob(long x, long n)
{
    long result = x;
    switch(n) {

 }
 return result;
 }

All that I asking for is helpful advice to get started. I know I can compile with -S or -O1. Thank you for your time.

This is what my c code displays in assembly enter image description here

here is my c code

enter image description here

if anyone can help me please it will be awesome, I am trying to get the quad to show 3 2 3 4 5 6


Solution

  • It's unclear what you have the problem with. I hope you know it uses a jump table.

    It should be obvious that you have 6 cases and a default, with some sharing code. The instructions are quite simple, I trust you have no problem with those.

    As for the switch expression itself, it's just a trivial transformation done by a single instruction.

    I tried not to give away the solution, you asked for advice to get started after all. Do you need any more hints?