This simple c code:
file bar.c:
#include <stdio.h>
#define BSIZE 5
typedef struct
{
int count;
int ar[BSIZE];
} foo;
int main()
{
foo f = {.count = 0};
printf("%ld\n",sizeof(foo));
}
which output 24 as size of the struct (5*4 + 4), so it is correct. The gas code is as follows:
.text
.section .rodata
.LC0:
.string "%ld\n"
.text
.globl main
.type main, @function
main:
endbr64
pushq %rbp #
movq %rsp, %rbp #,
subq $32, %rsp #,
# bar.c:12: {
movq %fs:40, %rax # MEM[(<address-space-1> long unsigned int *)40B], tmp85
movq %rax, -8(%rbp) # tmp85, D.2347
xorl %eax, %eax # tmp85
# bar.c:13: foo f = {.count = 0};
movq $0, -32(%rbp) #, f
movq $0, -24(%rbp) #, f
movq $0, -16(%rbp) #, f
# bar.c:14: printf("%ld\n",sizeof(foo));
movl $24, %esi #,
leaq .LC0(%rip), %rdi #,
movl $0, %eax #,
call printf@PLT #
movl $0, %eax #, _5
# bar.c:15: }
movq -8(%rbp), %rdx # D.2347, tmp86
subq %fs:40, %rdx # MEM[(<address-space-1> long unsigned int *)40B], tmp86
je .L3 #,
call __stack_chk_fail@PLT #
.L3:
leave
ret
.size main, .-main
.ident "GCC: (Ubuntu 10.2.0-13ubuntu1) 10.2.0"
.section .note.GNU-stack,"",@progbits
.section .note.gnu.property,"a"
.align 8
.long 1f - 0f
.long 4f - 1f
.long 5
0:
.string "GNU"
1:
.align 8
.long 0xc0000002
.long 3f - 2f
2:
.long 0x3
3:
.align 8
4:
Now I have multiple question about this output:
why is there
subq $32, %rspwhen the size of struct is24? Why is not substracted just24from the stack, but it needs another8 bytesfor what? alignment?what is
movq %fs:40, %rax # MEM[(<address-space-1> long unsigned int *)40B], tmp85? What is register%fs? What does the40mean, offset ? What the comment generated from compiler suggest? There is no datatypelong unsigned int *???
this statements:
# bar.c:13: foo f = {.count = 0};
movq $0, -32(%rbp) #, f
movq $0, -24(%rbp) #, f
movq $0, -16(%rbp) #, f
I do not fully understand. From my struct definition, I guess
-32(%rbp) == count
-24(%rbp) == ar[0]
-20(%rbp) == ar[1]
-16(%rbp) == ar[2]
-12(%rbp) == ar[3]
-8(%rbp) == ar[4]
Is this correct alignment of struct foo in stack? How otherwise is it align?