Detecting if iOS app is run in debugger

前端 未结 8 1855
北恋
北恋 2020-11-27 13:45

I set up my application to either send debugging output to console or a log file. Now, I\'d like to decide with in the code whether

  • it is run in the debugger
8条回答
  •  感动是毒
    2020-11-27 13:58

    There's a function from Apple to detect whether a program is being debugged in the Technical Q&A 1361 (entry in Mac library and entry in iOS library; they are identical).

    Code from the Technical Q&A:

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

    Also pay attention to this note at the end of the Q&A:

    Important: Because the definition of the kinfo_proc structure (in ) is conditionalized by __APPLE_API_UNSTABLE, you should restrict use of the above code to the debug build of your program.

提交回复
热议问题