github.com/dylandreimerink/gobpfld@v0.6.1-0.20220205171531-e79c330ad608/emulator/inst_call_helper.go (about)

     1  package emulator
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/dylandreimerink/gobpfld/ebpf"
     7  )
     8  
     9  var _ Instruction = (*CallHelper)(nil)
    10  
    11  type CallHelper struct {
    12  	ebpf.CallHelper
    13  }
    14  
    15  func (i *CallHelper) Clone() Instruction {
    16  	c := *i
    17  	return &c
    18  }
    19  
    20  func (i *CallHelper) Execute(vm *VM) error {
    21  	if int(i.Function) >= len(vm.HelperFunctions) {
    22  		return fmt.Errorf("VM has no helper function for ID '%d'", i.Function)
    23  	}
    24  
    25  	f := vm.HelperFunctions[i.Function]
    26  	if f == nil {
    27  		return fmt.Errorf("VM has no helper function for ID '%d'", i.Function)
    28  	}
    29  
    30  	err := f(vm)
    31  	if err != nil {
    32  		return fmt.Errorf("helper function paniced: %w", err)
    33  	}
    34  
    35  	return nil
    36  }
    37  
    38  var _ Instruction = (*CallHelperIndirect)(nil)
    39  
    40  type CallHelperIndirect struct {
    41  	ebpf.CallHelperIndirect
    42  }
    43  
    44  func (i *CallHelperIndirect) Clone() Instruction {
    45  	c := *i
    46  	return &c
    47  }
    48  
    49  func (i *CallHelperIndirect) Execute(vm *VM) error {
    50  	fReg, err := vm.Registers.Get(i.Register)
    51  	if err != nil {
    52  		return fmt.Errorf("get reg: %w", err)
    53  	}
    54  	fVal := fReg.Value()
    55  
    56  	if int(fVal) >= len(vm.HelperFunctions) {
    57  		return fmt.Errorf("VM has no helper function for ID '%d'", fVal)
    58  	}
    59  
    60  	f := vm.HelperFunctions[fVal]
    61  	if f == nil {
    62  		return fmt.Errorf("VM has no helper function for ID '%d'", fVal)
    63  	}
    64  
    65  	err = f(vm)
    66  	if err != nil {
    67  		return fmt.Errorf("helper function '%d' paniced: %w", fVal, err)
    68  	}
    69  
    70  	return nil
    71  }