diff --git a/src/cpu.cpp b/src/cpu.cpp index e56cd67098f..02d41fedeee 100644 --- a/src/cpu.cpp +++ b/src/cpu.cpp @@ -58,7 +58,10 @@ #include // __system_property_get() #include #endif +#include #include +#include +#include #include #include #endif @@ -69,6 +72,7 @@ #include #include #include +#include #include "TargetConditionals.h" #if TARGET_OS_IPHONE #define __IOS__ 1 @@ -183,6 +187,61 @@ static int g_cpu_is_arm_a53_a55; #endif // __aarch64__ #endif // defined __ANDROID__ || defined __linux__ +static bool g_is_being_debugged = false; +static bool is_being_debugged() +{ +#if defined _WIN32 + return IsDebuggerPresent(); +#elif defined __ANDROID__ || defined __linux__ + // https://stackoverflow.com/questions/3596781/how-to-detect-if-the-current-process-is-being-run-by-gdb + int status_fd = open("/proc/self/status", O_RDONLY); + if (status_fd == -1) + return false; + + char buf[4096]; + ssize_t num_read = read(status_fd, buf, sizeof(buf) - 1); + close(status_fd); + + if (num_read <= 0) + return false; + + buf[num_read] = '\0'; + const char tracerPidString[] = "TracerPid:"; + const char* tracer_pid_ptr = strstr(buf, tracerPidString); + if (!tracer_pid_ptr) + return false; + + for (const char* ch = tracer_pid_ptr + sizeof(tracerPidString) - 1; ch <= buf + num_read; ++ch) + { + if (isspace(*ch)) + continue; + + return isdigit(*ch) != 0 && *ch != '0'; + } + + return false; +#elif defined __APPLE__ + // https://stackoverflow.com/questions/2200277/detecting-debugger-on-mac-os-x + struct kinfo_proc info; + info.kp_proc.p_flag = 0; + + int mib[4]; + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); + + size_t size = sizeof(info); + sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); + + return ((info.kp_proc.p_flag & P_TRACED) != 0); +#else + // unknown platform :( + fprintf(stderr, "unknown platform!\n"); + return false; +#endif +} + #if defined _WIN32 static int g_sigill_caught = 0; static jmp_buf g_jmpbuf; @@ -200,6 +259,9 @@ static LONG CALLBACK catch_sigill(struct _EXCEPTION_POINTERS* ExceptionInfo) static int detectisa(const void* some_inst) { + if (g_is_being_debugged) + return 0; + g_sigill_caught = 0; PVOID eh = AddVectoredExceptionHandler(1, catch_sigill); @@ -246,6 +308,9 @@ static void catch_sigill(int /*signo*/, siginfo_t* /*si*/, void* /*data*/) static int detectisa(void (*some_inst)()) { + if (g_is_being_debugged) + return 0; + g_sigill_caught = 0; struct sigaction sa; @@ -1964,6 +2029,8 @@ static void initialize_global_cpu_info() g_powersave = 0; initialize_cpu_thread_affinity_mask(g_cpu_affinity_mask_all, g_cpu_affinity_mask_little, g_cpu_affinity_mask_big); + g_is_being_debugged = is_being_debugged(); + #if defined _WIN32 #if __arm__ g_cpu_support_arm_neon = detectisa(some_neon);