test_stacktrace_build_id.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright (c) 2018 Facebook
  3. #include <linux/bpf.h>
  4. #include "bpf_helpers.h"
  5. #ifndef PERF_MAX_STACK_DEPTH
  6. #define PERF_MAX_STACK_DEPTH 127
  7. #endif
  8. struct bpf_map_def SEC("maps") control_map = {
  9. .type = BPF_MAP_TYPE_ARRAY,
  10. .key_size = sizeof(__u32),
  11. .value_size = sizeof(__u32),
  12. .max_entries = 1,
  13. };
  14. struct bpf_map_def SEC("maps") stackid_hmap = {
  15. .type = BPF_MAP_TYPE_HASH,
  16. .key_size = sizeof(__u32),
  17. .value_size = sizeof(__u32),
  18. .max_entries = 16384,
  19. };
  20. struct bpf_map_def SEC("maps") stackmap = {
  21. .type = BPF_MAP_TYPE_STACK_TRACE,
  22. .key_size = sizeof(__u32),
  23. .value_size = sizeof(struct bpf_stack_build_id)
  24. * PERF_MAX_STACK_DEPTH,
  25. .max_entries = 128,
  26. .map_flags = BPF_F_STACK_BUILD_ID,
  27. };
  28. struct bpf_map_def SEC("maps") stack_amap = {
  29. .type = BPF_MAP_TYPE_ARRAY,
  30. .key_size = sizeof(__u32),
  31. .value_size = sizeof(struct bpf_stack_build_id)
  32. * PERF_MAX_STACK_DEPTH,
  33. .max_entries = 128,
  34. };
  35. /* taken from /sys/kernel/debug/tracing/events/random/urandom_read/format */
  36. struct random_urandom_args {
  37. unsigned long long pad;
  38. int got_bits;
  39. int pool_left;
  40. int input_left;
  41. };
  42. SEC("tracepoint/random/urandom_read")
  43. int oncpu(struct random_urandom_args *args)
  44. {
  45. __u32 max_len = sizeof(struct bpf_stack_build_id)
  46. * PERF_MAX_STACK_DEPTH;
  47. __u32 key = 0, val = 0, *value_p;
  48. void *stack_p;
  49. value_p = bpf_map_lookup_elem(&control_map, &key);
  50. if (value_p && *value_p)
  51. return 0; /* skip if non-zero *value_p */
  52. /* The size of stackmap and stackid_hmap should be the same */
  53. key = bpf_get_stackid(args, &stackmap, BPF_F_USER_STACK);
  54. if ((int)key >= 0) {
  55. bpf_map_update_elem(&stackid_hmap, &key, &val, 0);
  56. stack_p = bpf_map_lookup_elem(&stack_amap, &key);
  57. if (stack_p)
  58. bpf_get_stack(args, stack_p, max_len,
  59. BPF_F_USER_STACK | BPF_F_USER_BUILD_ID);
  60. }
  61. return 0;
  62. }
  63. char _license[] SEC("license") = "GPL";
  64. __u32 _version SEC("version") = 1; /* ignored by tracepoints, required by libbpf.a */