Search code examples
assemblyreverse-engineering

Assembly language - what does sarq do in the code?


I am trying to translate assembly code back into C code but I noticed this one operation called sarq. I think q is for what size the address is but I do not know what the sarq does to the address. I commented on what I believe the code does.

.LC0    .string "ans %d\n" 
main:
.LFB0:                  val = -8(%rbp), result = -12(%rbp)
        pushq   %rbp
        movq    %rsp, %rbp
        subq    $16, %rsp
        movabsq $53162464113523643, %rax
        movq    %rax, -8(%rbp)      //val(variable) address -8,inputs value in %rax
        movl    $0, -12(%rbp)       //result(variable) address -12, inputs 0
        jmp     .L2         //starts loop
.L3:
        movq    -8(%rbp), %rax      //moves value in val into rax
        andl    $1, %eax        //dunno what eax is but adds 1 into it
        xorl    %eax, -12(%rbp)     //compares the value of eax and result to see if they are not equal. so compares 1 to 0
        sarq    -8(%rbp)        //does something to val?
.L2:
        cmpq    $0, -8(%rbp)        //compares val to 0
        jg      .L3         //if greater, goes to L3
        movl    -12(%rbp), %eax     //else, moves value from result into eax
        movl    %eax, %esi      //moves eax into esi
        movl    $.LC0, %edi     //Moves w/e $.LC0 is into edi. Based on the top, edi now holds that string?
        movl    $0, %eax        //moves 0 into eax
        call    printf          //print statement
        leave
        ret

Solution

  • sar is an arithmetic right shift. The single operand form shifts its operand right by one place, filling the topmost bit with the sign of the number. the suffix q indicates that the operand is a 64 bit operand (a quadword). Thus sarq -8(%rbp) shifts the quadword eight bytes below %rbp right by one place.