Debian Codegraph @

ebpf.go

raw symbols SCIP
1 package cbpfc
2
3 import (
4 "fmt"
5 "math"
6
7 "github.com/cilium/ebpf/asm"
8 "github.com/pkg/errors"
9 "golang.org/x/net/bpf"
10 )
11
12 // internal label when packet doesn't match
13 const noMatchLabel = "nomatch"
14
15 // alu operation to eBPF
16 var aluToEBPF = map[bpf.ALUOp]asm.ALUOp{
17 bpf.ALUOpAdd: asm.Add,
18 bpf.ALUOpSub: asm.Sub,
19 bpf.ALUOpMul: asm.Mul,
20 bpf.ALUOpDiv: asm.Div,
21 bpf.ALUOpOr: asm.Or,
22 bpf.ALUOpAnd: asm.And,
23 bpf.ALUOpShiftLeft: asm.LSh,
24 bpf.ALUOpShiftRight: asm.RSh,
25 bpf.ALUOpMod: asm.Mod,
26 bpf.ALUOpXor: asm.Xor,
27 }
28
29 // bpf sizes to ebpf
30 var sizeToEBPF = map[int]asm.Size{
31 1: asm.Byte,
32 2: asm.Half,
33 4: asm.Word,
34 }
35
36 // EBPFOpts control how a cBPF filter is converted to eBPF
37 type EBPFOpts struct {
38 // PacketStart is a register holding a pointer to the start of the packet.
39 // If this pointer is offset from the original BPF context pointer,
40 // the maximum value of this offset must be set as PacketStartMaxOffset.
41 // Not modified.
42 PacketStart asm.Register
43 // PacketStartMaxOffset is the maximum offset PacketStart is at, in bytes.
44 PacketStartMaxOffset uint16
45 // PacketEnd is a register holding a pointer to the end of the packet.
46 // Not modified.
47 PacketEnd asm.Register
48 // Register to output the filter return value in.
49 Result asm.Register
50
51 // Label to jump to with the result of the filter in register Result.
52 ResultLabel string
53
54 // Working are registers used internally.
55 // Caller saved.
56 // Must be different to PacketStart and PacketEnd, but Result can be reused.
57 Working [4]asm.Register
58
59 // StackOffset is the number of bytes of stack already used / reserved.
60 // R10 (ebpf frame pointer) + StackOffset will be used as the top of the stack.
61 StackOffset int
62
63 // LabelPrefix is the prefix to prepend to labels used internally.
64 LabelPrefix string
65 }
66
67 // ebpfOpts is the internal version of EBPFOpts
68 type ebpfOpts struct {
69 EBPFOpts
70
71 // Registers mapping directly to cBPF
72 regA asm.Register
73 regX asm.Register
74
75 // Temp / scratch register
76 regTmp asm.Register
77
78 // Register for indirect packet loads
79 // Allows the range of a packet guard to be preserved across multiple loads by the verifier
80 regIndirect asm.Register
81 }
82
83 func (e ebpfOpts) reg(reg bpf.Register) asm.Register {
84 switch reg {
85 case bpf.RegA:
86 return e.regA
87 case bpf.RegX:
88 return e.regX
89 default:
90 panic("unknown bpf register")
91 }
92 }
93
94 func (e ebpfOpts) label(name string) string {
95 return fmt.Sprintf("%s_%s", e.LabelPrefix, name)
96 }
97
98 // eBPF stack address offset for BPF scratch slot scracth.
99 func (e ebpfOpts) stackOffset(scratch int) int16 {
100 // First usable stack space ends at StackOffset.
101 return -int16(e.StackOffset + (scratch+1)*4)
102 }
103
104 // ToEBF converts a cBPF filter to eBPF.
105 //
106 // The generated eBPF code always jumps to opts.ResultLabel, with register opts.Result containing the filter's return value:
107 // 0 if the packet does not match the cBPF filter,
108 // non 0 if the packet does match.
109 func ToEBPF(filter []bpf.Instruction, opts EBPFOpts) (asm.Instructions, error) {
110 blocks, err := compile(filter, compileOpts{
111 packetStartMaxOffset: opts.PacketStartMaxOffset,
112 })
113 if err != nil {
114 return nil, err
115 }
116
117 eOpts := ebpfOpts{
118 EBPFOpts: opts,
119 regA: opts.Working[0],
120 regX: opts.Working[1],
121 regTmp: opts.Working[2],
122 regIndirect: opts.Working[3],
123 }
124
125 // opts.Result does not have to be unique
126 err = registersUnique(eOpts.PacketStart, eOpts.PacketEnd, eOpts.regA, eOpts.regX, eOpts.regTmp, eOpts.regIndirect)
127 if err != nil {
128 return nil, err
129 }
130
131 err = registerValid(eOpts.Result)
132 if err != nil {
133 return nil, err
134 }
135
136 if eOpts.StackOffset&1 == 1 {
137 return nil, errors.Errorf("unaligned stack offset")
138 }
139
140 eInsns := asm.Instructions{}
141
142 for _, block := range blocks {
143 for i, insn := range block.insns {
144 eInsn, err := insnToEBPF(insn, block, eOpts)
145 if err != nil {
146 return nil, errors.Wrapf(err, "unable to compile %v", insn)
147 }
148
149 // First insn of the block, add symbol so it can be referenced in jumps
150 if i == 0 {
151 eInsn[0] = eInsn[0].WithSymbol(eOpts.label(block.Label()))
152 }
153
154 eInsns = append(eInsns, eInsn...)
155 }
156 }
157
158 // kernel verifier does not like dead code - only include no match block if we used it
159 if _, ok := eInsns.ReferenceOffsets()[eOpts.label(noMatchLabel)]; ok {
160 eInsns = append(eInsns,
161 asm.Mov.Imm(eOpts.Result, 0).WithSymbol(eOpts.label(noMatchLabel)),
162 asm.Ja.Label(opts.ResultLabel),
163 )
164 }
165
166 return eInsns, nil
167 }
168
169 // registersUnique ensures the registers are valid and unique
170 func registersUnique(regs ...asm.Register) error {
171 seen := make(map[asm.Register]struct{}, len(regs))
172
173 for _, reg := range regs {
174 if err := registerValid(reg); err != nil {
175 return err
176 }
177
178 if _, ok := seen[reg]; ok {
179 return errors.Errorf("register %v used twice", reg)
180 }
181 seen[reg] = struct{}{}
182 }
183
184 return nil
185 }
186
187 // registerValid ensures that a register is a valid ebpf register
188 func registerValid(reg asm.Register) error {
189 if reg > asm.R9 {
190 return errors.Errorf("invalid register %v", reg)
191 }
192
193 return nil
194 }
195
196 // insnToEBPF compiles an instruction to a set of eBPF instructions
197 func insnToEBPF(insn instruction, blk *block, opts ebpfOpts) (asm.Instructions, error) {
198 switch i := insn.Instruction.(type) {
199
200 case bpf.LoadConstant:
201 return ebpfInsn(asm.Mov.Imm32(opts.reg(i.Dst), int32(i.Val)))
202 case bpf.LoadScratch:
203 return ebpfInsn(asm.LoadMem(opts.reg(i.Dst), asm.R10, opts.stackOffset(i.N), asm.Word))
204
205 case bpf.LoadAbsolute:
206 return packetLoad(opts, opts.PacketStart, i.Off, i.Size, func(src asm.Register, offset int16, size asm.Size) asm.Instructions {
207 return appendNtoh(opts.regA, size,
208 asm.LoadMem(opts.regA, src, offset, size),
209 )
210 })
211
212 case bpf.LoadIndirect:
213 // last packet guard set opts.regIndirect to packetstart + x
214 return packetLoad(opts, opts.regIndirect, i.Off, i.Size, func(src asm.Register, offset int16, size asm.Size) asm.Instructions {
215 return appendNtoh(opts.regA, size,
216 asm.LoadMem(opts.regA, src, offset, size),
217 )
218 })
219
220 case bpf.LoadMemShift:
221 return packetLoad(opts, opts.PacketStart, i.Off, 1, func(src asm.Register, offset int16, size asm.Size) asm.Instructions {
222 return []asm.Instruction{
223 asm.LoadMem(opts.regX, src, offset, size),
224 asm.And.Imm32(opts.regX, 0xF), // clear upper 4 bits
225 asm.LSh.Imm32(opts.regX, 2), // 32bit words to bytes
226 }
227 })
228
229 case bpf.StoreScratch:
230 return ebpfInsn(asm.StoreMem(asm.R10, opts.stackOffset(i.N), opts.reg(i.Src), asm.Word))
231
232 case bpf.LoadExtension:
233 if i.Num != bpf.ExtLen {
234 return nil, errors.Errorf("unsupported BPF extension %v", i)
235 }
236
237 return ebpfInsn(
238 asm.Mov.Reg(opts.regA, opts.PacketEnd),
239 asm.Sub.Reg32(opts.regA, opts.PacketStart),
240 )
241
242 case bpf.ALUOpConstant:
243 return ebpfInsn(aluToEBPF[i.Op].Imm32(opts.regA, int32(i.Val)))
244 case bpf.ALUOpX:
245 return ebpfInsn(aluToEBPF[i.Op].Reg32(opts.regA, opts.regX))
246 case bpf.NegateA:
247 return ebpfInsn(asm.Neg.Imm32(opts.regA, 0))
248
249 case bpf.Jump:
250 return ebpfInsn(asm.Ja.Label(opts.label(blk.skipToBlock(skip(i.Skip)).Label())))
251 case bpf.JumpIf:
252 return condToEBPF(opts, skip(i.SkipTrue), skip(i.SkipFalse), blk, i.Cond, func(jo asm.JumpOp, label string) asm.Instructions {
253 // eBPF immediates are signed, zero extend into temp register
254 if int32(i.Val) < 0 {
255 return asm.Instructions{
256 asm.Mov.Imm32(opts.regTmp, int32(i.Val)),
257 jo.Reg(opts.regA, opts.regTmp, label),
258 }
259 }
260
261 return asm.Instructions{jo.Imm(opts.regA, int32(i.Val), label)}
262 })
263 case bpf.JumpIfX:
264 return condToEBPF(opts, skip(i.SkipTrue), skip(i.SkipFalse), blk, i.Cond, func(jo asm.JumpOp, label string) asm.Instructions {
265 return asm.Instructions{jo.Reg(opts.regA, opts.regX, label)}
266 })
267
268 case bpf.RetA:
269 return ebpfInsn(
270 asm.Mov.Reg32(opts.Result, opts.regA),
271 asm.Ja.Label(opts.ResultLabel),
272 )
273 case bpf.RetConstant:
274 return ebpfInsn(
275 asm.Mov.Imm32(opts.Result, int32(i.Val)),
276 asm.Ja.Label(opts.ResultLabel),
277 )
278
279 case bpf.TXA:
280 return ebpfInsn(asm.Mov.Reg32(opts.regA, opts.regX))
281 case bpf.TAX:
282 return ebpfInsn(asm.Mov.Reg32(opts.regX, opts.regA))
283
284 case packetGuardAbsolute:
285 return ebpfInsn(
286 asm.Mov.Reg(opts.regTmp, opts.PacketStart),
287 asm.Add.Imm(opts.regTmp, i.end),
288 asm.JGT.Reg(opts.regTmp, opts.PacketEnd, opts.label(noMatchLabel)),
289 )
290 case packetGuardIndirect:
291 return ebpfInsn(
292 // Sign extend RegX to 64bits so we can do signed ALU operations.
293 asm.Mov.Reg(opts.regIndirect, opts.regX),
294 asm.LSh.Imm(opts.regIndirect, 32),
295 asm.ArSh.Imm(opts.regIndirect, 32),
296
297 // Check maxStartOffset()
298 asm.Add.Imm(opts.regIndirect, i.start),
299 asm.JGE.Imm(opts.regIndirect, i.maxStartOffset(), opts.label(noMatchLabel)),
300
301 // packet_start + signed x + start
302 // This will have a smin_value >= 0
303 asm.Add.Reg(opts.regIndirect, opts.PacketStart),
304
305 // different reg (so actual load picks offset), but same verifier context id
306 asm.Mov.Reg(opts.regTmp, opts.regIndirect),
307 asm.Add.Imm(opts.regTmp, i.length()),
308 asm.JGT.Reg(opts.regTmp, opts.PacketEnd, opts.label(noMatchLabel)),
309 )
310
311 case checkXNotZero:
312 return ebpfInsn(asm.JEq.Imm(opts.regX, 0, opts.label(noMatchLabel)))
313
314 default:
315 return nil, errors.Errorf("unsupported instruction %v", insn)
316 }
317
318 }
319
320 type packetRead func(src asm.Register, offset int16, size asm.Size) asm.Instructions
321
322 func packetLoad(opts ebpfOpts, src asm.Register, offset uint32, size int, makeRead packetRead) (asm.Instructions, error) {
323 // cBPF supports 32 bit signed offsets, but eBPF only 16 bit natively.
324 if int32(offset) > math.MaxInt16 || int32(offset) < math.MinInt16 {
325 return append(asm.Instructions{
326 asm.Mov.Reg(opts.regTmp, src),
327 // cBPF offsets are signed, casting to int32 is safe.
328 asm.Add.Imm(opts.regTmp, int32(offset)),
329 }, makeRead(opts.regTmp, 0, sizeToEBPF[size])...), nil
330 }
331
332 return makeRead(src, int16(offset), sizeToEBPF[size]), nil
333 }
334
335 func appendNtoh(reg asm.Register, size asm.Size, insns ...asm.Instruction) asm.Instructions {
336 if size == asm.Byte {
337 return insns
338 }
339
340 // BPF_FROM_BE should be a nop on big endian architectures
341 return append(insns, asm.HostTo(asm.BE, reg, size))
342 }
343
344 func condToEBPF(opts ebpfOpts, skipTrue, skipFalse skip, blk *block, cond bpf.JumpTest, insn func(jo asm.JumpOp, label string) asm.Instructions) (asm.Instructions, error) {
345 var condToJump = map[bpf.JumpTest]asm.JumpOp{
346 bpf.JumpEqual: asm.JEq,
347 bpf.JumpNotEqual: asm.JNE,
348 bpf.JumpGreaterThan: asm.JGT,
349 bpf.JumpLessThan: asm.JLT,
350 bpf.JumpGreaterOrEqual: asm.JGE,
351 bpf.JumpLessOrEqual: asm.JLE,
352 bpf.JumpBitsSet: asm.JSet,
353 // BitsNotSet doesn't map to anything nicely
354 }
355
356 trueLabel := opts.label(blk.skipToBlock(skipTrue).Label())
357 falseLabel := opts.label(blk.skipToBlock(skipFalse).Label())
358
359 // no skipFalse, we only have to explicitly jump to one block
360 trueOnly := skipFalse == 0
361
362 // No native BitsNotSet, convert to BitsSet
363 if cond == bpf.JumpBitsNotSet {
364 cond = bpf.JumpBitsSet
365
366 trueLabel, falseLabel = falseLabel, trueLabel
367
368 trueOnly = false
369 }
370
371 if trueOnly {
372 return insn(condToJump[cond], trueLabel), nil
373 }
374
375 return append(
376 insn(condToJump[cond], trueLabel),
377 asm.Ja.Label(falseLabel),
378 ), nil
379 }
380
381 func ebpfInsn(insns ...asm.Instruction) (asm.Instructions, error) {
382 return insns, nil
383 }