在Mac OS X上检测调试器 [英] Detecting debugger on Mac OS X

查看:79
本文介绍了在Mac OS X上检测调试器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to detect whether my process is being run in a debugger or not and, while in Windows there are many solutions and in Linux I use:

ptrace(PTRACE_ME,0,0,0) 

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

and check its return value, I did not manage to perform the same basic check on Mac OS X. I tried to use the

ptrace(PT_TRACE_ME,0,0,0)

调用,但即使在gdb下运行,它也会始终返回0.

call but it always returns 0 even when run under gdb.

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

If I change the request to PT_DENY_ATTACH it correctly stops the debugging but that is not what I want to achieve. Any ideas?

推荐答案

您可以从

You can just call the function AmIBeingDebugged() from Apple Technical Q&A QA1361, which is reproduced here because Apple sometimes breaks documentation links and makes old documentation hard to find:

#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 );
}

这篇关于在Mac OS X上检测调试器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