| 1 | // Copyright 2013 The Flutter Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "flutter/testing/debugger_detection.h" |
| 6 | |
| 7 | #include "flutter/fml/build_config.h" |
| 8 | #include "flutter/fml/logging.h" |
| 9 | |
| 10 | #if FML_OS_MACOSX |
| 11 | #include <assert.h> |
| 12 | #include <stdbool.h> |
| 13 | #include <sys/sysctl.h> |
| 14 | #include <sys/types.h> |
| 15 | #include <unistd.h> |
| 16 | #endif // FML_OS_MACOSX |
| 17 | |
| 18 | #if FML_OS_WIN |
| 19 | #include <windows.h> |
| 20 | #endif // FML_OS_WIN |
| 21 | |
| 22 | namespace flutter { |
| 23 | namespace testing { |
| 24 | |
| 25 | DebuggerStatus GetDebuggerStatus() { |
| 26 | #if FML_OS_MACOSX |
| 27 | // From Technical Q&A QA1361 Detecting the Debugger |
| 28 | // https://developer.apple.com/library/archive/qa/qa1361/_index.html |
| 29 | int management_info_base[4]; |
| 30 | struct kinfo_proc info; |
| 31 | size_t size; |
| 32 | |
| 33 | // Initialize the flags so that, if sysctl fails for some bizarre |
| 34 | // reason, we get a predictable result. |
| 35 | info.kp_proc.p_flag = 0; |
| 36 | |
| 37 | // Initialize management_info_base, which tells sysctl the info we want, in |
| 38 | // this case we're looking for information about a specific process ID. |
| 39 | management_info_base[0] = CTL_KERN; |
| 40 | management_info_base[1] = KERN_PROC; |
| 41 | management_info_base[2] = KERN_PROC_PID; |
| 42 | management_info_base[3] = getpid(); |
| 43 | |
| 44 | // Call sysctl. |
| 45 | |
| 46 | size = sizeof(info); |
| 47 | auto status = |
| 48 | ::sysctl(management_info_base, |
| 49 | sizeof(management_info_base) / sizeof(*management_info_base), |
| 50 | &info, &size, NULL, 0); |
| 51 | FML_CHECK(status == 0); |
| 52 | |
| 53 | // We're being debugged if the P_TRACED flag is set. |
| 54 | return ((info.kp_proc.p_flag & P_TRACED) != 0) ? DebuggerStatus::kAttached |
| 55 | : DebuggerStatus::kDontKnow; |
| 56 | |
| 57 | #elif FML_OS_WIN |
| 58 | return ::IsDebuggerPresent() ? DebuggerStatus::kAttached |
| 59 | : DebuggerStatus::kDontKnow; |
| 60 | |
| 61 | #else |
| 62 | return DebuggerStatus::kDontKnow; |
| 63 | #endif |
| 64 | } // namespace testing |
| 65 | |
| 66 | } // namespace testing |
| 67 | } // namespace flutter |
| 68 | |