chore: enable gocritic linter

pull/1813/head
Matthieu MOREL 2 months ago
parent 92e037d58c
commit dfdd90ab72

@ -8,6 +8,7 @@ linters:
- durationcheck - durationcheck
- errorlint - errorlint
- gci - gci
- gocritic
- gofmt - gofmt
- gofumpt - gofumpt
- goimports - goimports
@ -38,6 +39,9 @@ linters-settings:
- standard - standard
- default - default
- prefix(github.com/shirou) - prefix(github.com/shirou)
gocritic:
disabled-checks:
- captLocal
gomodguard: gomodguard:
blocked: blocked:
modules: modules:

@ -105,14 +105,15 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
ret := InfoStat{} ret := InfoStat{}
for _, line := range strings.Split(string(out), "\n") { for _, line := range strings.Split(string(out), "\n") {
if strings.HasPrefix(line, "Number Of Processors:") { switch {
case strings.HasPrefix(line, "Number Of Processors:"):
p := strings.Fields(line) p := strings.Fields(line)
if len(p) > 3 { if len(p) > 3 {
if t, err := strconv.ParseUint(p[3], 10, 64); err == nil { if t, err := strconv.ParseUint(p[3], 10, 64); err == nil {
ret.Cores = int32(t) ret.Cores = int32(t)
} }
} }
} else if strings.HasPrefix(line, "Processor Clock Speed:") { case strings.HasPrefix(line, "Processor Clock Speed:"):
p := strings.Fields(line) p := strings.Fields(line)
if len(p) > 4 { if len(p) > 4 {
if t, err := strconv.ParseFloat(p[3], 64); err == nil { if t, err := strconv.ParseFloat(p[3], 64); err == nil {
@ -128,13 +129,12 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
} }
} }
} }
break case strings.HasPrefix(line, "System Model:"):
} else if strings.HasPrefix(line, "System Model:") {
p := strings.Split(string(line), ":") p := strings.Split(string(line), ":")
if p != nil { if p != nil {
ret.VendorID = strings.TrimSpace(p[1]) ret.VendorID = strings.TrimSpace(p[1])
} }
} else if strings.HasPrefix(line, "Processor Type:") { case strings.HasPrefix(line, "Processor Type:"):
p := strings.Split(string(line), ":") p := strings.Split(string(line), ":")
if p != nil { if p != nil {
c := strings.Split(string(p[1]), "_") c := strings.Split(string(p[1]), "_")

@ -157,7 +157,7 @@ func finishCPUInfo(ctx context.Context, c *InfoStat) {
} }
c.Mhz = value / 1000.0 // value is in kHz c.Mhz = value / 1000.0 // value is in kHz
if c.Mhz > 9999 { if c.Mhz > 9999 {
c.Mhz = c.Mhz / 1000.0 // value in Hz c.Mhz /= 1000.0 // value in Hz
} }
} }

@ -81,7 +81,7 @@ func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot parse iowait: %w", err) return nil, fmt.Errorf("cannot parse iowait: %w", err)
} }
//not sure how this translates, don't report, add to kernel, something else? // not sure how this translates, don't report, add to kernel, something else?
/*case "swap": /*case "swap":
swap[cpuNumber], err = strconv.ParseFloat(fields[4], 64) swap[cpuNumber], err = strconv.ParseFloat(fields[4], 64)
if err != nil { if err != nil {

@ -34,7 +34,7 @@ func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
ret := "" ret := ""
// Kind of inefficient, but it works // Kind of inefficient, but it works
lines := strings.Split(string(out[:]), "\n") lines := strings.Split(string(out), "\n")
for line := 1; line < len(lines); line++ { for line := 1; line < len(lines); line++ {
v := strings.TrimSpace(lines[line]) v := strings.TrimSpace(lines[line])
if strings.HasPrefix(v, "Serial Number...............") { if strings.HasPrefix(v, "Serial Number...............") {

@ -98,7 +98,7 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
return &UsageStat{}, common.ErrNotImplementedError return &UsageStat{}, common.ErrNotImplementedError
} }
hf := strings.Fields(strings.Replace(lines[0], "Mounted on", "Path", -1)) // headers hf := strings.Fields(strings.ReplaceAll(lines[0], "Mounted on", "Path")) // headers
for line := 1; line < len(lines); line++ { for line := 1; line < len(lines); line++ {
fs := strings.Fields(lines[line]) // values fs := strings.Fields(lines[line]) // values
for i, header := range hf { for i, header := range hf {
@ -137,7 +137,7 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
return nil, err return nil, err
} }
case `%Used`: case `%Used`:
val, err := strconv.ParseInt(strings.Replace(fs[i], "%", "", -1), 10, 32) val, err := strconv.ParseInt(strings.ReplaceAll(fs[i], "%", ""), 10, 32)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -153,7 +153,7 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
return nil, err return nil, err
} }
case `%Iused`: case `%Iused`:
val, err := strconv.ParseInt(strings.Replace(fs[i], "%", "", -1), 10, 32) val, err := strconv.ParseInt(strings.ReplaceAll(fs[i], "%", ""), 10, 32)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -178,7 +178,7 @@ func GetMountFSTypeWithContext(ctx context.Context, mp string) (string, error) {
} }
// Kind of inefficient, but it works // Kind of inefficient, but it works
lines := strings.Split(string(out[:]), "\n") lines := strings.Split(string(out), "\n")
for line := 1; line < len(lines); line++ { for line := 1; line < len(lines); line++ {
fields := strings.Fields(lines[line]) fields := strings.Fields(lines[line])
if strings.TrimSpace(fields[0]) == mp { if strings.TrimSpace(fields[0]) == mp {

@ -24,7 +24,7 @@ func HostIDWithContext(ctx context.Context) (string, error) {
} }
// The command always returns an extra newline, so we make use of Split() to get only the first line // The command always returns an extra newline, so we make use of Split() to get only the first line
return strings.Split(string(out[:]), "\n")[0], nil return strings.Split(string(out), "\n")[0], nil
} }
func numProcs(_ context.Context) (uint64, error) { func numProcs(_ context.Context) (uint64, error) {
@ -41,7 +41,7 @@ func BootTimeWithContext(ctx context.Context) (btime uint64, err error) {
return 0, errors.New("uptime was not set, so cannot calculate boot time from it") return 0, errors.New("uptime was not set, so cannot calculate boot time from it")
} }
ut = ut * 60 ut *= 60
return timeSince(ut), nil return timeSince(ut), nil
} }
@ -59,7 +59,7 @@ func UptimeWithContext(ctx context.Context) (uint64, error) {
return 0, err return 0, err
} }
return parseUptime(string(out[:])), nil return parseUptime(string(out)), nil
} }
func parseUptime(uptime string) uint64 { func parseUptime(uptime string) uint64 {
@ -166,17 +166,17 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil
if err != nil { if err != nil {
return "", "", "", err return "", "", "", err
} }
platform = strings.TrimRight(string(out[:]), "\n") platform = strings.TrimRight(string(out), "\n")
// Set the family // Set the family
family = strings.TrimRight(string(out[:]), "\n") family = strings.TrimRight(string(out), "\n")
// Set the version // Set the version
out, err = invoke.CommandWithContext(ctx, "oslevel") out, err = invoke.CommandWithContext(ctx, "oslevel")
if err != nil { if err != nil {
return "", "", "", err return "", "", "", err
} }
version = strings.TrimRight(string(out[:]), "\n") version = strings.TrimRight(string(out), "\n")
return platform, family, version, nil return platform, family, version, nil
} }
@ -186,7 +186,7 @@ func KernelVersionWithContext(ctx context.Context) (version string, err error) {
if err != nil { if err != nil {
return "", err return "", err
} }
version = strings.TrimRight(string(out[:]), "\n") version = strings.TrimRight(string(out), "\n")
return version, nil return version, nil
} }
@ -196,7 +196,7 @@ func KernelArch() (arch string, err error) {
if err != nil { if err != nil {
return "", err return "", err
} }
arch = strings.TrimRight(string(out[:]), "\n") arch = strings.TrimRight(string(out), "\n")
return arch, nil return arch, nil
} }

@ -176,45 +176,47 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil
lsb = &lsbStruct{} lsb = &lsbStruct{}
} }
if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "oracle-release")) { switch {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "oracle-release")):
platform = "oracle" platform = "oracle"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "oracle-release")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "oracle-release"))
if err == nil { if err == nil {
version = getRedhatishVersion(contents) version = getRedhatishVersion(contents)
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "enterprise-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "enterprise-release")):
platform = "oracle" platform = "oracle"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "enterprise-release")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "enterprise-release"))
if err == nil { if err == nil {
version = getRedhatishVersion(contents) version = getRedhatishVersion(contents)
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "slackware-version")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "slackware-version")):
platform = "slackware" platform = "slackware"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "slackware-version")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "slackware-version"))
if err == nil { if err == nil {
version = getSlackwareVersion(contents) version = getSlackwareVersion(contents)
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "debian_version")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "debian_version")):
if lsb.ID == "Ubuntu" { switch lsb.ID {
case "Ubuntu":
platform = "ubuntu" platform = "ubuntu"
version = lsb.Release version = lsb.Release
} else if lsb.ID == "LinuxMint" { case "LinuxMint":
platform = "linuxmint" platform = "linuxmint"
version = lsb.Release version = lsb.Release
} else if lsb.ID == "Kylin" { case "Kylin":
platform = "Kylin" platform = "Kylin"
version = lsb.Release version = lsb.Release
} else if lsb.ID == `"Cumulus Linux"` { case `"Cumulus Linux"`:
platform = "cumuluslinux" platform = "cumuluslinux"
version = lsb.Release version = lsb.Release
} else if lsb.ID == "uos" { case "uos":
platform = "uos" platform = "uos"
version = lsb.Release version = lsb.Release
} else if lsb.ID == "Deepin" { case "Deepin":
platform = "Deepin" platform = "Deepin"
version = lsb.Release version = lsb.Release
} else { default:
if common.PathExistsWithContents("/usr/bin/raspi-config") { if common.PathExistsWithContents("/usr/bin/raspi-config") {
platform = "raspbian" platform = "raspbian"
} else { } else {
@ -225,65 +227,65 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil
version = contents[0] version = contents[0]
} }
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "neokylin-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "neokylin-release")):
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "neokylin-release")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "neokylin-release"))
if err == nil { if err == nil {
version = getRedhatishVersion(contents) version = getRedhatishVersion(contents)
platform = getRedhatishPlatform(contents) platform = getRedhatishPlatform(contents)
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "redhat-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "redhat-release")):
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "redhat-release")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "redhat-release"))
if err == nil { if err == nil {
version = getRedhatishVersion(contents) version = getRedhatishVersion(contents)
platform = getRedhatishPlatform(contents) platform = getRedhatishPlatform(contents)
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "system-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "system-release")):
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "system-release")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "system-release"))
if err == nil { if err == nil {
version = getRedhatishVersion(contents) version = getRedhatishVersion(contents)
platform = getRedhatishPlatform(contents) platform = getRedhatishPlatform(contents)
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "gentoo-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "gentoo-release")):
platform = "gentoo" platform = "gentoo"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "gentoo-release")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "gentoo-release"))
if err == nil { if err == nil {
version = getRedhatishVersion(contents) version = getRedhatishVersion(contents)
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "SuSE-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "SuSE-release")):
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "SuSE-release")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "SuSE-release"))
if err == nil { if err == nil {
version = getSuseVersion(contents) version = getSuseVersion(contents)
platform = getSusePlatform(contents) platform = getSusePlatform(contents)
} }
// TODO: slackware detecion // TODO: slackware detecion
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "arch-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "arch-release")):
platform = "arch" platform = "arch"
version = lsb.Release version = lsb.Release
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "alpine-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "alpine-release")):
platform = "alpine" platform = "alpine"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "alpine-release")) contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "alpine-release"))
if err == nil && len(contents) > 0 && contents[0] != "" { if err == nil && len(contents) > 0 && contents[0] != "" {
version = contents[0] version = contents[0]
} }
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "os-release")) { case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "os-release")):
p, v, err := common.GetOSReleaseWithContext(ctx) p, v, err := common.GetOSReleaseWithContext(ctx)
if err == nil { if err == nil {
platform = p platform = p
version = v version = v
} }
} else if lsb.ID == "RedHat" { case lsb.ID == "RedHat":
platform = "redhat" platform = "redhat"
version = lsb.Release version = lsb.Release
} else if lsb.ID == "Amazon" { case lsb.ID == "Amazon":
platform = "amazon" platform = "amazon"
version = lsb.Release version = lsb.Release
} else if lsb.ID == "ScientificSL" { case lsb.ID == "ScientificSL":
platform = "scientific" platform = "scientific"
version = lsb.Release version = lsb.Release
} else if lsb.ID == "XenServer" { case lsb.ID == "XenServer":
platform = "xenserver" platform = "xenserver"
version = lsb.Release version = lsb.Release
} else if lsb.ID != "" { case lsb.ID != "":
platform = strings.ToLower(lsb.ID) platform = strings.ToLower(lsb.ID)
version = lsb.Release version = lsb.Release
} }

@ -174,14 +174,14 @@ func platformInformation() (platform, family, version, displayVersion string, er
if err != nil { if err != nil {
return //nolint:nakedret //FIXME return //nolint:nakedret //FIXME
} }
platform = windows.UTF16ToString(regBuf[:]) platform = windows.UTF16ToString(regBuf)
if strings.Contains(platform, "Windows 10") { // check build number to determine whether it's actually Windows 11 if strings.Contains(platform, "Windows 10") { // check build number to determine whether it's actually Windows 11
err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CurrentBuildNumber`), nil, &valType, nil, &bufLen) err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CurrentBuildNumber`), nil, &valType, nil, &bufLen)
if err == nil { if err == nil {
regBuf = make([]uint16, bufLen/2+1) regBuf = make([]uint16, bufLen/2+1)
err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CurrentBuildNumber`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen) err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CurrentBuildNumber`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen)
if err == nil { if err == nil {
buildNumberStr := windows.UTF16ToString(regBuf[:]) buildNumberStr := windows.UTF16ToString(regBuf)
if buildNumber, err := strconv.ParseInt(buildNumberStr, 10, 32); err == nil && buildNumber >= 22000 { if buildNumber, err := strconv.ParseInt(buildNumberStr, 10, 32); err == nil && buildNumber >= 22000 {
platform = strings.Replace(platform, "Windows 10", "Windows 11", 1) platform = strings.Replace(platform, "Windows 10", "Windows 11", 1)
} }
@ -196,7 +196,7 @@ func platformInformation() (platform, family, version, displayVersion string, er
regBuf = make([]uint16, bufLen/2+1) regBuf = make([]uint16, bufLen/2+1)
err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CSDVersion`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen) err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CSDVersion`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen)
if err == nil { if err == nil {
platform += " " + windows.UTF16ToString(regBuf[:]) platform += " " + windows.UTF16ToString(regBuf)
} }
} }
@ -213,7 +213,7 @@ func platformInformation() (platform, family, version, displayVersion string, er
if err == nil { if err == nil {
regBuf := make([]uint16, bufLen/2+1) regBuf := make([]uint16, bufLen/2+1)
err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`DisplayVersion`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen) err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`DisplayVersion`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen)
displayVersion = windows.UTF16ToString(regBuf[:]) displayVersion = windows.UTF16ToString(regBuf)
} }
// PlatformFamily // PlatformFamily

@ -196,19 +196,20 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filename) { if PathExists(filename) {
contents, err := ReadLines(filename) contents, err := ReadLines(filename)
if err == nil { if err == nil {
if StringsContains(contents, "kvm") { switch {
case StringsContains(contents, "kvm"):
system = "kvm" system = "kvm"
role = "host" role = "host"
} else if StringsContains(contents, "hv_util") { case StringsContains(contents, "hv_util"):
system = "hyperv" system = "hyperv"
role = "guest" role = "guest"
} else if StringsContains(contents, "vboxdrv") { case StringsContains(contents, "vboxdrv"):
system = "vbox" system = "vbox"
role = "host" role = "host"
} else if StringsContains(contents, "vboxguest") { case StringsContains(contents, "vboxguest"):
system = "vbox" system = "vbox"
role = "guest" role = "guest"
} else if StringsContains(contents, "vmware") { case StringsContains(contents, "vmware"):
system = "vmware" system = "vmware"
role = "guest" role = "guest"
} }
@ -273,16 +274,17 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "self", "cgroup")) { if PathExists(filepath.Join(filename, "self", "cgroup")) {
contents, err := ReadLines(filepath.Join(filename, "self", "cgroup")) contents, err := ReadLines(filepath.Join(filename, "self", "cgroup"))
if err == nil { if err == nil {
if StringsContains(contents, "lxc") { switch {
case StringsContains(contents, "lxc"):
system = "lxc" system = "lxc"
role = "guest" role = "guest"
} else if StringsContains(contents, "docker") { case StringsContains(contents, "docker"):
system = "docker" system = "docker"
role = "guest" role = "guest"
} else if StringsContains(contents, "machine-rkt") { case StringsContains(contents, "machine-rkt"):
system = "rkt" system = "rkt"
role = "guest" role = "guest"
} else if PathExists("/usr/bin/lxc-version") { case PathExists("/usr/bin/lxc-version"):
system = "lxc" system = "lxc"
role = "host" role = "host"
} }

@ -233,7 +233,7 @@ func ConvertDOSPath(p string) string {
ret, _, _ := procQueryDosDeviceW.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(szDeviceName))), ret, _, _ := procQueryDosDeviceW.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(szDeviceName))),
uintptr(unsafe.Pointer(&szTarget[0])), uintptr(unsafe.Pointer(&szTarget[0])),
uintptr(len(szTarget))) uintptr(len(szTarget)))
if ret != 0 && windows.UTF16ToString(szTarget[:]) == rawDrive { if ret != 0 && windows.UTF16ToString(szTarget) == rawDrive {
return filepath.Join(szDeviceName, p[len(rawDrive):]) return filepath.Join(szDeviceName, p[len(rawDrive):])
} }
} }

@ -139,7 +139,8 @@ func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
// first, try to parse with version 2 // first, try to parse with version 2
xsw := (*xswdev)(unsafe.Pointer(&buf[0])) xsw := (*xswdev)(unsafe.Pointer(&buf[0]))
if xsw.Version == XSWDEV_VERSION11 { switch {
case xsw.Version == XSWDEV_VERSION11:
// this is version 1, so try to parse again // this is version 1, so try to parse again
xsw := (*xswdev11)(unsafe.Pointer(&buf[0])) xsw := (*xswdev11)(unsafe.Pointer(&buf[0]))
if xsw.Version != XSWDEV_VERSION11 { if xsw.Version != XSWDEV_VERSION11 {
@ -147,9 +148,9 @@ func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
} }
s.Total += uint64(xsw.NBlks) s.Total += uint64(xsw.NBlks)
s.Used += uint64(xsw.Used) s.Used += uint64(xsw.Used)
} else if xsw.Version != XSWDEV_VERSION { case xsw.Version != XSWDEV_VERSION:
return nil, errors.New("xswdev version mismatch") return nil, errors.New("xswdev version mismatch")
} else { default:
s.Total += uint64(xsw.NBlks) s.Total += uint64(xsw.NBlks)
s.Used += uint64(xsw.Used) s.Used += uint64(xsw.Used)
} }

@ -50,7 +50,7 @@ func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *ExVir
} }
key := strings.TrimSpace(fields[0]) key := strings.TrimSpace(fields[0])
value := strings.TrimSpace(fields[1]) value := strings.TrimSpace(fields[1])
value = strings.Replace(value, " kB", "", -1) value = strings.ReplaceAll(value, " kB", "")
switch key { switch key {
case "MemTotal": case "MemTotal":

@ -193,7 +193,8 @@ func parseNetstatA(output string, kind string) ([]ConnectionStat, error) {
continue continue
} }
if strings.HasPrefix(fields[0], "f1") { switch {
case strings.HasPrefix(fields[0], "f1"):
// Unix lines // Unix lines
if len(fields) < 2 { if len(fields) < 2 {
// every unix connections have two lines // every unix connections have two lines
@ -207,7 +208,7 @@ func parseNetstatA(output string, kind string) ([]ConnectionStat, error) {
ret = append(ret, c) ret = append(ret, c)
} else if strings.HasPrefix(fields[0], "tcp") || strings.HasPrefix(fields[0], "udp") { case strings.HasPrefix(fields[0], "tcp") || strings.HasPrefix(fields[0], "udp"):
// Inet lines // Inet lines
if !hasCorrectInetProto(kind, fields[0]) { if !hasCorrectInetProto(kind, fields[0]) {
continue continue
@ -225,7 +226,7 @@ func parseNetstatA(output string, kind string) ([]ConnectionStat, error) {
} }
ret = append(ret, c) ret = append(ret, c)
} else { default:
// Header lines // Header lines
continue continue
} }

@ -269,13 +269,11 @@ func (p *Process) PercentWithContext(ctx context.Context, interval time.Duration
if err != nil { if err != nil {
return 0, err return 0, err
} }
} else { } else if p.lastCPUTimes == nil {
if p.lastCPUTimes == nil { // invoked first time
// invoked first time p.lastCPUTimes = cpuTimes
p.lastCPUTimes = cpuTimes p.lastCPUTime = now
p.lastCPUTime = now return 0, nil
return 0, nil
}
} }
numcpu := runtime.NumCPU() numcpu := runtime.NumCPU()

@ -240,11 +240,12 @@ func (p *Process) getKProc() (*unix.KinfoProc, error) {
// If passed arg pid is 0, get information from all process. // If passed arg pid is 0, get information from all process.
func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption bool, nameOption bool) ([][]string, error) { func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption bool, nameOption bool) ([][]string, error) {
var cmd []string var cmd []string
if pid == 0 { // will get from all processes. switch {
case pid == 0: // will get from all processes.
cmd = []string{"-ax", "-o", arg} cmd = []string{"-ax", "-o", arg}
} else if threadOption { case threadOption:
cmd = []string{"-x", "-o", arg, "-M", "-p", strconv.Itoa(int(pid))} cmd = []string{"-x", "-o", arg, "-M", "-p", strconv.Itoa(int(pid))}
} else { default:
cmd = []string{"-x", "-o", arg, "-p", strconv.Itoa(int(pid))} cmd = []string{"-x", "-o", arg, "-p", strconv.Itoa(int(pid))}
} }
if nameOption { if nameOption {
@ -394,7 +395,7 @@ func (p *Process) cmdlineSlice() ([]string, error) {
// are the arguments. Everything else in the slice is then the environment // are the arguments. Everything else in the slice is then the environment
// of the process. // of the process.
for _, arg := range args[1:] { for _, arg := range args[1:] {
argStr = string(arg[:]) argStr = string(arg)
if len(argStr) > 0 { if len(argStr) > 0 {
if nargs > 0 { if nargs > 0 {
argSlice = append(argSlice, argStr) argSlice = append(argSlice, argStr)

@ -71,7 +71,7 @@ func getTerminalMap() (map[uint64]string, error) {
return nil, err return nil, err
} }
rdev := uint64(stat.Rdev) rdev := uint64(stat.Rdev)
ret[rdev] = strings.Replace(name, "/dev", "", -1) ret[rdev] = strings.ReplaceAll(name, "/dev", "")
} }
return ret, nil return ret, nil
} }

@ -357,14 +357,14 @@ func (p *Process) ExeWithContext(ctx context.Context) (string, error) {
if ret == 0 { if ret == 0 {
return "", err return "", err
} }
return windows.UTF16ToString(buf[:]), nil return windows.UTF16ToString(buf), nil
} }
// XP fallback // XP fallback
ret, _, err := procGetProcessImageFileNameW.Call(uintptr(c), uintptr(unsafe.Pointer(&buf[0])), uintptr(size)) ret, _, err := procGetProcessImageFileNameW.Call(uintptr(c), uintptr(unsafe.Pointer(&buf[0])), uintptr(size))
if ret == 0 { if ret == 0 {
return "", err return "", err
} }
return common.ConvertDOSPath(windows.UTF16ToString(buf[:])), nil return common.ConvertDOSPath(windows.UTF16ToString(buf)), nil
} }
func (p *Process) CmdlineWithContext(_ context.Context) (string, error) { func (p *Process) CmdlineWithContext(_ context.Context) (string, error) {

@ -79,25 +79,23 @@ func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, si
if int(ret) >= 0 && read > 0 { if int(ret) >= 0 && read > 0 {
return buffer[:read] return buffer[:read]
} }
} else {
// reading a 64-bit process from a 32-bit one // reading a 64-bit process from a 32-bit one
if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { // avoid panic } else if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { // avoid panic
var read uint64 var read uint64
buffer := make([]byte, size) buffer := make([]byte, size)
ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call( ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call(
uintptr(h), uintptr(h),
uintptr(address&0xFFFFFFFF), // the call expects a 64-bit value uintptr(address&0xFFFFFFFF), // the call expects a 64-bit value
uintptr(address>>32), uintptr(address>>32),
uintptr(unsafe.Pointer(&buffer[0])), uintptr(unsafe.Pointer(&buffer[0])),
uintptr(size), // the call expects a 64-bit value uintptr(size), // the call expects a 64-bit value
uintptr(0), // but size is 32-bit so pass zero as the high dword uintptr(0), // but size is 32-bit so pass zero as the high dword
uintptr(unsafe.Pointer(&read)), uintptr(unsafe.Pointer(&read)),
) )
if int(ret) >= 0 && read > 0 { if int(ret) >= 0 && read > 0 {
return buffer[:uint(read)] return buffer[:uint(read)]
}
} }
} }

Loading…
Cancel
Save