Debian Codegraph @

ebpf_example_test.go

raw symbols SCIP
1 package cbpfc
2
3 import (
4 "github.com/cilium/ebpf/asm"
5 "github.com/pkg/errors"
6 "golang.org/x/net/bpf"
7 )
8
9 // ExampleToEBPF demonstrates how to use ToEBPF() to embed a cBPF filter
10 // in an eBPF assembly program.
11 func ExampleToEBPF() {
12 // simple cBPF filter that matches all packets
13 filter := []bpf.Instruction{
14 bpf.RetConstant{Val: 1},
15 }
16
17 prog, err := buildEBPF(filter, 0)
18 if err != nil {
19 panic(err)
20 }
21
22 // Prog can be loaded directly using cilium/ebpf,
23 // or converted to a '[]struct bpf_insn' for libbpf
24 _ = prog
25 }
26
27 // buildEBPF compiles a cBPF filter to eBPF, and embeds it an eBPF program.
28 // The XDP program XDP_DROP's incoming packets that match the filter.
29 // Returns the eBPF program instructions
30 func buildEBPF(filter []bpf.Instruction, offset uint16) (asm.Instructions, error) {
31 ebpfFilter, err := ToEBPF(filter, EBPFOpts{
32 // Pass packet start and end pointers in these registers
33 PacketStart: asm.R2,
34 PacketStartMaxOffset: offset,
35 PacketEnd: asm.R3,
36 // Result of filter
37 Result: asm.R4,
38 ResultLabel: "result",
39 // Registers used by generated code
40 Working: [4]asm.Register{asm.R4, asm.R5, asm.R6, asm.R7},
41 LabelPrefix: "filter",
42 })
43 if err != nil {
44 return nil, errors.Wrap(err, "converting filter to eBPF")
45 }
46
47 prog := asm.Instructions{
48 // R1 holds XDP context
49
50 // Packet start
51 asm.LoadMem(asm.R2, asm.R1, 0, asm.Word),
52 // Fixed offset
53 asm.Add.Imm(asm.R2, int32(offset)),
54
55 // Packet end
56 asm.LoadMem(asm.R3, asm.R1, 4, asm.Word),
57
58 // Fall through to filter
59 }
60
61 prog = append(prog, ebpfFilter...)
62
63 prog = append(prog,
64 asm.Mov.Imm(asm.R0, 2).WithSymbol("result"), // XDP_PASS
65 asm.JEq.Imm(asm.R4, 0, "return"),
66 asm.Mov.Imm(asm.R0, 1), // XDP_DROP
67 asm.Return().WithSymbol("return"),
68 )
69
70 return prog, nil
71 }