1

When I initialize an array in c, the assembly code generated by gcc adds a line that looks like this:

mov rax, QWORD PTR fs:40

I'm having a hard time understanding what fs:40 is doing. In gdb the fs pointer is pointing to zero:

(gdb) i r fs
fs             0x0  0

So based on this the first 128 bytes is just garbage. So why is it copying 8 bytes of garbage after the array?

This is my code:

int main(){
    char buffer[8];
}

This is how I compiled it into intel assembly format:

 gcc -S -O0 -masm=intel ch2.c -fno-asynchronous-unwind-tables

This is the output assembly file I get. I'm only showing the "Main" function area:

main:
    push    rbp
    mov rbp, rsp
    sub rsp, 16
    mov rax, QWORD PTR fs:40   ;;<<< this is the line
    mov QWORD PTR -8[rbp], rax
    xor eax, eax
    mov eax, 0
    mov rdx, QWORD PTR -8[rbp]
    xor rdx, QWORD PTR fs:40
    je  .L4
    call    __stack_chk_fail@PLT
.L4:
    leave
    ret

Thanks in advance.

pedrumj
  • 163
  • 2
  • 12
  • 4
    It's a [stack cookie](https://en.wikipedia.org/wiki/Buffer_overflow_protection#Canaries) – EOF Nov 08 '16 at 22:38
  • 2
    Also, `fs` being zero doesn't matter, 64 bit segmentation works differently and it isn't a pointer anyway. – Jester Nov 08 '16 at 22:42

0 Answers0