2

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?

Community
  • 1
  • 1
Puppy
  • 144,682
  • 38
  • 256
  • 465

1 Answers1

4

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

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Btw you want to use asm("int3"); not asm("int 3"); . The version with a space will not always be compiled to the correct opcode 0xCC. GCC does compile them to the same, but other compilers may not. – muusbolla Jun 28 '23 at 18:22