spintest_user.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. #include <sys/resource.h>
  7. #include <bpf/libbpf.h>
  8. #include <bpf/bpf.h>
  9. #include "trace_helpers.h"
  10. int main(int ac, char **argv)
  11. {
  12. struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY};
  13. char filename[256], symbol[256];
  14. struct bpf_object *obj = NULL;
  15. struct bpf_link *links[20];
  16. long key, next_key, value;
  17. struct bpf_program *prog;
  18. int map_fd, i, j = 0;
  19. const char *section;
  20. struct ksym *sym;
  21. if (setrlimit(RLIMIT_MEMLOCK, &r)) {
  22. perror("setrlimit(RLIMIT_MEMLOCK)");
  23. return 1;
  24. }
  25. if (load_kallsyms()) {
  26. printf("failed to process /proc/kallsyms\n");
  27. return 2;
  28. }
  29. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  30. obj = bpf_object__open_file(filename, NULL);
  31. if (libbpf_get_error(obj)) {
  32. fprintf(stderr, "ERROR: opening BPF object file failed\n");
  33. obj = NULL;
  34. goto cleanup;
  35. }
  36. /* load BPF program */
  37. if (bpf_object__load(obj)) {
  38. fprintf(stderr, "ERROR: loading BPF object file failed\n");
  39. goto cleanup;
  40. }
  41. map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
  42. if (map_fd < 0) {
  43. fprintf(stderr, "ERROR: finding a map in obj file failed\n");
  44. goto cleanup;
  45. }
  46. bpf_object__for_each_program(prog, obj) {
  47. section = bpf_program__section_name(prog);
  48. if (sscanf(section, "kprobe/%s", symbol) != 1)
  49. continue;
  50. /* Attach prog only when symbol exists */
  51. if (ksym_get_addr(symbol)) {
  52. links[j] = bpf_program__attach(prog);
  53. if (libbpf_get_error(links[j])) {
  54. fprintf(stderr, "bpf_program__attach failed\n");
  55. links[j] = NULL;
  56. goto cleanup;
  57. }
  58. j++;
  59. }
  60. }
  61. for (i = 0; i < 5; i++) {
  62. key = 0;
  63. printf("kprobing funcs:");
  64. while (bpf_map_get_next_key(map_fd, &key, &next_key) == 0) {
  65. bpf_map_lookup_elem(map_fd, &next_key, &value);
  66. assert(next_key == value);
  67. sym = ksym_search(value);
  68. key = next_key;
  69. if (!sym) {
  70. printf("ksym not found. Is kallsyms loaded?\n");
  71. continue;
  72. }
  73. printf(" %s", sym->name);
  74. }
  75. if (key)
  76. printf("\n");
  77. key = 0;
  78. while (bpf_map_get_next_key(map_fd, &key, &next_key) == 0)
  79. bpf_map_delete_elem(map_fd, &next_key);
  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. }