tracex4_user.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2015 PLUMgrid, http://plumgrid.com
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <signal.h>
  7. #include <unistd.h>
  8. #include <stdbool.h>
  9. #include <string.h>
  10. #include <time.h>
  11. #include <bpf/bpf.h>
  12. #include <bpf/libbpf.h>
  13. struct pair {
  14. long long val;
  15. __u64 ip;
  16. };
  17. static __u64 time_get_ns(void)
  18. {
  19. struct timespec ts;
  20. clock_gettime(CLOCK_MONOTONIC, &ts);
  21. return ts.tv_sec * 1000000000ull + ts.tv_nsec;
  22. }
  23. static void print_old_objects(int fd)
  24. {
  25. long long val = time_get_ns();
  26. __u64 key, next_key;
  27. struct pair v;
  28. key = write(1, "\e[1;1H\e[2J", 11); /* clear screen */
  29. key = -1;
  30. while (bpf_map_get_next_key(fd, &key, &next_key) == 0) {
  31. bpf_map_lookup_elem(fd, &next_key, &v);
  32. key = next_key;
  33. if (val - v.val < 1000000000ll)
  34. /* object was allocated more then 1 sec ago */
  35. continue;
  36. printf("obj 0x%llx is %2lldsec old was allocated at ip %llx\n",
  37. next_key, (val - v.val) / 1000000000ll, v.ip);
  38. }
  39. }
  40. int main(int ac, char **argv)
  41. {
  42. struct bpf_link *links[2];
  43. struct bpf_program *prog;
  44. struct bpf_object *obj;
  45. char filename[256];
  46. int map_fd, i, j = 0;
  47. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  48. obj = bpf_object__open_file(filename, NULL);
  49. if (libbpf_get_error(obj)) {
  50. fprintf(stderr, "ERROR: opening BPF object file failed\n");
  51. return 0;
  52. }
  53. /* load BPF program */
  54. if (bpf_object__load(obj)) {
  55. fprintf(stderr, "ERROR: loading BPF object file failed\n");
  56. goto cleanup;
  57. }
  58. map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
  59. if (map_fd < 0) {
  60. fprintf(stderr, "ERROR: finding a map in obj file failed\n");
  61. goto cleanup;
  62. }
  63. bpf_object__for_each_program(prog, obj) {
  64. links[j] = bpf_program__attach(prog);
  65. if (libbpf_get_error(links[j])) {
  66. fprintf(stderr, "ERROR: bpf_program__attach failed\n");
  67. links[j] = NULL;
  68. goto cleanup;
  69. }
  70. j++;
  71. }
  72. for (i = 0; ; i++) {
  73. print_old_objects(map_fd);
  74. sleep(1);
  75. }
  76. cleanup:
  77. for (j--; j >= 0; j--)
  78. bpf_link__destroy(links[j]);
  79. bpf_object__close(obj);
  80. return 0;
  81. }