Thursday, January 19, 2012

Embedding GDB breakpoints in C source code

Have you ever wanted to embed GDB breakpoints in C source code?

int main() {
return 0;

One way is to directly insert your CPU's breakpoint instruction. On x86:

#define EMBED_BREAKPOINT  asm volatile ("int3;")

There are at least two problems with this approach:

  • They aren't real GDB breakpoints. You can't disable them, count how many times they've been hit, etc.

  • If you run the program outside GDB, the breakpoint instruction will crash your process.

Here is a small hack which solves both problems:

    asm("0:"                              \
        ".pushsection embed-breakpoints;" \
        ".quad 0b;"                       \

We place a local label into the instruction stream, and then save its address in the embed-breakpoints linker section.

Then we need to convert these addresses into GDB breakpoint commands. I wrote a tool that does this, as a wrapper for the gdb command. Here's how it works, on our initial example:

$ gcc -g -o example example.c

$ ./gdb-with-breakpoints ./example
Reading symbols from example...done.
Breakpoint 1 at 0x4004f2: file example.c, line 8.
Breakpoint 2 at 0x4004fc: file example.c, line 10.
(gdb) run
Starting program: example 

Breakpoint 1, main () at example.c:8
8           printf("world!\n");
(gdb) info breakpoints
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004f2 in main at example.c:8
        breakpoint already hit 1 time
2       breakpoint     keep y   0x00000000004004fc in main at example.c:10

If we run the program normally, or in GDB without the wrapper, the EMBED_BREAKPOINT statements do nothing. The breakpoint addresses aren't even loaded into memory, because the embed-breakpoints section is not marked as allocatable.

You can find all of the code on GitHub under a BSD license. I've done only minimal testing, but I hope it will be a useful debugging tool for someone. Let me know if you find any bugs or improvements. You can comment here, or find my email address on GitHub.

I'm not sure about the decision to write the GDB wrapper in C using BFD. I also considered Haskell and elf, or Python and the new pyelftools. One can probably do something nicer using the GDB Python API, which was added a few years ago.

This code depends on a GNU toolchain: it uses GNU C extensions, GNU assembler syntax, and BFD. The GDB wrapper uses the Linux proc filesystem, so that it can pass to GDB a temporary file which has already been unlinked. You could port it to other UNIX systems by changing the tempfile handling. It should work on a variety of CPU architectures, but I've only tested it on 32- and 64-bit x86.


  1. call me a moron, but why would you want to put gdb breakpoints into the source code?

    1. This is how ASSERT works

    2. You can put complex if statements and other exploration of state to trigger the breakpoint.

    3. I thought gdb conditional breakpoints could inspect the state already, though.

    4. beeing able to put gdb breakpoint in the code can be useful when, in between runs you loose the debugging configuration, which is sometimes the case when you do embedded development (the device reboots, communication link goes down, gdb ide loose connection're done).
      Personally I would be very glad to see the equivalent for ARM, ST20, ST40 and boadcom chips...

    5. I am using asm("bkpt;"); to break on ARM architecture, but for some reason GDB cannot continue after this occurs. It says it cannot access the memory any more.

  2. Another technique I've seen, admittedly a bit more convoluted, is to redefine assert like the following (only relevant portions shown):

    #define assert(EXPR)\
    if (!(EXPR)) {\
    if (isatty(STDIN_FILENO)) {\
    cerr << "PID: " << getpid() << endl;\
    char c;\

    Basically, if you're running the program from a tty, upon assertion failure, the program outputs the PID and then waits for a single keystroke before aborting. At this point, the developer has a chance to fire up gdb, "attach" to the given PID. Once attached, you can then navigate the call stack, etc.

  3. Using pyelftools and the GDB Python API, I implemented the functionality of gdb-with-breakpoints.c a new "break-embed" GDB command here:

  4. How about

    #define EMBED_BREAKPOINT bp()
    void bp(void) {}

    Then when you start gdb, do this:

    (gdb) b bp

    1. This won't work while running with O[1/2/3] - GCC will omit all calls to bp

    2. Using something like this will prevent the function call from being optimised away (gcc):

      __attribute__((noinline)) void __brk(void) { asm (""); }

  5. How about: gdb -ex 'break example.c:8' -ex 'break example.c:10' -ex run ./example

  6. Or: gdb -x GDB_commands_file ./example

  7. Hi, Keegan!

    I’m the web editor at iMasters, one of the largest developer communities in Brazil. I´d like to talk to you about republishing your article at our site. Can you contact me at

    Rina Noronha
    Journalist – web editor
    +55 27 3327-0320 / +55 27 9973-0700

  8. I've used "sleep" routines in code: when the program hits that, it sleeps and you can attach gdb at that point. very useful for those programs that fork/exec and you typically need to step through the child.

    ifdef it out when you are done.

  9. It would be great if there was a standard way to do this throughout the GCC toolchain.

    Techniques that require you to set breakpoints are usable but not helpful for others who won't know where to set them.

    Here's an example of an assert implementation I recently did:

    For GUI app debug builds, I usually override assert to pop a dialog, but that doesn't necessarily catch assertions within library code.

    As I said, it would be great if this was fully supported through GCC toolchain !
    Hope that's helpful,
    Best Regards, Dave

  10. Good day! It was so amazing to visit your personal blog and in particularly to read this blog post. In addition to that I would like to ask you a question that is very intriguing for me. Did you try guest blogging?

  11. Nice article, thanks for the information. It's very complete information. I will bookmark for next reference
    jaring futsal | jaring golf | jaring pengaman proyek |
    jaring pengaman bangunan | jaring pengaman gedung


    telas mosquiteira
    telas mosquiteiro

    As telas mosquiteira sp , telas mosquiteiro sp garantem ar puro por toda casa livrando-a completamente dos mosquitos e insetos indesejáveis. As telas mosquiteira garantem um sono tranquilo a toda família, livrando e protegendo-nas dos mais diversos insetos. Muitos destes insetos são transmissores de doenças e a tela mosquiteira é indispensável no combate a mosquitos transmissores de doenças.

    A dengue, por exemplo, já matou centenas de pessoas só na capital de São Paulo e um pequeno investimento em nossas telas mosquiteiras podem salvar vidas. As telas mosquiteiras também impedem a entrada de insetos peçonhentos como as aranhas e os escorpiões, estes insetos também oferecem risco, pois seu veneno em poucos minutos podem levar uma criança a morte.
    telas mosquiteira jundiai
    telas mosquiteiro jundiai
    telas mosquiteira São Paulo
    telas mosquiteiro São Paulo
    telas mosquiteira granja viana
    telas mosquiteiro granja vinana
    telas mosquiteira cotia
    telas mosquiteiro cotia
    telas mosquiteira sao paulo
    telas mosquiteiro sao paulo

    A chegada da temporada Primavera/Verão traz consigo a elevação da temperatura e a maior ocorrência de chuvas. Mas não é só isso. As estações mais quentes do ano causam muita dor de cabeça e muitos zumbidos indesejáveis em função das pragas urbanas – pernilongos, baratas, cupins e outros insetos -, que afetam todas as regiões brasileiras.

    Nossa missão é oferecer telas mosquiteiras de qualidade a um preço acessível, fazendo com que as telas mosquiteiras sejam uma opção viável para muitas pessoas.

    telas mosquiteiras Jundiaí
    telas mosquiteiro Jundiai
    telas mosquiteiras jundiai
    telas mosquiteiro industria
    telas mosquiteira restaurante
    telas mosquiteiro restaurante
    telas mosquiteira empresa
    telas mosquiteiro empresa

  13. I am glad to find out that Embedding GDB breakpoints in C source code is not as complicated as i always thought, and i can say that you have created a very interesting post, and i would like to view more of this dome other time. With a Maroon Embossed Wallpaper, your house or office will get a very classy and beautiful appearance. You can easily get one, just by clicking on the link provided.

  14. This comment has been removed by the author.

  15. May be useful for all, helpful article once and pardon me permission to share also here :

    Cara Menyembuhkan Kista Payudara Secara Alami

  16. mpl mod apk download unlimited money, mpl ryzo mod apk download, mpl mod apk latest version download, mpl pro apk mod, mpl pro 1.0.21 mod apk download, mpl new mod apk, mpl mod apk version 1.0.37, mod apk download mpl, mpl mod apk 1.0.30, mpl pro mod apk 1.0 38, mpl pro ryzo mod apk download, mpl mod apk 2019 free download, mpl pro mod apk 2019, mpl app mod apk download, mpl gsg mod apk, mpl mod apk unlimited token apk download, mpl mod apk unlimited cash, nova mpl mod apk download link

    mpl mod apk


    mpl app mod apk, mpl mod apk revdl, mpl mod apk download unlimited money, mpl pro mod apk v1.0.49 , mpl mod apk latest version, mpl mod apk download, mpl v1.0.49 mod apk, mpl mod apk v1.0.49 , mpl mod apk v1.0.49 , mpl jd mod apk download, mpl pro mod apk new version, mpl mod apk v1.0.49 , mpl pro mod apk download, mpl v1.0.49 mod apk, what is mpl mod apk, mpl mod version apk download, mpl pro mod apk v1.0.49 , mpl mod apk download unlimited token, mpl pro mod apk fruit chop,

    ppl mod apk


    Pokemon Go Mod Apk


    tinder plus free apk


  17. When it comes to proper dental care, regular visits to seasoned dental clinics like 1728 Dental’s Jurong East Dental Clinic won’t always suffice. Undoubtedly, routine visits to 1728 Dental’s Jurong East Dental Clinic would prove futile if you don’t practice the right oral habits on a consistent basis. Visit Now

  18. this is great blog and your content is amazing also check slotomania free coins links

  19. So Today we are here with the new and the latest version of Pokemon Go Mod Apk pokemon go mod apk 2019
    pokemon go mod apk joystick download
    ,pokemon go mod apk 0.135.1
    ,pokemon go mod apk latest version
    ,pokemon go mod apk with joystick download latest version
    ,pokemon go mod apk all pokemon unlocked
    ,pokemon go mod apk april 2019
    ,pokemon go mod apk anti ban
    ,pokemon go mod apk joystick
    ,pokemon go mod apk 2018
    ,pokemon go mod apk unlimited coins
    ,pokemon go mod apk download for android
    ,pokemon go mod apk download unlimited coins
    ,pokemon go mod apk bot
    ,pokemon go mod apk pokeball
    ,pokemon go mod apk unlimited pokeball,Fake Gps By which you can easily catch any pokemon in the game and you can also unlock the gyms without moving from one place to another and this will be really fun to play.

    Depending on the degree of Gun Shot Strike Mod Apk Unlimited Money on Apksetting has many mod apk, Free apk new games mod, free mod apk new mod apk and these mods are 100% free apk setting and AI, you will encounter a number of obstacles.

  20. Do you Play Slotomania Slot Machines? Join our members share free bonus, tips, guides & valid cheats or tricks if found working.
    slotomaniafreebies is a Fan Site and is not endorsed by or affiliated with Slotomania Slot Machine.

  21. Great thing. Awesome details you have discussed also check this