0

I am trying to write data to space reserved in the .bss section of my code (NASM/Linux x64). Why do I get segmentation fault in this small code sample?

section .bss
  big_space: resb 80         ; reserve 80 bytes

section .text

global _start

_start:
  mov rbx, [rel big_space]   ; I use rel here otherwise I get linking error
  mov [rbx], byte 'H'        ; if I comment this, no segfault

  mov rax, 60                ; exits with code 0
  mov rdi, 0
  syscall

Isn't the address of big_space supposed to be reserved for my program? As far as I understand, the problematic instruction is trying to copy 'H' (as an 8-bit value) to the address in RBX. This address, as per the first instruction, I expect to be the address of my buffer big_space. What went wrong?

Xito Dev
  • 89
  • 7
  • 3
    Shouldn't it be `lea rbx, [rel big_space]` ? – Michael May 20 '20 at 08:38
  • You are right! This worked. I am still curious as to how can I get the relative address of `big_space` into a register using `mov`. I think `mov rbx, rel big_space` doesn't work, nor does `mov eax, qword rel big_space`. – Xito Dev May 20 '20 at 08:42
  • 1
    AFAIK the `rel` specifier is only for effective addresses (something that appears between `[]`). – Michael May 20 '20 at 08:49
  • 1
    @XitoDev To load an address, use `lea` (load effective address). `mov` is not the right instruction here. – fuz May 20 '20 at 11:56
  • 1
    *how can I get the relative address of big_space into a register using mov* - `mov reg, immediate` needs the absolute address as an immediate so that can't work. You could also load the correct absolute address from the GOT, if the dynamic linker created a GOT entry for it, like `mov rbx, [rel big_space wrt.. got]` or something (AT&T would be `mov big_space@GOTPCREL(%rip), %rbx`) https://godbolt.org/z/kUuQes. You're addressing the GOT entry in a PC-relative way, but still loading an absolute address that has to have been calculated / stored ahead of time. – Peter Cordes May 20 '20 at 19:15

0 Answers0