Search code examples
assemblyx86segmentation-faultnasmsections

Segfault when storing reg to var in section .DATA


So I am trying to write some code using x86 and I can't seem to get it to move contents of a register to a spot in memory.

The code is just this

global  main

SECTION .DATA
  var_i: DD  0

SECTION .TEXT
    main:
      push  DWORD 4
      pop   EAX
      mov   [var_i], EAX

    mov   EAX,  0
    ret

I am using nasm and gcc on the code. The problem I am having is that whenever I try to move to the spot in memory it segfaults


Solution

  • What kind of system/object format are you using? I'm guessing you're using ELF on Linux or Unix, as that would explain your problem:

    Section names in ELF are case sensitive, and most ELF-based OS's the special sections .text and .data are understood, but your sections .TEXT and .DATA have no meaning. As a result, they just get stuck into the executable after the other sections and get the same access permissions. If you're just linking the above code, that will be after the .fini section, so it will executable and read-only. So when you try to write to the variable, you get a segfault.

    Change your code to use .data and .text as section names and it should work.