Debian Codegraph @

c.go

raw symbols SCIP
1 package cbpfc
2
3 import (
4 "fmt"
5 "regexp"
6 "strings"
7 "text/template"
8
9 "github.com/pkg/errors"
10 "golang.org/x/net/bpf"
11 )
12
13 const funcTemplate = `
14 // True if packet matches, false otherwise
15 {{- if not .NoInline}}
16 __attribute__((__always_inline__)) static inline
17 {{- end}}
18 uint32_t {{.Name}}(const uint8_t *const data, const uint8_t *const data_end) {
19 __attribute__((unused))
20 uint32_t a, x, m[16];
21 __attribute__((unused))
22 const uint8_t *indirect;
23
24 {{range $i, $b := .Blocks}}
25 {{$b.Label}}:
26 __attribute__((unused));
27 {{- range $i, $s := $b.Statements}}
28 {{$s}}
29 {{- end}}
30 {{end}}
31 }`
32
33 type cFunction struct {
34 Name string
35 NoInline bool
36 Blocks []cBlock
37 }
38
39 // cBPF reg to C symbol
40 var regToCSym = map[bpf.Register]string{
41 bpf.RegA: "a",
42 bpf.RegX: "x",
43 }
44
45 // alu operation to C operator
46 var aluToCOp = map[bpf.ALUOp]string{
47 bpf.ALUOpAdd: "+",
48 bpf.ALUOpSub: "-",
49 bpf.ALUOpMul: "*",
50 bpf.ALUOpDiv: "/",
51 bpf.ALUOpOr: "|",
52 bpf.ALUOpAnd: "&",
53 bpf.ALUOpShiftLeft: "<<",
54 bpf.ALUOpShiftRight: ">>",
55 bpf.ALUOpMod: "%",
56 bpf.ALUOpXor: "^",
57 }
58
59 // jump test to a C fmt string for condition
60 var condToCFmt = map[bpf.JumpTest]string{
61 bpf.JumpEqual: "a == %v",
62 bpf.JumpNotEqual: "a != %v",
63 bpf.JumpGreaterThan: "a > %v",
64 bpf.JumpLessThan: "a < %v",
65 bpf.JumpGreaterOrEqual: "a >= %v",
66 bpf.JumpLessOrEqual: "a <= %v",
67 bpf.JumpBitsSet: "a & %v",
68 bpf.JumpBitsNotSet: "!(a & %v)",
69 }
70
71 var funcNameRegex = regexp.MustCompile(`^[A-Za-z_][0-9A-Za-z_]*$`)
72
73 // cBLock is a block of compiled C
74 type cBlock struct {
75 *block
76
77 Statements []string
78 }
79
80 type COpts struct {
81 // FunctionName is the symbol to use as the generated C function. Must match regex:
82 // [A-Za-z_][0-9A-Za-z_]*
83 FunctionName string
84
85 // NoInline doesn't force the generated function to be inlined, allowing clang to emit
86 // a BPF to BPF call.
87 // Requires at least kernel 5.10 (for x86, later for other architectures) if used with tail-calls.
88 NoInline bool
89
90 // PacketStartMaxOffset is the maximum offset the packet start / data is at, in bytes.
91 PacketStartMaxOffset uint16
92 }
93
94 // ToC compiles a cBPF filter to a C function with a signature of:
95 //
96 // uint32_t opts.FunctionName(const uint8_t *const data, const uint8_t *const data_end)
97 //
98 // If the data pointer is offset from the original BPF context pointer,
99 // the maximum value of this offset must be set as COpts.PacketStartMaxOffset.
100 //
101 // The function returns the filter's return value:
102 // 0 if the packet does not match the cBPF filter,
103 // non 0 if the packet does match.
104 func ToC(filter []bpf.Instruction, opts COpts) (string, error) {
105 if !funcNameRegex.MatchString(opts.FunctionName) {
106 return "", errors.Errorf("invalid FunctionName %q", opts.FunctionName)
107 }
108
109 blocks, err := compile(filter, compileOpts{
110 packetStartMaxOffset: opts.PacketStartMaxOffset,
111 })
112 if err != nil {
113 return "", err
114 }
115
116 fun := cFunction{
117 Name: opts.FunctionName,
118 NoInline: opts.NoInline,
119 Blocks: make([]cBlock, len(blocks)),
120 }
121
122 // Compile blocks to C
123 for i, block := range blocks {
124 fun.Blocks[i], err = blockToC(block)
125 if err != nil {
126 return "", err
127 }
128 }
129
130 // Fill in the template
131 tmpl, err := template.New("cbfp_func").Parse(funcTemplate)
132 if err != nil {
133 return "", errors.Wrapf(err, "unable to parse func template")
134 }
135
136 c := strings.Builder{}
137
138 if err := tmpl.Execute(&c, fun); err != nil {
139 return "", errors.Wrapf(err, "unable to execute func template")
140 }
141
142 return c.String(), nil
143 }
144
145 // blockToC compiles a block to C.
146 func blockToC(blk *block) (cBlock, error) {
147 cBlk := cBlock{
148 block: blk,
149 }
150
151 for _, insn := range blk.insns {
152 stat, err := insnToC(insn, blk)
153 if err != nil {
154 return cBlk, errors.Wrapf(err, "unable to compile %v", insn)
155 }
156
157 cBlk.Statements = append(cBlk.Statements, stat...)
158 }
159
160 return cBlk, nil
161 }
162
163 // insnToC compiles an instruction to a single C line / statement.
164 func insnToC(insn instruction, blk *block) ([]string, error) {
165 switch i := insn.Instruction.(type) {
166
167 case bpf.LoadConstant:
168 return stat("%s = %d;", regToCSym[i.Dst], i.Val)
169 case bpf.LoadScratch:
170 return stat("%s = m[%d];", regToCSym[i.Dst], i.N)
171 case bpf.LoadAbsolute:
172 return packetLoadToC(i.Size, "data + %d", i.Off)
173 case bpf.LoadIndirect:
174 return packetLoadToC(i.Size, "indirect + %d", i.Off)
175 case bpf.LoadMemShift:
176 return stat("x = 4*(*(data + %d) & 0xf);", i.Off)
177
178 case bpf.StoreScratch:
179 return stat("m[%d] = %s;", i.N, regToCSym[i.Src])
180
181 case bpf.LoadExtension:
182 if i.Num != bpf.ExtLen {
183 return nil, errors.Errorf("unsupported BPF extension %v", i)
184 }
185
186 return stat("a = data_end - data;")
187
188 case bpf.ALUOpConstant:
189 return stat("a %s= %d;", aluToCOp[i.Op], i.Val)
190 case bpf.ALUOpX:
191 return stat("a %s= x;", aluToCOp[i.Op])
192 case bpf.NegateA:
193 return stat("a = -a;")
194
195 case bpf.Jump:
196 return stat("goto %s;", blk.skipToBlock(skip(i.Skip)).Label())
197 case bpf.JumpIf:
198 return condToC(skip(i.SkipTrue), skip(i.SkipFalse), blk, condToCFmt[i.Cond], i.Val)
199 case bpf.JumpIfX:
200 return condToC(skip(i.SkipTrue), skip(i.SkipFalse), blk, condToCFmt[i.Cond], "x")
201
202 case bpf.RetA:
203 return stat("return a;")
204 case bpf.RetConstant:
205 return stat("return %d;", i.Val)
206
207 case bpf.TXA:
208 return stat("a = x;")
209 case bpf.TAX:
210 return stat("x = a;")
211
212 case packetGuardAbsolute:
213 return stat("if (data + %d > data_end) return 0;", i.end)
214 case packetGuardIndirect:
215 return []string{
216 // Sign extend RegX to 64bits.
217 fmt.Sprintf("indirect = (uint8_t *) (((int64_t) (int32_t) x) + %d);", i.start),
218 fmt.Sprintf("if ((uint64_t)indirect >= %d) return false;", i.maxStartOffset()),
219 fmt.Sprintf("indirect = data + (uint64_t)indirect;"),
220 // Prevent clang from calculating indirect + delta() directly from the packet start when RegX is constant:
221 // only indirect has the correct bounds check.
222 fmt.Sprintf(`asm volatile("" : : "r" (indirect));`),
223 fmt.Sprintf("if (indirect + %d > data_end) return false;", i.length()),
224 }, nil
225
226 case checkXNotZero:
227 return stat("if (x == 0) return 0;")
228
229 default:
230 return nil, errors.Errorf("unsupported instruction %v", insn)
231 }
232 }
233
234 func packetLoadToC(size int, offsetFmt string, offsetArgs ...interface{}) ([]string, error) {
235 offset := fmt.Sprintf(offsetFmt, offsetArgs...)
236
237 switch size {
238 case 1:
239 return stat("a = *(%s);", offset)
240 case 2:
241 return stat("a = ntohs(*((uint16_t *) (%s)));", offset)
242 case 4:
243 return stat("a = ntohl(*((uint32_t *) (%s)));", offset)
244 }
245
246 return nil, errors.Errorf("unsupported load size %d", size)
247 }
248
249 func condToC(skipTrue, skipFalse skip, blk *block, condFmt string, condArgs ...interface{}) ([]string, error) {
250 cond := fmt.Sprintf(condFmt, condArgs...)
251
252 if skipFalse == 0 {
253 return stat("if (%s) goto %s;", cond, blk.skipToBlock(skipTrue).Label())
254 }
255
256 return stat("if (%s) goto %s; else goto %s;", cond, blk.skipToBlock(skipTrue).Label(), blk.skipToBlock(skipFalse).Label())
257 }
258
259 func stat(format string, a ...interface{}) ([]string, error) {
260 return []string{fmt.Sprintf(format, a...)}, nil
261 }