在Mac OS X上检测调试器

Ali*_*uin 4 c++ debugging macos reverse-engineering process

我试图检测我的进程是否在调试器中运行,而在Windows中有许多解决方案,在Linux中我使用:

ptrace(PTRACE_ME,0,0,0) 
Run Code Online (Sandbox Code Playgroud)

并检查其返回值,我没有设法在Mac OS X上执行相同的基本检查.我试图使用

ptrace(PT_TRACE_ME,0,0,0)
Run Code Online (Sandbox Code Playgroud)

调用但它总是返回0,即使在gdb下运行.

如果我更改了PT_DENY_ATTACH它的请求正确停止调试,但这不是我想要实现的.有任何想法吗?

Pau*_*l R 9

您可以AmIBeingDebugged()Apple Technical Q&A QA1361中调用此功能,该功能在此处转载,因为Apple有时会破坏文档链接并使旧文档很难找到:

#include <assert.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sysctl.h>

static bool AmIBeingDebugged(void)
    // Returns true if the current process is being debugged (either 
    // running under the debugger or has a debugger attached post facto).
{
    int                 junk;
    int                 mib[4];
    struct kinfo_proc   info;
    size_t              size;

    // Initialize the flags so that, if sysctl fails for some bizarre 
    // reason, we get a predictable result.

    info.kp_proc.p_flag = 0;

    // Initialize mib, which tells sysctl the info we want, in this case
    // we're looking for information about a specific process ID.

    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_PID;
    mib[3] = getpid();

    // Call sysctl.

    size = sizeof(info);
    junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
    assert(junk == 0);

    // We're being debugged if the P_TRACED flag is set.

    return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
}
Run Code Online (Sandbox Code Playgroud)