seccomp_benchmark.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * Strictly speaking, this is not a test. But it can report during test
  3. * runs so relative performace can be measured.
  4. */
  5. #define _GNU_SOURCE
  6. #include <assert.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <time.h>
  10. #include <unistd.h>
  11. #include <linux/filter.h>
  12. #include <linux/seccomp.h>
  13. #include <sys/prctl.h>
  14. #include <sys/syscall.h>
  15. #include <sys/types.h>
  16. #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
  17. unsigned long long timing(clockid_t clk_id, unsigned long long samples)
  18. {
  19. pid_t pid, ret;
  20. unsigned long long i;
  21. struct timespec start, finish;
  22. pid = getpid();
  23. assert(clock_gettime(clk_id, &start) == 0);
  24. for (i = 0; i < samples; i++) {
  25. ret = syscall(__NR_getpid);
  26. assert(pid == ret);
  27. }
  28. assert(clock_gettime(clk_id, &finish) == 0);
  29. i = finish.tv_sec - start.tv_sec;
  30. i *= 1000000000;
  31. i += finish.tv_nsec - start.tv_nsec;
  32. printf("%lu.%09lu - %lu.%09lu = %llu\n",
  33. finish.tv_sec, finish.tv_nsec,
  34. start.tv_sec, start.tv_nsec,
  35. i);
  36. return i;
  37. }
  38. unsigned long long calibrate(void)
  39. {
  40. unsigned long long i;
  41. printf("Calibrating reasonable sample size...\n");
  42. for (i = 5; ; i++) {
  43. unsigned long long samples = 1 << i;
  44. /* Find something that takes more than 5 seconds to run. */
  45. if (timing(CLOCK_REALTIME, samples) / 1000000000ULL > 5)
  46. return samples;
  47. }
  48. }
  49. int main(int argc, char *argv[])
  50. {
  51. struct sock_filter filter[] = {
  52. BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
  53. };
  54. struct sock_fprog prog = {
  55. .len = (unsigned short)ARRAY_SIZE(filter),
  56. .filter = filter,
  57. };
  58. long ret;
  59. unsigned long long samples;
  60. unsigned long long native, filtered;
  61. if (argc > 1)
  62. samples = strtoull(argv[1], NULL, 0);
  63. else
  64. samples = calibrate();
  65. printf("Benchmarking %llu samples...\n", samples);
  66. native = timing(CLOCK_PROCESS_CPUTIME_ID, samples) / samples;
  67. printf("getpid native: %llu ns\n", native);
  68. ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
  69. assert(ret == 0);
  70. ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
  71. assert(ret == 0);
  72. filtered = timing(CLOCK_PROCESS_CPUTIME_ID, samples) / samples;
  73. printf("getpid RET_ALLOW: %llu ns\n", filtered);
  74. printf("Estimated seccomp overhead per syscall: %llu ns\n",
  75. filtered - native);
  76. if (filtered == native)
  77. printf("Trying running again with more samples.\n");
  78. return 0;
  79. }