2 * Strictly speaking, this is not a test. But it can report during test
3 * runs so relative performace can be measured.
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>
17 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
19 unsigned long long timing(clockid_t clk_id, unsigned long long samples)
21 struct timespec start, finish;
26 assert(clock_gettime(clk_id, &start) == 0);
27 for (i = 0; i < samples; i++) {
28 ret = syscall(__NR_getpid);
31 assert(clock_gettime(clk_id, &finish) == 0);
33 i = finish.tv_sec - start.tv_sec;
35 i += finish.tv_nsec - start.tv_nsec;
37 printf("%lu.%09lu - %lu.%09lu = %llu (%.1fs)\n",
38 finish.tv_sec, finish.tv_nsec,
39 start.tv_sec, start.tv_nsec,
40 i, (double)i / 1000000000.0);
45 unsigned long long calibrate(void)
47 struct timespec start, finish;
48 unsigned long long i, samples, step = 9973;
52 printf("Calibrating sample size for %d seconds worth of syscalls ...\n", seconds);
56 assert(clock_gettime(CLOCK_MONOTONIC, &start) == 0);
58 for (i = 0; i < step; i++) {
59 ret = syscall(__NR_getpid);
62 assert(clock_gettime(CLOCK_MONOTONIC, &finish) == 0);
65 i = finish.tv_sec - start.tv_sec;
67 i += finish.tv_nsec - start.tv_nsec;
68 } while (i < 1000000000ULL);
70 return samples * seconds;
73 int main(int argc, char *argv[])
75 struct sock_filter filter[] = {
76 BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),
78 struct sock_fprog prog = {
79 .len = (unsigned short)ARRAY_SIZE(filter),
83 unsigned long long samples;
84 unsigned long long native, filter1, filter2;
86 printf("Current BPF sysctl settings:\n");
87 system("sysctl net.core.bpf_jit_enable");
88 system("sysctl net.core.bpf_jit_harden");
91 samples = strtoull(argv[1], NULL, 0);
93 samples = calibrate();
95 printf("Benchmarking %llu syscalls...\n", samples);
98 native = timing(CLOCK_PROCESS_CPUTIME_ID, samples) / samples;
99 printf("getpid native: %llu ns\n", native);
101 ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
105 ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
108 filter1 = timing(CLOCK_PROCESS_CPUTIME_ID, samples) / samples;
109 printf("getpid RET_ALLOW 1 filter: %llu ns\n", filter1);
111 if (filter1 == native)
112 printf("No overhead measured!? Try running again with more samples.\n");
115 ret = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
118 filter2 = timing(CLOCK_PROCESS_CPUTIME_ID, samples) / samples;
119 printf("getpid RET_ALLOW 2 filters: %llu ns\n", filter2);
122 printf("Estimated total seccomp overhead for 1 filter: %llu ns\n",
125 printf("Estimated total seccomp overhead for 2 filters: %llu ns\n",
128 printf("Estimated seccomp per-filter overhead: %llu ns\n",
131 printf("Estimated seccomp entry overhead: %llu ns\n",
132 filter1 - native - (filter2 - filter1));