Search code examples
linuxdebuggingassemblygdbnasm

How do I use gdb to debug a stack segmentation fault?


I wrote this simple program in NASM, I know that Linux ends the program when the stack grows into the program code, but how would I debug such an issue in a real scenario, obviously ignoring the fact that this should never happen.

section .data

section .bss

section .text
global _start
_start:
        nop
        mov eax,42
        SillyLoop:      push eax
                        jmp SillyLoop
        nop

When I run gdb I receive

Continuing.

Program received signal SIGSEGV, Segmentation fault.
SillyLoop () at sandbox.asm:10

This is not very helpful, how do I extract more information (in a real program)?


Solution

  • This is not very helpful, how do I extract more information (in a real program)?

    You can examine the call stack using where command (not going to help here, since there is only one routine on the stack), and examine the current faulting instruction using x/i $pc. Given:

    (gdb) x/i $pc
    => 0x8049006 <SillyLoop>:       push   %eax
    

    you can immediately tell that there is something wrong with the stack (since that's the only reason a PUSH can fail) -- either your ESP has been screwed up, or you've run out of stack. Examining stack pointer with info reg esp (which prints 0xff7fe000) provides another clue: you are on a page boundary.

    But in the end, programming in assembly is like using a very sharp knife -- you need to know what you are doing, or you can write a program that will be hard to debug.