6

I am using the gdb debugger to run a program that has a loop in it (let's sat of 10). When I get to the loop, I don't want to go into it. I know I can make a second breakpoint after the loop and than do c (continue). But I also remember there is a possibility to do something like n 10 (next 10 times). n 10 doesn't work (gdb doesn't say I've done something wrong, but it doesn't do what I am expecting).

Is it possible to run a command n times?

Hana
  • 535
  • 2
  • 7
  • 17

3 Answers3

12

To perform any gdb command N times, the easiest way is:

(gdb) python [gdb.execute('YOUR_COMMAND') for x in range(N)]

It can be very helpful for your custom gdb commands (see gdb define)

For example,

(gdb) python [gdb.execute('next') for x in range(10)]
(gdb) python [gdb.execute('step') for x in range(5)]
Rohan Ghige
  • 479
  • 5
  • 11
Juraj Michalak
  • 1,138
  • 10
  • 9
8

Do you know the command until?

Try use it to go until line X.

Example:

(gdb) until 123

or

(gdb) u 123

(gdb) help until

Execute until the program reaches a source line greater than the current or a specified location (same args as break command) within the current frame.

Community
  • 1
  • 1
gfleck
  • 223
  • 2
  • 13
2

GDB Python API

You can run a command n times with the GDB Python API if someone really needs it:

class RepeatCmd(gdb.Command):
    """
    Repeat a command n times:
    repeat-cmd <n> <cmd>
    """
    def __init__(self):
        super().__init__(
            'repeat-cmd',
            gdb.COMMAND_NONE,
            gdb.COMPLETE_NONE,
            False
        )
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)
        n = int(args[0])
        cmd = ' '.join(args[1:])
        for i in range(n):
            gdb.execute(cmd)
RepeatCmd()

GitHub upstream.

For the use case, you may also be interested in continue <n>.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985