Search code examples
cgdbsetjmp

How to step through a longjmp in gdb


I'm trying to fix a bug in code someone else wrote, and I'm trying to step though it in gdb to figure out what is going on. But one of the lines I hit is a call to longjmp(), and after hitting "next" on that line gdb continues regular execution rather than breaking on the next source line being executed. Similar continue occurs if I try "step" on the longjmp() line. Is there any gdb command I can use to break on the next source line being executed after longjmp()?


Solution

  • You need to set a breakpoint at the line following a non-zero return code by setjmp.

    For example:

    #include <stdio.h>
    #include <setjmp.h>
    
    jmp_buf jb;
    
    void f1()
    {
        printf("jumping\n");
        longjmp(jb, 1);
        printf("what???\n");
    }
    
    int main()
    {
        if (!setjmp(jb)) {
            printf("calling f1\n");
            f1();
        } else {
            printf("jumped!!\n");    // line 19
        }
        return 0;
    }
    

    After calling longjmp, the next line to be executed is line 19 (see comment). So in this case run break 19 at the gdb prompt and you'll stop at that line after the call to longjmp.

    gdb output:

    (gdb) break 19
    Breakpoint 2 at 0x40056d: file /tmp/x1.c, line 19.
    (gdb) start
    Temporary breakpoint 3 at 0x400549: file /tmp/x1.c, line 15.
    Starting program: /tmp/x1
    warning: no loadable sections found in added symbol-file system-supplied DSO at 0x2aaaaaaab000
    
    Temporary breakpoint 3, main () at /tmp/x1.c:15
    15          if (!setjmp(jb)) {
    (gdb) step
    16              printf("calling f1\n");
    (gdb)
    calling f1
    17              f1();
    (gdb)
    f1 () at /tmp/x1.c:8
    8           printf("jumping\n");
    (gdb)
    jumping
    9           longjmp(jb, 1);
    (gdb)
    
    Breakpoint 2, main () at /tmp/x1.c:19
    19              printf("jumped!!\n");
    (gdb)
    jumped!!
    21          return 0;
    (gdb)
    22      }
    (gdb)
    0x0000003fa441d9f4 in __libc_start_main () from /lib64/libc.so.6
    (gdb)