Hi all,
I’ve asked previously how to detect if a process is being run under a debugger (in order to change the execution path if it’s the case).
I’ve now a cross platform solution for this:
static bool runningUnderDebugger();
#ifndef _WIN32
#include <sys/types.h>
#include <sys/ptrace.h>
int underDebugger = 0;
// This works on both linux and MacOSX (and any BSD kernel).
bool runningUnderDebugger()
{
static bool isCheckedAlready = false;
if (!isCheckedAlready)
{
if (ptrace(PTRACE_TRACEME, 0, 1, 0) < 0)
underDebugger = 1;
else ptrace(PTRACE_DETACH, 0, 1, 0);
isCheckedAlready = true;
}
return underDebugger == 1;
}
#else
bool runningUnderDebugger()
{
return IsDebuggerPresent() == TRUE;
}
#endif
The goal of this code is to avoid DEBUG compiled builds to stop with the awful "This program made a … " dialog box (or SIGTRAP) as soon as it encounters an assert when not run under a debugger.
You can use it like this:
#define BreakIfBeingDebugged \
if (runningUnderDebugger()) { __asm__{ int 3 }; /* or assert */ } \
else { /* log the error or whatever, but don't assert */ }
So, if you run your code in Debug mode (-DDEBUG) and not under a debugger, the program will simply ignore the assert (with all bad thing happening through).
If you start your program under GDB or WinDebug, then it’s gonna stop on the int 3 line, in the middle of the bad assertion code (like currently).
The initial idea comes from here.