Debian Codegraph @

internal/version.go

raw symbols SCIP
1 package internal
2
3 import (
4 "fmt"
5 )
6
7 const (
8 // Version constant used in ELF binaries indicating that the loader needs to
9 // substitute the eBPF program's version with the value of the kernel's
10 // KERNEL_VERSION compile-time macro. Used for compatibility with BCC, gobpf
11 // and RedSift.
12 MagicKernelVersion = 0xFFFFFFFE
13 )
14
15 // A Version in the form Major.Minor.Patch.
16 type Version [3]uint16
17
18 // NewVersion creates a version from a string like "Major.Minor.Patch".
19 //
20 // Patch is optional.
21 func NewVersion(ver string) (Version, error) {
22 var major, minor, patch uint16
23 n, _ := fmt.Sscanf(ver, "%d.%d.%d", &major, &minor, &patch)
24 if n < 2 {
25 return Version{}, fmt.Errorf("invalid version: %s", ver)
26 }
27 return Version{major, minor, patch}, nil
28 }
29
30 // NewVersionFromCode creates a version from a LINUX_VERSION_CODE.
31 func NewVersionFromCode(code uint32) Version {
32 return Version{
33 uint16(uint8(code >> 16)),
34 uint16(uint8(code >> 8)),
35 uint16(uint8(code)),
36 }
37 }
38
39 func (v Version) String() string {
40 if v[2] == 0 {
41 return fmt.Sprintf("v%d.%d", v[0], v[1])
42 }
43 return fmt.Sprintf("v%d.%d.%d", v[0], v[1], v[2])
44 }
45
46 // Less returns true if the version is less than another version.
47 func (v Version) Less(other Version) bool {
48 for i, a := range v {
49 if a == other[i] {
50 continue
51 }
52 return a < other[i]
53 }
54 return false
55 }
56
57 // Unspecified returns true if the version is all zero.
58 func (v Version) Unspecified() bool {
59 return v[0] == 0 && v[1] == 0 && v[2] == 0
60 }
61
62 // Kernel implements the kernel's KERNEL_VERSION macro from linux/version.h.
63 // It represents the kernel version and patch level as a single value.
64 func (v Version) Kernel() uint32 {
65
66 // Kernels 4.4 and 4.9 have their SUBLEVEL clamped to 255 to avoid
67 // overflowing into PATCHLEVEL.
68 // See kernel commit 9b82f13e7ef3 ("kbuild: clamp SUBLEVEL to 255").
69 s := min(v[2], 255)
70
71 // Truncate members to uint8 to prevent them from spilling over into
72 // each other when overflowing 8 bits.
73 return uint32(uint8(v[0]))<<16 | uint32(uint8(v[1]))<<8 | uint32(uint8(s))
74 }