68

My program has a segmentation fault problem, but it faults rarely(once in 20 times or more), and to debug it in GDB, I need to manually rerun the program until the segmentation fault occurs (during a half day of reruns only once it fails :( ).

So the questions is, is there any way to tell the GDB to rerun program until some segfault?

Flow
  • 23,572
  • 15
  • 99
  • 156
MKo
  • 4,768
  • 8
  • 32
  • 35

2 Answers2

93

Put a breakpoint at the exit of your program that triggers the run command, and don't forget set pagination off. Information on settings commands is available in the Breakpoint Command Lists section of the gdb documentation. In short:

set pagination off
break _exit
commands
run
end

After the commands line you'll see that the next two lines are being entered as the command to execute when the breakpoint is reached.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
borrible
  • 17,120
  • 7
  • 53
  • 75
  • 12
    Put a breakpoint at exit function, "break exit commands run end" :) – MKo Jul 01 '11 at 10:54
  • This works in my case, but it runs 5 times and then I have to press return to continue, and runs another 5 times. Is this usual? – Javi Jul 23 '14 at 11:48
  • 5
    the answer seems to be "set pagination off" in gdb – fijal Sep 26 '14 at 15:08
  • 1
    What is the equivalent for lldb? – montefuscolo Nov 10 '15 at 21:07
  • I found this for lldb, but it's not a direct replacement https://llvm.org/svn/llvm-project/lldb/trunk/utils/test/run-until-faulted.py. For example, hitting Ctrl-C exits completely. – sourcedelica Sep 01 '17 at 20:41
  • 4
    @montefuscolo This will run and exit if the subprocess exits cleanly, and dump you into an interactive lldb if it segfaults: "lldb -o run -b /path/to/binary -- args args args" so you can wrap it in a shell loop to get the desired effect. "while lldb -o run -b /path/to/binary -- args args args; do sleep 1; done" – Lawrence D'Anna Mar 07 '18 at 21:56
  • Note that the line `commands` is a keyword, not a placeholder for your commands! It is a context-sensitive keyword, so it refers to the last breakpoint that was set during that gdb session. You literally just type `commands` on a line by itself, and gdb magically understands that you want to add commands to the breakpoint. This is *highly* non-intuitive. Fortunately there is a prompt in gdb to guide the remaining steps. – Byron Hawkins May 09 '20 at 09:17
10
(gdb) set pagination off
(gdb) break exit
(gdb) commands
>run
>end
(gdb) run
Oleksandr Kozlov
  • 697
  • 6
  • 11