Debian Codegraph @

collection.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "encoding/binary"
5 "errors"
6 "fmt"
7 "path/filepath"
8 "reflect"
9 "runtime"
10 "slices"
11 "strings"
12
13 "github.com/cilium/ebpf/btf"
14 "github.com/cilium/ebpf/internal"
15 "github.com/cilium/ebpf/internal/kallsyms"
16 "github.com/cilium/ebpf/internal/kconfig"
17 "github.com/cilium/ebpf/internal/linux"
18 "github.com/cilium/ebpf/internal/platform"
19 "github.com/cilium/ebpf/internal/sys"
20 )
21
22 // CollectionOptions control loading a collection into the kernel.
23 //
24 // Maps and Programs are passed to NewMapWithOptions and NewProgramsWithOptions.
25 type CollectionOptions struct {
26 Maps MapOptions
27 Programs ProgramOptions
28
29 // MapReplacements takes a set of Maps that will be used instead of
30 // creating new ones when loading the CollectionSpec.
31 //
32 // For each given Map, there must be a corresponding MapSpec in
33 // CollectionSpec.Maps, and its type, key/value size, max entries and flags
34 // must match the values of the MapSpec.
35 //
36 // The given Maps are Clone()d before being used in the Collection, so the
37 // caller can Close() them freely when they are no longer needed.
38 MapReplacements map[string]*Map
39
40 // Cache amortises the cost of decoding kernel BTF across multiple
41 // Collection loads. Callers loading more than one Collection should
42 // allocate a Cache via [btf.NewCache] and share it across loads.
43 // If nil, a fresh cache is allocated per load and discarded.
44 Cache *btf.Cache
45 }
46
47 // CollectionSpec describes a collection.
48 type CollectionSpec struct {
49 Maps map[string]*MapSpec
50 Programs map[string]*ProgramSpec
51
52 // Variables refer to global variables declared in the ELF. They can be read
53 // and modified freely before loading the Collection. Modifying them after
54 // loading has no effect on a running eBPF program.
55 Variables map[string]*VariableSpec
56
57 // Types holds type information about Maps and Programs.
58 // Modifications to Types are currently undefined behaviour.
59 Types *btf.Spec
60
61 // ByteOrder specifies whether the ELF was compiled for
62 // big-endian or little-endian architectures.
63 ByteOrder binary.ByteOrder
64 }
65
66 // Copy returns a recursive copy of the spec.
67 func (cs *CollectionSpec) Copy() *CollectionSpec {
68 if cs == nil {
69 return nil
70 }
71
72 cpy := CollectionSpec{
73 Maps: copyMapOfSpecs(cs.Maps),
74 Programs: copyMapOfSpecs(cs.Programs),
75 Variables: make(map[string]*VariableSpec, len(cs.Variables)),
76 ByteOrder: cs.ByteOrder,
77 Types: cs.Types.Copy(),
78 }
79
80 for name, spec := range cs.Variables {
81 cpy.Variables[name] = spec.Copy()
82 }
83 if cs.Variables == nil {
84 cpy.Variables = nil
85 }
86
87 return &cpy
88 }
89
90 func copyMapOfSpecs[T interface{ Copy() T }](m map[string]T) map[string]T {
91 if m == nil {
92 return nil
93 }
94
95 cpy := make(map[string]T, len(m))
96 for k, v := range m {
97 cpy[k] = v.Copy()
98 }
99
100 return cpy
101 }
102
103 // Assign the contents of a CollectionSpec to a struct.
104 //
105 // This function is a shortcut to manually checking the presence
106 // of maps and programs in a CollectionSpec. Consider using bpf2go
107 // if this sounds useful.
108 //
109 // 'to' must be a pointer to a struct. A field of the
110 // struct is updated with values from Programs, Maps or Variables if it
111 // has an `ebpf` tag and its type is *ProgramSpec, *MapSpec or *VariableSpec.
112 // The tag's value specifies the name of the program or map as
113 // found in the CollectionSpec.
114 //
115 // struct {
116 // Foo *ebpf.ProgramSpec `ebpf:"xdp_foo"`
117 // Bar *ebpf.MapSpec `ebpf:"bar_map"`
118 // Var *ebpf.VariableSpec `ebpf:"some_var"`
119 // Ignored int
120 // }
121 //
122 // Returns an error if any of the eBPF objects can't be found, or
123 // if the same Spec is assigned multiple times.
124 func (cs *CollectionSpec) Assign(to any) error {
125 getValue := func(typ reflect.Type, name string) (any, error) {
126 switch typ {
127 case reflect.TypeFor[*ProgramSpec]():
128 if p := cs.Programs[name]; p != nil {
129 return p, nil
130 }
131 return nil, fmt.Errorf("missing program %q", name)
132
133 case reflect.TypeFor[*MapSpec]():
134 if m := cs.Maps[name]; m != nil {
135 return m, nil
136 }
137 return nil, fmt.Errorf("missing map %q", name)
138
139 case reflect.TypeFor[*VariableSpec]():
140 if v := cs.Variables[name]; v != nil {
141 return v, nil
142 }
143 return nil, fmt.Errorf("missing variable %q", name)
144
145 default:
146 return nil, fmt.Errorf("unsupported type %s", typ)
147 }
148 }
149
150 return assignValues(to, getValue)
151 }
152
153 // LoadAndAssign loads Maps and Programs into the kernel and assigns them
154 // to a struct.
155 //
156 // Omitting Map/Program.Close() during application shutdown is an error.
157 // See the package documentation for details around Map and Program lifecycle.
158 //
159 // This function is a shortcut to manually checking the presence
160 // of maps and programs in a CollectionSpec. Consider using bpf2go
161 // if this sounds useful.
162 //
163 // 'to' must be a pointer to a struct. A field of the struct is updated with
164 // a Program or Map if it has an `ebpf` tag and its type is *Program or *Map.
165 // The tag's value specifies the name of the program or map as found in the
166 // CollectionSpec. Before updating the struct, the requested objects and their
167 // dependent resources are loaded into the kernel and populated with values if
168 // specified.
169 //
170 // struct {
171 // Foo *ebpf.Program `ebpf:"xdp_foo"`
172 // Bar *ebpf.Map `ebpf:"bar_map"`
173 // Ignored int
174 // }
175 //
176 // opts may be nil.
177 //
178 // Returns an error if any of the fields can't be found, or
179 // if the same Map or Program is assigned multiple times.
180 func (cs *CollectionSpec) LoadAndAssign(to any, opts *CollectionOptions) error {
181 loader, err := newCollectionLoader(cs, opts)
182 if err != nil {
183 return err
184 }
185 defer loader.close()
186
187 // Support assigning Programs and Maps, lazy-loading the required objects.
188 assignedMaps := make(map[string]bool)
189 assignedProgs := make(map[string]bool)
190 assignedVars := make(map[string]bool)
191
192 getValue := func(typ reflect.Type, name string) (any, error) {
193 switch typ {
194
195 case reflect.TypeFor[*Program]():
196 assignedProgs[name] = true
197 return loader.loadProgram(name)
198
199 case reflect.TypeFor[*Map]():
200 assignedMaps[name] = true
201 return loader.loadMap(name)
202
203 case reflect.TypeFor[*Variable]():
204 assignedVars[name] = true
205 return loader.loadVariable(name)
206
207 default:
208 return nil, fmt.Errorf("unsupported type %s", typ)
209 }
210 }
211
212 // Load the Maps and Programs requested by the annotated struct.
213 if err := assignValues(to, getValue); err != nil {
214 return fmt.Errorf("assign values: %w", err)
215 }
216
217 // Populate the requested maps. Has a chance of lazy-loading other dependent maps.
218 if err := loader.populateDeferredMaps(); err != nil {
219 return fmt.Errorf("populate deferred maps: %w", err)
220 }
221
222 // Evaluate the loader's objects after all (lazy)loading has taken place.
223 for n, m := range loader.maps {
224 if m.typ.canStoreProgram() {
225 // Require all lazy-loaded ProgramArrays to be assigned to the given object.
226 // The kernel empties a ProgramArray once the last user space reference
227 // to it closes, which leads to failed tail calls. Combined with the library
228 // closing map fds via GC finalizers this can lead to surprising behaviour.
229 // Only allow unassigned ProgramArrays when the library hasn't pre-populated
230 // any entries from static value declarations. At this point, we know the map
231 // is empty and there's no way for the caller to interact with the map going
232 // forward.
233 if !assignedMaps[n] && len(cs.Maps[n].Contents) > 0 {
234 return fmt.Errorf("ProgramArray %s must be assigned to prevent missed tail calls", n)
235 }
236 }
237 }
238
239 // Prevent loader.cleanup() from closing assigned Maps and Programs.
240 for m := range assignedMaps {
241 delete(loader.maps, m)
242 }
243 for p := range assignedProgs {
244 delete(loader.programs, p)
245 }
246 for p := range assignedVars {
247 delete(loader.vars, p)
248 }
249
250 return nil
251 }
252
253 // Collection is a collection of live BPF resources present in the kernel.
254 type Collection struct {
255 Programs map[string]*Program
256 Maps map[string]*Map
257
258 // Variables contains global variables used by the Collection's program(s). On
259 // kernels older than 5.5, most interactions with Variables return
260 // [ErrNotSupported].
261 Variables map[string]*Variable
262 }
263
264 // NewCollection creates a Collection from the given spec, creating and
265 // loading its declared resources into the kernel.
266 //
267 // Omitting Collection.Close() during application shutdown is an error.
268 // See the package documentation for details around Map and Program lifecycle.
269 func NewCollection(spec *CollectionSpec) (*Collection, error) {
270 return NewCollectionWithOptions(spec, CollectionOptions{})
271 }
272
273 // NewCollectionWithOptions creates a Collection from the given spec using
274 // options, creating and loading its declared resources into the kernel.
275 //
276 // Omitting Collection.Close() during application shutdown is an error.
277 // See the package documentation for details around Map and Program lifecycle.
278 func NewCollectionWithOptions(spec *CollectionSpec, opts CollectionOptions) (*Collection, error) {
279 loader, err := newCollectionLoader(spec, &opts)
280 if err != nil {
281 return nil, err
282 }
283 defer loader.close()
284
285 // Create maps first, as their fds need to be linked into programs.
286 for mapName := range spec.Maps {
287 if _, err := loader.loadMap(mapName); err != nil {
288 return nil, err
289 }
290 }
291
292 for progName, prog := range spec.Programs {
293 if prog.Type == UnspecifiedProgram {
294 continue
295 }
296
297 if _, err := loader.loadProgram(progName); err != nil {
298 return nil, err
299 }
300 }
301
302 for varName := range spec.Variables {
303 if _, err := loader.loadVariable(varName); err != nil {
304 return nil, err
305 }
306 }
307
308 // Maps can contain Program and Map stubs, so populate them after
309 // all Maps and Programs have been successfully loaded.
310 if err := loader.populateDeferredMaps(); err != nil {
311 return nil, err
312 }
313
314 // Prevent loader.cleanup from closing maps, programs and vars.
315 maps, progs, vars := loader.maps, loader.programs, loader.vars
316 loader.maps, loader.programs, loader.vars = nil, nil, nil
317
318 return &Collection{
319 progs,
320 maps,
321 vars,
322 }, nil
323 }
324
325 type collectionLoader struct {
326 coll *CollectionSpec
327 opts *CollectionOptions
328 maps map[string]*Map
329 programs map[string]*Program
330 vars map[string]*Variable
331 types *btf.Cache
332 }
333
334 func newCollectionLoader(coll *CollectionSpec, opts *CollectionOptions) (*collectionLoader, error) {
335 if opts == nil {
336 opts = &CollectionOptions{}
337 }
338
339 // Check for existing MapSpecs in the CollectionSpec for all provided replacement maps.
340 for name := range opts.MapReplacements {
341 if _, ok := coll.Maps[name]; !ok {
342 return nil, fmt.Errorf("replacement map %s not found in CollectionSpec", name)
343 }
344 }
345
346 if err := populateKallsyms(coll.Programs); err != nil {
347 return nil, fmt.Errorf("populating kallsyms caches: %w", err)
348 }
349
350 cache := opts.Cache
351 if cache == nil {
352 cache = btf.NewCache()
353 }
354
355 return &collectionLoader{
356 coll,
357 opts,
358 make(map[string]*Map),
359 make(map[string]*Program),
360 make(map[string]*Variable),
361 cache,
362 }, nil
363 }
364
365 // populateKallsyms populates kallsyms caches, making lookups cheaper later on
366 // during individual program loading. Since we have less context available
367 // at those stages, we batch the lookups here instead to avoid redundant work.
368 func populateKallsyms(progs map[string]*ProgramSpec) error {
369 // Look up addresses of all kernel symbols referenced by all programs.
370 addrs := make(map[string]uint64)
371 for _, p := range progs {
372 iter := p.Instructions.Iterate()
373 for iter.Next() {
374 ins := iter.Ins
375 meta, _ := ins.Metadata.Get(ksymMetaKey{}).(*ksymMeta)
376 if meta != nil {
377 addrs[meta.Name] = 0
378 }
379 }
380 }
381 if len(addrs) != 0 {
382 if err := kallsyms.AssignAddresses(addrs); err != nil {
383 return fmt.Errorf("getting addresses from kallsyms: %w", err)
384 }
385 }
386
387 return nil
388 }
389
390 // close all resources left over in the collectionLoader.
391 func (cl *collectionLoader) close() {
392 for _, m := range cl.maps {
393 m.Close()
394 }
395 for _, p := range cl.programs {
396 p.Close()
397 }
398 }
399
400 func (cl *collectionLoader) loadMap(mapName string) (*Map, error) {
401 if m := cl.maps[mapName]; m != nil {
402 return m, nil
403 }
404
405 mapSpec := cl.coll.Maps[mapName]
406 if mapSpec == nil {
407 return nil, fmt.Errorf("missing map %s", mapName)
408 }
409
410 mapSpec = mapSpec.Copy()
411
412 // Defer setting the mmapable flag on maps until load time. This avoids the
413 // MapSpec having different flags on some kernel versions. Also avoid running
414 // syscalls during ELF loading, so platforms like wasm can also parse an ELF.
415 if isDataSection(mapSpec.Name) && haveMmapableMaps() == nil {
416 mapSpec.Flags |= sys.BPF_F_MMAPABLE
417 }
418
419 if replaceMap, ok := cl.opts.MapReplacements[mapName]; ok {
420 // Check compatibility with the replacement map after setting
421 // feature-dependent map flags.
422 if err := mapSpec.Compatible(replaceMap); err != nil {
423 return nil, fmt.Errorf("using replacement map %s: %w", mapSpec.Name, err)
424 }
425
426 // Clone the map to avoid closing user's map later on.
427 m, err := replaceMap.Clone()
428 if err != nil {
429 return nil, err
430 }
431
432 cl.maps[mapName] = m
433 return m, nil
434 }
435
436 if err := mapSpec.updateDataSection(cl.coll.Variables, mapName); err != nil {
437 return nil, fmt.Errorf("assembling contents of map %s: %w", mapName, err)
438 }
439
440 m, err := newMapWithOptions(mapSpec, cl.opts.Maps, cl.types)
441 if err != nil {
442 return nil, fmt.Errorf("map %s: %w", mapName, err)
443 }
444
445 // Finalize 'scalar' maps that don't refer to any other eBPF resources
446 // potentially pending creation. This is needed for frozen maps like .rodata
447 // that need to be finalized before invoking the verifier.
448 if !mapSpec.Type.canStoreMapOrProgram() {
449 if err := m.finalize(mapSpec); err != nil {
450 _ = m.Close()
451 return nil, fmt.Errorf("finalizing map %s: %w", mapName, err)
452 }
453 }
454
455 cl.maps[mapName] = m
456 return m, nil
457 }
458
459 func (cl *collectionLoader) loadProgram(progName string) (*Program, error) {
460 if prog := cl.programs[progName]; prog != nil {
461 return prog, nil
462 }
463
464 progSpec := cl.coll.Programs[progName]
465 if progSpec == nil {
466 return nil, fmt.Errorf("unknown program %s", progName)
467 }
468
469 // Bail out early if we know the kernel is going to reject the program.
470 // This skips loading map dependencies, saving some cleanup work later.
471 if progSpec.Type == UnspecifiedProgram {
472 return nil, fmt.Errorf("cannot load program %s: program type is unspecified", progName)
473 }
474
475 progSpec = progSpec.Copy()
476
477 // Rewrite any reference to a valid map in the program's instructions,
478 // which includes all of its dependencies.
479 for i := range progSpec.Instructions {
480 ins := &progSpec.Instructions[i]
481
482 if !ins.IsLoadFromMap() || ins.Reference() == "" {
483 continue
484 }
485
486 // Don't overwrite map loads containing non-zero map fd's,
487 // they can be manually included by the caller.
488 // Map FDs/IDs are placed in the lower 32 bits of Constant.
489 if int32(ins.Constant) > 0 {
490 continue
491 }
492
493 m, err := cl.loadMap(ins.Reference())
494 if err != nil {
495 return nil, fmt.Errorf("program %s: %w", progName, err)
496 }
497
498 if err := ins.AssociateMap(m); err != nil {
499 return nil, fmt.Errorf("program %s: map %s: %w", progName, ins.Reference(), err)
500 }
501 }
502
503 prog, err := newProgramWithOptions(progSpec, cl.opts.Programs, cl.types)
504 if err != nil {
505 return nil, fmt.Errorf("program %s: %w", progName, err)
506 }
507
508 cl.programs[progName] = prog
509
510 return prog, nil
511 }
512
513 func (cl *collectionLoader) loadVariable(varName string) (*Variable, error) {
514 if v := cl.vars[varName]; v != nil {
515 return v, nil
516 }
517
518 varSpec := cl.coll.Variables[varName]
519 if varSpec == nil {
520 return nil, fmt.Errorf("unknown variable %s", varName)
521 }
522
523 m, err := cl.loadMap(varSpec.SectionName)
524 if err != nil {
525 return nil, fmt.Errorf("variable %s: %w", varName, err)
526 }
527
528 // If the kernel is too old or the underlying map was created without
529 // BPF_F_MMAPABLE, [Map.Memory] will return ErrNotSupported. In this case,
530 // emit a Variable with a nil Memory. This keeps Collection{Spec}.Variables
531 // consistent across systems with different feature sets without breaking
532 // LoadAndAssign.
533 var mm *Memory
534 if unsafeMemory {
535 mm, err = m.unsafeMemory()
536 } else {
537 mm, err = m.Memory()
538 }
539 if err != nil && !errors.Is(err, ErrNotSupported) {
540 return nil, fmt.Errorf("variable %s: getting memory for map %s: %w", varName, varSpec.SectionName, err)
541 }
542
543 v, err := newVariable(
544 varSpec.Name,
545 varSpec.Offset,
546 varSpec.Size(),
547 varSpec.Type,
548 mm,
549 )
550 if err != nil {
551 return nil, fmt.Errorf("variable %s: %w", varName, err)
552 }
553
554 cl.vars[varName] = v
555 return v, nil
556 }
557
558 // populateDeferredMaps iterates maps holding programs or other maps and loads
559 // any dependencies. Populates all maps in cl and freezes them if specified.
560 func (cl *collectionLoader) populateDeferredMaps() error {
561 for mapName, m := range cl.maps {
562 mapSpec, ok := cl.coll.Maps[mapName]
563 if !ok {
564 return fmt.Errorf("missing map spec %s", mapName)
565 }
566
567 // Scalar maps without Map or Program references are finalized during
568 // creation. Don't finalize them again.
569 if !mapSpec.Type.canStoreMapOrProgram() {
570 continue
571 }
572
573 mapSpec = mapSpec.Copy()
574
575 // MapSpecs that refer to inner maps or programs within the same
576 // CollectionSpec do so using strings. These strings are used as the key
577 // to look up the respective object in the Maps or Programs fields.
578 // Resolve those references to actual Map or Program resources that
579 // have been loaded into the kernel.
580 for i, kv := range mapSpec.Contents {
581 objName, ok := kv.Value.(string)
582 if !ok {
583 continue
584 }
585
586 switch t := mapSpec.Type; {
587 case t.canStoreProgram():
588 // loadProgram is idempotent and could return an existing Program.
589 prog, err := cl.loadProgram(objName)
590 if err != nil {
591 return fmt.Errorf("loading program %s, for map %s: %w", objName, mapName, err)
592 }
593 mapSpec.Contents[i] = MapKV{kv.Key, prog}
594
595 case t.canStoreMap():
596 // loadMap is idempotent and could return an existing Map.
597 innerMap, err := cl.loadMap(objName)
598 if err != nil {
599 return fmt.Errorf("loading inner map %s, for map %s: %w", objName, mapName, err)
600 }
601 mapSpec.Contents[i] = MapKV{kv.Key, innerMap}
602 }
603 }
604
605 if mapSpec.Type == StructOpsMap {
606 // populate StructOps data into `kernVData`
607 if err := cl.populateStructOps(m, mapSpec); err != nil {
608 return err
609 }
610 }
611
612 // Populate and freeze the map if specified.
613 if err := m.finalize(mapSpec); err != nil {
614 return fmt.Errorf("populating map %s: %w", mapName, err)
615 }
616 }
617
618 return nil
619 }
620
621 // populateStructOps translates the user struct bytes into the kernel value struct
622 // layout for a struct_ops map and writes the result back to mapSpec.Contents[0].
623 func (cl *collectionLoader) populateStructOps(m *Map, mapSpec *MapSpec) error {
624 userType, ok := btf.As[*btf.Struct](mapSpec.Value)
625 if !ok {
626 return fmt.Errorf("value should be a *Struct")
627 }
628
629 userData, err := mapSpec.dataSection()
630 if err != nil {
631 return fmt.Errorf("getting data section: %w", err)
632 }
633 if len(userData) < int(userType.Size) {
634 return fmt.Errorf("user data too short: have %d, need at least %d", len(userData), userType.Size)
635 }
636
637 vType, _, module, err := structOpsFindTarget(userType, cl.types)
638 if err != nil {
639 return fmt.Errorf("struct_ops value type %q: %w", userType.Name, err)
640 }
641 defer module.Close()
642
643 // Find the inner ops struct embedded in the value struct.
644 kType, kTypeOff, err := structOpsFindInnerType(vType)
645 if err != nil {
646 return err
647 }
648
649 kernVData := make([]byte, int(vType.Size))
650 for _, m := range userType.Members {
651 i := slices.IndexFunc(kType.Members, func(km btf.Member) bool {
652 return km.Name == m.Name
653 })
654
655 // Allow field to not exist in target as long as the source is zero.
656 if i == -1 {
657 mSize, err := btf.Sizeof(m.Type)
658 if err != nil {
659 return fmt.Errorf("sizeof(user.%s): %w", m.Name, err)
660 }
661 srcOff := int(m.Offset.Bytes())
662 if srcOff < 0 || srcOff+mSize > len(userData) {
663 return fmt.Errorf("member %q: userdata is too small", m.Name)
664 }
665
666 // let fail if the field in type user type is missing in type kern type
667 if !structOpsIsMemZeroed(userData[srcOff : srcOff+mSize]) {
668 return fmt.Errorf("%s doesn't exist in %s, but it has non-zero value", m.Name, kType.Name)
669 }
670
671 continue
672 }
673
674 km := kType.Members[i]
675
676 switch btf.UnderlyingType(m.Type).(type) {
677 case *btf.Pointer:
678 // If this is a pointer → resolve struct_ops program.
679 psKey := kType.Name + ":" + m.Name
680 for k, ps := range cl.coll.Programs {
681 if ps.AttachTo == psKey {
682 p, ok := cl.programs[k]
683 if !ok || p == nil {
684 return nil
685 }
686 if err := structOpsPopulateValue(km, kernVData[kTypeOff:], p); err != nil {
687 return err
688 }
689 }
690 }
691
692 default:
693 // Otherwise → memcpy the field contents.
694 if err := structOpsCopyMember(m, km, userData, kernVData[kTypeOff:]); err != nil {
695 return fmt.Errorf("field %s: %w", kType.Name, err)
696 }
697 }
698 }
699
700 // Populate the map explicitly and keep a reference on cl.programs.
701 // This is necessary because we may inline fds into kernVData which
702 // may become invalid if the GC frees them.
703 if err := m.Put(uint32(0), kernVData); err != nil {
704 return err
705 }
706 mapSpec.Contents = nil
707 runtime.KeepAlive(cl.programs)
708
709 return nil
710 }
711
712 // resolveKconfig resolves all variables declared in .kconfig and populates
713 // m.Contents. Does nothing if the given m.Contents is non-empty.
714 func resolveKconfig(m *MapSpec) error {
715 ds, ok := m.Value.(*btf.Datasec)
716 if !ok {
717 return errors.New("map value is not a Datasec")
718 }
719
720 if platform.IsWindows {
721 return fmt.Errorf(".kconfig: %w", internal.ErrNotSupportedOnOS)
722 }
723
724 type configInfo struct {
725 offset uint32
726 size uint32
727 typ btf.Type
728 }
729
730 configs := make(map[string]configInfo)
731
732 data := make([]byte, ds.Size)
733 for _, vsi := range ds.Vars {
734 v := vsi.Type.(*btf.Var)
735 n := v.TypeName()
736
737 switch n {
738 case "LINUX_KERNEL_VERSION":
739 if integer, ok := v.Type.(*btf.Int); !ok || integer.Size != 4 {
740 return fmt.Errorf("variable %s must be a 32 bits integer, got %s", n, v.Type)
741 }
742
743 kv, err := linux.KernelVersion()
744 if err != nil {
745 return fmt.Errorf("getting kernel version: %w", err)
746 }
747 internal.NativeEndian.PutUint32(data[vsi.Offset:], kv.Kernel())
748
749 case "LINUX_HAS_SYSCALL_WRAPPER":
750 integer, ok := v.Type.(*btf.Int)
751 if !ok {
752 return fmt.Errorf("variable %s must be an integer, got %s", n, v.Type)
753 }
754 var value uint64 = 1
755 if err := haveSyscallWrapper(); errors.Is(err, ErrNotSupported) {
756 value = 0
757 } else if err != nil {
758 return fmt.Errorf("unable to derive a value for LINUX_HAS_SYSCALL_WRAPPER: %w", err)
759 }
760
761 if err := kconfig.PutInteger(data[vsi.Offset:], integer, value); err != nil {
762 return fmt.Errorf("set LINUX_HAS_SYSCALL_WRAPPER: %w", err)
763 }
764
765 default: // Catch CONFIG_*.
766 configs[n] = configInfo{
767 offset: vsi.Offset,
768 size: vsi.Size,
769 typ: v.Type,
770 }
771 }
772 }
773
774 // We only parse kconfig file if a CONFIG_* variable was found.
775 if len(configs) > 0 {
776 f, err := linux.FindKConfig()
777 if err != nil {
778 return fmt.Errorf("cannot find a kconfig file: %w", err)
779 }
780 defer f.Close()
781
782 filter := make(map[string]struct{}, len(configs))
783 for config := range configs {
784 filter[config] = struct{}{}
785 }
786
787 kernelConfig, err := kconfig.Parse(f, filter)
788 if err != nil {
789 return fmt.Errorf("cannot parse kconfig file: %w", err)
790 }
791
792 for n, info := range configs {
793 value, ok := kernelConfig[n]
794 if !ok {
795 return fmt.Errorf("config option %q does not exist on this kernel", n)
796 }
797
798 err := kconfig.PutValue(data[info.offset:info.offset+info.size], info.typ, value)
799 if err != nil {
800 return fmt.Errorf("problem adding value for %s: %w", n, err)
801 }
802 }
803 }
804
805 m.Contents = []MapKV{{uint32(0), data}}
806
807 return nil
808 }
809
810 // LoadCollection reads an object file and creates and loads its declared
811 // resources into the kernel.
812 //
813 // Omitting Collection.Close() during application shutdown is an error.
814 // See the package documentation for details around Map and Program lifecycle.
815 func LoadCollection(file string) (*Collection, error) {
816 if platform.IsWindows {
817 // This mirrors a check in efW.
818 if ext := filepath.Ext(file); ext == ".sys" {
819 return loadCollectionFromNativeImage(file)
820 }
821 }
822
823 spec, err := LoadCollectionSpec(file)
824 if err != nil {
825 return nil, err
826 }
827 return NewCollection(spec)
828 }
829
830 // Assign the contents of a Collection to a struct.
831 //
832 // This function bridges functionality between bpf2go generated
833 // code and any functionality better implemented in Collection.
834 //
835 // 'to' must be a pointer to a struct. A field of the
836 // struct is updated with values from Programs or Maps if it
837 // has an `ebpf` tag and its type is *Program or *Map.
838 // The tag's value specifies the name of the program or map as
839 // found in the CollectionSpec.
840 //
841 // struct {
842 // Foo *ebpf.Program `ebpf:"xdp_foo"`
843 // Bar *ebpf.Map `ebpf:"bar_map"`
844 // Ignored int
845 // }
846 //
847 // Returns an error if any of the eBPF objects can't be found, or
848 // if the same Map or Program is assigned multiple times.
849 //
850 // Ownership and Close()ing responsibility is transferred to `to`
851 // for any successful assigns. On error `to` is left in an undefined state.
852 func (coll *Collection) Assign(to any) error {
853 assignedMaps := make(map[string]bool)
854 assignedProgs := make(map[string]bool)
855 assignedVars := make(map[string]bool)
856
857 // Assign() only transfers already-loaded Maps and Programs. No extra
858 // loading is done.
859 getValue := func(typ reflect.Type, name string) (any, error) {
860 switch typ {
861
862 case reflect.TypeFor[*Program]():
863 if p := coll.Programs[name]; p != nil {
864 assignedProgs[name] = true
865 return p, nil
866 }
867 return nil, fmt.Errorf("missing program %q", name)
868
869 case reflect.TypeFor[*Map]():
870 if m := coll.Maps[name]; m != nil {
871 assignedMaps[name] = true
872 return m, nil
873 }
874 return nil, fmt.Errorf("missing map %q", name)
875
876 case reflect.TypeFor[*Variable]():
877 if v := coll.Variables[name]; v != nil {
878 assignedVars[name] = true
879 return v, nil
880 }
881 return nil, fmt.Errorf("missing variable %q", name)
882
883 default:
884 return nil, fmt.Errorf("unsupported type %s", typ)
885 }
886 }
887
888 if err := assignValues(to, getValue); err != nil {
889 return fmt.Errorf("assign values: %w", err)
890 }
891
892 // Finalize ownership transfer
893 for p := range assignedProgs {
894 delete(coll.Programs, p)
895 }
896 for m := range assignedMaps {
897 delete(coll.Maps, m)
898 }
899 for s := range assignedVars {
900 delete(coll.Variables, s)
901 }
902
903 return nil
904 }
905
906 // Close frees all maps and programs associated with the collection.
907 //
908 // The collection mustn't be used afterwards.
909 func (coll *Collection) Close() {
910 for _, prog := range coll.Programs {
911 prog.Close()
912 }
913 for _, m := range coll.Maps {
914 m.Close()
915 }
916 }
917
918 // DetachMap removes the named map from the Collection.
919 //
920 // This means that a later call to Close() will not affect this map.
921 //
922 // Returns nil if no map of that name exists.
923 func (coll *Collection) DetachMap(name string) *Map {
924 m := coll.Maps[name]
925 delete(coll.Maps, name)
926 return m
927 }
928
929 // DetachProgram removes the named program from the Collection.
930 //
931 // This means that a later call to Close() will not affect this program.
932 //
933 // Returns nil if no program of that name exists.
934 func (coll *Collection) DetachProgram(name string) *Program {
935 p := coll.Programs[name]
936 delete(coll.Programs, name)
937 return p
938 }
939
940 // structField represents a struct field containing the ebpf struct tag.
941 type structField struct {
942 reflect.StructField
943 value reflect.Value
944 }
945
946 // ebpfFields extracts field names tagged with 'ebpf' from a struct type.
947 // Keep track of visited types to avoid infinite recursion.
948 func ebpfFields(structVal reflect.Value, visited map[reflect.Type]bool) ([]structField, error) {
949 if visited == nil {
950 visited = make(map[reflect.Type]bool)
951 }
952
953 structType := structVal.Type()
954 if structType.Kind() != reflect.Struct {
955 return nil, fmt.Errorf("%s is not a struct", structType)
956 }
957
958 if visited[structType] {
959 return nil, fmt.Errorf("recursion on type %s", structType)
960 }
961
962 fields := make([]structField, 0, structType.NumField())
963 for i := 0; i < structType.NumField(); i++ {
964 field := structField{structType.Field(i), structVal.Field(i)}
965
966 // If the field is tagged, gather it and move on.
967 name := field.Tag.Get("ebpf")
968 if name != "" {
969 fields = append(fields, field)
970 continue
971 }
972
973 // If the field does not have an ebpf tag, but is a struct or a pointer
974 // to a struct, attempt to gather its fields as well.
975 var v reflect.Value
976 switch field.Type.Kind() {
977 case reflect.Pointer:
978 if field.Type.Elem().Kind() != reflect.Struct {
979 continue
980 }
981
982 if field.value.IsNil() {
983 return nil, fmt.Errorf("nil pointer to %s", structType)
984 }
985
986 // Obtain the destination type of the pointer.
987 v = field.value.Elem()
988
989 case reflect.Struct:
990 // Reference the value's type directly.
991 v = field.value
992
993 default:
994 continue
995 }
996
997 inner, err := ebpfFields(v, visited)
998 if err != nil {
999 return nil, fmt.Errorf("field %s: %w", field.Name, err)
1000 }
1001
1002 fields = append(fields, inner...)
1003 }
1004
1005 return fields, nil
1006 }
1007
1008 // assignValues attempts to populate all fields of 'to' tagged with 'ebpf'.
1009 //
1010 // getValue is called for every tagged field of 'to' and must return the value
1011 // to be assigned to the field with the given typ and name.
1012 func assignValues(to any, getValue func(typ reflect.Type, name string) (any, error)) error {
1013 if err := internal.IsNilPointer(to); err != nil {
1014 return err
1015 }
1016
1017 toValue := reflect.ValueOf(to)
1018 if toValue.Type().Kind() != reflect.Pointer {
1019 return fmt.Errorf("%T is not a pointer to struct", to)
1020 }
1021
1022 fields, err := ebpfFields(toValue.Elem(), nil)
1023 if err != nil {
1024 return err
1025 }
1026
1027 type elem struct {
1028 // Either *Map or *Program
1029 typ reflect.Type
1030 name string
1031 }
1032
1033 assigned := make(map[elem]string)
1034 for _, field := range fields {
1035 // Get string value the field is tagged with.
1036 tag := field.Tag.Get("ebpf")
1037 if strings.Contains(tag, ",") {
1038 return fmt.Errorf("field %s: ebpf tag contains a comma", field.Name)
1039 }
1040
1041 // Check if the eBPF object with the requested
1042 // type and tag was already assigned elsewhere.
1043 e := elem{field.Type, tag}
1044 if af := assigned[e]; af != "" {
1045 return fmt.Errorf("field %s: object %q was already assigned to %s", field.Name, tag, af)
1046 }
1047
1048 // Get the eBPF object referred to by the tag.
1049 value, err := getValue(field.Type, tag)
1050 if err != nil {
1051 return fmt.Errorf("field %s: %w", field.Name, err)
1052 }
1053
1054 if !field.value.CanSet() {
1055 return fmt.Errorf("field %s: can't set value", field.Name)
1056 }
1057 field.value.Set(reflect.ValueOf(value))
1058
1059 assigned[e] = field.Name
1060 }
1061
1062 return nil
1063 }