v2 / vlib / os / debugger_linux.c.v
45 lines · 40 sloc · 1.06 KB · 09cc0c5133d075ee6dcff29286dce7eb7d4421da
Raw
1module os
2
3#include <sys/ptrace.h>
4
5fn C.ptrace(u32, u32, voidptr, voidptr) u64
6
7// debugger_present returns a bool indicating if the process is being debugged.
8pub fn debugger_present() bool {
9 $if cross ? {
10 return false
11 }
12 $if !cross ? {
13 $if linux {
14 // check if a child process could trace its parent process,
15 // if not a debugger must be present
16 pid := fork()
17 if pid == 0 {
18 ppid := getppid()
19 if C.ptrace(C.PTRACE_ATTACH, ppid, 0, 0) == 0 {
20 C.waitpid(ppid, 0, 0)
21
22 // detach ptrace, otherwise further checks would indicate a debugger is present (ptrace is the Debugger then)
23 C.ptrace(C.PTRACE_DETACH, ppid, 0, 0)
24
25 // no external debugger
26 exit(0)
27 } else {
28 // an error occurred, a external debugger must be present
29 exit(1)
30 }
31 } else {
32 mut status := 0
33 // wait until the child process dies
34 C.waitpid(pid, &status, 0)
35 // check the exit code of the child process check
36 if posix_wait_status_exit_code(status) == 0 {
37 return false
38 } else {
39 return true
40 }
41 }
42 }
43 }
44 return false
45}
46