Puppy
Puppy

Reputation: 146940

Portable equivalent of __debugbreak

I've written some code using __debugbreak() on Windows, and I'd like to support other compilers, so I'm looking to create a more portable version of this function (Clang and GCC).

I've rejected using inline assembler for now because it does not provide a target-independent means of specifying a debug break. I've also looked at __builtin_trap() but apparently it doesn't really permit for example step in/step over afterwards and that kind of thing. I've also looked at this question but the accepted answer doesn't actually specify the bit that I'm looking for- the bit that goes in the "...".

I've also seen some patches for Clang about supporting this, but apparently Clang still rejected code containing __debugbreak().

Any suggestions?

Upvotes: 3

Views: 4111

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129374

I can confirm that __builtin_trap() does not give you the right type of breakpoint to continue in gcc. It gives an illegal opcode trap, which doesn't allow the code to continue at all - if you do next in gdb, it just exits with a SIGILL, which isn't particularly beneficial if you actually wanted to be able to continue.

As far as I can see, the only solution is to use inline assembler. I tried using an int 3 in a "hello, world" program, and although gdb didn't recognise the breakpoint, it did stop at the instruction, and I was able to continue after the break.

#include <stdio.h>

#define BREAKPOINT \
    asm("int $3")

int main()
{

    BREAKPOINT;

    printf("Hello, world!\n");
    return 0;
}

(Compiled with both gcc and clang on Linux x86_64, both 32 and 64 bit mode)

I did find this blog: http://mainisusuallyafunction.blogspot.co.uk/2012/01/embedding-gdb-breakpoints-in-c-source.html

but it requires a script to parse the executable file (and may not work under Windows at all).

Upvotes: 5

Related Questions