go-delve_delve/pkg/debugdetect/detect_linux.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

43 lines
982 B
Go

//go:build linux
package debugdetect
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func detectDebuggerAttached() (bool, error) {
// Read /proc/self/status and look for TracerPid field
f, err := os.Open("/proc/self/status")
if err != nil {
return false, fmt.Errorf("failed to read /proc/self/status: %w", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "TracerPid:") {
fields := strings.Fields(line)
if len(fields) < 2 {
return false, fmt.Errorf("malformed TracerPid line in /proc/self/status: %s", line)
}
pid, err := strconv.Atoi(fields[1])
if err != nil {
return false, fmt.Errorf("failed to parse TracerPid value: %w", err)
}
return pid != 0, nil
}
}
if err := scanner.Err(); err != nil {
return false, fmt.Errorf("error reading /proc/self/status: %w", err)
}
return false, fmt.Errorf("TracerPid field not found in /proc/self/status")
}