11

Quick one this time.

Is it possible (other than pressing enter forever) for gdb to continually next through a program line by line to find where a bug is happening?

Edit: continue isn't what I would like; I would like to see effectively the complete program execution, line by line, as you would get from nexting over and over.

2
  • 4
    How is gdb supposed to know when it hits the bug? What changes? Commented Apr 28, 2011 at 0:59
  • 1
    Frankly, it segfaults :)
    – Bolster
    Commented Apr 28, 2011 at 1:30

6 Answers 6

13

Here's something's that's such a hack I'm a bit embarrassed to post it. But if you need just a one-off, it might do well enough to let you get the information you want. There really should be a better way.

You can define a stupid little gdb script that executes the step or next command a certain number of times:

# file: step_mult.gdb

define step_mult
    set $step_mult_max = 1000
    if $argc >= 1
        set $step_mult_max = $arg0
    end

    set $step_mult_count = 0
    while ($step_mult_count < $step_mult_max)
        set $step_mult_count = $step_mult_count + 1
        printf "step #%d\n", $step_mult_count
        step
    end
end

(I used step instead of next for no particularly good reason; just change it to whatever you need.)

Then you can run that command (with an optional count), and it'll display each step or next nicely.

Here's a sample program that'll crash when it tries to dereference a NULL pointer:

#include<stdio.h>

int x[] = {
    0, 1, 2, 3, 4, 5, 6, 7, 8,9, 10 
};

int* p[11];

int main()
{
    int i;

    for (i = 0; i < 11; ++i) {
        p[i] = &x[i];
    }

    p[5] = 0;

    for (i = 0; i < 11; ++i) {
        printf( "*p[%d] == %d\n", i, *p[i]);
    }

    return 0;
}

Here's a gdb session (on Windows) debugging that program and using the step_mult script:

C:\temp>gdb test.exe
GNU gdb (GDB) 7.2
...
Reading symbols from C:\temp/test.exe...done.

(gdb) source c:/temp/step_mult.gdb
(gdb) start

Temporary breakpoint 1 at 0x401385: file C:\temp\test.c, line 23.
Starting program: C:\temp/test.exe
[New Thread 5396.0x1638]

