Satirez
Satirez

Reputation: 17

C asm jmp going back to jmp after performing the jmp

I'm performing a relative jump in some asm code in C. I've got the jump working as intended, but it goes back to right after the jump happens and finished running the code.

#include <stdio.h>

void function() {
    asm("jmp .+0x31"); //this happens to be where I want to jump to from the function call
}

void main(int argc, char* argv[]) {
    int x;
    x = 0;
    function();
    x = 1;
    x = x + 1;
    printf("%d\n", x);
}

0x000000000040053f <+0>:     push   %rbp
0x0000000000400540 <+1>:     mov    %rsp,%rbp
0x0000000000400543 <+4>:     sub    $0x20,%rsp
0x0000000000400547 <+8>:     mov    %edi,-0x14(%rbp)
0x000000000040054a <+11>:    mov    %rsi,-0x20(%rbp)
0x000000000040054e <+15>:    movl   $0x0,-0x4(%rbp)
0x0000000000400555 <+22>:    mov    $0x0,%eax
0x000000000040055a <+27>:    callq  0x400536 <function>
0x000000000040055f <+32>:    movl   $0x1,-0x4(%rbp)
0x0000000000400566 <+39>:    addl   $0x1,-0x4(%rbp)
0x000000000040056a <+43>:    mov    -0x4(%rbp),%eax
0x000000000040056d <+46>:    mov    %eax,%esi
0x000000000040056f <+48>:    mov    $0x400620,%edi
0x0000000000400574 <+53>:    mov    $0x0,%eax
0x0000000000400579 <+58>:    callq  0x400410 <printf@plt>
0x000000000040057e <+63>:    nop
0x000000000040057f <+64>:    leaveq
0x0000000000400580 <+65>:    retq

Following the call of function(), it prints a 0 as intended, but it then goes back through the code after function() is called and prints 2 as well. Am I missing how jmp works? Is there a way to exit via asm code?

The goal of this is to skip

x = 1;
x = x + 1;

and just print 0, then exit the file.

Upvotes: 0

Views: 484

Answers (1)

user58697
user58697

Reputation: 7923

Since function doesn't execute a ret instruction, its return address is still there on the stack. That is, when main executes its ret, the return address it uses is in fact an address left by function, and lands back at x = 1; line.

To achieve your goal, function before doing a jump must adjust the stack pointer as if it has never been called.

That said, don't try this at home.

Upvotes: 2

Related Questions