Based on Apple's recommended method as described in http://developer.apple.com/qa/qa2004/qa1361.html
| 57 | // Based on Apple's recommended method as described in |
| 58 | // http://developer.apple.com/qa/qa2004/qa1361.html |
| 59 | bool BeingDebugged() { |
| 60 | // NOTE: This code MUST be async-signal safe (it's used by in-process |
| 61 | // stack dumping signal handler). NO malloc or stdio is allowed here. |
| 62 | // |
| 63 | // While some code used below may be async-signal unsafe, note how |
| 64 | // the result is cached (see |is_set| and |being_debugged| static variables |
| 65 | // right below). If this code is properly warmed-up early |
| 66 | // in the start-up process, it should be safe to use later. |
| 67 | |
| 68 | // If the process is sandboxed then we can't use the sysctl, so cache the |
| 69 | // value. |
| 70 | static bool is_set = false; |
| 71 | static bool being_debugged = false; |
| 72 | |
| 73 | if (is_set) |
| 74 | return being_debugged; |
| 75 | |
| 76 | // Initialize mib, which tells sysctl what info we want. In this case, |
| 77 | // we're looking for information about a specific process ID. |
| 78 | int mib[] = { |
| 79 | CTL_KERN, |
| 80 | KERN_PROC, |
| 81 | KERN_PROC_PID, |
| 82 | getpid() |
| 83 | #if defined(OS_OPENBSD) |
| 84 | , sizeof(struct kinfo_proc), |
| 85 | 0 |
| 86 | #endif |
| 87 | }; |
| 88 | |
| 89 | // Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and |
| 90 | // binary interfaces may change. |
| 91 | struct kinfo_proc info; |
| 92 | size_t info_size = sizeof(info); |
| 93 | |
| 94 | #if defined(OS_OPENBSD) |
| 95 | if (sysctl(mib, arraysize(mib), NULL, &info_size, NULL, 0) < 0) |
| 96 | return -1; |
| 97 | |
| 98 | mib[5] = (info_size / sizeof(struct kinfo_proc)); |
| 99 | #endif |
| 100 | |
| 101 | int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0); |
| 102 | DCHECK_EQ(sysctl_result, 0); |
| 103 | if (sysctl_result != 0) { |
| 104 | is_set = true; |
| 105 | being_debugged = false; |
| 106 | return being_debugged; |
| 107 | } |
| 108 | |
| 109 | // This process is being debugged if the P_TRACED flag is set. |
| 110 | is_set = true; |
| 111 | #if defined(OS_FREEBSD) |
| 112 | being_debugged = (info.ki_flag & P_TRACED) != 0; |
| 113 | #elif defined(OS_BSD) |
| 114 | being_debugged = (info.p_flag & P_TRACED) != 0; |
| 115 | #else |
| 116 | being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0; |
no test coverage detected