Temporary breakpoint 1, main () at C:\temp\test.c:23
23          for (i = 0; i < 11; ++i) {

(gdb) step_mult 70

step #1
24              p[i] = &x[i];
step #2
23          for (i = 0; i < 11; ++i) {
step #3
24              p[i] = &x[i];
step #4
23          for (i = 0; i < 11; ++i) {
step #5
24              p[i] = &x[i];
step #6
23          for (i = 0; i < 11; ++i) {
step #7
24              p[i] = &x[i];
step #8
23          for (i = 0; i < 11; ++i) {
step #9
24              p[i] = &x[i];
step #10
23          for (i = 0; i < 11; ++i) {
step #11
24              p[i] = &x[i];
step #12
23          for (i = 0; i < 11; ++i) {
step #13
24              p[i] = &x[i];
step #14
23          for (i = 0; i < 11; ++i) {
step #15
24              p[i] = &x[i];
step #16
23          for (i = 0; i < 11; ++i) {
step #17
24              p[i] = &x[i];
step #18
23          for (i = 0; i < 11; ++i) {
step #19
24              p[i] = &x[i];
step #20
23          for (i = 0; i < 11; ++i) {
step #21
24              p[i] = &x[i];
step #22
23          for (i = 0; i < 11; ++i) {
step #23
27          p[5] = 0;
step #24
29          for (i = 0; i < 11; ++i) {
step #25
30              printf( "*p[%d] == %d\n", i, *p[i]);
step #26
*p[0] == 0
29          for (i = 0; i < 11; ++i) {
step #27
30              printf( "*p[%d] == %d\n", i, *p[i]);
step #28
*p[1] == 1
29          for (i = 0; i < 11; ++i) {
step #29
30              printf( "*p[%d] == %d\n", i, *p[i]);
step #30
*p[2] == 2
29          for (i = 0; i < 11; ++i) {
step #31
30              printf( "*p[%d] == %d\n", i, *p[i]);
step #32
*p[3] == 3
29          for (i = 0; i < 11; ++i) {
step #33
30              printf( "*p[%d] == %d\n", i, *p[i]);
step #34
*p[4] == 4
29          for (i = 0; i < 11; ++i) {
step #35
30              printf( "*p[%d] == %d\n", i, *p[i]);
step #36

Program received signal SIGSEGV, Segmentation fault.
0x004013d2 in main () at C:\temp\test.c:30
30              printf( "*p[%d] == %d\n", i, *p[i]);
step #37

Program received signal SIGSEGV, Segmentation fault.
0x004013d2 in main () at C:\temp\test.c:30
30              printf( "*p[%d] == %d\n", i, *p[i]);
step #38

Program exited with code 030000000005.
step #39
The program is not being run.
(gdb)

Unfortunately, since the script doesn't stop when the segfault happens, gdb decides to simply stop debugging the program, so you can't make any further useful inquiries. But the log might still be useful.

I'm sure there are numerous ways one might make the script more intelligent. Unfortunately, I have no idea how to do that, and the user level docs for GDB don't seem too helpful for those details. The best way would be if the script could detect the segfault or signal had happened and just stop then instead of relying on some arbitrary count. I imagine the gdb/MI interface, or probably even the Python scripting interface might have a good mechanism, but I don't know anything about those.

After your first run you could use the count displayed (37 in my example) and restart the program and give a count that's just shy of where it crashed before and take control manually.

Like I said, it's not particularly pretty - but it might get you there.

3
0

You can use continue or c to continue execution to the next breakpoint.

Also see Run an Application in GDB Until an Exception Occurs (StackOverflow) on how to set a "catchpoint", which will break execution when an exception is thrown.

0

See also this post: c - GDB auto stepping - automatic printout of lines, while free running?, which uses python interface for gdb.

0

Actually, I have a Github repo with a Python-GDB extension, which does exactly the same thing as You have described, but with some more functionality.

You can just clone the repo:

git clone https://github.com/Viaceslavus/gdb-debug-until.git

and feed the python script to GDB with the following command inside GDB:

source ../gdb-debug-until/debug_until.py

(change python script path is needed)

This extension expects a starting breakpoint, from where debugging will run, and an event, that should be tracked. For example if you want to catch the moment, when some variable contains unexpected value, you can run the following command inside GDB:

debug-until main --args="" --var-eq="may_var:-1"

So:

  • the starting breakpoint here is the 'main' function.
  • "--args" parameter specifies the arguments that should be passed to your program when running.
  • And "--var-eq" is an event that will be tracked, when the variable called 'my_var' will contain the value -1. When an event will be triggered you will receive some pretty message in the terminal.

All in all, the command above will start debugging in the 'main' function and run through each line of your code until the specified event triggers.

Actually, there are some more events that may be handled by this script, for more info see:
https://github.com/Viaceslavus/gdb-debug-until

0

When the program segfaults then GDB will by default stop (like with many other signals) you so are able to check the backtrace and the state, for example by changing the frame N and then print vars.

If you want to issue next until something happens then the python api can help (needs a python enabled GDB, but most support that nowadays, and if you're debugging "embedded" or in other cases where this does not work one can often use gdbserver on the system to be debugged and use remote-debugging from GDB with a "fat pc" (that is then current, python enabled and likely supports multiple targets [you can eve remote-debug from win32 to GNU/Linux). The following code implements the auto-next feature:

import gdb
import time

class CmdAutoNext (gdb.Command):
    """Auto-Next through the code until something happens or manually interrupted.
An argument says how often `next` is done (1-19, default 5)."""
    def __init__(self):
        print('Registering command auto-next')
        super(CmdAutoNext, self).__init__("auto-next", gdb.COMMAND_RUNNING)
        gdb.events.stop.connect(stop_handler_auto_next)
    def invoke(self, argument, from_tty):

        number = 5 # optional: use a parameter for the default
        if argument:
            if not argument.isdigit():
                raise gdb.GdbError("argument must be a digit, not " + argument)
            number = int(argument)
            if number == 0 or number > 19:
                raise gdb.GdbError("argument must be a digit between 1 and 19")

        sleep_time = 3.0 / (number * 1.4)
        try:
            frame = gdb.newest_frame()
        except gdb.error:
            raise gdb.GdbError("No stack.")

        global last_stop_was_simple
        last_stop_was_simple = True

        pagination = gdb.execute("show pagination", False, True).find("on")
        if pagination:
            gdb.execute("set pagination off", False, False)
        
        try:
            while (last_stop_was_simple):
                gdb.execute ("next")
                time.sleep(sleep_time)
        except KeyboardInterrupt as ki:
            if pagination:
                gdb.execute("set pagination on", False, False)
        except gdb.GdbError as user_error:
            if pagination:
                gdb.execute("set pagination on", False, False)
            # pass user errors unchanged
            raise user_error
        except:
            if pagination:
                gdb.execute("set pagination on", False, False)
            traceback.print_exc()

def stop_handler_auto_next(event):
    # check the type of stop, the following is the common one after step/next,
    # a more complex one would be a subclass (for example breakpoint or signal)
    global last_stop_was_simple
    last_stop_was_simple = type(event) is gdb.StopEvent

CmdAutoNext()

You can place that in a gdb-auto-next.py which can be made active with source gdb-auto-next.py whenever you want that (or include in the .gdbinit file to make it always available).

Explanation of the code:

  • defines a user command (with additional argument to say how fast to auto-step)
  • possibly to add: define a parameter for the default (replaced here for simplicity by a fixed value)
  • loop "next" commands within python, handle the "expected" keyboard interrupt of CTRL-C
  • register a stop event handler that checks for the stop reason and store the kind of step there
  • adjust the while loop to stop for a "not simple" stop (breakpoint/watchpoint/signal/...) - if you really want it to ignore watchpoints or other scenarios you could tweak the stop-handler

See https://stackoverflow.com/a/67470615/5027456 for a more complete (and updated) code including a parameter for the speed, both auto-next and auto-step and better error handling.

-1

The continue command will run until either a breakpoint occurs, the app causes an exception (ie. crash) or the app terminates.

1
  • 2
    or until you Ctrl+C (which pauses the execution)
    – Lie Ryan
    Commented May 1, 2011 at 2:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.