I want to learn about C calling convention. To do this I wrote the following code:
#include <stdio.h>
#include <stdlib.h>
struct tstStruct
{
void *sp;
int k;
};
void my_func(struct tstStruct*);
typedef struct tstStruct strc;
int main()
{
char a;
a = 'b';
strc* t1 = (strc*) malloc(sizeof(strc));
t1 -> sp = &a;
t1 -> k = 40;
my_func(t1);
return 0;
}
void my_func(strc* s1)
{
void* n = s1 -> sp + 121;
int d = s1 -> k + 323;
}
Then I used GCC with the following command:
gcc -S test3.c
and came up with its assembly. I won't show the whole code I got but rather paste the code for the function my_func. It is this:
my_func:
.LFB1:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movq %rdi, -24(%rbp)
movq -24(%rbp), %rax
movq (%rax), %rax
addq $121, %rax
movq %rax, -16(%rbp)
movq -24(%rbp), %rax
movl 8(%rax), %eax
addl $323, %eax
movl %eax, -4(%rbp)
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
As far as I understood, this is what happens: First the callers base pointer is pushed into stack and its stack pointer is made the new base pointer to set up the stack for the new function. But then the rest I don't understand. As far as I know, the arguments (or the pointer to the argument) is stored in the stack. If so what is the purpose of the second instruction,
movq -24(%rbp), %rax
Here, the content of the %rax register is moved to the address 24 bytes away from the address in the register %rbp. But what is in %rax???? Nothing is initially stored there??? I think I'm confused. Please help to understand how this function works. Thanks in advance!