bpf_linux.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package netlink
  2. /*
  3. #include <asm/types.h>
  4. #include <asm/unistd.h>
  5. #include <errno.h>
  6. #include <stdio.h>
  7. #include <stdint.h>
  8. #include <unistd.h>
  9. static int load_simple_bpf(int prog_type, int ret) {
  10. #ifdef __NR_bpf
  11. // { return ret; }
  12. __u64 __attribute__((aligned(8))) insns[] = {
  13. 0x00000000000000b7ull | ((__u64)ret<<32),
  14. 0x0000000000000095ull,
  15. };
  16. __u8 __attribute__((aligned(8))) license[] = "ASL2";
  17. // Copied from a header file since libc is notoriously slow to update.
  18. // The call will succeed or fail and that will be our indication on
  19. // whether or not it is supported.
  20. struct {
  21. __u32 prog_type;
  22. __u32 insn_cnt;
  23. __u64 insns;
  24. __u64 license;
  25. __u32 log_level;
  26. __u32 log_size;
  27. __u64 log_buf;
  28. __u32 kern_version;
  29. } __attribute__((aligned(8))) attr = {
  30. .prog_type = prog_type,
  31. .insn_cnt = 2,
  32. .insns = (uintptr_t)&insns,
  33. .license = (uintptr_t)&license,
  34. };
  35. return syscall(__NR_bpf, 5, &attr, sizeof(attr));
  36. #else
  37. errno = EINVAL;
  38. return -1;
  39. #endif
  40. }
  41. */
  42. import "C"
  43. type BpfProgType C.int
  44. const (
  45. BPF_PROG_TYPE_UNSPEC BpfProgType = iota
  46. BPF_PROG_TYPE_SOCKET_FILTER
  47. BPF_PROG_TYPE_KPROBE
  48. BPF_PROG_TYPE_SCHED_CLS
  49. BPF_PROG_TYPE_SCHED_ACT
  50. BPF_PROG_TYPE_TRACEPOINT
  51. BPF_PROG_TYPE_XDP
  52. )
  53. // loadSimpleBpf loads a trivial bpf program for testing purposes
  54. func loadSimpleBpf(progType BpfProgType, ret int) (int, error) {
  55. fd, err := C.load_simple_bpf(C.int(progType), C.int(ret))
  56. return int(fd), err
  57. }