2021-12-23 05:54:41 +08:00
|
|
|
//go:build darwin
|
2014-08-08 22:09:28 +08:00
|
|
|
// +build darwin
|
|
|
|
|
2014-12-30 21:09:05 +08:00
|
|
|
package common
|
2014-08-08 22:09:28 +08:00
|
|
|
|
|
|
|
import (
|
2018-03-31 20:35:53 +08:00
|
|
|
"context"
|
2016-02-17 15:29:35 +08:00
|
|
|
"os"
|
2014-08-08 22:09:28 +08:00
|
|
|
"os/exec"
|
|
|
|
"strings"
|
2015-03-01 21:29:37 +08:00
|
|
|
"unsafe"
|
2017-06-03 04:51:00 +08:00
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
2014-08-08 22:09:28 +08:00
|
|
|
)
|
|
|
|
|
2018-03-31 20:35:53 +08:00
|
|
|
func DoSysctrlWithContext(ctx context.Context, mib string) ([]string, error) {
|
2022-03-05 00:18:03 +08:00
|
|
|
cmd := exec.CommandContext(ctx, "sysctl", "-n", mib)
|
2017-08-17 06:32:21 +08:00
|
|
|
cmd.Env = getSysctrlEnv(os.Environ())
|
|
|
|
out, err := cmd.Output()
|
2014-08-08 22:09:28 +08:00
|
|
|
if err != nil {
|
|
|
|
return []string{}, err
|
|
|
|
}
|
|
|
|
v := strings.Replace(string(out), "{ ", "", 1)
|
|
|
|
v = strings.Replace(string(v), " }", "", 1)
|
|
|
|
values := strings.Fields(string(v))
|
|
|
|
|
|
|
|
return values, nil
|
|
|
|
}
|
2015-03-01 21:29:37 +08:00
|
|
|
|
|
|
|
func CallSyscall(mib []int32) ([]byte, uint64, error) {
|
|
|
|
miblen := uint64(len(mib))
|
|
|
|
|
|
|
|
// get required buffer size
|
|
|
|
length := uint64(0)
|
2017-06-03 04:51:00 +08:00
|
|
|
_, _, err := unix.Syscall6(
|
2020-09-08 02:24:18 +08:00
|
|
|
202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146
|
2015-03-01 21:29:37 +08:00
|
|
|
uintptr(unsafe.Pointer(&mib[0])),
|
|
|
|
uintptr(miblen),
|
|
|
|
0,
|
|
|
|
uintptr(unsafe.Pointer(&length)),
|
|
|
|
0,
|
|
|
|
0)
|
|
|
|
if err != 0 {
|
|
|
|
var b []byte
|
|
|
|
return b, length, err
|
|
|
|
}
|
|
|
|
if length == 0 {
|
|
|
|
var b []byte
|
|
|
|
return b, length, err
|
|
|
|
}
|
|
|
|
// get proc info itself
|
|
|
|
buf := make([]byte, length)
|
2017-06-03 04:51:00 +08:00
|
|
|
_, _, err = unix.Syscall6(
|
2020-09-08 02:24:18 +08:00
|
|
|
202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146
|
2015-03-01 21:29:37 +08:00
|
|
|
uintptr(unsafe.Pointer(&mib[0])),
|
|
|
|
uintptr(miblen),
|
|
|
|
uintptr(unsafe.Pointer(&buf[0])),
|
|
|
|
uintptr(unsafe.Pointer(&length)),
|
|
|
|
0,
|
|
|
|
0)
|
|
|
|
if err != 0 {
|
|
|
|
return buf, length, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return buf, length, nil
|
|
|
|
}
|