Something went wrong. Try again.
forked from shirou/gopsutil
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423// SPDX-License-Identifier: BSD-3-Clause//go:build openbsd
package process
import ( "bytes" "context" "encoding/binary" "errors" "fmt" "io" "path/filepath" "sort" "strconv" "strings" "unsafe"
"golang.org/x/sys/unix"
"github.com/shirou/gopsutil/v4/cpu" "github.com/shirou/gopsutil/v4/internal/common" "github.com/shirou/gopsutil/v4/mem" "github.com/shirou/gopsutil/v4/net")
func pidsWithContext(ctx context.Context) ([]int32, error) { var ret []int32 procs, err := ProcessesWithContext(ctx) if err != nil { return ret, nil }
for _, p := range procs { ret = append(ret, p.Pid) }
return ret, nil}
func (p *Process) PpidWithContext(_ context.Context) (int32, error) { k, err := p.getKProc() if err != nil { return 0, err }
return k.Ppid, nil}
func (p *Process) NameWithContext(ctx context.Context) (string, error) { k, err := p.getKProc() if err != nil { return "", err } name := common.IntToString(k.Comm[:])
if len(name) >= 15 { cmdlineSlice, err := p.CmdlineSliceWithContext(ctx) if err != nil { return "", err } if len(cmdlineSlice) > 0 { extendedName := filepath.Base(cmdlineSlice[0]) if strings.HasPrefix(extendedName, p.name) { name = extendedName } } }
return name, nil}
func (p *Process) CwdWithContext(_ context.Context) (string, error) { mib := []int32{CTLKern, KernProcCwd, p.Pid} buf, _, err := common.CallSyscall(mib) if err != nil { return "", err } return common.ByteToString(buf), nil}
func (*Process) ExeWithContext(_ context.Context) (string, error) { return "", common.ErrNotImplementedError}
func (p *Process) CmdlineSliceWithContext(_ context.Context) ([]string, error) { mib := []int32{CTLKern, KernProcArgs, p.Pid, KernProcArgv} buf, _, err := common.CallSyscall(mib) if err != nil { return nil, err }
/* From man sysctl(2): The buffer pointed to by oldp is filled with an array of char pointers followed by the strings themselves. The last char pointer is a NULL pointer. */ var strParts []string if len(buf) == 0 { return strParts, nil } r := bytes.NewReader(buf) baseAddr := uintptr(unsafe.Pointer(&buf[0])) for { argvp, err := readPtr(r) if err != nil { return nil, err } if argvp == 0 { // check for a NULL pointer break } offset := argvp - baseAddr // Reject a malformed/truncated sysctl reply whose pointers fall // outside buf or whose strings are not NUL-terminated, which would // otherwise cause the slice operations below to panic. if offset >= uintptr(len(buf)) { return nil, fmt.Errorf("malformed KERN_PROC_ARGV reply for pid %d: argv pointer out of bounds", p.Pid) } idx := bytes.IndexByte(buf[offset:], 0) if idx < 0 { return nil, fmt.Errorf("malformed KERN_PROC_ARGV reply for pid %d: argv string not NUL-terminated", p.Pid) } length := uintptr(idx) str := string(buf[offset : offset+length]) strParts = append(strParts, str) }
return strParts, nil}
// readPtr reads a pointer data from a given reader. WARNING: only little// endian architectures are supported.func readPtr(r io.Reader) (uintptr, error) { switch sizeofPtr { case 4: var p uint32 if err := binary.Read(r, binary.LittleEndian, &p); err != nil { return 0, err } return uintptr(p), nil case 8: var p uint64 if err := binary.Read(r, binary.LittleEndian, &p); err != nil { return 0, err } return uintptr(p), nil default: return 0, errors.New("unsupported pointer size") }}
func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { argv, err := p.CmdlineSliceWithContext(ctx) if err != nil { return "", err } return strings.Join(argv, " "), nil}
func (*Process) createTimeWithContext(_ context.Context) (int64, error) { return 0, common.ErrNotImplementedError}
func (p *Process) StatusWithContext(_ context.Context) ([]string, error) { k, err := p.getKProc() if err != nil { return []string{""}, err } var s string switch k.Stat { case SIDL: case SRUN: case SONPROC: s = Running case SSLEEP: s = Sleep case SSTOP: s = Stop case SDEAD: s = Zombie }
return []string{s}, nil}
func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details pid := p.Pid out, err := invoke.CommandWithContext(ctx, "ps", "-o", "stat=", "-p", strconv.Itoa(int(pid))) if err != nil { return false, err } return strings.IndexByte(string(out), '+') != -1, nil}
func (p *Process) UidsWithContext(_ context.Context) ([]uint32, error) { k, err := p.getKProc() if err != nil { return nil, err }
uids := make([]uint32, 0, 3)
uids = append(uids, uint32(k.Ruid), uint32(k.Uid), uint32(k.Svuid))
return uids, nil}
func (p *Process) GidsWithContext(_ context.Context) ([]uint32, error) { k, err := p.getKProc() if err != nil { return nil, err }
gids := make([]uint32, 0, 3) gids = append(gids, uint32(k.Rgid), uint32(k.Ngroups), uint32(k.Svgid))
return gids, nil}
func (p *Process) GroupsWithContext(_ context.Context) ([]uint32, error) { k, err := p.getKProc() if err != nil { return nil, err }
groups := make([]uint32, k.Ngroups) for i := int16(0); i < k.Ngroups; i++ { groups[i] = uint32(k.Groups[i]) }
return groups, nil}
func (p *Process) TerminalWithContext(_ context.Context) (string, error) { k, err := p.getKProc() if err != nil { return "", err }
ttyNr := uint64(k.Tdev)
termmap, err := getTerminalMap() if err != nil { return "", err }
return termmap[ttyNr], nil}
func (p *Process) NiceWithContext(_ context.Context) (int32, error) { k, err := p.getKProc() if err != nil { return 0, err } return int32(k.Nice), nil}
func (p *Process) IOCountersWithContext(_ context.Context) (*IOCountersStat, error) { k, err := p.getKProc() if err != nil { return nil, err } return &IOCountersStat{ ReadCount: uint64(k.Uru_inblock), WriteCount: uint64(k.Uru_oublock), }, nil}
func (*Process) NumThreadsWithContext(_ context.Context) (int32, error) { /* not supported, just return 1 */ return 1, nil}
func (p *Process) TimesWithContext(_ context.Context) (*cpu.TimesStat, error) { k, err := p.getKProc() if err != nil { return nil, err } return &cpu.TimesStat{ CPU: "cpu", User: float64(k.Uutime_sec) + float64(k.Uutime_usec)/1000000, System: float64(k.Ustime_sec) + float64(k.Ustime_usec)/1000000, }, nil}
func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { k, err := p.getKProc() if err != nil { return nil, err } pageSize, err := mem.GetPageSizeWithContext(ctx) if err != nil { return nil, err }
return &MemoryInfoStat{ RSS: uint64(k.Vm_rssize) * pageSize, VMS: uint64(k.Vm_tsize) + uint64(k.Vm_dsize) + uint64(k.Vm_ssize), }, nil}
func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { procs, err := ProcessesWithContext(ctx) if err != nil { return nil, nil } ret := make([]*Process, 0, len(procs)) for _, proc := range procs { ppid, err := proc.PpidWithContext(ctx) if err != nil { continue } if ppid == p.Pid { ret = append(ret, proc) } } sort.Slice(ret, func(i, j int) bool { return ret[i].Pid < ret[j].Pid }) return ret, nil}
func (*Process) ConnectionsWithContext(_ context.Context) ([]net.ConnectionStat, error) { return nil, common.ErrNotImplementedError}
func (*Process) ConnectionsMaxWithContext(_ context.Context, _ int) ([]net.ConnectionStat, error) { return nil, common.ErrNotImplementedError}
func ProcessesWithContext(ctx context.Context) ([]*Process, error) { results := []*Process{}
buf, length, err := callKernProcSyscall(KernProcAll, 0) if err != nil { return results, err }
// get kinfo_proc size count := int(length / uint64(sizeOfKinfoProc))
// parse buf to procs for i := 0; i < count; i++ { b := buf[i*sizeOfKinfoProc : (i+1)*sizeOfKinfoProc] k, err := parseKinfoProc(b) if err != nil { continue } p, err := NewProcessWithContext(ctx, int32(k.Pid)) if err != nil { continue }
results = append(results, p) }
return results, nil}
func (*Process) NumFDsWithContext(_ context.Context) (int32, error) { return 0, common.ErrNotImplementedError}
func (*Process) EnvironWithContext(_ context.Context) ([]string, error) { return nil, common.ErrNotImplementedError}
func (p *Process) getKProc() (*KinfoProc, error) { buf, length, err := callKernProcSyscall(KernProcPID, p.Pid) if err != nil { return nil, err } if length != sizeOfKinfoProc { return nil, errors.New("unexpected size of KinfoProc") }
k, err := parseKinfoProc(buf) if err != nil { return nil, err } return &k, nil}
func callKernProcSyscall(op, arg int32) ([]byte, uint64, error) { mib := []int32{CTLKern, KernProc, op, arg, sizeOfKinfoProc, 0} mibptr := unsafe.Pointer(&mib[0]) miblen := uint64(len(mib)) length := uint64(0) _, _, err := unix.Syscall6( unix.SYS___SYSCTL, uintptr(mibptr), uintptr(miblen), 0, uintptr(unsafe.Pointer(&length)), 0, 0) if err != 0 { return nil, length, err } if length == 0 { return nil, 0, errors.New("empty KinfoProc") }
count := int32(length / uint64(sizeOfKinfoProc)) mib = []int32{CTLKern, KernProc, op, arg, sizeOfKinfoProc, count} mibptr = unsafe.Pointer(&mib[0]) miblen = uint64(len(mib)) // get proc info itself buf := make([]byte, length) _, _, err = unix.Syscall6( unix.SYS___SYSCTL, uintptr(mibptr), uintptr(miblen), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&length)), 0, 0) if err != 0 { return buf, length, err }
return buf, length, nil}