reloc.btf.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // clang-format off
  2. #include <linux/bpf.h>
  3. #include <bpf/bpf_helpers.h>
  4. #include <bpf/bpf_core_read.h>
  5. // clang-format on
  6. struct {
  7. __uint(type, BPF_MAP_TYPE_ARRAY);
  8. __type(key, __u32);
  9. __type(value, __u64);
  10. __uint(max_entries, 1);
  11. } output_map SEC(".maps");
  12. long set_output(__u64 value) {
  13. __u32 key = 0;
  14. return bpf_map_update_elem(&output_map, &key, &value, BPF_ANY);
  15. }
  16. struct relocated_struct_with_scalars {
  17. __u8 b;
  18. __u8 c;
  19. __u8 d;
  20. };
  21. __attribute__((noinline)) int field_global() {
  22. struct relocated_struct_with_scalars s = {1, 2, 3};
  23. return set_output(__builtin_preserve_access_index(s.b));
  24. }
  25. struct relocated_struct_with_pointer {
  26. struct relocated_struct_with_pointer *second;
  27. struct relocated_struct_with_pointer *first;
  28. };
  29. __attribute__((noinline)) int pointer_global() {
  30. struct relocated_struct_with_pointer s = {
  31. (struct relocated_struct_with_pointer *)42,
  32. (struct relocated_struct_with_pointer *)21,
  33. };
  34. return set_output((__u64)__builtin_preserve_access_index(s.first));
  35. }
  36. __attribute__((noinline)) int struct_flavors_global() {
  37. struct relocated_struct_with_scalars s = {1, 2, 3};
  38. if (bpf_core_field_exists(s.b)) {
  39. return set_output(__builtin_preserve_access_index(s.b));
  40. } else {
  41. return set_output(__builtin_preserve_access_index(s.c));
  42. }
  43. }
  44. enum relocated_enum_unsigned_32 { U32_VAL = 0xBBBBBBBB };
  45. __attribute__((noinline)) int enum_unsigned_32_global() {
  46. return set_output(
  47. bpf_core_enum_value(enum relocated_enum_unsigned_32, U32_VAL));
  48. }
  49. enum relocated_enum_signed_32 { S32_VAL = -0x7BBBBBBB };
  50. __attribute__((noinline)) int enum_signed_32_global() {
  51. return set_output(
  52. bpf_core_enum_value(enum relocated_enum_signed_32, S32_VAL));
  53. }
  54. enum relocated_enum_unsigned_64 { U64_VAL = 0xCCCCCCCCDDDDDDDD };
  55. __attribute__((noinline)) int enum_unsigned_64_global() {
  56. return set_output(
  57. bpf_core_enum_value(enum relocated_enum_unsigned_64, U64_VAL));
  58. }
  59. enum relocated_enum_signed_64 { S64_VAL = -0xCCCCCCCDDDDDDDD };
  60. __attribute__((noinline)) int enum_signed_64_global() {
  61. return set_output(
  62. bpf_core_enum_value(enum relocated_enum_signed_64, S64_VAL));
  63. }
  64. // Avoids dead code elimination by the compiler.
  65. int main() {
  66. field_global();
  67. pointer_global();
  68. struct_flavors_global();
  69. enum_unsigned_32_global();
  70. enum_signed_32_global();
  71. enum_unsigned_64_global();
  72. enum_signed_64_global();
  73. }