Debian Codegraph @

btf/kernel.go

raw symbols SCIP
1 package btf
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7 "path/filepath"
8 "runtime"
9 "slices"
10 "sort"
11 "sync"
12
13 "github.com/cilium/ebpf/internal"
14 "github.com/cilium/ebpf/internal/linux"
15 "github.com/cilium/ebpf/internal/platform"
16 "github.com/cilium/ebpf/internal/unix"
17 )
18
19 // LoadKernelSpec returns the current kernel's BTF information.
20 //
21 // Defaults to /sys/kernel/btf/vmlinux and falls back to scanning the file
22 // system for vmlinux ELFs. Returns an error wrapping [ErrNotSupported] if BTF
23 // is not enabled.
24 //
25 // Consider using [Cache] instead.
26 func LoadKernelSpec() (*Spec, error) {
27 if platform.IsWindows {
28 return nil, internal.ErrNotSupportedOnOS
29 }
30
31 fh, err := os.Open("/sys/kernel/btf/vmlinux")
32 if err == nil {
33 defer fh.Close()
34
35 info, err := fh.Stat()
36 if err != nil {
37 return nil, fmt.Errorf("stat vmlinux: %w", err)
38 }
39
40 // NB: It's not safe to mmap arbitrary files because mmap(2) doesn't
41 // guarantee that changes made after mmap are not visible in the mapping.
42 //
43 // This is not a problem for vmlinux, since it is always a read-only file.
44 raw, err := unix.Mmap(int(fh.Fd()), 0, int(info.Size()), unix.PROT_READ, unix.MAP_PRIVATE)
45 if err != nil {
46 return LoadSplitSpecFromReader(fh, nil)
47 }
48
49 spec, err := loadRawSpec(raw, nil)
50 if err != nil {
51 _ = unix.Munmap(raw)
52 return nil, fmt.Errorf("load vmlinux: %w", err)
53 }
54
55 runtime.AddCleanup(spec.decoder.sharedBuf, func(b []byte) {
56 _ = unix.Munmap(b)
57 }, raw)
58
59 return spec, nil
60 }
61
62 file, err := findVMLinux()
63 if err != nil {
64 return nil, err
65 }
66 defer file.Close()
67
68 spec, err := LoadSpecFromReader(file)
69 return spec, err
70 }
71
72 // LoadKernelModuleSpec returns the BTF information for the named kernel module.
73 //
74 // Using [Cache.Module] is faster when loading BTF for more than one module.
75 //
76 // Defaults to /sys/kernel/btf/<module>.
77 // Returns an error wrapping ErrNotSupported if BTF is not enabled.
78 // Returns an error wrapping fs.ErrNotExist if BTF for the specific module doesn't exist.
79 func LoadKernelModuleSpec(module string) (*Spec, error) {
80 base, err := LoadKernelSpec()
81 if err != nil {
82 return nil, err
83 }
84 return loadKernelModuleSpec(module, base)
85 }
86
87 func loadKernelModuleSpec(module string, base *Spec) (*Spec, error) {
88 if platform.IsWindows {
89 return nil, internal.ErrNotSupportedOnOS
90 }
91
92 dir, file := filepath.Split(module)
93 if dir != "" || filepath.Ext(file) != "" {
94 return nil, fmt.Errorf("invalid module name %q", module)
95 }
96
97 fh, err := os.Open(filepath.Join("/sys/kernel/btf", module))
98 if err != nil {
99 return nil, err
100 }
101 defer fh.Close()
102
103 return LoadSplitSpecFromReader(fh, base)
104 }
105
106 // findVMLinux scans multiple well-known paths for vmlinux kernel images.
107 func findVMLinux() (*os.File, error) {
108 if platform.IsWindows {
109 return nil, fmt.Errorf("find vmlinux: %w", internal.ErrNotSupportedOnOS)
110 }
111
112 release, err := linux.KernelRelease()
113 if err != nil {
114 return nil, err
115 }
116
117 // use same list of locations as libbpf
118 // https://github.com/libbpf/libbpf/blob/9a3a42608dbe3731256a5682a125ac1e23bced8f/src/btf.c#L3114-L3122
119 locations := []string{
120 "/boot/vmlinux-%s",
121 "/lib/modules/%s/vmlinux-%[1]s",
122 "/lib/modules/%s/build/vmlinux",
123 "/usr/lib/modules/%s/kernel/vmlinux",
124 "/usr/lib/debug/boot/vmlinux-%s",
125 "/usr/lib/debug/boot/vmlinux-%s.debug",
126 "/usr/lib/debug/lib/modules/%s/vmlinux",
127 }
128
129 for _, loc := range locations {
130 file, err := os.Open(fmt.Sprintf(loc, release))
131 if errors.Is(err, os.ErrNotExist) {
132 continue
133 }
134 return file, err
135 }
136
137 return nil, fmt.Errorf("no BTF found for kernel version %s: %w", release, internal.ErrNotSupported)
138 }
139
140 // Cache allows to amortise the cost of decoding BTF across multiple call-sites.
141 //
142 // It is safe for concurrent use.
143 type Cache struct {
144 mu sync.RWMutex
145 kernelTypes *Spec
146 moduleTypes map[string]*Spec
147 loadedModules []string
148 }
149
150 // NewCache returns an empty Cache.
151 //
152 // Pass it to [CollectionOptions] to share kernel BTF across multiple
153 // Collection loads.
154 func NewCache() *Cache {
155 return &Cache{}
156 }
157
158 // Kernel is equivalent to [LoadKernelSpec], except that repeated calls do
159 // not copy the Spec.
160 //
161 // Returns an error wrapping [ErrNotSupported] if BTF is not enabled.
162 func (c *Cache) Kernel() (*Spec, error) {
163 c.mu.RLock()
164 if c.kernelTypes != nil {
165 spec := c.kernelTypes
166 c.mu.RUnlock()
167 return spec, nil
168 }
169 c.mu.RUnlock()
170
171 c.mu.Lock()
172 defer c.mu.Unlock()
173 return c.kernel()
174 }
175
176 func (c *Cache) kernel() (*Spec, error) {
177 if c.kernelTypes != nil {
178 return c.kernelTypes, nil
179 }
180
181 var err error
182 c.kernelTypes, err = LoadKernelSpec()
183 return c.kernelTypes, err
184 }
185
186 // Module is equivalent to [LoadKernelModuleSpec], except that repeated calls do
187 // not copy the spec.
188 //
189 // All modules also share the return value of [Kernel] as their base.
190 func (c *Cache) Module(name string) (*Spec, error) {
191 c.mu.RLock()
192 if spec := c.moduleTypes[name]; spec != nil {
193 c.mu.RUnlock()
194 return spec, nil
195 }
196 c.mu.RUnlock()
197
198 c.mu.Lock()
199 defer c.mu.Unlock()
200
201 if spec := c.moduleTypes[name]; spec != nil {
202 return spec, nil
203 }
204
205 if c.moduleTypes == nil {
206 c.moduleTypes = make(map[string]*Spec)
207 }
208
209 base, err := c.kernel()
210 if err != nil {
211 return nil, err
212 }
213
214 spec, err := loadKernelModuleSpec(name, base)
215 if err != nil {
216 return nil, err
217 }
218
219 c.moduleTypes[name] = spec
220 return spec, nil
221 }
222
223 // Modules returns a sorted list of all loaded modules.
224 func (c *Cache) Modules() ([]string, error) {
225 c.mu.RLock()
226 if c.loadedModules != nil {
227 modules := slices.Clone(c.loadedModules)
228 c.mu.RUnlock()
229 return modules, nil
230 }
231 c.mu.RUnlock()
232
233 c.mu.Lock()
234 defer c.mu.Unlock()
235
236 if c.loadedModules != nil {
237 return slices.Clone(c.loadedModules), nil
238 }
239
240 btfDir, err := os.Open("/sys/kernel/btf")
241 if err != nil {
242 return nil, err
243 }
244 defer btfDir.Close()
245
246 entries, err := btfDir.Readdirnames(-1)
247 if err != nil {
248 return nil, err
249 }
250
251 entries = slices.DeleteFunc(entries, func(s string) bool {
252 return s == "vmlinux"
253 })
254
255 sort.Strings(entries)
256 c.loadedModules = entries
257 return slices.Clone(entries), nil
258 }