bpf_endian.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #ifndef __BPF_ENDIAN__
  2. #define __BPF_ENDIAN__
  3. #include <linux/swab.h>
  4. /* LLVM's BPF target selects the endianness of the CPU
  5. * it compiles on, or the user specifies (bpfel/bpfeb),
  6. * respectively. The used __BYTE_ORDER__ is defined by
  7. * the compiler, we cannot rely on __BYTE_ORDER from
  8. * libc headers, since it doesn't reflect the actual
  9. * requested byte order.
  10. *
  11. * Note, LLVM's BPF target has different __builtin_bswapX()
  12. * semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE
  13. * in bpfel and bpfeb case, which means below, that we map
  14. * to cpu_to_be16(). We could use it unconditionally in BPF
  15. * case, but better not rely on it, so that this header here
  16. * can be used from application and BPF program side, which
  17. * use different targets.
  18. */
  19. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  20. # define __bpf_ntohs(x) __builtin_bswap16(x)
  21. # define __bpf_htons(x) __builtin_bswap16(x)
  22. # define __bpf_constant_ntohs(x) ___constant_swab16(x)
  23. # define __bpf_constant_htons(x) ___constant_swab16(x)
  24. # define __bpf_ntohl(x) __builtin_bswap32(x)
  25. # define __bpf_htonl(x) __builtin_bswap32(x)
  26. # define __bpf_constant_ntohl(x) ___constant_swab32(x)
  27. # define __bpf_constant_htonl(x) ___constant_swab32(x)
  28. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  29. # define __bpf_ntohs(x) (x)
  30. # define __bpf_htons(x) (x)
  31. # define __bpf_constant_ntohs(x) (x)
  32. # define __bpf_constant_htons(x) (x)
  33. # define __bpf_ntohl(x) (x)
  34. # define __bpf_htonl(x) (x)
  35. # define __bpf_constant_ntohl(x) (x)
  36. # define __bpf_constant_htonl(x) (x)
  37. #else
  38. # error "Fix your compiler's __BYTE_ORDER__?!"
  39. #endif
  40. #define bpf_htons(x) \
  41. (__builtin_constant_p(x) ? \
  42. __bpf_constant_htons(x) : __bpf_htons(x))
  43. #define bpf_ntohs(x) \
  44. (__builtin_constant_p(x) ? \
  45. __bpf_constant_ntohs(x) : __bpf_ntohs(x))
  46. #define bpf_htonl(x) \
  47. (__builtin_constant_p(x) ? \
  48. __bpf_constant_htonl(x) : __bpf_htonl(x))
  49. #define bpf_ntohl(x) \
  50. (__builtin_constant_p(x) ? \
  51. __bpf_constant_ntohl(x) : __bpf_ntohl(x))
  52. #endif /* __BPF_ENDIAN__ */