github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/docs/examples/docs_test.go (about) 1 package examples 2 3 import ( 4 "fmt" 5 6 "github.com/cilium/ebpf" 7 ) 8 9 func DocLoadCollectionSpec() { 10 // Parse an ELF into a CollectionSpec. 11 // bpf_prog.o is the result of compiling BPF C code. 12 spec, err := ebpf.LoadCollectionSpec("bpf_prog.o") 13 if err != nil { 14 panic(err) 15 } 16 17 // Look up the MapSpec and ProgramSpec in the CollectionSpec. 18 m := spec.Maps["my_map"] 19 p := spec.Programs["my_prog"] 20 // Note: We've omitted nil checks for brevity, take a look at 21 // LoadAndAssign for an automated way of checking for maps/programs. 22 23 // Inspect the map and program type. 24 fmt.Println(m.Type, p.Type) 25 26 // Print the map's key and value BTF types. 27 fmt.Println(m.Key, m.Value) 28 29 // Print the program's instructions in a human-readable form, 30 // similar to llvm-objdump -S. 31 fmt.Println(p.Instructions) 32 } 33 34 func DocNewCollection() { 35 spec, err := ebpf.LoadCollectionSpec("bpf_prog.o") 36 if err != nil { 37 panic(err) 38 } 39 40 // Instantiate a Collection from a CollectionSpec. 41 coll, err := ebpf.NewCollection(spec) 42 if err != nil { 43 panic(err) 44 } 45 // Close the Collection before the enclosing function returns. 46 defer coll.Close() 47 48 // Obtain a reference to 'my_map'. 49 m := coll.Maps["my_map"] 50 51 // Set map key '1' to value '2'. 52 if err := m.Put(uint32(1), uint64(2)); err != nil { 53 panic(err) 54 } 55 } 56 57 // DocLoadAndAssignObjs { 58 type myObjs struct { 59 MyMap *ebpf.Map `ebpf:"my_map"` 60 MyProg *ebpf.Program `ebpf:"my_prog"` 61 } 62 63 func (objs *myObjs) Close() error { 64 if err := objs.MyMap.Close(); err != nil { 65 return err 66 } 67 if err := objs.MyProg.Close(); err != nil { 68 return err 69 } 70 return nil 71 } 72 73 // } 74 75 func DocLoadAndAssign() { 76 spec, err := ebpf.LoadCollectionSpec("bpf_prog.o") 77 if err != nil { 78 panic(err) 79 } 80 81 // Insert only the resources specified in 'obj' into the kernel and assign 82 // them to their respective fields. If any requested resources are not found 83 // in the ELF, this will fail. Any errors encountered while loading Maps or 84 // Programs will also be returned here. 85 var objs myObjs 86 if err := spec.LoadAndAssign(&objs, nil); err != nil { 87 panic(err) 88 } 89 defer objs.Close() 90 91 // Interact with MyMap through the custom struct. 92 if err := objs.MyMap.Put(uint32(1), uint64(2)); err != nil { 93 panic(err) 94 } 95 } 96 97 func DocBTFTypeByName() { 98 spec, err := ebpf.LoadCollectionSpec("bpf_prog.o") 99 if err != nil { 100 panic(err) 101 } 102 103 // Look up the __64 type declared in linux/bpf.h. 104 t, err := spec.Types.AnyTypeByName("__u64") 105 if err != nil { 106 panic(err) 107 } 108 fmt.Println(t) 109 }