GDB catchpoints

Written by Dr Greg Law | Last updated 31st May 2020

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).

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

#include <stdio.h>
  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.

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.

Don't miss my next GDB tutorial: sign up to the gdbWatchPoint 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.
Related content
  • Concurrency Defects Resolution
    New techniques to help quickly find and resolve defects in multithreaded and multiprocess applications
    Download the technical paper

A dedicated resource to learn about debugging in GDB by industry leader in debugging and founder of Undo

Meet Greg