Debian Codegraph @

asm/instruction.go

raw symbols SCIP
1 package asm
2
3 import (
4 "crypto/sha1"
5 "crypto/sha256"
6 "encoding/binary"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "hash"
11 "io"
12 "math"
13 "sort"
14 "strings"
15
16 "github.com/cilium/ebpf/internal"
17 "github.com/cilium/ebpf/internal/platform"
18 "github.com/cilium/ebpf/internal/sys"
19 )
20
21 // InstructionSize is the size of a BPF instruction in bytes
22 const InstructionSize = 8
23
24 // RawInstructionOffset is an offset in units of raw BPF instructions.
25 type RawInstructionOffset uint64
26
27 var ErrUnreferencedSymbol = errors.New("unreferenced symbol")
28 var ErrUnsatisfiedMapReference = errors.New("unsatisfied map reference")
29 var ErrUnsatisfiedProgramReference = errors.New("unsatisfied program reference")
30
31 // Bytes returns the offset of an instruction in bytes.
32 func (rio RawInstructionOffset) Bytes() uint64 {
33 return uint64(rio) * InstructionSize
34 }
35
36 // Instruction is a single eBPF instruction.
37 type Instruction struct {
38 OpCode OpCode
39 Dst Register
40 Src Register
41 Offset int16
42 Constant int64
43
44 // Metadata contains optional metadata about this instruction.
45 Metadata Metadata
46 }
47
48 // Width returns how many raw BPF instructions the Instruction occupies within
49 // an instruction stream. For example, an Instruction encoding a 64-bit value
50 // will typically occupy 2 raw instructions, while a 32-bit constant can be
51 // encoded in a single raw instruction.
52 func (ins *Instruction) Width() RawInstructionOffset {
53 return RawInstructionOffset(ins.OpCode.rawInstructions())
54 }
55
56 // Unmarshal decodes a BPF instruction.
57 func (ins *Instruction) Unmarshal(r io.Reader, bo binary.ByteOrder, platform string) error {
58 data := make([]byte, InstructionSize)
59 if _, err := io.ReadFull(r, data); err != nil {
60 return err
61 }
62
63 ins.OpCode = OpCode(data[0])
64
65 regs := data[1]
66 switch bo {
67 case binary.LittleEndian:
68 ins.Dst, ins.Src = Register(regs&0xF), Register(regs>>4)
69 case binary.BigEndian:
70 ins.Dst, ins.Src = Register(regs>>4), Register(regs&0xf)
71 }
72
73 ins.Offset = int16(bo.Uint16(data[2:4]))
74
75 // Convert to int32 before widening to int64
76 // to ensure the signed bit is carried over.
77 ins.Constant = int64(int32(bo.Uint32(data[4:8])))
78
79 if ins.IsBuiltinCall() {
80 if ins.Constant >= 0 {
81 // Leave negative constants from the instruction stream
82 // unchanged. These are sometimes used as placeholders for later
83 // patching.
84 // This relies on not having a valid platform tag with a high bit set.
85 fn, err := BuiltinFuncForPlatform(platform, uint32(ins.Constant))
86 if err != nil {
87 return err
88 }
89 ins.Constant = int64(fn)
90 }
91 } else if ins.OpCode.Class().IsALU() {
92 switch ins.OpCode.ALUOp() {
93 case Div:
94 if ins.Offset == 1 {
95 ins.OpCode = ins.OpCode.SetALUOp(SDiv)
96 ins.Offset = 0
97 }
98 case Mod:
99 if ins.Offset == 1 {
100 ins.OpCode = ins.OpCode.SetALUOp(SMod)
101 ins.Offset = 0
102 }
103 case Mov:
104 switch ins.Offset {
105 case 8:
106 ins.OpCode = ins.OpCode.SetALUOp(MovSX8)
107 ins.Offset = 0
108 case 16:
109 ins.OpCode = ins.OpCode.SetALUOp(MovSX16)
110 ins.Offset = 0
111 case 32:
112 ins.OpCode = ins.OpCode.SetALUOp(MovSX32)
113 ins.Offset = 0
114 }
115 }
116 } else if ins.OpCode.Class() == StXClass &&
117 ins.OpCode.Mode() == AtomicMode {
118 // For atomic ops, part of the opcode is stored in the
119 // constant field. Shift over 8 bytes so we can OR with the actual opcode and
120 // apply `atomicMask` to avoid merging unknown bits that may be added in the future.
121 ins.OpCode |= (OpCode((ins.Constant << 8)) & atomicMask)
122 }
123
124 if !ins.OpCode.IsDWordLoad() {
125 return nil
126 }
127
128 // Pull another instruction from the stream to retrieve the second
129 // half of the 64-bit immediate value.
130 if _, err := io.ReadFull(r, data); err != nil {
131 // No Wrap, to avoid io.EOF clash
132 return errors.New("64bit immediate is missing second half")
133 }
134
135 // Require that all fields other than the value are zero.
136 if bo.Uint32(data[0:4]) != 0 {
137 return errors.New("64bit immediate has non-zero fields")
138 }
139
140 cons1 := uint32(ins.Constant)
141 cons2 := int32(bo.Uint32(data[4:8]))
142 ins.Constant = int64(cons2)<<32 | int64(cons1)
143
144 return nil
145 }
146
147 // Marshal encodes a BPF instruction.
148 func (ins Instruction) Marshal(w io.Writer, bo binary.ByteOrder) (uint64, error) {
149 if ins.OpCode == InvalidOpCode {
150 return 0, errors.New("invalid opcode")
151 }
152
153 isDWordLoad := ins.OpCode.IsDWordLoad()
154
155 cons := int32(ins.Constant)
156 if isDWordLoad {
157 // Encode least significant 32bit first for 64bit operations.
158 cons = int32(uint32(ins.Constant))
159 }
160
161 regs, err := newBPFRegisters(ins.Dst, ins.Src, bo)
162 if err != nil {
163 return 0, fmt.Errorf("can't marshal registers: %s", err)
164 }
165
166 if ins.IsBuiltinCall() {
167 fn := BuiltinFunc(ins.Constant)
168 plat, value := platform.DecodeConstant(fn)
169 if plat != platform.Native {
170 return 0, fmt.Errorf("function %s (%s): %w", fn, plat, internal.ErrNotSupportedOnOS)
171 }
172 cons = int32(value)
173 } else if ins.OpCode.Class().IsALU() {
174 newOffset := int16(0)
175 switch ins.OpCode.ALUOp() {
176 case SDiv:
177 ins.OpCode = ins.OpCode.SetALUOp(Div)
178 newOffset = 1
179 case SMod:
180 ins.OpCode = ins.OpCode.SetALUOp(Mod)
181 newOffset = 1
182 case MovSX8:
183 ins.OpCode = ins.OpCode.SetALUOp(Mov)
184 newOffset = 8
185 case MovSX16:
186 ins.OpCode = ins.OpCode.SetALUOp(Mov)
187 newOffset = 16
188 case MovSX32:
189 ins.OpCode = ins.OpCode.SetALUOp(Mov)
190 newOffset = 32
191 }
192 if newOffset != 0 && ins.Offset != 0 {
193 return 0, fmt.Errorf("extended ALU opcodes should have an .Offset of 0: %s", ins)
194 }
195 ins.Offset = newOffset
196 } else if atomic := ins.OpCode.AtomicOp(); atomic != InvalidAtomic {
197 ins.OpCode = ins.OpCode &^ atomicMask
198 ins.Constant = int64(atomic >> 8)
199 }
200
201 op, err := ins.OpCode.bpfOpCode()
202 if err != nil {
203 return 0, err
204 }
205
206 data := make([]byte, InstructionSize)
207 data[0] = op
208 data[1] = byte(regs)
209 bo.PutUint16(data[2:4], uint16(ins.Offset))
210 bo.PutUint32(data[4:8], uint32(cons))
211 if _, err := w.Write(data); err != nil {
212 return 0, err
213 }
214
215 if !isDWordLoad {
216 return InstructionSize, nil
217 }
218
219 // The first half of the second part of a double-wide instruction
220 // must be zero. The second half carries the value.
221 bo.PutUint32(data[0:4], 0)
222 bo.PutUint32(data[4:8], uint32(ins.Constant>>32))
223 if _, err := w.Write(data); err != nil {
224 return 0, err
225 }
226
227 return 2 * InstructionSize, nil
228 }
229
230 // AssociateMap associates a Map with this Instruction.
231 //
232 // Implicitly clears the Instruction's Reference field.
233 //
234 // Returns an error if the Instruction is not a map load.
235 func (ins *Instruction) AssociateMap(m FDer) error {
236 if !ins.IsLoadFromMap() {
237 return errors.New("not a load from a map")
238 }
239
240 ins.Metadata.Set(referenceMeta{}, nil)
241 ins.Metadata.Set(mapMeta{}, m)
242
243 return nil
244 }
245
246 func (ins *Instruction) encodeMapFD(fd int) {
247 // Preserve the offset value for direct map loads.
248 offset := uint64(ins.Constant) & (math.MaxUint32 << 32)
249 rawFd := uint64(uint32(fd))
250 ins.Constant = int64(offset | rawFd)
251 }
252
253 // mapFd returns the map file descriptor stored in the 32 least significant
254 // bits of ins' Constant field.
255 func (ins *Instruction) mapFd() int {
256 return int(int32(ins.Constant))
257 }
258
259 // RewriteMapOffset changes the offset of a direct load from a map.
260 //
261 // Returns an error if the instruction is not a direct load.
262 func (ins *Instruction) RewriteMapOffset(offset uint32) error {
263 if !ins.OpCode.IsDWordLoad() {
264 return fmt.Errorf("%s is not a 64 bit load", ins.OpCode)
265 }
266
267 if ins.Src != PseudoMapValue {
268 return errors.New("not a direct load from a map")
269 }
270
271 fd := uint64(ins.Constant) & math.MaxUint32
272 ins.Constant = int64(uint64(offset)<<32 | fd)
273 return nil
274 }
275
276 func (ins *Instruction) mapOffset() uint32 {
277 return uint32(uint64(ins.Constant) >> 32)
278 }
279
280 // IsLoadFromMap returns true if the instruction loads from a map.
281 //
282 // This covers both loading the map pointer and direct map value loads.
283 func (ins *Instruction) IsLoadFromMap() bool {
284 return ins.OpCode == LoadImmOp(DWord) && (ins.Src == PseudoMapFD || ins.Src == PseudoMapValue)
285 }
286
287 // IsFunctionCall returns true if the instruction calls another BPF function.
288 //
289 // This is not the same thing as a BPF helper call.
290 func (ins *Instruction) IsFunctionCall() bool {
291 return ins.OpCode.JumpOp() == Call && ins.Src == PseudoCall
292 }
293
294 // IsKfuncCall returns true if the instruction calls a kfunc.
295 //
296 // This is not the same thing as a BPF helper call.
297 func (ins *Instruction) IsKfuncCall() bool {
298 return ins.OpCode.JumpOp() == Call && ins.Src == PseudoKfuncCall
299 }
300
301 // IsLoadOfFunctionPointer returns true if the instruction loads a function pointer.
302 func (ins *Instruction) IsLoadOfFunctionPointer() bool {
303 return ins.OpCode.IsDWordLoad() && ins.Src == PseudoFunc
304 }
305
306 // IsFunctionReference returns true if the instruction references another BPF
307 // function, either by invoking a Call jump operation or by loading a function
308 // pointer.
309 func (ins *Instruction) IsFunctionReference() bool {
310 return ins.IsFunctionCall() || ins.IsLoadOfFunctionPointer()
311 }
312
313 // IsBuiltinCall returns true if the instruction is a built-in call, i.e. BPF helper call.
314 func (ins *Instruction) IsBuiltinCall() bool {
315 return ins.OpCode.JumpOp() == Call && ins.Src == R0 && ins.Dst == R0
316 }
317
318 // IsConstantLoad returns true if the instruction loads a constant of the
319 // given size.
320 func (ins *Instruction) IsConstantLoad(size Size) bool {
321 return ins.OpCode == LoadImmOp(size) && ins.Src == R0 && ins.Offset == 0
322 }
323
324 // Format implements fmt.Formatter.
325 func (ins Instruction) Format(f fmt.State, c rune) {
326 if c != 'v' {
327 fmt.Fprintf(f, "{UNRECOGNIZED: %c}", c)
328 return
329 }
330
331 op := ins.OpCode
332
333 if op == InvalidOpCode {
334 fmt.Fprint(f, "INVALID")
335 return
336 }
337
338 // Omit trailing space for Exit
339 if op.JumpOp() == Exit {
340 fmt.Fprint(f, op)
341 return
342 }
343
344 if ins.IsLoadFromMap() {
345 fd := ins.mapFd()
346 m := ins.Map()
347 switch ins.Src {
348 case PseudoMapFD:
349 if m != nil {
350 fmt.Fprintf(f, "LoadMapPtr dst: %s map: %s", ins.Dst, m)
351 } else {
352 fmt.Fprintf(f, "LoadMapPtr dst: %s fd: %d", ins.Dst, fd)
353 }
354
355 case PseudoMapValue:
356 if m != nil {
357 fmt.Fprintf(f, "LoadMapValue dst: %s, map: %s off: %d", ins.Dst, m, ins.mapOffset())
358 } else {
359 fmt.Fprintf(f, "LoadMapValue dst: %s, fd: %d off: %d", ins.Dst, fd, ins.mapOffset())
360 }
361 }
362
363 goto ref
364 }
365
366 switch cls := op.Class(); {
367 case cls.isLoadOrStore():
368 fmt.Fprintf(f, "%v ", op)
369 switch op.Mode() {
370 case ImmMode:
371 fmt.Fprintf(f, "dst: %s imm: %d", ins.Dst, ins.Constant)
372 case AbsMode:
373 fmt.Fprintf(f, "imm: %d", ins.Constant)
374 case IndMode:
375 fmt.Fprintf(f, "dst: %s src: %s imm: %d", ins.Dst, ins.Src, ins.Constant)
376 case MemMode, MemSXMode:
377 fmt.Fprintf(f, "dst: %s src: %s off: %d imm: %d", ins.Dst, ins.Src, ins.Offset, ins.Constant)
378 case AtomicMode:
379 fmt.Fprintf(f, "dst: %s src: %s off: %d", ins.Dst, ins.Src, ins.Offset)
380 }
381
382 case cls.IsALU():
383 fmt.Fprintf(f, "%v", op)
384 if op == Swap.Op(ImmSource) {
385 fmt.Fprintf(f, "%d", ins.Constant)
386 }
387
388 fmt.Fprintf(f, " dst: %s ", ins.Dst)
389 switch {
390 case op.ALUOp() == Swap:
391 break
392 case op.Source() == ImmSource:
393 fmt.Fprintf(f, "imm: %d", ins.Constant)
394 default:
395 fmt.Fprintf(f, "src: %s", ins.Src)
396 }
397
398 case cls.IsJump():
399 switch jop := op.JumpOp(); jop {
400 case Call:
401 fmt.Fprintf(f, "%v ", op)
402 switch ins.Src {
403 case PseudoCall:
404 // bpf-to-bpf call. For JIT-compiled programs, the kernel stores
405 // the PC offset in the 'off' field (ins.Offset) rather than 'imm'
406 // (ins.Constant). See kernel bpf_insn_prepare_dump in verifier.c.
407 if ins.Offset != 0 {
408 fmt.Fprint(f, ins.Offset)
409 } else {
410 fmt.Fprint(f, ins.Constant)
411 }
412 case PseudoKfuncCall:
413 // kfunc call
414 fmt.Fprintf(f, "Kfunc(%d)", ins.Constant)
415 default:
416 fmt.Fprint(f, BuiltinFunc(ins.Constant))
417 }
418
419 case Ja:
420 fmt.Fprintf(f, "%v ", op)
421 if ins.OpCode.Class() == Jump32Class {
422 fmt.Fprintf(f, "imm: %d", ins.Constant)
423 } else {
424 fmt.Fprintf(f, "off: %d", ins.Offset)
425 }
426
427 case JCOND:
428 switch ins.Src {
429 case PseudoMayGoto:
430 fmt.Fprintf(f, "JCond may_goto off: %d", ins.Offset)
431 default:
432 fmt.Fprintf(f, "%v", op)
433 }
434
435 default:
436 fmt.Fprintf(f, "%v ", op)
437 fmt.Fprintf(f, "dst: %s off: %d ", ins.Dst, ins.Offset)
438 if op.Source() == ImmSource {
439 fmt.Fprintf(f, "imm: %d", ins.Constant)
440 } else {
441 fmt.Fprintf(f, "src: %s", ins.Src)
442 }
443 }
444 default:
445 fmt.Fprintf(f, "%v ", op)
446 }
447
448 ref:
449 if ins.Reference() != "" {
450 fmt.Fprintf(f, " <%s>", ins.Reference())
451 }
452 }
453
454 func (ins Instruction) equal(other Instruction) bool {
455 return ins.OpCode == other.OpCode &&
456 ins.Dst == other.Dst &&
457 ins.Src == other.Src &&
458 ins.Offset == other.Offset &&
459 ins.Constant == other.Constant
460 }
461
462 // Size returns the amount of bytes ins would occupy in binary form.
463 func (ins Instruction) Size() uint64 {
464 return uint64(InstructionSize * ins.OpCode.rawInstructions())
465 }
466
467 // WithMetadata sets the given Metadata on the Instruction. e.g. to copy
468 // Metadata from another Instruction when replacing it.
469 func (ins Instruction) WithMetadata(meta Metadata) Instruction {
470 ins.Metadata = meta
471 return ins
472 }
473
474 type symbolMeta struct{}
475
476 // WithSymbol marks the Instruction as a Symbol, which other Instructions
477 // can point to using corresponding calls to WithReference.
478 func (ins Instruction) WithSymbol(name string) Instruction {
479 ins.Metadata.Set(symbolMeta{}, name)
480 return ins
481 }
482
483 // Symbol returns the value ins has been marked with using WithSymbol,
484 // otherwise returns an empty string. A symbol is often an Instruction
485 // at the start of a function body.
486 func (ins Instruction) Symbol() string {
487 sym, _ := ins.Metadata.Get(symbolMeta{}).(string)
488 return sym
489 }
490
491 type referenceMeta struct{}
492
493 // WithReference makes ins reference another Symbol or map by name.
494 func (ins Instruction) WithReference(ref string) Instruction {
495 ins.Metadata.Set(referenceMeta{}, ref)
496 return ins
497 }
498
499 // Reference returns the Symbol or map name referenced by ins, if any.
500 func (ins Instruction) Reference() string {
501 ref, _ := ins.Metadata.Get(referenceMeta{}).(string)
502 return ref
503 }
504
505 type mapMeta struct{}
506
507 // Map returns the Map referenced by ins, if any.
508 // An Instruction will contain a Map if e.g. it references an existing,
509 // pinned map that was opened during ELF loading.
510 func (ins Instruction) Map() FDer {
511 fd, _ := ins.Metadata.Get(mapMeta{}).(FDer)
512 return fd
513 }
514
515 type sourceMeta struct{}
516
517 // WithSource adds source information about the Instruction.
518 func (ins Instruction) WithSource(src fmt.Stringer) Instruction {
519 ins.Metadata.Set(sourceMeta{}, src)
520 return ins
521 }
522
523 // Source returns source information about the Instruction. The field is
524 // present when the compiler emits BTF line info about the Instruction and
525 // usually contains the line of source code responsible for it.
526 func (ins Instruction) Source() fmt.Stringer {
527 str, _ := ins.Metadata.Get(sourceMeta{}).(fmt.Stringer)
528 return str
529 }
530
531 // A Comment can be passed to Instruction.WithSource to add a comment
532 // to an instruction.
533 type Comment string
534
535 func (s Comment) String() string {
536 return string(s)
537 }
538
539 // FDer represents a resource tied to an underlying file descriptor.
540 // Used as a stand-in for e.g. ebpf.Map since that type cannot be
541 // imported here and FD() is the only method we rely on.
542 type FDer interface {
543 FD() int
544 }
545
546 // Instructions is an eBPF program.
547 type Instructions []Instruction
548
549 // AppendInstructions decodes [Instruction] from r and appends them to insns.
550 func AppendInstructions(insns Instructions, r io.Reader, bo binary.ByteOrder, platform string) (Instructions, error) {
551 var offset uint64
552 for {
553 var ins Instruction
554 err := ins.Unmarshal(r, bo, platform)
555 if errors.Is(err, io.EOF) {
556 break
557 }
558 if err != nil {
559 return nil, fmt.Errorf("offset %d: %w", offset, err)
560 }
561
562 insns = append(insns, ins)
563 offset += ins.Size()
564 }
565
566 return insns, nil
567 }
568
569 // Name returns the name of the function insns belongs to, if any.
570 func (insns Instructions) Name() string {
571 if len(insns) == 0 {
572 return ""
573 }
574 return insns[0].Symbol()
575 }
576
577 func (insns Instructions) String() string {
578 return fmt.Sprint(insns)
579 }
580
581 // Size returns the amount of bytes insns would occupy in binary form.
582 func (insns Instructions) Size() uint64 {
583 var sum uint64
584 for _, ins := range insns {
585 sum += ins.Size()
586 }
587 return sum
588 }
589
590 // AssociateMap updates all Instructions that Reference the given symbol
591 // to point to an existing Map m instead.
592 //
593 // Returns ErrUnreferencedSymbol error if no references to symbol are found
594 // in insns. If symbol is anything else than the symbol name of map (e.g.
595 // a bpf2bpf subprogram), an error is returned.
596 func (insns Instructions) AssociateMap(symbol string, m FDer) error {
597 if symbol == "" {
598 return errors.New("empty symbol")
599 }
600
601 var found bool
602 for i := range insns {
603 ins := &insns[i]
604 if ins.Reference() != symbol {
605 continue
606 }
607
608 if err := ins.AssociateMap(m); err != nil {
609 return err
610 }
611
612 found = true
613 }
614
615 if !found {
616 return fmt.Errorf("symbol %s: %w", symbol, ErrUnreferencedSymbol)
617 }
618
619 return nil
620 }
621
622 // SymbolOffsets returns the set of symbols and their offset in
623 // the instructions.
624 func (insns Instructions) SymbolOffsets() (map[string]int, error) {
625 offsets := make(map[string]int)
626
627 for i, ins := range insns {
628 if ins.Symbol() == "" {
629 continue
630 }
631
632 if _, ok := offsets[ins.Symbol()]; ok {
633 return nil, fmt.Errorf("duplicate symbol %s", ins.Symbol())
634 }
635
636 offsets[ins.Symbol()] = i
637 }
638
639 return offsets, nil
640 }
641
642 // FunctionReferences returns a set of symbol names these Instructions make
643 // bpf-to-bpf calls to.
644 func (insns Instructions) FunctionReferences() []string {
645 calls := make(map[string]struct{})
646 for _, ins := range insns {
647 if ins.Constant != -1 {
648 // BPF-to-BPF calls have -1 constants.
649 continue
650 }
651
652 if ins.Reference() == "" {
653 continue
654 }
655
656 if !ins.IsFunctionReference() {
657 continue
658 }
659
660 calls[ins.Reference()] = struct{}{}
661 }
662
663 result := make([]string, 0, len(calls))
664 for call := range calls {
665 result = append(result, call)
666 }
667
668 sort.Strings(result)
669 return result
670 }
671
672 // ReferenceOffsets returns the set of references and their offset in
673 // the instructions.
674 func (insns Instructions) ReferenceOffsets() map[string][]int {
675 offsets := make(map[string][]int)
676
677 for i, ins := range insns {
678 if ins.Reference() == "" {
679 continue
680 }
681
682 offsets[ins.Reference()] = append(offsets[ins.Reference()], i)
683 }
684
685 return offsets
686 }
687
688 // Format implements fmt.Formatter.
689 //
690 // You can control indentation of symbols by
691 // specifying a width. Setting a precision controls the indentation of
692 // instructions.
693 // The default character is a tab, which can be overridden by specifying
694 // the ' ' space flag.
695 func (insns Instructions) Format(f fmt.State, c rune) {
696 if c != 's' && c != 'v' {
697 fmt.Fprintf(f, "{UNKNOWN FORMAT '%c'}", c)
698 return
699 }
700
701 // Precision is better in this case, because it allows
702 // specifying 0 padding easily.
703 padding, ok := f.Precision()
704 if !ok {
705 padding = 1
706 }
707
708 indent := strings.Repeat("\t", padding)
709 if f.Flag(' ') {
710 indent = strings.Repeat(" ", padding)
711 }
712
713 symPadding, ok := f.Width()
714 if !ok {
715 symPadding = padding - 1
716 }
717 if symPadding < 0 {
718 symPadding = 0
719 }
720
721 symIndent := strings.Repeat("\t", symPadding)
722 if f.Flag(' ') {
723 symIndent = strings.Repeat(" ", symPadding)
724 }
725
726 // Guess how many digits we need at most, by assuming that all instructions
727 // are double wide.
728 highestOffset := len(insns) * 2
729 offsetWidth := int(math.Ceil(math.Log10(float64(highestOffset))))
730
731 iter := insns.Iterate()
732 for iter.Next() {
733 if iter.Ins.Symbol() != "" {
734 fmt.Fprintf(f, "%s%s:\n", symIndent, iter.Ins.Symbol())
735 }
736 if src := iter.Ins.Source(); src != nil {
737 line := strings.TrimSpace(src.String())
738 if line != "" {
739 fmt.Fprintf(f, "%s%*s; %s\n", indent, offsetWidth, " ", line)
740 }
741 }
742 fmt.Fprintf(f, "%s%*d: %v\n", indent, offsetWidth, iter.Offset, iter.Ins)
743 }
744 }
745
746 // Marshal encodes a BPF program into the kernel format.
747 //
748 // insns may be modified if there are unresolved jumps or bpf2bpf calls.
749 //
750 // Returns ErrUnsatisfiedProgramReference if there is a Reference Instruction
751 // without a matching Symbol Instruction within insns.
752 func (insns Instructions) Marshal(w io.Writer, bo binary.ByteOrder) error {
753 if err := insns.encodeFunctionReferences(); err != nil {
754 return err
755 }
756
757 if err := insns.encodeMapPointers(); err != nil {
758 return err
759 }
760
761 for i, ins := range insns {
762 if _, err := ins.Marshal(w, bo); err != nil {
763 return fmt.Errorf("instruction %d: %w", i, err)
764 }
765 }
766 return nil
767 }
768
769 // Tag calculates the kernel tag for a series of instructions.
770 //
771 // It mirrors bpf_prog_calc_tag in the kernel and so can be compared
772 // to ProgramInfo.Tag to figure out whether a loaded program matches
773 // certain instructions.
774 //
775 // Deprecated: The value produced by this method no longer matches tags produced
776 // by the kernel since Linux 6.18. Use [Instructions.HasTag] instead.
777 func (insns Instructions) Tag(bo binary.ByteOrder) (string, error) {
778 // We cannot determine which hashing function to use without probing the kernel.
779 // So use the legacy SHA-1 implementation and deprecate this method.
780 return insns.tagSha1(bo)
781 }
782
783 // HasTag returns true if the given tag matches the kernel tag of insns.
784 func (insns Instructions) HasTag(tag string, bo binary.ByteOrder) (bool, error) {
785 sha256Tag, err := insns.tagSha256(bo)
786 if err != nil {
787 return false, fmt.Errorf("hashing sha256: %w", err)
788 }
789 if tag == sha256Tag {
790 return true, nil
791 }
792
793 sha1Tag, err := insns.tagSha1(bo)
794 if err != nil {
795 return false, fmt.Errorf("hashing sha1: %w", err)
796 }
797
798 return tag == sha1Tag, nil
799 }
800
801 // tagSha1 calculates the kernel tag for a series of instructions.
802 //
803 // It mirrors bpf_prog_calc_tag in kernels up to v6.18 and can be compared to
804 // ProgramInfo.Tag to figure out whether a loaded Program matches insns.
805 func (insns Instructions) tagSha1(bo binary.ByteOrder) (string, error) {
806 h := sha1.New()
807 if err := insns.hash(h, bo); err != nil {
808 return "", err
809 }
810 return hex.EncodeToString(h.Sum(nil)[:sys.BPF_TAG_SIZE]), nil
811 }
812
813 // tagSha256 calculates the kernel tag for a series of instructions.
814 //
815 // It mirrors bpf_prog_calc_tag in the kernel and can be compared to
816 // ProgramInfo.Tag to figure out whether a loaded Program matches insns.
817 func (insns Instructions) tagSha256(bo binary.ByteOrder) (string, error) {
818 h := sha256.New()
819 if err := insns.hash(h, bo); err != nil {
820 return "", err
821 }
822 return hex.EncodeToString(h.Sum(nil)[:sys.BPF_TAG_SIZE]), nil
823 }
824
825 // hash calculates the hash of the instruction stream. Map load instructions
826 // are zeroed out, since these contain map file descriptors or pointers to
827 // maps, which will be different from load to load and would make the hash
828 // non-deterministic.
829 func (insns Instructions) hash(h hash.Hash, bo binary.ByteOrder) error {
830 for i, ins := range insns {
831 if ins.IsLoadFromMap() {
832 ins.Constant = 0
833 }
834 _, err := ins.Marshal(h, bo)
835 if err != nil {
836 return fmt.Errorf("instruction %d: %w", i, err)
837 }
838 }
839 return nil
840 }
841
842 // encodeFunctionReferences populates the Offset (or Constant, depending on
843 // the instruction type) field of instructions with a Reference field to point
844 // to the offset of the corresponding instruction with a matching Symbol field.
845 //
846 // Only Reference Instructions that are either jumps or BPF function references
847 // (calls or function pointer loads) are populated.
848 //
849 // Returns ErrUnsatisfiedProgramReference if there is a Reference Instruction
850 // without at least one corresponding Symbol Instruction within insns.
851 func (insns Instructions) encodeFunctionReferences() error {
852 // Index the offsets of instructions tagged as a symbol.
853 symbolOffsets := make(map[string]RawInstructionOffset)
854 iter := insns.Iterate()
855 for iter.Next() {
856 ins := iter.Ins
857
858 if ins.Symbol() == "" {
859 continue
860 }
861
862 if _, ok := symbolOffsets[ins.Symbol()]; ok {
863 return fmt.Errorf("duplicate symbol %s", ins.Symbol())
864 }
865
866 symbolOffsets[ins.Symbol()] = iter.Offset
867 }
868
869 // Find all instructions tagged as references to other symbols.
870 // Depending on the instruction type, populate their constant or offset
871 // fields to point to the symbol they refer to within the insn stream.
872 iter = insns.Iterate()
873 for iter.Next() {
874 i := iter.Index
875 offset := iter.Offset
876 ins := iter.Ins
877
878 if ins.Reference() == "" {
879 continue
880 }
881
882 switch {
883 case ins.IsFunctionReference() && ins.Constant == -1,
884 ins.OpCode == Ja.opCode(Jump32Class, ImmSource) && ins.Constant == -1:
885 symOffset, ok := symbolOffsets[ins.Reference()]
886 if !ok {
887 return fmt.Errorf("%s at insn %d: symbol %q: %w", ins.OpCode, i, ins.Reference(), ErrUnsatisfiedProgramReference)
888 }
889
890 ins.Constant = int64(symOffset - offset - 1)
891
892 case ins.OpCode.Class().IsJump() && ins.Offset == -1:
893 symOffset, ok := symbolOffsets[ins.Reference()]
894 if !ok {
895 return fmt.Errorf("%s at insn %d: symbol %q: %w", ins.OpCode, i, ins.Reference(), ErrUnsatisfiedProgramReference)
896 }
897
898 ins.Offset = int16(symOffset - offset - 1)
899 }
900 }
901
902 return nil
903 }
904
905 // encodeMapPointers finds all Map Instructions and encodes their FDs
906 // into their Constant fields.
907 func (insns Instructions) encodeMapPointers() error {
908 iter := insns.Iterate()
909 for iter.Next() {
910 ins := iter.Ins
911
912 if !ins.IsLoadFromMap() {
913 continue
914 }
915
916 m := ins.Map()
917 if m == nil {
918 continue
919 }
920
921 fd := m.FD()
922 if fd < 0 {
923 return fmt.Errorf("map %s: %w", m, sys.ErrClosedFd)
924 }
925
926 ins.encodeMapFD(m.FD())
927 }
928
929 return nil
930 }
931
932 // Iterate allows iterating a BPF program while keeping track of
933 // various offsets.
934 //
935 // Modifying the instruction slice will lead to undefined behaviour.
936 func (insns Instructions) Iterate() *InstructionIterator {
937 return &InstructionIterator{insns: insns}
938 }
939
940 // InstructionIterator iterates over a BPF program.
941 type InstructionIterator struct {
942 insns Instructions
943 // The instruction in question.
944 Ins *Instruction
945 // The index of the instruction in the original instruction slice.
946 Index int
947 // The offset of the instruction in raw BPF instructions. This accounts
948 // for double-wide instructions.
949 Offset RawInstructionOffset
950 }
951
952 // Next returns true as long as there are any instructions remaining.
953 func (iter *InstructionIterator) Next() bool {
954 if len(iter.insns) == 0 {
955 return false
956 }
957
958 if iter.Ins != nil {
959 iter.Index++
960 iter.Offset += RawInstructionOffset(iter.Ins.OpCode.rawInstructions())
961 }
962 iter.Ins = &iter.insns[0]
963 iter.insns = iter.insns[1:]
964 return true
965 }
966
967 type bpfRegisters uint8
968
969 func newBPFRegisters(dst, src Register, bo binary.ByteOrder) (bpfRegisters, error) {
970 switch bo {
971 case binary.LittleEndian:
972 return bpfRegisters((src << 4) | (dst & 0xF)), nil
973 case binary.BigEndian:
974 return bpfRegisters((dst << 4) | (src & 0xF)), nil
975 default:
976 return 0, fmt.Errorf("unrecognized ByteOrder %T", bo)
977 }
978 }