tracex4_user.c 2.2 KB

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