bpf_linux.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package netlink
  2. import (
  3. "unsafe"
  4. "golang.org/x/sys/unix"
  5. )
  6. type BpfProgType uint32
  7. const (
  8. BPF_PROG_TYPE_UNSPEC BpfProgType = iota
  9. BPF_PROG_TYPE_SOCKET_FILTER
  10. BPF_PROG_TYPE_KPROBE
  11. BPF_PROG_TYPE_SCHED_CLS
  12. BPF_PROG_TYPE_SCHED_ACT
  13. BPF_PROG_TYPE_TRACEPOINT
  14. BPF_PROG_TYPE_XDP
  15. )
  16. type BPFAttr struct {
  17. ProgType uint32
  18. InsnCnt uint32
  19. Insns uintptr
  20. License uintptr
  21. LogLevel uint32
  22. LogSize uint32
  23. LogBuf uintptr
  24. KernVersion uint32
  25. }
  26. // loadSimpleBpf loads a trivial bpf program for testing purposes.
  27. func loadSimpleBpf(progType BpfProgType, ret uint32) (int, error) {
  28. insns := []uint64{
  29. 0x00000000000000b7 | (uint64(ret) << 32),
  30. 0x0000000000000095,
  31. }
  32. license := []byte{'A', 'S', 'L', '2', '\x00'}
  33. attr := BPFAttr{
  34. ProgType: uint32(progType),
  35. InsnCnt: uint32(len(insns)),
  36. Insns: uintptr(unsafe.Pointer(&insns[0])),
  37. License: uintptr(unsafe.Pointer(&license[0])),
  38. }
  39. fd, _, errno := unix.Syscall(unix.SYS_BPF,
  40. 5, /* bpf cmd */
  41. uintptr(unsafe.Pointer(&attr)),
  42. unsafe.Sizeof(attr))
  43. if errno != 0 {
  44. return 0, errno
  45. }
  46. return int(fd), nil
  47. }