Debian Codegraph @

docs/examples/variables/main.go

raw symbols SCIP
1 package main
2
3 import (
4 "fmt"
5
6 "github.com/cilium/ebpf"
7 )
8
9 func main() {
10 DocVariablesSetConst()
11 DocVariablesSetGlobal()
12 }
13
14 // Full example written to be displayed in its entirety, so is commented generously.
15 func DocVariablesSetConst() {
16 // Load the object file from disk using a bpf2go-generated scaffolding.
17 spec, err := loadVariables()
18 if err != nil {
19 panicf("loading CollectionSpec: %s", err)
20 }
21
22 // Set the 'const_u32' variable to 42 in the CollectionSpec.
23 want := uint32(42) // (1)!
24 if err := spec.Variables["const_u32"].Set(want); err != nil {
25 panicf("setting variable: %s", err)
26 }
27
28 // Load the CollectionSpec.
29 //
30 // Note: modifying spec.Variables after this point is ineffectual!
31 // Modifying *Spec resources does not affect loaded/running BPF programs.
32 var obj variablesPrograms
33 if err := spec.LoadAndAssign(&obj, nil); err != nil {
34 panicf("loading BPF program: %s", err)
35 }
36
37 fmt.Println("Running program with const_u32 set to", want)
38
39 // Dry-run the BPF program with an empty context.
40 ret, _, err := obj.ConstExample.Test(make([]byte, 15)) // (2)!
41 if err != nil {
42 panicf("running BPF program: %s", err)
43 }
44
45 if ret != want {
46 panicf("unexpected return value %d", ret)
47 }
48
49 fmt.Println("BPF program returned", ret)
50
51 // Output:
52 // Running program with const_u32 set to 42
53 // BPF program returned 42
54 }
55
56 func DocVariablesSetGlobal() {
57 spec, err := loadVariables()
58 if err != nil {
59 panicf("loading CollectionSpec: %s", err)
60 }
61
62 // DocVariablesSetGlobalU16 {
63 set := uint16(9000)
64 if err := spec.Variables["global_u16"].Set(set); err != nil {
65 panicf("setting variable: %s", err)
66 }
67 // }
68
69 coll, err := ebpf.NewCollection(spec)
70 if err != nil {
71 panicf("loading BPF program: %s", err)
72 }
73
74 fmt.Println("Running program with global_u16 set to", set)
75
76 // DocVariablesSetGlobalRun {
77 for range 3 {
78 ret, _, err := coll.Programs["global_example"].Test(make([]byte, 15))
79 if err != nil {
80 panicf("running BPF program: %s", err)
81 }
82 fmt.Println("BPF program returned", ret)
83 }
84
85 // Output:
86 // Running program with global_u16 set to 9000
87 // BPF program returned 9000
88 // BPF program returned 9001
89 // BPF program returned 9002
90 // }
91
92 // DocVariablesGetGlobalU16 {
93 var global_u16 uint16
94 if err := coll.Variables["global_u16"].Get(&global_u16); err != nil {
95 panicf("getting variable: %s", err)
96 }
97 fmt.Println("Variable global_u16 is now", global_u16)
98
99 // Output:
100 // Variable global_u16 is now 9003
101 // }
102 }
103
104 func panicf(format string, args ...any) {
105 panic(fmt.Sprintf(format, args...))
106 }