test_current_task_under_cgroup_user.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Copyright (c) 2016 Sargun Dhillon <sargun@sargun.me>
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of version 2 of the GNU General Public
  5. * License as published by the Free Software Foundation.
  6. */
  7. #define _GNU_SOURCE
  8. #include <stdio.h>
  9. #include <linux/bpf.h>
  10. #include <unistd.h>
  11. #include <bpf/bpf.h>
  12. #include "bpf_load.h"
  13. #include "cgroup_helpers.h"
  14. #define CGROUP_PATH "/my-cgroup"
  15. int main(int argc, char **argv)
  16. {
  17. pid_t remote_pid, local_pid = getpid();
  18. int cg2, idx = 0, rc = 0;
  19. char filename[256];
  20. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  21. if (load_bpf_file(filename)) {
  22. printf("%s", bpf_log_buf);
  23. return 1;
  24. }
  25. if (setup_cgroup_environment())
  26. goto err;
  27. cg2 = create_and_get_cgroup(CGROUP_PATH);
  28. if (!cg2)
  29. goto err;
  30. if (bpf_map_update_elem(map_fd[0], &idx, &cg2, BPF_ANY)) {
  31. log_err("Adding target cgroup to map");
  32. goto err;
  33. }
  34. if (join_cgroup(CGROUP_PATH))
  35. goto err;
  36. /*
  37. * The installed helper program catched the sync call, and should
  38. * write it to the map.
  39. */
  40. sync();
  41. bpf_map_lookup_elem(map_fd[1], &idx, &remote_pid);
  42. if (local_pid != remote_pid) {
  43. fprintf(stderr,
  44. "BPF Helper didn't write correct PID to map, but: %d\n",
  45. remote_pid);
  46. goto err;
  47. }
  48. /* Verify the negative scenario; leave the cgroup */
  49. if (join_cgroup("/"))
  50. goto err;
  51. remote_pid = 0;
  52. bpf_map_update_elem(map_fd[1], &idx, &remote_pid, BPF_ANY);
  53. sync();
  54. bpf_map_lookup_elem(map_fd[1], &idx, &remote_pid);
  55. if (local_pid == remote_pid) {
  56. fprintf(stderr, "BPF cgroup negative test did not work\n");
  57. goto err;
  58. }
  59. goto out;
  60. err:
  61. rc = 1;
  62. out:
  63. close(cg2);
  64. cleanup_cgroup_environment();
  65. return rc;
  66. }