segmentation fault with .text .data and main (main in .data section)

后端 未结 2 531
遇见更好的自我
遇见更好的自我 2020-12-19 20:50

I\'m just trying to load the value of myarray[0] to eax:

        .text
        .data

        # define an array of 3 words
array_wo         


        
相关标签:
2条回答
  • 2020-12-19 20:59

    It seems the label main is in the .data section.

    It leads to a segmentation fault on systems that doesn't allow to execute code in the .data section. (Most modern systems map .data with read + write but not exec permission.)

    Program code should be in the .text section. (Read + exec)

    Surprisingly, on GNU/Linux systems, hand-written asm often results in an executable .data unless you're careful to avoid that, so this is often not the real problem: See Why data and stack segments are executable? But putting code in .text where it belongs can make some debugging tools work better.


    Also you need to ret from main or call exit (or make an _exit system call) so execution doesn't fall off the end of main into whatever bytes come next. See What happens if there is no exit system call in an assembly program?

    0 讨论(0)
  • 2020-12-19 21:10

    You need to properly terminate your program, e.g. on Linux x86_64 by calling the sys_exit system call:

    ...
    main:
         # assign array_words[0] to eax
         mov $0, %edi
         lea array_words(,%edi,4), %eax
    
         mov $60, %rax       # System-call "sys_exit"
         mov $0, %rdi        # exit code 0
         syscall
    

    Otherwise program execution continues with the memory contents following your last instruction, which are most likely in all cases invalid instructions (or even invalid memory locations).

    0 讨论(0)
提交回复
热议问题