Detecting if iOS app is run in debugger

前端 未结 8 1815
北恋
北恋 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 14:05

    Based off an answer in a duplicate thread that was for Objective-C as well and showed how HockeyApp-iOS does it, here's a Swift 5 version:

    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.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!*/, 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
    }()
    

提交回复
热议问题