0

In a C++, how can I pause execution and wait for a debugger (e.g. GDB or LLDB) to attach to the process (if it isn't already)?

Some other question suggested raise(SIGTRAP) but that simply breaks into the debugger if it is already attached. I want to pause execution until the debugger attaches.

I also can't really mess around with signals because the my code runs inside a program that installs its own signal handlers.

It only needs to work on Linux.

Timmmm
  • 88,195
  • 71
  • 364
  • 509

1 Answers1

1

Consider this example program:

#include <unistd.h>

volatile int gdb_attached = 0;

int
main ()
{
  while (gdb_attached == 0)
    sleep (1);
  return 0;
}

I compile this then set it running. And here's what I do with GDB:

$ gdb -q -p 253454
Attaching to process 253454
... snip library loading output ...
(gdb) set gdb_attached = 1
(gdb) continue
Continuing.
[Inferior 1 (process 253454) exited normally]
(gdb) 

The set gdb_attached = 1 will allow the inferior to continue past the delay loop. I can also set this before the inferior reaches the delay loop if I attach GDB earlier.

Andrew
  • 3,770
  • 15
  • 22
  • Yeah this is what I was considering. I think it's the best solution. I found some other answers on here that check `/proc/self/status` for a tracer PID, or use various ptrace syscalls, but they all have the same problem - they let you wait until the debugger is attached, but not until it has actually finished initialising. E.g. it still needs to set up breakpoint. This solution doesn't have that problem. – Timmmm Jul 12 '23 at 12:06
  • I agree if you can modify your code, the artificial spin loop is by far the easiest method. But attaching to a process usually stops it, and then the debugger sets all its breakpoints, and only then continues the process. So a "wait till you are traced" shouldn't get to run and return true till the debugger restarts you -after its set breakpoints and whatnot. That's not true if you run the debugger in "no-stop" mode, but should work short of that. – Jim Ingham Jul 12 '23 at 21:25