-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpromptargv_darwin.go
More file actions
75 lines (69 loc) · 1.86 KB
/
Copy pathpromptargv_darwin.go
File metadata and controls
75 lines (69 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package agenthooks
import (
"bytes"
"encoding/binary"
"fmt"
"os"
"golang.org/x/sys/unix"
)
func parentPID() int { return os.Getppid() }
// procArgs reads another process's argv via the kern.procargs2 sysctl (same
// uid only, which is exactly the hook's situation). Layout: int32 argc,
// exec path, NUL padding, then argc NUL-separated argv strings.
func procArgs(pid int) ([]string, error) {
raw, err := unix.SysctlRaw("kern.procargs2", pid)
if err != nil {
return nil, err
}
if len(raw) < 4 {
return nil, fmt.Errorf("agenthooks: short procargs2 for pid %d", pid)
}
argc := int(binary.LittleEndian.Uint32(raw[:4]))
if argc <= 0 {
return nil, fmt.Errorf("agenthooks: invalid argc for pid %d", pid)
}
rest := raw[4:]
// Skip the exec path and its NUL padding.
i := bytes.IndexByte(rest, 0)
if i < 0 {
return nil, fmt.Errorf("agenthooks: malformed procargs2 for pid %d", pid)
}
rest = rest[i:]
for len(rest) > 0 && rest[0] == 0 {
rest = rest[1:]
}
fields := bytes.Split(rest, []byte{0})
args := make([]string, 0, argc)
for _, f := range fields {
if len(args) == argc {
break
}
args = append(args, string(f))
}
if len(args) != argc {
return nil, fmt.Errorf("agenthooks: incomplete procargs2 for pid %d", pid)
}
return args, nil
}
func procExecutable(pid int) (string, error) {
raw, err := unix.SysctlRaw("kern.procargs2", pid)
if err != nil {
return "", err
}
if len(raw) < 4 {
return "", fmt.Errorf("agenthooks: short procargs2 for pid %d", pid)
}
rest := raw[4:]
if i := bytes.IndexByte(rest, 0); i >= 0 {
return string(rest[:i]), nil
}
return "", fmt.Errorf("agenthooks: malformed procargs2 for pid %d", pid)
}
// procPPID reads the parent pid from the process's kinfo_proc.
func procPPID(pid int) (int, error) {
kp, err := unix.SysctlKinfoProc("kern.proc.pid", pid)
if err != nil {
return 0, err
}
return int(kp.Eproc.Ppid), nil
}