In our app, we need to detect if the debugger is attached to either allow CrashPad to catch the crash or allow the developer to dive into the wonderful world of debugging in the IDE.
The app runs on both Windows and macOS and 99% of the code is cross-platform.
So, on Windows, there is a WinAPI <IsDebuggerPresent> function.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms680345(v=vs.85).aspx
On a macOS, we have to implement this functionality ourselves.
My colleague wrote something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#ifdef WIN32
#include <windows.h>
#else
bool IsDebuggerPresent()
{
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
struct kinfo_proc info;
info.kp_proc.p_flag = 0;
size_t size = sizeof(info);
sysctl(mib, 4, &info, &size, NULL, 0);
return (info.kp_proc.p_flag & P_TRACED) != 0;
}
#endif
|
As seen from the snippet above, on macOS he defines the <IsDebuggerPresent> function, that is included in windows.h on a Windows platform.
And he calls this functions below in the CPP file like that:
1 2 3 4
|
if (IsDebuggerPresent())
{
// ...
}
|
Personally, I dislike this approach.
I recommended to create a separate function:
1 2 3 4 5 6 7 8 9 10 11 12
|
// debugger_detector.h
bool isDebuggerAttached();
// debugger_detector.cpp
bool isDebuggerAttached()
{
#ifdef WIN32
return IsDebuggerPresent();
#else
// here goes macOS implementation
#endif
}
|
What's your opinion on these approaches?
I think that the latter one is a better design but I don't know if there is a common pattern or approach that describes this. Are you aware of any?
My colleague doesn't disagree with me but he thinks that his implementation is pretty logical and I would like to point him to some document/book/article that would argue that.
Thank you