Writing C function from this x86 assembly

I am trying to rebuild this secret function. This function returns an integer and takes a struct node as an argument

#include "mystery.h"
int mystery(struct e4_struct *s){}

The header file is a simple structure declaration

struct my_struct {
    int a;
    int b; 
};

The assembly I'm trying to redo is

400596:    8b 07                    mov    (%rdi),%eax
400598:    8d 04 40                 lea    (%rax,%rax,2),%eax
40059b:    89 07                    mov    %eax,(%rdi)
40059d:    83 47 04 07              addl   $0x7,0x4(%rdi)
4005a1:    c3                       retq  

So far, I think the function is similar:

int mystery(struct m_struct *s){
    int i = s->a;
    i = 3*i;
    int j = s->b;
    j += 7;
    return i;
}

But this is not true. I don’t understand what exactly does mov %eax,(%rdi)and what the function returns at the end, because it must be returned and the whole.

+4
source share
1 answer

Given that the RDI is a pointer to the beginning of the structure (the first parameter of the function), the next line gets the value s->aand puts it in the temporary EAX register.

mov    (%rdi),%eax

It is permissible that this may be int x = s->a. This line:

lea    (%rax,%rax,2),%eax

, temp 3, RAX + RAX * 2 = 3 * RAX ( , s- > a * 3). , :

int x = s->a * 3;

mov %eax,(%rdi) x s- > a, :

s->a = x;

addl $0x7,0x4(%rdi) 7 4 (RDI). 4 (RDI) - s- > b. ​​ s->b += 7;.

, ? EAX, EAX - , , x = s->a * 3;. , x.

:

int mystery(struct my_struct *s)
{
    int x = s->a * 3;
    s->a = x;
    s->b += 7;
    return x;    
}

GCC 4.9.x godbolt -O1, :

mystery:
        movl    (%rdi), %eax
        leal    (%rax,%rax,2), %eax
        movl    %eax, (%rdi)
        addl    $7, 4(%rdi)
        ret

, . GCC 4.9.x, , , .


. - SO mystery, GCC 4.9.x -O1 , . , , .

+7

Source: https://habr.com/ru/post/1695024/


All Articles