检测iOS应用程序是否在调试器中运行

Axe*_*xel 43 iphone debugging objective-c ios

我将应用程序设置为将调试输出发送到控制台或日志文件.现在,我想在代码中决定是否

  • 它在调试器(或模拟器)中运行,因此有一个控制台窗口,我想直接读取输出或如果
  • 没有控制台窗口,因此输出应重定向到文件.

有没有办法确定应用程序是否在调试器中运行?

Dar*_*ust 41

有来自苹果的功能,以检测是否一个程序在被调试技术Q&A 1361(在Mac库条目,并在iOS的库条目,它们是相同的).

技术问答代码:

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

在问答结束时也要注意这个注释:

重要说明:由于kinfo_proc结构(in <sys/sysctl.h>)的定义是以条件为条件的__APPLE_API_UNSTABLE,因此您应该将上述代码的使用限制在程序的调试版本中.

  • 在该文档中有一件我不理解的事情......在代码之后它说:"因为kinfo_proc结构的定义(在<sys/sysctl.h>中)是由__APPLE_API_UNSTABLE条件化的,所以你应该限制使用以上代码到程序的调试版本." 那么......如果我只能在调试版本中包含它,那么代码的重点是什么?如果我只能在调试版本中使用它...这意味着我已经知道我在调试版本中...... (6认同)
  • 问题不在于_build_是否是_debug build_,而是应用程序是否在调试器中运行_.问题已经假设调试构建已经完成并运行,然后只想决定如何处理日志消息.你说得对,说明你不应该在发给客户的发布版本中使用这种技术. (4认同)

Eva*_*van 17

可以指示调试器在启动要调试的进程时设置环境变量.这可以通过转到菜单项Product-> Edit Scheme在Xcode中完成.然后在Debug方案的Arguments选项卡下添加一个新的环境变量.该变量应命名为"debugger",值为"true".然后,可以使用以下代码段来确定调试器是否启动了您的进程:

NSDictionary* env = [NSProcessInfo processInfo].environment;

if ([env[@"debugger"] isEqual:@"true"]) {
    NSLog(@"debugger yes");
}
else {
    NSLog(@"debugger no");
}
Run Code Online (Sandbox Code Playgroud)


Nik*_*uhe 6

总是很高兴有不同的解决方案,所以这是我的两分钱:

我们的想法是检查stderr文件句柄(这是NSLog打印到的地方).至少从iOS 4开始,这个解决方案已经可靠地运行了,并且在iOS 9中一直在模拟器和设备上都这样做.

#import <sys/ioctl.h>
#import <sys/param.h>
#if TARGET_IPHONE_SIMULATOR
    #import <sys/conf.h>
#else
// Not sure why <sys/conf.h> is missing on the iPhoneOS.platform.
// It's there on iPhoneSimulator.platform, though. We need it for D_DISK, only:
    #if ! defined(D_DISK)
        #define D_DISK  2
    #endif
#endif

BOOL isDebuggerAttatchedToConsole(void)
{
    // We use the type of the stderr file descriptor
    // to guess if a debugger is attached.

    int fd = STDERR_FILENO;

    // is the file handle open?
    if (fcntl(fd, F_GETFD, 0) < 0) {
        return NO;
    }

    // get the path of stderr's file handle
    char buf[MAXPATHLEN + 1];
    if (fcntl(fd, F_GETPATH, buf ) >= 0) {
        if (strcmp(buf, "/dev/null") == 0)
            return NO;
        if (strncmp(buf, "/dev/tty", 8) == 0)
            return YES;
    }

    // On the device, without attached Xcode, the type is D_DISK (otherwise it's D_TTY)
    int type;
    if (ioctl(fd, FIODTYPE, &type) < 0) {
        return NO;
    }

    return type != D_DISK;
}
Run Code Online (Sandbox Code Playgroud)


cti*_*tze 6

基于同样适用于 Objective-C的重复线程的答案,并展示了HockeyApp-iOS如何做到这一点,这是一个 Swift 5 版本:

let isDebuggerAttached: Bool = {
    var debuggerIsAttached = false

    var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
    var info: kinfo_proc = kinfo_proc()
    var info_size = MemoryLayout<kinfo_proc>.size

    let success = name.withUnsafeMutableBytes { (nameBytePtr: UnsafeMutableRawBufferPointer) -> Bool in
        guard let nameBytesBlindMemory = nameBytePtr.bindMemory(to: Int32.self).baseAddress else { return false }
        return -1 != sysctl(nameBytesBlindMemory, 4, &info/*UnsafeMutableRawPointer!*/, &info_size/*UnsafeMutablePointer<Int>!*/, nil, 0)
    }

    // The original HockeyApp code checks for this; you could just as well remove these lines:
    if !success {
        debuggerIsAttached = false
    }

    if !debuggerIsAttached && (info.kp_proc.p_flag & P_TRACED) != 0 {
        debuggerIsAttached = true
    }

    return debuggerIsAttached
}()
Run Code Online (Sandbox Code Playgroud)


Siy*_*Ren 5

实际上,最简单的解决方案是

_isDebugging = isatty(STDERR_FILENO);
Run Code Online (Sandbox Code Playgroud)

这与判断应用程序是否在调试器下运行并不完全相同,但是足以(甚至更好)确定日志是否应该写入磁盘。


Joc*_*zer 5

对我来说,这段快速代码非常有效:

func isDebuggerAttached() -> Bool {
    return getppid() != 1
}
Run Code Online (Sandbox Code Playgroud)