go-delve_delve/pkg/debugdetect/detect_darwin.go
Derek Parker 57b6496c2e
pkg/debugdetect: add package for detecting debugger attachment (#4258)
* pkg/debugdetect: add package for detecting debugger attachment

Implement new pkg/debugdetect package that detects if a program is
running under a debugger on Linux, macOS, Windows, and FreeBSD.

Platform-specific detection methods:
- Linux: Parse /proc/self/status for TracerPid field
- macOS: Use sysctl with KERN_PROC_PID to check P_TRACED flag
- Windows: Call IsDebuggerPresent() Win32 API
- FreeBSD: Try sysctl first, fall back to /proc/curproc/status

Fixes #4243

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-16 10:34:01 +01:00

42 lines
765 B
Go

package debugdetect
import (
"fmt"
"os"
"unsafe"
"golang.org/x/sys/unix"
)
const (
// P_TRACED flag from sys/proc.h
pTracedFlag = 0x00000800
// sysctl constants from sys/sysctl.h
kernProc = 14 // KERN_PROC
kernProcPID = 1 // KERN_PROC_PID
)
func detectDebuggerAttached() (bool, error) {
var info unix.KinfoProc
mib := [4]int32{unix.CTL_KERN, kernProc, kernProcPID, int32(os.Getpid())}
size := uintptr(unsafe.Sizeof(info))
_, _, errno := unix.Syscall6(
unix.SYS___SYSCTL,
uintptr(unsafe.Pointer(&mib[0])),
uintptr(len(mib)),
uintptr(unsafe.Pointer(&info)),
uintptr(unsafe.Pointer(&size)),
0,
0,
)
if errno != 0 {
return false, fmt.Errorf("sysctl failed: %w", errno)
}
return (info.Proc.P_flag & pTracedFlag) != 0, nil
}