0

I recently programmed a simple Assembly program, which opened a SDL2 Window.

Now I'm tying to implement a close function by using the SDL_WaitEvent Function.

I am using this script to compile:

clear
gcc -c pong.S -o pong.o
gcc pong.o -lSDL2 -nostdlib -e main -o pong -I /usr/local/include -L /usr/local/lib
./pong

And this is the Assembly Code:

    .section    .rodata

windowTitle:    .string "Window"
window:     .zero   8
event:      .zero   56

.text

.globl main
main:


    #Init SDL
    mov $62001, %edi
    call    SDL_Init@PLT


    #Create WIndow
    movq    windowTitle(%rip), %rdi
    movl    $4, %r9d
    movl    $600, %r8d
    movl    $800, %ecx
    movl    $100, %edx
    movl    $100, %esi
    movq    %rax, %rdi
    call    SDL_CreateWindow
    movq    %rax, window(%rip)

loop:

    leaq    event(%rip), %rdi
    call    SDL_WaitEvent@PLT
    movl    event(%rip), %eax
    cmpl    $256, %eax
    jne loop    


end:
    ret 

Can anyone explain to me, why there is coming this Segmentation Fault error?

I am using 64 bit Mx-Linux an the gcc version 10.2.1.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 3
    Use a debugger to pinpoint the fault. Depending on where you crash, note that you can't use `ret` to exit a process. Also you do not ensure stack alignment. Furthermore SDL certainly requires the C library so you should really not use `-nostdlib`. Most importantly do not put `window` and `event` into read-only section. – Jester Dec 05 '21 at 19:40
  • It's generally bad style to call your process entry point `main` instead of the normal `_start`. It's *not* a `main` function; it's not called with a return address, or args in normal places. – Peter Cordes Dec 06 '21 at 00:17
  • More importantly in this case, RSP % 16 == 0 at the process entry point, rather than == 8 on entry to a function. So it actually *is* safe to call functions without moving RSP first, without violating the ABI ([Why does the x86-64 / AMD64 System V ABI mandate a 16 byte stack alignment?](https://stackoverflow.com/q/49391001)). If you change to not using `-nostartfiles` and using an actual main, you'll need to change your code. – Peter Cordes Dec 06 '21 at 00:17
  • @Jester, how do I not put them in a read only Section? And how do I exit the process correctly. It is crashing at SDL_WaitEvent. – Dawxtreme Dec 06 '21 at 13:49
  • `.section .rodata` specifically says "read-only data". Use `.section .data` at least for the `window` and the `event`. You exit by invoking the exit system call, or you can simply build using `gcc pong.o -lSDL2 -o pong -I /usr/local/include -L /usr/local/lib ./pong` and then you can keep your `ret` (recommended) but need to align the stack e.g. by a `push %rbp` (at `main`) / `pop %rbp` (before the `ret`) pair. – Jester Dec 06 '21 at 13:54

0 Answers0