WatchPoint

Image link

Using catchpoints in GDB to inspect program state

Introduction

Hello! Welcome to gdbWatchPoint where we’re looking at GDB tips and tricks to make your debugging life easier.

GDB catchpoints are a nice feature which allows you to intercept certain interesting things that your program might do. Most noticeably when a C++ exception is thrown, asserts, syscalls and signals.

You can start with the docs which are pretty good:

info gdb

But it’s not always easy to search the GDB docs (which is why we’re doing this series).

 

Video Example

If you want to play along with the video, the example I give is:

#include 
int
main(void)
{
  printf("Hello, world!\n");
  printf("That is all, goodbye.\n");
}

The two `printf` calls will result in a write system call, which we can use catchpoints to intercept to listen out for.

Compile it as normal with gcc -g hello.c and run it in gdb:

gdb a.out

In the video, I set a catch point for the syscall write:

catch syscall write

If you run the program with this, each syscall write will pause the execution so you can inspect the state.

New call-to-action

Even More Powerful

To make this more powerful, you can automatically trigger commands when the catchpoint is reached. We do this using `commands`:

(gdb) commands 2
Type commands for breakpoint(s) 2, one per line.
End with a line saying just "end".
> bt
> continue

If you run this, you’ll see a backtrace at each syscall write and then continue, allowing you to see the context within which each write was made.

However, the program will exit which means you can not longer inspect it but we can use catchpoints to prevent this from happening, keeping us in the running program. Add:

catch syscall exit
catch syscall exit_group

And then run.

Now run the program and it will be paused just before it exits allowing you to inspect the state and debug.

 

UDB Time Travel Debugger
Find and fix bugs in minutes  – even C/C++ concurrency issues
Learn more »

Don’t miss my next C++ debugging tutorial: sign up to my WatchPoint mailing list below.
Get tutorials straight to your inbox

Become a GDB Power User. Get Greg’s debugging tips directly in your inbox every 2 weeks.

Want GDB pro tips directly in your inbox?

Share this tutorial