github.com/vishvananda/netlink@v1.3.0/bpf_linux.go (about)

     1  package netlink
     2  
     3  import (
     4  	"unsafe"
     5  
     6  	"golang.org/x/sys/unix"
     7  )
     8  
     9  type BpfProgType uint32
    10  
    11  const (
    12  	BPF_PROG_TYPE_UNSPEC BpfProgType = iota
    13  	BPF_PROG_TYPE_SOCKET_FILTER
    14  	BPF_PROG_TYPE_KPROBE
    15  	BPF_PROG_TYPE_SCHED_CLS
    16  	BPF_PROG_TYPE_SCHED_ACT
    17  	BPF_PROG_TYPE_TRACEPOINT
    18  	BPF_PROG_TYPE_XDP
    19  	BPF_PROG_TYPE_PERF_EVENT
    20  	BPF_PROG_TYPE_CGROUP_SKB
    21  	BPF_PROG_TYPE_CGROUP_SOCK
    22  	BPF_PROG_TYPE_LWT_IN
    23  	BPF_PROG_TYPE_LWT_OUT
    24  	BPF_PROG_TYPE_LWT_XMIT
    25  	BPF_PROG_TYPE_SOCK_OPS
    26  	BPF_PROG_TYPE_SK_SKB
    27  	BPF_PROG_TYPE_CGROUP_DEVICE
    28  	BPF_PROG_TYPE_SK_MSG
    29  	BPF_PROG_TYPE_RAW_TRACEPOINT
    30  	BPF_PROG_TYPE_CGROUP_SOCK_ADDR
    31  	BPF_PROG_TYPE_LWT_SEG6LOCAL
    32  	BPF_PROG_TYPE_LIRC_MODE2
    33  	BPF_PROG_TYPE_SK_REUSEPORT
    34  	BPF_PROG_TYPE_FLOW_DISSECTOR
    35  	BPF_PROG_TYPE_CGROUP_SYSCTL
    36  	BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE
    37  	BPF_PROG_TYPE_CGROUP_SOCKOPT
    38  	BPF_PROG_TYPE_TRACING
    39  	BPF_PROG_TYPE_STRUCT_OPS
    40  	BPF_PROG_TYPE_EXT
    41  	BPF_PROG_TYPE_LSM
    42  	BPF_PROG_TYPE_SK_LOOKUP
    43  )
    44  
    45  type BPFAttr struct {
    46  	ProgType    uint32
    47  	InsnCnt     uint32
    48  	Insns       uintptr
    49  	License     uintptr
    50  	LogLevel    uint32
    51  	LogSize     uint32
    52  	LogBuf      uintptr
    53  	KernVersion uint32
    54  }
    55  
    56  // loadSimpleBpf loads a trivial bpf program for testing purposes.
    57  func loadSimpleBpf(progType BpfProgType, ret uint32) (int, error) {
    58  	insns := []uint64{
    59  		0x00000000000000b7 | (uint64(ret) << 32),
    60  		0x0000000000000095,
    61  	}
    62  	license := []byte{'A', 'S', 'L', '2', '\x00'}
    63  	attr := BPFAttr{
    64  		ProgType: uint32(progType),
    65  		InsnCnt:  uint32(len(insns)),
    66  		Insns:    uintptr(unsafe.Pointer(&insns[0])),
    67  		License:  uintptr(unsafe.Pointer(&license[0])),
    68  	}
    69  	fd, _, errno := unix.Syscall(unix.SYS_BPF,
    70  		5, /* bpf cmd */
    71  		uintptr(unsafe.Pointer(&attr)),
    72  		unsafe.Sizeof(attr))
    73  	if errno != 0 {
    74  		return 0, errno
    75  	}
    76  	return int(fd), nil
    77  }