Using GDB to Dump Program State

Sometimes when a program is running for you want to dump the complete state of all the calls stacks of all threads in a program. This is not so easy to do yourself, but thankfully there are tools like GDB, the Gnu Debugger which can do this for you.

The idea is simple. Use a system call to execute a script that will start GDB, run commands to dump all stacks to a file and exit.

Running GDB in Command Mode

The first insight is that GDB can be run in a non-interactive mode where it attaches to a program runs some GDB commands and exits:

/bin/echo -e "set pagination off\nthread apply all backtrace\nquit\n" | 
   gdb --pid 1234 > dump1234.dump 

In the script above we echo the script into GDB. We use echo -e because that will interpret c-style character sequences allowing us to embed newlines.

We could just put these commands into a script file.. but since we want to run this command from within a c++ program, its easier to do it like this than have a separate script file to manage.

Executing it from Within a Program

This will work on any process that the calling process has permission to open. It can be ones own process or some other process that you need a dump of.

void dumpStacks( pid_t pid )
{
   char buf[4096];
   sprintf( buf, 
            "/bin/echo -e \"set pagination off\\nthread apply all \
             backtrace\\nquit\\n\" | gdb --pid %d > dump%d.out",
            pid, pid );
       
   system( buf );
}

Not hard, but very useful.