| 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 |
|
| 10 |
|
| 11 |
func ExampleToEBPF() { |
| 12 |
|
| 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 |
|
| 23 |
|
| 24 |
_ = prog |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
func buildEBPF(filter []bpf.Instruction, offset uint16) (asm.Instructions, error) { |
| 31 |
ebpfFilter, err := ToEBPF(filter, EBPFOpts{ |
| 32 |
|
| 33 |
PacketStart: asm.R2, |
| 34 |
PacketStartMaxOffset: offset, |
| 35 |
PacketEnd: asm.R3, |
| 36 |
|
| 37 |
Result: asm.R4, |
| 38 |
ResultLabel: "result", |
| 39 |
|
| 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 |
|
| 49 |
|
| 50 |
|
| 51 |
asm.LoadMem(asm.R2, asm.R1, 0, asm.Word), |
| 52 |
|
| 53 |
asm.Add.Imm(asm.R2, int32(offset)), |
| 54 |
|
| 55 |
|
| 56 |
asm.LoadMem(asm.R3, asm.R1, 4, asm.Word), |
| 57 |
|
| 58 |
|
| 59 |
} |
| 60 |
|
| 61 |
prog = append(prog, ebpfFilter...) |
| 62 |
|
| 63 |
prog = append(prog, |
| 64 |
asm.Mov.Imm(asm.R0, 2).WithSymbol("result"), |
| 65 |
asm.JEq.Imm(asm.R4, 0, "return"), |
| 66 |
asm.Mov.Imm(asm.R0, 1), |
| 67 |
asm.Return().WithSymbol("return"), |
| 68 |
) |
| 69 |
|
| 70 |
return prog, nil |
| 71 |
} |