Calling GDB (Gnu debugger) within your code.

I spent a lot of time finding the right way to do this, so here is a quick note. For work, I need to debug a small piece of code I wrote. But the main software (closed source) load my library (via dlopen) and run it in a single thread.

That’s fine, but I’m unable to debug this part of the code because I’m unable to place a breakpoint. So I want to place a “break” in my code that’s return back to GDB. (exactly like you can launch the debugger within Python w/ a simple pdb.set_trace().

This is quite easy to do, and really useful but not really popular. The main trick is to call the interrupt number 3. This will rise a SIGTRAP signal in the Linux kernel that GDB can intercept .. so in your code simply add a macro :

#define GDB()  asm("int $0x3")
int main()
{
 int a = 12;
 GDB();
 printf("A ==> %u \n",a);
 return 0;   
}



Call the GDB(); macro in your code, compile it with gcc -g, simply run your program in GDB, and wait for the macro to be called :)

/Enjoy gdb



Related Posts

One thought on “Calling GDB (Gnu debugger) within your code.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>