test_current_task_under_cgroup_user.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 <linux/bpf.h>
  14. #include "cgroup_helpers.h"
  15. #define CGROUP_PATH "/my-cgroup"
  16. int main(int argc, char **argv)
  17. {
  18. pid_t remote_pid, local_pid = getpid();
  19. int cg2, idx = 0, rc = 0;
  20. char filename[256];
  21. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  22. if (load_bpf_file(filename)) {
  23. printf("%s", bpf_log_buf);
  24. return 1;
  25. }
  26. if (setup_cgroup_environment())
  27. goto err;
  28. cg2 = create_and_get_cgroup(CGROUP_PATH);
  29. if (!cg2)
  30. goto err;
  31. if (bpf_map_update_elem(map_fd[0], &idx, &cg2, BPF_ANY)) {
  32. log_err("Adding target cgroup to map");
  33. goto err;
  34. }
  35. if (join_cgroup(CGROUP_PATH))
  36. goto err;
  37. /*
  38. * The installed helper program catched the sync call, and should
  39. * write it to the map.
  40. */
  41. sync();
  42. bpf_map_lookup_elem(map_fd[1], &idx, &remote_pid);
  43. if (local_pid != remote_pid) {
  44. fprintf(stderr,
  45. "BPF Helper didn't write correct PID to map, but: %d\n",
  46. remote_pid);
  47. goto err;
  48. }
  49. /* Verify the negative scenario; leave the cgroup */
  50. if (join_cgroup("/"))
  51. goto err;
  52. remote_pid = 0;
  53. bpf_map_update_elem(map_fd[1], &idx, &remote_pid, BPF_ANY);
  54. sync();
  55. bpf_map_lookup_elem(map_fd[1], &idx, &remote_pid);
  56. if (local_pid == remote_pid) {
  57. fprintf(stderr, "BPF cgroup negative test did not work\n");
  58. goto err;
  59. }
  60. goto out;
  61. err:
  62. rc = 1;
  63. out:
  64. close(cg2);
  65. cleanup_cgroup_environment();
  66. return rc;
  67. }