optimize: fallback to syscall if failed to detect kernel version

This commit is contained in:
mzz2017 2023-03-08 16:44:15 +08:00
parent 41cab77f67
commit 1b5ef8a192

View File

@ -1,10 +1,11 @@
// Copied from https://github.com/cilium/ebpf/blob/v0.10.0/internal/version.go // Modified from https://github.com/cilium/ebpf/blob/v0.10.0/internal/version.go
package internal package internal
import ( import (
"fmt" "fmt"
"sync" "sync"
"syscall"
"github.com/v2rayA/dae/pkg/ebpf_internal/internal/unix" "github.com/v2rayA/dae/pkg/ebpf_internal/internal/unix"
) )
@ -89,10 +90,34 @@ func (v Version) Kernel() uint32 {
return uint32(uint8(v[0]))<<16 | uint32(uint8(v[1]))<<8 | uint32(uint8(s)) return uint32(uint8(v[0]))<<16 | uint32(uint8(v[1]))<<8 | uint32(uint8(s))
} }
// utsnameToString converts the utsname to a string and returns it.
func utsnameToString(unameArray [65]int8) string {
var byteString [65]byte
var indexLength int
for ; unameArray[indexLength] != 0; indexLength++ {
byteString[indexLength] = uint8(unameArray[indexLength])
}
return string(byteString[:indexLength])
}
// KernelVersion returns the version of the currently running kernel. // KernelVersion returns the version of the currently running kernel.
func KernelVersion() (Version, error) { func KernelVersion() (Version, error) {
kernelVersion.once.Do(func() { kernelVersion.once.Do(func() {
kernelVersion.version, kernelVersion.err = detectKernelVersion() kernelVersion.version, kernelVersion.err = detectKernelVersion()
if kernelVersion.err != nil {
// Try syscall.
var utsname syscall.Utsname
if err := syscall.Uname(&utsname); err != nil {
kernelVersion.err = fmt.Errorf("%w; %v", kernelVersion.err, err)
return
}
version, err := NewVersion(utsnameToString(utsname.Release))
if err != nil {
kernelVersion.err = fmt.Errorf("%w; %v", kernelVersion.err, err)
return
}
kernelVersion.version = version
}
}) })
if kernelVersion.err != nil { if kernelVersion.err != nil {