Loading...
1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * Testsuite for eBPF verifier
4 *
5 * Copyright (c) 2014 PLUMgrid, http://plumgrid.com
6 * Copyright (c) 2017 Facebook
7 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
8 */
9
10#include <endian.h>
11#include <asm/types.h>
12#include <linux/types.h>
13#include <stdint.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <unistd.h>
17#include <errno.h>
18#include <string.h>
19#include <stddef.h>
20#include <stdbool.h>
21#include <sched.h>
22#include <limits.h>
23#include <assert.h>
24
25#include <linux/unistd.h>
26#include <linux/filter.h>
27#include <linux/bpf_perf_event.h>
28#include <linux/bpf.h>
29#include <linux/if_ether.h>
30#include <linux/btf.h>
31
32#include <bpf/btf.h>
33#include <bpf/bpf.h>
34#include <bpf/libbpf.h>
35
36#include "autoconf_helper.h"
37#include "unpriv_helpers.h"
38#include "cap_helpers.h"
39#include "bpf_rand.h"
40#include "bpf_util.h"
41#include "test_btf.h"
42#include "../../../include/linux/filter.h"
43#include "testing_helpers.h"
44
45#define MAX_INSNS BPF_MAXINSNS
46#define MAX_EXPECTED_INSNS 32
47#define MAX_UNEXPECTED_INSNS 32
48#define MAX_TEST_INSNS 1000000
49#define MAX_FIXUPS 8
50#define MAX_NR_MAPS 23
51#define MAX_TEST_RUNS 8
52#define POINTER_VALUE 0xcafe4all
53#define TEST_DATA_LEN 64
54#define MAX_FUNC_INFOS 8
55#define MAX_BTF_STRINGS 256
56#define MAX_BTF_TYPES 256
57
58#define INSN_OFF_MASK ((__s16)0xFFFF)
59#define INSN_IMM_MASK ((__s32)0xFFFFFFFF)
60#define SKIP_INSNS() BPF_RAW_INSN(0xde, 0xa, 0xd, 0xbeef, 0xdeadbeef)
61
62#define DEFAULT_LIBBPF_LOG_LEVEL 4
63
64#define F_NEEDS_EFFICIENT_UNALIGNED_ACCESS (1 << 0)
65#define F_LOAD_WITH_STRICT_ALIGNMENT (1 << 1)
66#define F_NEEDS_JIT_ENABLED (1 << 2)
67
68/* need CAP_BPF, CAP_NET_ADMIN, CAP_PERFMON to load progs */
69#define ADMIN_CAPS (1ULL << CAP_NET_ADMIN | \
70 1ULL << CAP_PERFMON | \
71 1ULL << CAP_BPF)
72#define UNPRIV_SYSCTL "kernel/unprivileged_bpf_disabled"
73static bool unpriv_disabled = false;
74static bool jit_disabled;
75static int skips;
76static bool verbose = false;
77static int verif_log_level = 0;
78
79struct kfunc_btf_id_pair {
80 const char *kfunc;
81 int insn_idx;
82};
83
84struct bpf_test {
85 const char *descr;
86 struct bpf_insn insns[MAX_INSNS];
87 struct bpf_insn *fill_insns;
88 /* If specified, test engine looks for this sequence of
89 * instructions in the BPF program after loading. Allows to
90 * test rewrites applied by verifier. Use values
91 * INSN_OFF_MASK and INSN_IMM_MASK to mask `off` and `imm`
92 * fields if content does not matter. The test case fails if
93 * specified instructions are not found.
94 *
95 * The sequence could be split into sub-sequences by adding
96 * SKIP_INSNS instruction at the end of each sub-sequence. In
97 * such case sub-sequences are searched for one after another.
98 */
99 struct bpf_insn expected_insns[MAX_EXPECTED_INSNS];
100 /* If specified, test engine applies same pattern matching
101 * logic as for `expected_insns`. If the specified pattern is
102 * matched test case is marked as failed.
103 */
104 struct bpf_insn unexpected_insns[MAX_UNEXPECTED_INSNS];
105 int fixup_map_hash_8b[MAX_FIXUPS];
106 int fixup_map_hash_48b[MAX_FIXUPS];
107 int fixup_map_hash_16b[MAX_FIXUPS];
108 int fixup_map_array_48b[MAX_FIXUPS];
109 int fixup_map_sockmap[MAX_FIXUPS];
110 int fixup_map_sockhash[MAX_FIXUPS];
111 int fixup_map_xskmap[MAX_FIXUPS];
112 int fixup_map_stacktrace[MAX_FIXUPS];
113 int fixup_prog1[MAX_FIXUPS];
114 int fixup_prog2[MAX_FIXUPS];
115 int fixup_map_in_map[MAX_FIXUPS];
116 int fixup_cgroup_storage[MAX_FIXUPS];
117 int fixup_percpu_cgroup_storage[MAX_FIXUPS];
118 int fixup_map_spin_lock[MAX_FIXUPS];
119 int fixup_map_array_ro[MAX_FIXUPS];
120 int fixup_map_array_wo[MAX_FIXUPS];
121 int fixup_map_array_small[MAX_FIXUPS];
122 int fixup_sk_storage_map[MAX_FIXUPS];
123 int fixup_map_event_output[MAX_FIXUPS];
124 int fixup_map_reuseport_array[MAX_FIXUPS];
125 int fixup_map_ringbuf[MAX_FIXUPS];
126 int fixup_map_timer[MAX_FIXUPS];
127 int fixup_map_kptr[MAX_FIXUPS];
128 struct kfunc_btf_id_pair fixup_kfunc_btf_id[MAX_FIXUPS];
129 /* Expected verifier log output for result REJECT or VERBOSE_ACCEPT.
130 * Can be a tab-separated sequence of expected strings. An empty string
131 * means no log verification.
132 */
133 const char *errstr;
134 const char *errstr_unpriv;
135 uint32_t insn_processed;
136 int prog_len;
137 enum {
138 UNDEF,
139 ACCEPT,
140 REJECT,
141 VERBOSE_ACCEPT,
142 } result, result_unpriv;
143 enum bpf_prog_type prog_type;
144 uint8_t flags;
145 void (*fill_helper)(struct bpf_test *self);
146 int runs;
147#define bpf_testdata_struct_t \
148 struct { \
149 uint32_t retval, retval_unpriv; \
150 union { \
151 __u8 data[TEST_DATA_LEN]; \
152 __u64 data64[TEST_DATA_LEN / 8]; \
153 }; \
154 }
155 union {
156 bpf_testdata_struct_t;
157 bpf_testdata_struct_t retvals[MAX_TEST_RUNS];
158 };
159 enum bpf_attach_type expected_attach_type;
160 const char *kfunc;
161 struct bpf_func_info func_info[MAX_FUNC_INFOS];
162 int func_info_cnt;
163 char btf_strings[MAX_BTF_STRINGS];
164 /* A set of BTF types to load when specified,
165 * use macro definitions from test_btf.h,
166 * must end with BTF_END_RAW
167 */
168 __u32 btf_types[MAX_BTF_TYPES];
169};
170
171/* Note we want this to be 64 bit aligned so that the end of our array is
172 * actually the end of the structure.
173 */
174#define MAX_ENTRIES 11
175
176struct test_val {
177 unsigned int index;
178 int foo[MAX_ENTRIES];
179};
180
181struct other_val {
182 long long foo;
183 long long bar;
184};
185
186static void bpf_fill_ld_abs_vlan_push_pop(struct bpf_test *self)
187{
188 /* test: {skb->data[0], vlan_push} x 51 + {skb->data[0], vlan_pop} x 51 */
189#define PUSH_CNT 51
190 /* jump range is limited to 16 bit. PUSH_CNT of ld_abs needs room */
191 unsigned int len = (1 << 15) - PUSH_CNT * 2 * 5 * 6;
192 struct bpf_insn *insn = self->fill_insns;
193 int i = 0, j, k = 0;
194
195 insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
196loop:
197 for (j = 0; j < PUSH_CNT; j++) {
198 insn[i++] = BPF_LD_ABS(BPF_B, 0);
199 /* jump to error label */
200 insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
201 i++;
202 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
203 insn[i++] = BPF_MOV64_IMM(BPF_REG_2, 1);
204 insn[i++] = BPF_MOV64_IMM(BPF_REG_3, 2);
205 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
206 BPF_FUNC_skb_vlan_push);
207 insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
208 i++;
209 }
210
211 for (j = 0; j < PUSH_CNT; j++) {
212 insn[i++] = BPF_LD_ABS(BPF_B, 0);
213 insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
214 i++;
215 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
216 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
217 BPF_FUNC_skb_vlan_pop);
218 insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
219 i++;
220 }
221 if (++k < 5)
222 goto loop;
223
224 for (; i < len - 3; i++)
225 insn[i] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0xbef);
226 insn[len - 3] = BPF_JMP_A(1);
227 /* error label */
228 insn[len - 2] = BPF_MOV32_IMM(BPF_REG_0, 0);
229 insn[len - 1] = BPF_EXIT_INSN();
230 self->prog_len = len;
231}
232
233static void bpf_fill_jump_around_ld_abs(struct bpf_test *self)
234{
235 struct bpf_insn *insn = self->fill_insns;
236 /* jump range is limited to 16 bit. every ld_abs is replaced by 6 insns,
237 * but on arches like arm, ppc etc, there will be one BPF_ZEXT inserted
238 * to extend the error value of the inlined ld_abs sequence which then
239 * contains 7 insns. so, set the dividend to 7 so the testcase could
240 * work on all arches.
241 */
242 unsigned int len = (1 << 15) / 7;
243 int i = 0;
244
245 insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
246 insn[i++] = BPF_LD_ABS(BPF_B, 0);
247 insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 10, len - i - 2);
248 i++;
249 while (i < len - 1)
250 insn[i++] = BPF_LD_ABS(BPF_B, 1);
251 insn[i] = BPF_EXIT_INSN();
252 self->prog_len = i + 1;
253}
254
255static void bpf_fill_rand_ld_dw(struct bpf_test *self)
256{
257 struct bpf_insn *insn = self->fill_insns;
258 uint64_t res = 0;
259 int i = 0;
260
261 insn[i++] = BPF_MOV32_IMM(BPF_REG_0, 0);
262 while (i < self->retval) {
263 uint64_t val = bpf_semi_rand_get();
264 struct bpf_insn tmp[2] = { BPF_LD_IMM64(BPF_REG_1, val) };
265
266 res ^= val;
267 insn[i++] = tmp[0];
268 insn[i++] = tmp[1];
269 insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
270 }
271 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_0);
272 insn[i++] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 32);
273 insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
274 insn[i] = BPF_EXIT_INSN();
275 self->prog_len = i + 1;
276 res ^= (res >> 32);
277 self->retval = (uint32_t)res;
278}
279
280#define MAX_JMP_SEQ 8192
281
282/* test the sequence of 8k jumps */
283static void bpf_fill_scale1(struct bpf_test *self)
284{
285 struct bpf_insn *insn = self->fill_insns;
286 int i = 0, k = 0;
287
288 insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
289 /* test to check that the long sequence of jumps is acceptable */
290 while (k++ < MAX_JMP_SEQ) {
291 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
292 BPF_FUNC_get_prandom_u32);
293 insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
294 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
295 insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
296 -8 * (k % 64 + 1));
297 }
298 /* is_state_visited() doesn't allocate state for pruning for every jump.
299 * Hence multiply jmps by 4 to accommodate that heuristic
300 */
301 while (i < MAX_TEST_INSNS - MAX_JMP_SEQ * 4)
302 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
303 insn[i] = BPF_EXIT_INSN();
304 self->prog_len = i + 1;
305 self->retval = 42;
306}
307
308/* test the sequence of 8k jumps in inner most function (function depth 8)*/
309static void bpf_fill_scale2(struct bpf_test *self)
310{
311 struct bpf_insn *insn = self->fill_insns;
312 int i = 0, k = 0;
313
314#define FUNC_NEST 7
315 for (k = 0; k < FUNC_NEST; k++) {
316 insn[i++] = BPF_CALL_REL(1);
317 insn[i++] = BPF_EXIT_INSN();
318 }
319 insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
320 /* test to check that the long sequence of jumps is acceptable */
321 k = 0;
322 while (k++ < MAX_JMP_SEQ) {
323 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
324 BPF_FUNC_get_prandom_u32);
325 insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
326 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
327 insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
328 -8 * (k % (64 - 4 * FUNC_NEST) + 1));
329 }
330 while (i < MAX_TEST_INSNS - MAX_JMP_SEQ * 4)
331 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
332 insn[i] = BPF_EXIT_INSN();
333 self->prog_len = i + 1;
334 self->retval = 42;
335}
336
337static void bpf_fill_scale(struct bpf_test *self)
338{
339 switch (self->retval) {
340 case 1:
341 return bpf_fill_scale1(self);
342 case 2:
343 return bpf_fill_scale2(self);
344 default:
345 self->prog_len = 0;
346 break;
347 }
348}
349
350static int bpf_fill_torturous_jumps_insn_1(struct bpf_insn *insn)
351{
352 unsigned int len = 259, hlen = 128;
353 int i;
354
355 insn[0] = BPF_EMIT_CALL(BPF_FUNC_get_prandom_u32);
356 for (i = 1; i <= hlen; i++) {
357 insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, i, hlen);
358 insn[i + hlen] = BPF_JMP_A(hlen - i);
359 }
360 insn[len - 2] = BPF_MOV64_IMM(BPF_REG_0, 1);
361 insn[len - 1] = BPF_EXIT_INSN();
362
363 return len;
364}
365
366static int bpf_fill_torturous_jumps_insn_2(struct bpf_insn *insn)
367{
368 unsigned int len = 4100, jmp_off = 2048;
369 int i, j;
370
371 insn[0] = BPF_EMIT_CALL(BPF_FUNC_get_prandom_u32);
372 for (i = 1; i <= jmp_off; i++) {
373 insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, i, jmp_off);
374 }
375 insn[i++] = BPF_JMP_A(jmp_off);
376 for (; i <= jmp_off * 2 + 1; i+=16) {
377 for (j = 0; j < 16; j++) {
378 insn[i + j] = BPF_JMP_A(16 - j - 1);
379 }
380 }
381
382 insn[len - 2] = BPF_MOV64_IMM(BPF_REG_0, 2);
383 insn[len - 1] = BPF_EXIT_INSN();
384
385 return len;
386}
387
388static void bpf_fill_torturous_jumps(struct bpf_test *self)
389{
390 struct bpf_insn *insn = self->fill_insns;
391 int i = 0;
392
393 switch (self->retval) {
394 case 1:
395 self->prog_len = bpf_fill_torturous_jumps_insn_1(insn);
396 return;
397 case 2:
398 self->prog_len = bpf_fill_torturous_jumps_insn_2(insn);
399 return;
400 case 3:
401 /* main */
402 insn[i++] = BPF_RAW_INSN(BPF_JMP|BPF_CALL, 0, 1, 0, 4);
403 insn[i++] = BPF_RAW_INSN(BPF_JMP|BPF_CALL, 0, 1, 0, 262);
404 insn[i++] = BPF_ST_MEM(BPF_B, BPF_REG_10, -32, 0);
405 insn[i++] = BPF_MOV64_IMM(BPF_REG_0, 3);
406 insn[i++] = BPF_EXIT_INSN();
407
408 /* subprog 1 */
409 i += bpf_fill_torturous_jumps_insn_1(insn + i);
410
411 /* subprog 2 */
412 i += bpf_fill_torturous_jumps_insn_2(insn + i);
413
414 self->prog_len = i;
415 return;
416 default:
417 self->prog_len = 0;
418 break;
419 }
420}
421
422static void bpf_fill_big_prog_with_loop_1(struct bpf_test *self)
423{
424 struct bpf_insn *insn = self->fill_insns;
425 /* This test was added to catch a specific use after free
426 * error, which happened upon BPF program reallocation.
427 * Reallocation is handled by core.c:bpf_prog_realloc, which
428 * reuses old memory if page boundary is not crossed. The
429 * value of `len` is chosen to cross this boundary on bpf_loop
430 * patching.
431 */
432 const int len = getpagesize() - 25;
433 int callback_load_idx;
434 int callback_idx;
435 int i = 0;
436
437 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_1, 1);
438 callback_load_idx = i;
439 insn[i++] = BPF_RAW_INSN(BPF_LD | BPF_IMM | BPF_DW,
440 BPF_REG_2, BPF_PSEUDO_FUNC, 0,
441 777 /* filled below */);
442 insn[i++] = BPF_RAW_INSN(0, 0, 0, 0, 0);
443 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_3, 0);
444 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_4, 0);
445 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_loop);
446
447 while (i < len - 3)
448 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0);
449 insn[i++] = BPF_EXIT_INSN();
450
451 callback_idx = i;
452 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0);
453 insn[i++] = BPF_EXIT_INSN();
454
455 insn[callback_load_idx].imm = callback_idx - callback_load_idx - 1;
456 self->func_info[1].insn_off = callback_idx;
457 self->prog_len = i;
458 assert(i == len);
459}
460
461/* BPF_SK_LOOKUP contains 13 instructions, if you need to fix up maps */
462#define BPF_SK_LOOKUP(func) \
463 /* struct bpf_sock_tuple tuple = {} */ \
464 BPF_MOV64_IMM(BPF_REG_2, 0), \
465 BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_2, -8), \
466 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -16), \
467 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -24), \
468 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -32), \
469 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -40), \
470 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -48), \
471 /* sk = func(ctx, &tuple, sizeof tuple, 0, 0) */ \
472 BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), \
473 BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -48), \
474 BPF_MOV64_IMM(BPF_REG_3, sizeof(struct bpf_sock_tuple)), \
475 BPF_MOV64_IMM(BPF_REG_4, 0), \
476 BPF_MOV64_IMM(BPF_REG_5, 0), \
477 BPF_EMIT_CALL(BPF_FUNC_ ## func)
478
479/* BPF_DIRECT_PKT_R2 contains 7 instructions, it initializes default return
480 * value into 0 and does necessary preparation for direct packet access
481 * through r2. The allowed access range is 8 bytes.
482 */
483#define BPF_DIRECT_PKT_R2 \
484 BPF_MOV64_IMM(BPF_REG_0, 0), \
485 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, \
486 offsetof(struct __sk_buff, data)), \
487 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1, \
488 offsetof(struct __sk_buff, data_end)), \
489 BPF_MOV64_REG(BPF_REG_4, BPF_REG_2), \
490 BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 8), \
491 BPF_JMP_REG(BPF_JLE, BPF_REG_4, BPF_REG_3, 1), \
492 BPF_EXIT_INSN()
493
494/* BPF_RAND_UEXT_R7 contains 4 instructions, it initializes R7 into a random
495 * positive u32, and zero-extend it into 64-bit.
496 */
497#define BPF_RAND_UEXT_R7 \
498 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, \
499 BPF_FUNC_get_prandom_u32), \
500 BPF_MOV64_REG(BPF_REG_7, BPF_REG_0), \
501 BPF_ALU64_IMM(BPF_LSH, BPF_REG_7, 33), \
502 BPF_ALU64_IMM(BPF_RSH, BPF_REG_7, 33)
503
504/* BPF_RAND_SEXT_R7 contains 5 instructions, it initializes R7 into a random
505 * negative u32, and sign-extend it into 64-bit.
506 */
507#define BPF_RAND_SEXT_R7 \
508 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, \
509 BPF_FUNC_get_prandom_u32), \
510 BPF_MOV64_REG(BPF_REG_7, BPF_REG_0), \
511 BPF_ALU64_IMM(BPF_OR, BPF_REG_7, 0x80000000), \
512 BPF_ALU64_IMM(BPF_LSH, BPF_REG_7, 32), \
513 BPF_ALU64_IMM(BPF_ARSH, BPF_REG_7, 32)
514
515static struct bpf_test tests[] = {
516#define FILL_ARRAY
517#include <verifier/tests.h>
518#undef FILL_ARRAY
519};
520
521static int probe_filter_length(const struct bpf_insn *fp)
522{
523 int len;
524
525 for (len = MAX_INSNS - 1; len > 0; --len)
526 if (fp[len].code != 0 || fp[len].imm != 0)
527 break;
528 return len + 1;
529}
530
531static bool skip_unsupported_map(enum bpf_map_type map_type)
532{
533 if (!libbpf_probe_bpf_map_type(map_type, NULL)) {
534 printf("SKIP (unsupported map type %d)\n", map_type);
535 skips++;
536 return true;
537 }
538 return false;
539}
540
541static int __create_map(uint32_t type, uint32_t size_key,
542 uint32_t size_value, uint32_t max_elem,
543 uint32_t extra_flags)
544{
545 LIBBPF_OPTS(bpf_map_create_opts, opts);
546 int fd;
547
548 opts.map_flags = (type == BPF_MAP_TYPE_HASH ? BPF_F_NO_PREALLOC : 0) | extra_flags;
549 fd = bpf_map_create(type, NULL, size_key, size_value, max_elem, &opts);
550 if (fd < 0) {
551 if (skip_unsupported_map(type))
552 return -1;
553 printf("Failed to create hash map '%s'!\n", strerror(errno));
554 }
555
556 return fd;
557}
558
559static int create_map(uint32_t type, uint32_t size_key,
560 uint32_t size_value, uint32_t max_elem)
561{
562 return __create_map(type, size_key, size_value, max_elem, 0);
563}
564
565static void update_map(int fd, int index)
566{
567 struct test_val value = {
568 .index = (6 + 1) * sizeof(int),
569 .foo[6] = 0xabcdef12,
570 };
571
572 assert(!bpf_map_update_elem(fd, &index, &value, 0));
573}
574
575static int create_prog_dummy_simple(enum bpf_prog_type prog_type, int ret)
576{
577 struct bpf_insn prog[] = {
578 BPF_MOV64_IMM(BPF_REG_0, ret),
579 BPF_EXIT_INSN(),
580 };
581
582 return bpf_prog_load(prog_type, NULL, "GPL", prog, ARRAY_SIZE(prog), NULL);
583}
584
585static int create_prog_dummy_loop(enum bpf_prog_type prog_type, int mfd,
586 int idx, int ret)
587{
588 struct bpf_insn prog[] = {
589 BPF_MOV64_IMM(BPF_REG_3, idx),
590 BPF_LD_MAP_FD(BPF_REG_2, mfd),
591 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
592 BPF_FUNC_tail_call),
593 BPF_MOV64_IMM(BPF_REG_0, ret),
594 BPF_EXIT_INSN(),
595 };
596
597 return bpf_prog_load(prog_type, NULL, "GPL", prog, ARRAY_SIZE(prog), NULL);
598}
599
600static int create_prog_array(enum bpf_prog_type prog_type, uint32_t max_elem,
601 int p1key, int p2key, int p3key)
602{
603 int mfd, p1fd, p2fd, p3fd;
604
605 mfd = bpf_map_create(BPF_MAP_TYPE_PROG_ARRAY, NULL, sizeof(int),
606 sizeof(int), max_elem, NULL);
607 if (mfd < 0) {
608 if (skip_unsupported_map(BPF_MAP_TYPE_PROG_ARRAY))
609 return -1;
610 printf("Failed to create prog array '%s'!\n", strerror(errno));
611 return -1;
612 }
613
614 p1fd = create_prog_dummy_simple(prog_type, 42);
615 p2fd = create_prog_dummy_loop(prog_type, mfd, p2key, 41);
616 p3fd = create_prog_dummy_simple(prog_type, 24);
617 if (p1fd < 0 || p2fd < 0 || p3fd < 0)
618 goto err;
619 if (bpf_map_update_elem(mfd, &p1key, &p1fd, BPF_ANY) < 0)
620 goto err;
621 if (bpf_map_update_elem(mfd, &p2key, &p2fd, BPF_ANY) < 0)
622 goto err;
623 if (bpf_map_update_elem(mfd, &p3key, &p3fd, BPF_ANY) < 0) {
624err:
625 close(mfd);
626 mfd = -1;
627 }
628 close(p3fd);
629 close(p2fd);
630 close(p1fd);
631 return mfd;
632}
633
634static int create_map_in_map(void)
635{
636 LIBBPF_OPTS(bpf_map_create_opts, opts);
637 int inner_map_fd, outer_map_fd;
638
639 inner_map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int),
640 sizeof(int), 1, NULL);
641 if (inner_map_fd < 0) {
642 if (skip_unsupported_map(BPF_MAP_TYPE_ARRAY))
643 return -1;
644 printf("Failed to create array '%s'!\n", strerror(errno));
645 return inner_map_fd;
646 }
647
648 opts.inner_map_fd = inner_map_fd;
649 outer_map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY_OF_MAPS, NULL,
650 sizeof(int), sizeof(int), 1, &opts);
651 if (outer_map_fd < 0) {
652 if (skip_unsupported_map(BPF_MAP_TYPE_ARRAY_OF_MAPS))
653 return -1;
654 printf("Failed to create array of maps '%s'!\n",
655 strerror(errno));
656 }
657
658 close(inner_map_fd);
659
660 return outer_map_fd;
661}
662
663static int create_cgroup_storage(bool percpu)
664{
665 enum bpf_map_type type = percpu ? BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE :
666 BPF_MAP_TYPE_CGROUP_STORAGE;
667 int fd;
668
669 fd = bpf_map_create(type, NULL, sizeof(struct bpf_cgroup_storage_key),
670 TEST_DATA_LEN, 0, NULL);
671 if (fd < 0) {
672 if (skip_unsupported_map(type))
673 return -1;
674 printf("Failed to create cgroup storage '%s'!\n",
675 strerror(errno));
676 }
677
678 return fd;
679}
680
681/* struct bpf_spin_lock {
682 * int val;
683 * };
684 * struct val {
685 * int cnt;
686 * struct bpf_spin_lock l;
687 * };
688 * struct bpf_timer {
689 * __u64 :64;
690 * __u64 :64;
691 * } __attribute__((aligned(8)));
692 * struct timer {
693 * struct bpf_timer t;
694 * };
695 * struct btf_ptr {
696 * struct prog_test_ref_kfunc __kptr_untrusted *ptr;
697 * struct prog_test_ref_kfunc __kptr *ptr;
698 * struct prog_test_member __kptr *ptr;
699 * }
700 */
701static const char btf_str_sec[] = "\0bpf_spin_lock\0val\0cnt\0l\0bpf_timer\0timer\0t"
702 "\0btf_ptr\0prog_test_ref_kfunc\0ptr\0kptr\0kptr_untrusted"
703 "\0prog_test_member";
704static __u32 btf_raw_types[] = {
705 /* int */
706 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
707 /* struct bpf_spin_lock */ /* [2] */
708 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 1), 4),
709 BTF_MEMBER_ENC(15, 1, 0), /* int val; */
710 /* struct val */ /* [3] */
711 BTF_TYPE_ENC(15, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 2), 8),
712 BTF_MEMBER_ENC(19, 1, 0), /* int cnt; */
713 BTF_MEMBER_ENC(23, 2, 32),/* struct bpf_spin_lock l; */
714 /* struct bpf_timer */ /* [4] */
715 BTF_TYPE_ENC(25, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0), 16),
716 /* struct timer */ /* [5] */
717 BTF_TYPE_ENC(35, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 1), 16),
718 BTF_MEMBER_ENC(41, 4, 0), /* struct bpf_timer t; */
719 /* struct prog_test_ref_kfunc */ /* [6] */
720 BTF_STRUCT_ENC(51, 0, 0),
721 BTF_STRUCT_ENC(95, 0, 0), /* [7] */
722 /* type tag "kptr_untrusted" */
723 BTF_TYPE_TAG_ENC(80, 6), /* [8] */
724 /* type tag "kptr" */
725 BTF_TYPE_TAG_ENC(75, 6), /* [9] */
726 BTF_TYPE_TAG_ENC(75, 7), /* [10] */
727 BTF_PTR_ENC(8), /* [11] */
728 BTF_PTR_ENC(9), /* [12] */
729 BTF_PTR_ENC(10), /* [13] */
730 /* struct btf_ptr */ /* [14] */
731 BTF_STRUCT_ENC(43, 3, 24),
732 BTF_MEMBER_ENC(71, 11, 0), /* struct prog_test_ref_kfunc __kptr_untrusted *ptr; */
733 BTF_MEMBER_ENC(71, 12, 64), /* struct prog_test_ref_kfunc __kptr *ptr; */
734 BTF_MEMBER_ENC(71, 13, 128), /* struct prog_test_member __kptr *ptr; */
735};
736
737static char bpf_vlog[UINT_MAX >> 8];
738
739static int load_btf_spec(__u32 *types, int types_len,
740 const char *strings, int strings_len)
741{
742 struct btf_header hdr = {
743 .magic = BTF_MAGIC,
744 .version = BTF_VERSION,
745 .hdr_len = sizeof(struct btf_header),
746 .type_len = types_len,
747 .str_off = types_len,
748 .str_len = strings_len,
749 };
750 void *ptr, *raw_btf;
751 int btf_fd;
752 LIBBPF_OPTS(bpf_btf_load_opts, opts,
753 .log_buf = bpf_vlog,
754 .log_size = sizeof(bpf_vlog),
755 .log_level = (verbose
756 ? verif_log_level
757 : DEFAULT_LIBBPF_LOG_LEVEL),
758 );
759
760 raw_btf = malloc(sizeof(hdr) + types_len + strings_len);
761
762 ptr = raw_btf;
763 memcpy(ptr, &hdr, sizeof(hdr));
764 ptr += sizeof(hdr);
765 memcpy(ptr, types, hdr.type_len);
766 ptr += hdr.type_len;
767 memcpy(ptr, strings, hdr.str_len);
768 ptr += hdr.str_len;
769
770 btf_fd = bpf_btf_load(raw_btf, ptr - raw_btf, &opts);
771 if (btf_fd < 0)
772 printf("Failed to load BTF spec: '%s'\n", strerror(errno));
773
774 free(raw_btf);
775
776 return btf_fd < 0 ? -1 : btf_fd;
777}
778
779static int load_btf(void)
780{
781 return load_btf_spec(btf_raw_types, sizeof(btf_raw_types),
782 btf_str_sec, sizeof(btf_str_sec));
783}
784
785static int load_btf_for_test(struct bpf_test *test)
786{
787 int types_num = 0;
788
789 while (types_num < MAX_BTF_TYPES &&
790 test->btf_types[types_num] != BTF_END_RAW)
791 ++types_num;
792
793 int types_len = types_num * sizeof(test->btf_types[0]);
794
795 return load_btf_spec(test->btf_types, types_len,
796 test->btf_strings, sizeof(test->btf_strings));
797}
798
799static int create_map_spin_lock(void)
800{
801 LIBBPF_OPTS(bpf_map_create_opts, opts,
802 .btf_key_type_id = 1,
803 .btf_value_type_id = 3,
804 );
805 int fd, btf_fd;
806
807 btf_fd = load_btf();
808 if (btf_fd < 0)
809 return -1;
810 opts.btf_fd = btf_fd;
811 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "test_map", 4, 8, 1, &opts);
812 if (fd < 0)
813 printf("Failed to create map with spin_lock\n");
814 return fd;
815}
816
817static int create_sk_storage_map(void)
818{
819 LIBBPF_OPTS(bpf_map_create_opts, opts,
820 .map_flags = BPF_F_NO_PREALLOC,
821 .btf_key_type_id = 1,
822 .btf_value_type_id = 3,
823 );
824 int fd, btf_fd;
825
826 btf_fd = load_btf();
827 if (btf_fd < 0)
828 return -1;
829 opts.btf_fd = btf_fd;
830 fd = bpf_map_create(BPF_MAP_TYPE_SK_STORAGE, "test_map", 4, 8, 0, &opts);
831 close(opts.btf_fd);
832 if (fd < 0)
833 printf("Failed to create sk_storage_map\n");
834 return fd;
835}
836
837static int create_map_timer(void)
838{
839 LIBBPF_OPTS(bpf_map_create_opts, opts,
840 .btf_key_type_id = 1,
841 .btf_value_type_id = 5,
842 );
843 int fd, btf_fd;
844
845 btf_fd = load_btf();
846 if (btf_fd < 0)
847 return -1;
848
849 opts.btf_fd = btf_fd;
850 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "test_map", 4, 16, 1, &opts);
851 if (fd < 0)
852 printf("Failed to create map with timer\n");
853 return fd;
854}
855
856static int create_map_kptr(void)
857{
858 LIBBPF_OPTS(bpf_map_create_opts, opts,
859 .btf_key_type_id = 1,
860 .btf_value_type_id = 14,
861 );
862 int fd, btf_fd;
863
864 btf_fd = load_btf();
865 if (btf_fd < 0)
866 return -1;
867
868 opts.btf_fd = btf_fd;
869 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "test_map", 4, 24, 1, &opts);
870 if (fd < 0)
871 printf("Failed to create map with btf_id pointer\n");
872 return fd;
873}
874
875static void set_root(bool set)
876{
877 __u64 caps;
878
879 if (set) {
880 if (cap_enable_effective(1ULL << CAP_SYS_ADMIN, &caps))
881 perror("cap_disable_effective(CAP_SYS_ADMIN)");
882 } else {
883 if (cap_disable_effective(1ULL << CAP_SYS_ADMIN, &caps))
884 perror("cap_disable_effective(CAP_SYS_ADMIN)");
885 }
886}
887
888static __u64 ptr_to_u64(const void *ptr)
889{
890 return (uintptr_t) ptr;
891}
892
893static struct btf *btf__load_testmod_btf(struct btf *vmlinux)
894{
895 struct bpf_btf_info info;
896 __u32 len = sizeof(info);
897 struct btf *btf = NULL;
898 char name[64];
899 __u32 id = 0;
900 int err, fd;
901
902 /* Iterate all loaded BTF objects and find bpf_testmod,
903 * we need SYS_ADMIN cap for that.
904 */
905 set_root(true);
906
907 while (true) {
908 err = bpf_btf_get_next_id(id, &id);
909 if (err) {
910 if (errno == ENOENT)
911 break;
912 perror("bpf_btf_get_next_id failed");
913 break;
914 }
915
916 fd = bpf_btf_get_fd_by_id(id);
917 if (fd < 0) {
918 if (errno == ENOENT)
919 continue;
920 perror("bpf_btf_get_fd_by_id failed");
921 break;
922 }
923
924 memset(&info, 0, sizeof(info));
925 info.name_len = sizeof(name);
926 info.name = ptr_to_u64(name);
927 len = sizeof(info);
928
929 err = bpf_obj_get_info_by_fd(fd, &info, &len);
930 if (err) {
931 close(fd);
932 perror("bpf_obj_get_info_by_fd failed");
933 break;
934 }
935
936 if (strcmp("bpf_testmod", name)) {
937 close(fd);
938 continue;
939 }
940
941 btf = btf__load_from_kernel_by_id_split(id, vmlinux);
942 if (!btf) {
943 close(fd);
944 break;
945 }
946
947 /* We need the fd to stay open so it can be used in fd_array.
948 * The final cleanup call to btf__free will free btf object
949 * and close the file descriptor.
950 */
951 btf__set_fd(btf, fd);
952 break;
953 }
954
955 set_root(false);
956 return btf;
957}
958
959static struct btf *testmod_btf;
960static struct btf *vmlinux_btf;
961
962static void kfuncs_cleanup(void)
963{
964 btf__free(testmod_btf);
965 btf__free(vmlinux_btf);
966}
967
968static void fixup_prog_kfuncs(struct bpf_insn *prog, int *fd_array,
969 struct kfunc_btf_id_pair *fixup_kfunc_btf_id)
970{
971 /* Patch in kfunc BTF IDs */
972 while (fixup_kfunc_btf_id->kfunc) {
973 int btf_id = 0;
974
975 /* try to find kfunc in kernel BTF */
976 vmlinux_btf = vmlinux_btf ?: btf__load_vmlinux_btf();
977 if (vmlinux_btf) {
978 btf_id = btf__find_by_name_kind(vmlinux_btf,
979 fixup_kfunc_btf_id->kfunc,
980 BTF_KIND_FUNC);
981 btf_id = btf_id < 0 ? 0 : btf_id;
982 }
983
984 /* kfunc not found in kernel BTF, try bpf_testmod BTF */
985 if (!btf_id) {
986 testmod_btf = testmod_btf ?: btf__load_testmod_btf(vmlinux_btf);
987 if (testmod_btf) {
988 btf_id = btf__find_by_name_kind(testmod_btf,
989 fixup_kfunc_btf_id->kfunc,
990 BTF_KIND_FUNC);
991 btf_id = btf_id < 0 ? 0 : btf_id;
992 if (btf_id) {
993 /* We put bpf_testmod module fd into fd_array
994 * and its index 1 into instruction 'off'.
995 */
996 *fd_array = btf__fd(testmod_btf);
997 prog[fixup_kfunc_btf_id->insn_idx].off = 1;
998 }
999 }
1000 }
1001
1002 prog[fixup_kfunc_btf_id->insn_idx].imm = btf_id;
1003 fixup_kfunc_btf_id++;
1004 }
1005}
1006
1007static void do_test_fixup(struct bpf_test *test, enum bpf_prog_type prog_type,
1008 struct bpf_insn *prog, int *map_fds, int *fd_array)
1009{
1010 int *fixup_map_hash_8b = test->fixup_map_hash_8b;
1011 int *fixup_map_hash_48b = test->fixup_map_hash_48b;
1012 int *fixup_map_hash_16b = test->fixup_map_hash_16b;
1013 int *fixup_map_array_48b = test->fixup_map_array_48b;
1014 int *fixup_map_sockmap = test->fixup_map_sockmap;
1015 int *fixup_map_sockhash = test->fixup_map_sockhash;
1016 int *fixup_map_xskmap = test->fixup_map_xskmap;
1017 int *fixup_map_stacktrace = test->fixup_map_stacktrace;
1018 int *fixup_prog1 = test->fixup_prog1;
1019 int *fixup_prog2 = test->fixup_prog2;
1020 int *fixup_map_in_map = test->fixup_map_in_map;
1021 int *fixup_cgroup_storage = test->fixup_cgroup_storage;
1022 int *fixup_percpu_cgroup_storage = test->fixup_percpu_cgroup_storage;
1023 int *fixup_map_spin_lock = test->fixup_map_spin_lock;
1024 int *fixup_map_array_ro = test->fixup_map_array_ro;
1025 int *fixup_map_array_wo = test->fixup_map_array_wo;
1026 int *fixup_map_array_small = test->fixup_map_array_small;
1027 int *fixup_sk_storage_map = test->fixup_sk_storage_map;
1028 int *fixup_map_event_output = test->fixup_map_event_output;
1029 int *fixup_map_reuseport_array = test->fixup_map_reuseport_array;
1030 int *fixup_map_ringbuf = test->fixup_map_ringbuf;
1031 int *fixup_map_timer = test->fixup_map_timer;
1032 int *fixup_map_kptr = test->fixup_map_kptr;
1033
1034 if (test->fill_helper) {
1035 test->fill_insns = calloc(MAX_TEST_INSNS, sizeof(struct bpf_insn));
1036 test->fill_helper(test);
1037 }
1038
1039 /* Allocating HTs with 1 elem is fine here, since we only test
1040 * for verifier and not do a runtime lookup, so the only thing
1041 * that really matters is value size in this case.
1042 */
1043 if (*fixup_map_hash_8b) {
1044 map_fds[0] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
1045 sizeof(long long), 1);
1046 do {
1047 prog[*fixup_map_hash_8b].imm = map_fds[0];
1048 fixup_map_hash_8b++;
1049 } while (*fixup_map_hash_8b);
1050 }
1051
1052 if (*fixup_map_hash_48b) {
1053 map_fds[1] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
1054 sizeof(struct test_val), 1);
1055 do {
1056 prog[*fixup_map_hash_48b].imm = map_fds[1];
1057 fixup_map_hash_48b++;
1058 } while (*fixup_map_hash_48b);
1059 }
1060
1061 if (*fixup_map_hash_16b) {
1062 map_fds[2] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
1063 sizeof(struct other_val), 1);
1064 do {
1065 prog[*fixup_map_hash_16b].imm = map_fds[2];
1066 fixup_map_hash_16b++;
1067 } while (*fixup_map_hash_16b);
1068 }
1069
1070 if (*fixup_map_array_48b) {
1071 map_fds[3] = create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
1072 sizeof(struct test_val), 1);
1073 update_map(map_fds[3], 0);
1074 do {
1075 prog[*fixup_map_array_48b].imm = map_fds[3];
1076 fixup_map_array_48b++;
1077 } while (*fixup_map_array_48b);
1078 }
1079
1080 if (*fixup_prog1) {
1081 map_fds[4] = create_prog_array(prog_type, 4, 0, 1, 2);
1082 do {
1083 prog[*fixup_prog1].imm = map_fds[4];
1084 fixup_prog1++;
1085 } while (*fixup_prog1);
1086 }
1087
1088 if (*fixup_prog2) {
1089 map_fds[5] = create_prog_array(prog_type, 8, 7, 1, 2);
1090 do {
1091 prog[*fixup_prog2].imm = map_fds[5];
1092 fixup_prog2++;
1093 } while (*fixup_prog2);
1094 }
1095
1096 if (*fixup_map_in_map) {
1097 map_fds[6] = create_map_in_map();
1098 do {
1099 prog[*fixup_map_in_map].imm = map_fds[6];
1100 fixup_map_in_map++;
1101 } while (*fixup_map_in_map);
1102 }
1103
1104 if (*fixup_cgroup_storage) {
1105 map_fds[7] = create_cgroup_storage(false);
1106 do {
1107 prog[*fixup_cgroup_storage].imm = map_fds[7];
1108 fixup_cgroup_storage++;
1109 } while (*fixup_cgroup_storage);
1110 }
1111
1112 if (*fixup_percpu_cgroup_storage) {
1113 map_fds[8] = create_cgroup_storage(true);
1114 do {
1115 prog[*fixup_percpu_cgroup_storage].imm = map_fds[8];
1116 fixup_percpu_cgroup_storage++;
1117 } while (*fixup_percpu_cgroup_storage);
1118 }
1119 if (*fixup_map_sockmap) {
1120 map_fds[9] = create_map(BPF_MAP_TYPE_SOCKMAP, sizeof(int),
1121 sizeof(int), 1);
1122 do {
1123 prog[*fixup_map_sockmap].imm = map_fds[9];
1124 fixup_map_sockmap++;
1125 } while (*fixup_map_sockmap);
1126 }
1127 if (*fixup_map_sockhash) {
1128 map_fds[10] = create_map(BPF_MAP_TYPE_SOCKHASH, sizeof(int),
1129 sizeof(int), 1);
1130 do {
1131 prog[*fixup_map_sockhash].imm = map_fds[10];
1132 fixup_map_sockhash++;
1133 } while (*fixup_map_sockhash);
1134 }
1135 if (*fixup_map_xskmap) {
1136 map_fds[11] = create_map(BPF_MAP_TYPE_XSKMAP, sizeof(int),
1137 sizeof(int), 1);
1138 do {
1139 prog[*fixup_map_xskmap].imm = map_fds[11];
1140 fixup_map_xskmap++;
1141 } while (*fixup_map_xskmap);
1142 }
1143 if (*fixup_map_stacktrace) {
1144 map_fds[12] = create_map(BPF_MAP_TYPE_STACK_TRACE, sizeof(u32),
1145 sizeof(u64), 1);
1146 do {
1147 prog[*fixup_map_stacktrace].imm = map_fds[12];
1148 fixup_map_stacktrace++;
1149 } while (*fixup_map_stacktrace);
1150 }
1151 if (*fixup_map_spin_lock) {
1152 map_fds[13] = create_map_spin_lock();
1153 do {
1154 prog[*fixup_map_spin_lock].imm = map_fds[13];
1155 fixup_map_spin_lock++;
1156 } while (*fixup_map_spin_lock);
1157 }
1158 if (*fixup_map_array_ro) {
1159 map_fds[14] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
1160 sizeof(struct test_val), 1,
1161 BPF_F_RDONLY_PROG);
1162 update_map(map_fds[14], 0);
1163 do {
1164 prog[*fixup_map_array_ro].imm = map_fds[14];
1165 fixup_map_array_ro++;
1166 } while (*fixup_map_array_ro);
1167 }
1168 if (*fixup_map_array_wo) {
1169 map_fds[15] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
1170 sizeof(struct test_val), 1,
1171 BPF_F_WRONLY_PROG);
1172 update_map(map_fds[15], 0);
1173 do {
1174 prog[*fixup_map_array_wo].imm = map_fds[15];
1175 fixup_map_array_wo++;
1176 } while (*fixup_map_array_wo);
1177 }
1178 if (*fixup_map_array_small) {
1179 map_fds[16] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
1180 1, 1, 0);
1181 update_map(map_fds[16], 0);
1182 do {
1183 prog[*fixup_map_array_small].imm = map_fds[16];
1184 fixup_map_array_small++;
1185 } while (*fixup_map_array_small);
1186 }
1187 if (*fixup_sk_storage_map) {
1188 map_fds[17] = create_sk_storage_map();
1189 do {
1190 prog[*fixup_sk_storage_map].imm = map_fds[17];
1191 fixup_sk_storage_map++;
1192 } while (*fixup_sk_storage_map);
1193 }
1194 if (*fixup_map_event_output) {
1195 map_fds[18] = __create_map(BPF_MAP_TYPE_PERF_EVENT_ARRAY,
1196 sizeof(int), sizeof(int), 1, 0);
1197 do {
1198 prog[*fixup_map_event_output].imm = map_fds[18];
1199 fixup_map_event_output++;
1200 } while (*fixup_map_event_output);
1201 }
1202 if (*fixup_map_reuseport_array) {
1203 map_fds[19] = __create_map(BPF_MAP_TYPE_REUSEPORT_SOCKARRAY,
1204 sizeof(u32), sizeof(u64), 1, 0);
1205 do {
1206 prog[*fixup_map_reuseport_array].imm = map_fds[19];
1207 fixup_map_reuseport_array++;
1208 } while (*fixup_map_reuseport_array);
1209 }
1210 if (*fixup_map_ringbuf) {
1211 map_fds[20] = create_map(BPF_MAP_TYPE_RINGBUF, 0,
1212 0, getpagesize());
1213 do {
1214 prog[*fixup_map_ringbuf].imm = map_fds[20];
1215 fixup_map_ringbuf++;
1216 } while (*fixup_map_ringbuf);
1217 }
1218 if (*fixup_map_timer) {
1219 map_fds[21] = create_map_timer();
1220 do {
1221 prog[*fixup_map_timer].imm = map_fds[21];
1222 fixup_map_timer++;
1223 } while (*fixup_map_timer);
1224 }
1225 if (*fixup_map_kptr) {
1226 map_fds[22] = create_map_kptr();
1227 do {
1228 prog[*fixup_map_kptr].imm = map_fds[22];
1229 fixup_map_kptr++;
1230 } while (*fixup_map_kptr);
1231 }
1232
1233 fixup_prog_kfuncs(prog, fd_array, test->fixup_kfunc_btf_id);
1234}
1235
1236static int set_admin(bool admin)
1237{
1238 int err;
1239
1240 if (admin) {
1241 err = cap_enable_effective(ADMIN_CAPS, NULL);
1242 if (err)
1243 perror("cap_enable_effective(ADMIN_CAPS)");
1244 } else {
1245 err = cap_disable_effective(ADMIN_CAPS, NULL);
1246 if (err)
1247 perror("cap_disable_effective(ADMIN_CAPS)");
1248 }
1249
1250 return err;
1251}
1252
1253static int do_prog_test_run(int fd_prog, bool unpriv, uint32_t expected_val,
1254 void *data, size_t size_data)
1255{
1256 __u8 tmp[TEST_DATA_LEN << 2];
1257 __u32 size_tmp = sizeof(tmp);
1258 int err, saved_errno;
1259 LIBBPF_OPTS(bpf_test_run_opts, topts,
1260 .data_in = data,
1261 .data_size_in = size_data,
1262 .data_out = tmp,
1263 .data_size_out = size_tmp,
1264 .repeat = 1,
1265 );
1266
1267 if (unpriv)
1268 set_admin(true);
1269 err = bpf_prog_test_run_opts(fd_prog, &topts);
1270 saved_errno = errno;
1271
1272 if (unpriv)
1273 set_admin(false);
1274
1275 if (err) {
1276 switch (saved_errno) {
1277 case ENOTSUPP:
1278 printf("Did not run the program (not supported) ");
1279 return 0;
1280 case EPERM:
1281 if (unpriv) {
1282 printf("Did not run the program (no permission) ");
1283 return 0;
1284 }
1285 /* fallthrough; */
1286 default:
1287 printf("FAIL: Unexpected bpf_prog_test_run error (%s) ",
1288 strerror(saved_errno));
1289 return err;
1290 }
1291 }
1292
1293 if (topts.retval != expected_val && expected_val != POINTER_VALUE) {
1294 printf("FAIL retval %d != %d ", topts.retval, expected_val);
1295 return 1;
1296 }
1297
1298 return 0;
1299}
1300
1301/* Returns true if every part of exp (tab-separated) appears in log, in order.
1302 *
1303 * If exp is an empty string, returns true.
1304 */
1305static bool cmp_str_seq(const char *log, const char *exp)
1306{
1307 char needle[200];
1308 const char *p, *q;
1309 int len;
1310
1311 do {
1312 if (!strlen(exp))
1313 break;
1314 p = strchr(exp, '\t');
1315 if (!p)
1316 p = exp + strlen(exp);
1317
1318 len = p - exp;
1319 if (len >= sizeof(needle) || !len) {
1320 printf("FAIL\nTestcase bug\n");
1321 return false;
1322 }
1323 strncpy(needle, exp, len);
1324 needle[len] = 0;
1325 q = strstr(log, needle);
1326 if (!q) {
1327 printf("FAIL\nUnexpected verifier log!\n"
1328 "EXP: %s\nRES:\n", needle);
1329 return false;
1330 }
1331 log = q + len;
1332 exp = p + 1;
1333 } while (*p);
1334 return true;
1335}
1336
1337static bool is_null_insn(struct bpf_insn *insn)
1338{
1339 struct bpf_insn null_insn = {};
1340
1341 return memcmp(insn, &null_insn, sizeof(null_insn)) == 0;
1342}
1343
1344static bool is_skip_insn(struct bpf_insn *insn)
1345{
1346 struct bpf_insn skip_insn = SKIP_INSNS();
1347
1348 return memcmp(insn, &skip_insn, sizeof(skip_insn)) == 0;
1349}
1350
1351static int null_terminated_insn_len(struct bpf_insn *seq, int max_len)
1352{
1353 int i;
1354
1355 for (i = 0; i < max_len; ++i) {
1356 if (is_null_insn(&seq[i]))
1357 return i;
1358 }
1359 return max_len;
1360}
1361
1362static bool compare_masked_insn(struct bpf_insn *orig, struct bpf_insn *masked)
1363{
1364 struct bpf_insn orig_masked;
1365
1366 memcpy(&orig_masked, orig, sizeof(orig_masked));
1367 if (masked->imm == INSN_IMM_MASK)
1368 orig_masked.imm = INSN_IMM_MASK;
1369 if (masked->off == INSN_OFF_MASK)
1370 orig_masked.off = INSN_OFF_MASK;
1371
1372 return memcmp(&orig_masked, masked, sizeof(orig_masked)) == 0;
1373}
1374
1375static int find_insn_subseq(struct bpf_insn *seq, struct bpf_insn *subseq,
1376 int seq_len, int subseq_len)
1377{
1378 int i, j;
1379
1380 if (subseq_len > seq_len)
1381 return -1;
1382
1383 for (i = 0; i < seq_len - subseq_len + 1; ++i) {
1384 bool found = true;
1385
1386 for (j = 0; j < subseq_len; ++j) {
1387 if (!compare_masked_insn(&seq[i + j], &subseq[j])) {
1388 found = false;
1389 break;
1390 }
1391 }
1392 if (found)
1393 return i;
1394 }
1395
1396 return -1;
1397}
1398
1399static int find_skip_insn_marker(struct bpf_insn *seq, int len)
1400{
1401 int i;
1402
1403 for (i = 0; i < len; ++i)
1404 if (is_skip_insn(&seq[i]))
1405 return i;
1406
1407 return -1;
1408}
1409
1410/* Return true if all sub-sequences in `subseqs` could be found in
1411 * `seq` one after another. Sub-sequences are separated by a single
1412 * nil instruction.
1413 */
1414static bool find_all_insn_subseqs(struct bpf_insn *seq, struct bpf_insn *subseqs,
1415 int seq_len, int max_subseqs_len)
1416{
1417 int subseqs_len = null_terminated_insn_len(subseqs, max_subseqs_len);
1418
1419 while (subseqs_len > 0) {
1420 int skip_idx = find_skip_insn_marker(subseqs, subseqs_len);
1421 int cur_subseq_len = skip_idx < 0 ? subseqs_len : skip_idx;
1422 int subseq_idx = find_insn_subseq(seq, subseqs,
1423 seq_len, cur_subseq_len);
1424
1425 if (subseq_idx < 0)
1426 return false;
1427 seq += subseq_idx + cur_subseq_len;
1428 seq_len -= subseq_idx + cur_subseq_len;
1429 subseqs += cur_subseq_len + 1;
1430 subseqs_len -= cur_subseq_len + 1;
1431 }
1432
1433 return true;
1434}
1435
1436static void print_insn(struct bpf_insn *buf, int cnt)
1437{
1438 int i;
1439
1440 printf(" addr op d s off imm\n");
1441 for (i = 0; i < cnt; ++i) {
1442 struct bpf_insn *insn = &buf[i];
1443
1444 if (is_null_insn(insn))
1445 break;
1446
1447 if (is_skip_insn(insn))
1448 printf(" ...\n");
1449 else
1450 printf(" %04x: %02x %1x %x %04hx %08x\n",
1451 i, insn->code, insn->dst_reg,
1452 insn->src_reg, insn->off, insn->imm);
1453 }
1454}
1455
1456static bool check_xlated_program(struct bpf_test *test, int fd_prog)
1457{
1458 struct bpf_insn *buf;
1459 unsigned int cnt;
1460 bool result = true;
1461 bool check_expected = !is_null_insn(test->expected_insns);
1462 bool check_unexpected = !is_null_insn(test->unexpected_insns);
1463
1464 if (!check_expected && !check_unexpected)
1465 goto out;
1466
1467 if (get_xlated_program(fd_prog, &buf, &cnt)) {
1468 printf("FAIL: can't get xlated program\n");
1469 result = false;
1470 goto out;
1471 }
1472
1473 if (check_expected &&
1474 !find_all_insn_subseqs(buf, test->expected_insns,
1475 cnt, MAX_EXPECTED_INSNS)) {
1476 printf("FAIL: can't find expected subsequence of instructions\n");
1477 result = false;
1478 if (verbose) {
1479 printf("Program:\n");
1480 print_insn(buf, cnt);
1481 printf("Expected subsequence:\n");
1482 print_insn(test->expected_insns, MAX_EXPECTED_INSNS);
1483 }
1484 }
1485
1486 if (check_unexpected &&
1487 find_all_insn_subseqs(buf, test->unexpected_insns,
1488 cnt, MAX_UNEXPECTED_INSNS)) {
1489 printf("FAIL: found unexpected subsequence of instructions\n");
1490 result = false;
1491 if (verbose) {
1492 printf("Program:\n");
1493 print_insn(buf, cnt);
1494 printf("Un-expected subsequence:\n");
1495 print_insn(test->unexpected_insns, MAX_UNEXPECTED_INSNS);
1496 }
1497 }
1498
1499 free(buf);
1500 out:
1501 return result;
1502}
1503
1504static void do_test_single(struct bpf_test *test, bool unpriv,
1505 int *passes, int *errors)
1506{
1507 int fd_prog, btf_fd, expected_ret, alignment_prevented_execution;
1508 int prog_len, prog_type = test->prog_type;
1509 struct bpf_insn *prog = test->insns;
1510 LIBBPF_OPTS(bpf_prog_load_opts, opts);
1511 int run_errs, run_successes;
1512 int map_fds[MAX_NR_MAPS];
1513 const char *expected_err;
1514 int fd_array[2] = { -1, -1 };
1515 int saved_errno;
1516 int fixup_skips;
1517 __u32 pflags;
1518 int i, err;
1519
1520 if ((test->flags & F_NEEDS_JIT_ENABLED) && jit_disabled) {
1521 printf("SKIP (requires BPF JIT)\n");
1522 skips++;
1523 sched_yield();
1524 return;
1525 }
1526
1527 fd_prog = -1;
1528 for (i = 0; i < MAX_NR_MAPS; i++)
1529 map_fds[i] = -1;
1530 btf_fd = -1;
1531
1532 if (!prog_type)
1533 prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1534 fixup_skips = skips;
1535 do_test_fixup(test, prog_type, prog, map_fds, &fd_array[1]);
1536 if (test->fill_insns) {
1537 prog = test->fill_insns;
1538 prog_len = test->prog_len;
1539 } else {
1540 prog_len = probe_filter_length(prog);
1541 }
1542 /* If there were some map skips during fixup due to missing bpf
1543 * features, skip this test.
1544 */
1545 if (fixup_skips != skips)
1546 return;
1547
1548 pflags = testing_prog_flags();
1549 if (test->flags & F_LOAD_WITH_STRICT_ALIGNMENT)
1550 pflags |= BPF_F_STRICT_ALIGNMENT;
1551 if (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS)
1552 pflags |= BPF_F_ANY_ALIGNMENT;
1553 if (test->flags & ~3)
1554 pflags |= test->flags;
1555
1556 expected_ret = unpriv && test->result_unpriv != UNDEF ?
1557 test->result_unpriv : test->result;
1558 expected_err = unpriv && test->errstr_unpriv ?
1559 test->errstr_unpriv : test->errstr;
1560
1561 opts.expected_attach_type = test->expected_attach_type;
1562 if (verbose)
1563 opts.log_level = verif_log_level | 4; /* force stats */
1564 else if (expected_ret == VERBOSE_ACCEPT)
1565 opts.log_level = 2;
1566 else
1567 opts.log_level = DEFAULT_LIBBPF_LOG_LEVEL;
1568 opts.prog_flags = pflags;
1569 if (fd_array[1] != -1)
1570 opts.fd_array = &fd_array[0];
1571
1572 if ((prog_type == BPF_PROG_TYPE_TRACING ||
1573 prog_type == BPF_PROG_TYPE_LSM) && test->kfunc) {
1574 int attach_btf_id;
1575
1576 attach_btf_id = libbpf_find_vmlinux_btf_id(test->kfunc,
1577 opts.expected_attach_type);
1578 if (attach_btf_id < 0) {
1579 printf("FAIL\nFailed to find BTF ID for '%s'!\n",
1580 test->kfunc);
1581 (*errors)++;
1582 return;
1583 }
1584
1585 opts.attach_btf_id = attach_btf_id;
1586 }
1587
1588 if (test->btf_types[0] != 0) {
1589 btf_fd = load_btf_for_test(test);
1590 if (btf_fd < 0)
1591 goto fail_log;
1592 opts.prog_btf_fd = btf_fd;
1593 }
1594
1595 if (test->func_info_cnt != 0) {
1596 opts.func_info = test->func_info;
1597 opts.func_info_cnt = test->func_info_cnt;
1598 opts.func_info_rec_size = sizeof(test->func_info[0]);
1599 }
1600
1601 opts.log_buf = bpf_vlog;
1602 opts.log_size = sizeof(bpf_vlog);
1603 fd_prog = bpf_prog_load(prog_type, NULL, "GPL", prog, prog_len, &opts);
1604 saved_errno = errno;
1605
1606 /* BPF_PROG_TYPE_TRACING requires more setup and
1607 * bpf_probe_prog_type won't give correct answer
1608 */
1609 if (fd_prog < 0 && prog_type != BPF_PROG_TYPE_TRACING &&
1610 !libbpf_probe_bpf_prog_type(prog_type, NULL)) {
1611 printf("SKIP (unsupported program type %d)\n", prog_type);
1612 skips++;
1613 goto close_fds;
1614 }
1615
1616 if (fd_prog < 0 && saved_errno == ENOTSUPP) {
1617 printf("SKIP (program uses an unsupported feature)\n");
1618 skips++;
1619 goto close_fds;
1620 }
1621
1622 alignment_prevented_execution = 0;
1623
1624 if (expected_ret == ACCEPT || expected_ret == VERBOSE_ACCEPT) {
1625 if (fd_prog < 0) {
1626 printf("FAIL\nFailed to load prog '%s'!\n",
1627 strerror(saved_errno));
1628 goto fail_log;
1629 }
1630#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
1631 if (fd_prog >= 0 &&
1632 (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS))
1633 alignment_prevented_execution = 1;
1634#endif
1635 if (expected_ret == VERBOSE_ACCEPT && !cmp_str_seq(bpf_vlog, expected_err)) {
1636 goto fail_log;
1637 }
1638 } else {
1639 if (fd_prog >= 0) {
1640 printf("FAIL\nUnexpected success to load!\n");
1641 goto fail_log;
1642 }
1643 if (!expected_err || !cmp_str_seq(bpf_vlog, expected_err)) {
1644 printf("FAIL\nUnexpected error message!\n\tEXP: %s\n\tRES: %s\n",
1645 expected_err, bpf_vlog);
1646 goto fail_log;
1647 }
1648 }
1649
1650 if (!unpriv && test->insn_processed) {
1651 uint32_t insn_processed;
1652 char *proc;
1653
1654 proc = strstr(bpf_vlog, "processed ");
1655 insn_processed = atoi(proc + 10);
1656 if (test->insn_processed != insn_processed) {
1657 printf("FAIL\nUnexpected insn_processed %u vs %u\n",
1658 insn_processed, test->insn_processed);
1659 goto fail_log;
1660 }
1661 }
1662
1663 if (verbose)
1664 printf(", verifier log:\n%s", bpf_vlog);
1665
1666 if (!check_xlated_program(test, fd_prog))
1667 goto fail_log;
1668
1669 run_errs = 0;
1670 run_successes = 0;
1671 if (!alignment_prevented_execution && fd_prog >= 0 && test->runs >= 0) {
1672 uint32_t expected_val;
1673 int i;
1674
1675 if (!test->runs)
1676 test->runs = 1;
1677
1678 for (i = 0; i < test->runs; i++) {
1679 if (unpriv && test->retvals[i].retval_unpriv)
1680 expected_val = test->retvals[i].retval_unpriv;
1681 else
1682 expected_val = test->retvals[i].retval;
1683
1684 err = do_prog_test_run(fd_prog, unpriv, expected_val,
1685 test->retvals[i].data,
1686 sizeof(test->retvals[i].data));
1687 if (err) {
1688 printf("(run %d/%d) ", i + 1, test->runs);
1689 run_errs++;
1690 } else {
1691 run_successes++;
1692 }
1693 }
1694 }
1695
1696 if (!run_errs) {
1697 (*passes)++;
1698 if (run_successes > 1)
1699 printf("%d cases ", run_successes);
1700 printf("OK");
1701 if (alignment_prevented_execution)
1702 printf(" (NOTE: not executed due to unknown alignment)");
1703 printf("\n");
1704 } else {
1705 printf("\n");
1706 goto fail_log;
1707 }
1708close_fds:
1709 if (test->fill_insns)
1710 free(test->fill_insns);
1711 close(fd_prog);
1712 close(btf_fd);
1713 for (i = 0; i < MAX_NR_MAPS; i++)
1714 close(map_fds[i]);
1715 sched_yield();
1716 return;
1717fail_log:
1718 (*errors)++;
1719 printf("%s", bpf_vlog);
1720 goto close_fds;
1721}
1722
1723static bool is_admin(void)
1724{
1725 __u64 caps;
1726
1727 /* The test checks for finer cap as CAP_NET_ADMIN,
1728 * CAP_PERFMON, and CAP_BPF instead of CAP_SYS_ADMIN.
1729 * Thus, disable CAP_SYS_ADMIN at the beginning.
1730 */
1731 if (cap_disable_effective(1ULL << CAP_SYS_ADMIN, &caps)) {
1732 perror("cap_disable_effective(CAP_SYS_ADMIN)");
1733 return false;
1734 }
1735
1736 return (caps & ADMIN_CAPS) == ADMIN_CAPS;
1737}
1738
1739static bool test_as_unpriv(struct bpf_test *test)
1740{
1741#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
1742 /* Some architectures have strict alignment requirements. In
1743 * that case, the BPF verifier detects if a program has
1744 * unaligned accesses and rejects them. A user can pass
1745 * BPF_F_ANY_ALIGNMENT to a program to override this
1746 * check. That, however, will only work when a privileged user
1747 * loads a program. An unprivileged user loading a program
1748 * with this flag will be rejected prior entering the
1749 * verifier.
1750 */
1751 if (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS)
1752 return false;
1753#endif
1754 return !test->prog_type ||
1755 test->prog_type == BPF_PROG_TYPE_SOCKET_FILTER ||
1756 test->prog_type == BPF_PROG_TYPE_CGROUP_SKB;
1757}
1758
1759static int do_test(bool unpriv, unsigned int from, unsigned int to)
1760{
1761 int i, passes = 0, errors = 0;
1762
1763 /* ensure previous instance of the module is unloaded */
1764 unload_bpf_testmod(verbose);
1765
1766 if (load_bpf_testmod(verbose))
1767 return EXIT_FAILURE;
1768
1769 for (i = from; i < to; i++) {
1770 struct bpf_test *test = &tests[i];
1771
1772 /* Program types that are not supported by non-root we
1773 * skip right away.
1774 */
1775 if (test_as_unpriv(test) && unpriv_disabled) {
1776 printf("#%d/u %s SKIP\n", i, test->descr);
1777 skips++;
1778 } else if (test_as_unpriv(test)) {
1779 if (!unpriv)
1780 set_admin(false);
1781 printf("#%d/u %s ", i, test->descr);
1782 do_test_single(test, true, &passes, &errors);
1783 if (!unpriv)
1784 set_admin(true);
1785 }
1786
1787 if (unpriv) {
1788 printf("#%d/p %s SKIP\n", i, test->descr);
1789 skips++;
1790 } else {
1791 printf("#%d/p %s ", i, test->descr);
1792 do_test_single(test, false, &passes, &errors);
1793 }
1794 }
1795
1796 unload_bpf_testmod(verbose);
1797 kfuncs_cleanup();
1798
1799 printf("Summary: %d PASSED, %d SKIPPED, %d FAILED\n", passes,
1800 skips, errors);
1801 return errors ? EXIT_FAILURE : EXIT_SUCCESS;
1802}
1803
1804int main(int argc, char **argv)
1805{
1806 unsigned int from = 0, to = ARRAY_SIZE(tests);
1807 bool unpriv = !is_admin();
1808 int arg = 1;
1809
1810 if (argc > 1 && strcmp(argv[1], "-v") == 0) {
1811 arg++;
1812 verbose = true;
1813 verif_log_level = 1;
1814 argc--;
1815 }
1816 if (argc > 1 && strcmp(argv[1], "-vv") == 0) {
1817 arg++;
1818 verbose = true;
1819 verif_log_level = 2;
1820 argc--;
1821 }
1822
1823 if (argc == 3) {
1824 unsigned int l = atoi(argv[arg]);
1825 unsigned int u = atoi(argv[arg + 1]);
1826
1827 if (l < to && u < to) {
1828 from = l;
1829 to = u + 1;
1830 }
1831 } else if (argc == 2) {
1832 unsigned int t = atoi(argv[arg]);
1833
1834 if (t < to) {
1835 from = t;
1836 to = t + 1;
1837 }
1838 }
1839
1840 unpriv_disabled = get_unpriv_disabled();
1841 if (unpriv && unpriv_disabled) {
1842 printf("Cannot run as unprivileged user with sysctl %s.\n",
1843 UNPRIV_SYSCTL);
1844 return EXIT_FAILURE;
1845 }
1846
1847 jit_disabled = !is_jit_enabled();
1848
1849 /* Use libbpf 1.0 API mode */
1850 libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
1851
1852 bpf_semi_rand_init();
1853 return do_test(unpriv, from, to);
1854}
1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * Testsuite for eBPF verifier
4 *
5 * Copyright (c) 2014 PLUMgrid, http://plumgrid.com
6 * Copyright (c) 2017 Facebook
7 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
8 */
9
10#include <endian.h>
11#include <asm/types.h>
12#include <linux/types.h>
13#include <stdint.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <unistd.h>
17#include <errno.h>
18#include <string.h>
19#include <stddef.h>
20#include <stdbool.h>
21#include <sched.h>
22#include <limits.h>
23#include <assert.h>
24
25#include <sys/capability.h>
26
27#include <linux/unistd.h>
28#include <linux/filter.h>
29#include <linux/bpf_perf_event.h>
30#include <linux/bpf.h>
31#include <linux/if_ether.h>
32#include <linux/btf.h>
33
34#include <bpf/bpf.h>
35#include <bpf/libbpf.h>
36
37#ifdef HAVE_GENHDR
38# include "autoconf.h"
39#else
40# if defined(__i386) || defined(__x86_64) || defined(__s390x__) || defined(__aarch64__)
41# define CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS 1
42# endif
43#endif
44#include "bpf_rlimit.h"
45#include "bpf_rand.h"
46#include "bpf_util.h"
47#include "test_btf.h"
48#include "../../../include/linux/filter.h"
49
50#define MAX_INSNS BPF_MAXINSNS
51#define MAX_TEST_INSNS 1000000
52#define MAX_FIXUPS 8
53#define MAX_NR_MAPS 21
54#define MAX_TEST_RUNS 8
55#define POINTER_VALUE 0xcafe4all
56#define TEST_DATA_LEN 64
57
58#define F_NEEDS_EFFICIENT_UNALIGNED_ACCESS (1 << 0)
59#define F_LOAD_WITH_STRICT_ALIGNMENT (1 << 1)
60
61#define UNPRIV_SYSCTL "kernel/unprivileged_bpf_disabled"
62static bool unpriv_disabled = false;
63static int skips;
64static bool verbose = false;
65
66struct bpf_test {
67 const char *descr;
68 struct bpf_insn insns[MAX_INSNS];
69 struct bpf_insn *fill_insns;
70 int fixup_map_hash_8b[MAX_FIXUPS];
71 int fixup_map_hash_48b[MAX_FIXUPS];
72 int fixup_map_hash_16b[MAX_FIXUPS];
73 int fixup_map_array_48b[MAX_FIXUPS];
74 int fixup_map_sockmap[MAX_FIXUPS];
75 int fixup_map_sockhash[MAX_FIXUPS];
76 int fixup_map_xskmap[MAX_FIXUPS];
77 int fixup_map_stacktrace[MAX_FIXUPS];
78 int fixup_prog1[MAX_FIXUPS];
79 int fixup_prog2[MAX_FIXUPS];
80 int fixup_map_in_map[MAX_FIXUPS];
81 int fixup_cgroup_storage[MAX_FIXUPS];
82 int fixup_percpu_cgroup_storage[MAX_FIXUPS];
83 int fixup_map_spin_lock[MAX_FIXUPS];
84 int fixup_map_array_ro[MAX_FIXUPS];
85 int fixup_map_array_wo[MAX_FIXUPS];
86 int fixup_map_array_small[MAX_FIXUPS];
87 int fixup_sk_storage_map[MAX_FIXUPS];
88 int fixup_map_event_output[MAX_FIXUPS];
89 int fixup_map_reuseport_array[MAX_FIXUPS];
90 int fixup_map_ringbuf[MAX_FIXUPS];
91 /* Expected verifier log output for result REJECT or VERBOSE_ACCEPT.
92 * Can be a tab-separated sequence of expected strings. An empty string
93 * means no log verification.
94 */
95 const char *errstr;
96 const char *errstr_unpriv;
97 uint32_t insn_processed;
98 int prog_len;
99 enum {
100 UNDEF,
101 ACCEPT,
102 REJECT,
103 VERBOSE_ACCEPT,
104 } result, result_unpriv;
105 enum bpf_prog_type prog_type;
106 uint8_t flags;
107 void (*fill_helper)(struct bpf_test *self);
108 int runs;
109#define bpf_testdata_struct_t \
110 struct { \
111 uint32_t retval, retval_unpriv; \
112 union { \
113 __u8 data[TEST_DATA_LEN]; \
114 __u64 data64[TEST_DATA_LEN / 8]; \
115 }; \
116 }
117 union {
118 bpf_testdata_struct_t;
119 bpf_testdata_struct_t retvals[MAX_TEST_RUNS];
120 };
121 enum bpf_attach_type expected_attach_type;
122 const char *kfunc;
123};
124
125/* Note we want this to be 64 bit aligned so that the end of our array is
126 * actually the end of the structure.
127 */
128#define MAX_ENTRIES 11
129
130struct test_val {
131 unsigned int index;
132 int foo[MAX_ENTRIES];
133};
134
135struct other_val {
136 long long foo;
137 long long bar;
138};
139
140static void bpf_fill_ld_abs_vlan_push_pop(struct bpf_test *self)
141{
142 /* test: {skb->data[0], vlan_push} x 51 + {skb->data[0], vlan_pop} x 51 */
143#define PUSH_CNT 51
144 /* jump range is limited to 16 bit. PUSH_CNT of ld_abs needs room */
145 unsigned int len = (1 << 15) - PUSH_CNT * 2 * 5 * 6;
146 struct bpf_insn *insn = self->fill_insns;
147 int i = 0, j, k = 0;
148
149 insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
150loop:
151 for (j = 0; j < PUSH_CNT; j++) {
152 insn[i++] = BPF_LD_ABS(BPF_B, 0);
153 /* jump to error label */
154 insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
155 i++;
156 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
157 insn[i++] = BPF_MOV64_IMM(BPF_REG_2, 1);
158 insn[i++] = BPF_MOV64_IMM(BPF_REG_3, 2);
159 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
160 BPF_FUNC_skb_vlan_push),
161 insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
162 i++;
163 }
164
165 for (j = 0; j < PUSH_CNT; j++) {
166 insn[i++] = BPF_LD_ABS(BPF_B, 0);
167 insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
168 i++;
169 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
170 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
171 BPF_FUNC_skb_vlan_pop),
172 insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
173 i++;
174 }
175 if (++k < 5)
176 goto loop;
177
178 for (; i < len - 3; i++)
179 insn[i] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0xbef);
180 insn[len - 3] = BPF_JMP_A(1);
181 /* error label */
182 insn[len - 2] = BPF_MOV32_IMM(BPF_REG_0, 0);
183 insn[len - 1] = BPF_EXIT_INSN();
184 self->prog_len = len;
185}
186
187static void bpf_fill_jump_around_ld_abs(struct bpf_test *self)
188{
189 struct bpf_insn *insn = self->fill_insns;
190 /* jump range is limited to 16 bit. every ld_abs is replaced by 6 insns,
191 * but on arches like arm, ppc etc, there will be one BPF_ZEXT inserted
192 * to extend the error value of the inlined ld_abs sequence which then
193 * contains 7 insns. so, set the dividend to 7 so the testcase could
194 * work on all arches.
195 */
196 unsigned int len = (1 << 15) / 7;
197 int i = 0;
198
199 insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
200 insn[i++] = BPF_LD_ABS(BPF_B, 0);
201 insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 10, len - i - 2);
202 i++;
203 while (i < len - 1)
204 insn[i++] = BPF_LD_ABS(BPF_B, 1);
205 insn[i] = BPF_EXIT_INSN();
206 self->prog_len = i + 1;
207}
208
209static void bpf_fill_rand_ld_dw(struct bpf_test *self)
210{
211 struct bpf_insn *insn = self->fill_insns;
212 uint64_t res = 0;
213 int i = 0;
214
215 insn[i++] = BPF_MOV32_IMM(BPF_REG_0, 0);
216 while (i < self->retval) {
217 uint64_t val = bpf_semi_rand_get();
218 struct bpf_insn tmp[2] = { BPF_LD_IMM64(BPF_REG_1, val) };
219
220 res ^= val;
221 insn[i++] = tmp[0];
222 insn[i++] = tmp[1];
223 insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
224 }
225 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_0);
226 insn[i++] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 32);
227 insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
228 insn[i] = BPF_EXIT_INSN();
229 self->prog_len = i + 1;
230 res ^= (res >> 32);
231 self->retval = (uint32_t)res;
232}
233
234#define MAX_JMP_SEQ 8192
235
236/* test the sequence of 8k jumps */
237static void bpf_fill_scale1(struct bpf_test *self)
238{
239 struct bpf_insn *insn = self->fill_insns;
240 int i = 0, k = 0;
241
242 insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
243 /* test to check that the long sequence of jumps is acceptable */
244 while (k++ < MAX_JMP_SEQ) {
245 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
246 BPF_FUNC_get_prandom_u32);
247 insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
248 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
249 insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
250 -8 * (k % 64 + 1));
251 }
252 /* is_state_visited() doesn't allocate state for pruning for every jump.
253 * Hence multiply jmps by 4 to accommodate that heuristic
254 */
255 while (i < MAX_TEST_INSNS - MAX_JMP_SEQ * 4)
256 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
257 insn[i] = BPF_EXIT_INSN();
258 self->prog_len = i + 1;
259 self->retval = 42;
260}
261
262/* test the sequence of 8k jumps in inner most function (function depth 8)*/
263static void bpf_fill_scale2(struct bpf_test *self)
264{
265 struct bpf_insn *insn = self->fill_insns;
266 int i = 0, k = 0;
267
268#define FUNC_NEST 7
269 for (k = 0; k < FUNC_NEST; k++) {
270 insn[i++] = BPF_CALL_REL(1);
271 insn[i++] = BPF_EXIT_INSN();
272 }
273 insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
274 /* test to check that the long sequence of jumps is acceptable */
275 k = 0;
276 while (k++ < MAX_JMP_SEQ) {
277 insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
278 BPF_FUNC_get_prandom_u32);
279 insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
280 insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
281 insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
282 -8 * (k % (64 - 4 * FUNC_NEST) + 1));
283 }
284 while (i < MAX_TEST_INSNS - MAX_JMP_SEQ * 4)
285 insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
286 insn[i] = BPF_EXIT_INSN();
287 self->prog_len = i + 1;
288 self->retval = 42;
289}
290
291static void bpf_fill_scale(struct bpf_test *self)
292{
293 switch (self->retval) {
294 case 1:
295 return bpf_fill_scale1(self);
296 case 2:
297 return bpf_fill_scale2(self);
298 default:
299 self->prog_len = 0;
300 break;
301 }
302}
303
304static int bpf_fill_torturous_jumps_insn_1(struct bpf_insn *insn)
305{
306 unsigned int len = 259, hlen = 128;
307 int i;
308
309 insn[0] = BPF_EMIT_CALL(BPF_FUNC_get_prandom_u32);
310 for (i = 1; i <= hlen; i++) {
311 insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, i, hlen);
312 insn[i + hlen] = BPF_JMP_A(hlen - i);
313 }
314 insn[len - 2] = BPF_MOV64_IMM(BPF_REG_0, 1);
315 insn[len - 1] = BPF_EXIT_INSN();
316
317 return len;
318}
319
320static int bpf_fill_torturous_jumps_insn_2(struct bpf_insn *insn)
321{
322 unsigned int len = 4100, jmp_off = 2048;
323 int i, j;
324
325 insn[0] = BPF_EMIT_CALL(BPF_FUNC_get_prandom_u32);
326 for (i = 1; i <= jmp_off; i++) {
327 insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, i, jmp_off);
328 }
329 insn[i++] = BPF_JMP_A(jmp_off);
330 for (; i <= jmp_off * 2 + 1; i+=16) {
331 for (j = 0; j < 16; j++) {
332 insn[i + j] = BPF_JMP_A(16 - j - 1);
333 }
334 }
335
336 insn[len - 2] = BPF_MOV64_IMM(BPF_REG_0, 2);
337 insn[len - 1] = BPF_EXIT_INSN();
338
339 return len;
340}
341
342static void bpf_fill_torturous_jumps(struct bpf_test *self)
343{
344 struct bpf_insn *insn = self->fill_insns;
345 int i = 0;
346
347 switch (self->retval) {
348 case 1:
349 self->prog_len = bpf_fill_torturous_jumps_insn_1(insn);
350 return;
351 case 2:
352 self->prog_len = bpf_fill_torturous_jumps_insn_2(insn);
353 return;
354 case 3:
355 /* main */
356 insn[i++] = BPF_RAW_INSN(BPF_JMP|BPF_CALL, 0, 1, 0, 4);
357 insn[i++] = BPF_RAW_INSN(BPF_JMP|BPF_CALL, 0, 1, 0, 262);
358 insn[i++] = BPF_ST_MEM(BPF_B, BPF_REG_10, -32, 0);
359 insn[i++] = BPF_MOV64_IMM(BPF_REG_0, 3);
360 insn[i++] = BPF_EXIT_INSN();
361
362 /* subprog 1 */
363 i += bpf_fill_torturous_jumps_insn_1(insn + i);
364
365 /* subprog 2 */
366 i += bpf_fill_torturous_jumps_insn_2(insn + i);
367
368 self->prog_len = i;
369 return;
370 default:
371 self->prog_len = 0;
372 break;
373 }
374}
375
376/* BPF_SK_LOOKUP contains 13 instructions, if you need to fix up maps */
377#define BPF_SK_LOOKUP(func) \
378 /* struct bpf_sock_tuple tuple = {} */ \
379 BPF_MOV64_IMM(BPF_REG_2, 0), \
380 BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_2, -8), \
381 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -16), \
382 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -24), \
383 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -32), \
384 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -40), \
385 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -48), \
386 /* sk = func(ctx, &tuple, sizeof tuple, 0, 0) */ \
387 BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), \
388 BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -48), \
389 BPF_MOV64_IMM(BPF_REG_3, sizeof(struct bpf_sock_tuple)), \
390 BPF_MOV64_IMM(BPF_REG_4, 0), \
391 BPF_MOV64_IMM(BPF_REG_5, 0), \
392 BPF_EMIT_CALL(BPF_FUNC_ ## func)
393
394/* BPF_DIRECT_PKT_R2 contains 7 instructions, it initializes default return
395 * value into 0 and does necessary preparation for direct packet access
396 * through r2. The allowed access range is 8 bytes.
397 */
398#define BPF_DIRECT_PKT_R2 \
399 BPF_MOV64_IMM(BPF_REG_0, 0), \
400 BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, \
401 offsetof(struct __sk_buff, data)), \
402 BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1, \
403 offsetof(struct __sk_buff, data_end)), \
404 BPF_MOV64_REG(BPF_REG_4, BPF_REG_2), \
405 BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 8), \
406 BPF_JMP_REG(BPF_JLE, BPF_REG_4, BPF_REG_3, 1), \
407 BPF_EXIT_INSN()
408
409/* BPF_RAND_UEXT_R7 contains 4 instructions, it initializes R7 into a random
410 * positive u32, and zero-extend it into 64-bit.
411 */
412#define BPF_RAND_UEXT_R7 \
413 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, \
414 BPF_FUNC_get_prandom_u32), \
415 BPF_MOV64_REG(BPF_REG_7, BPF_REG_0), \
416 BPF_ALU64_IMM(BPF_LSH, BPF_REG_7, 33), \
417 BPF_ALU64_IMM(BPF_RSH, BPF_REG_7, 33)
418
419/* BPF_RAND_SEXT_R7 contains 5 instructions, it initializes R7 into a random
420 * negative u32, and sign-extend it into 64-bit.
421 */
422#define BPF_RAND_SEXT_R7 \
423 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, \
424 BPF_FUNC_get_prandom_u32), \
425 BPF_MOV64_REG(BPF_REG_7, BPF_REG_0), \
426 BPF_ALU64_IMM(BPF_OR, BPF_REG_7, 0x80000000), \
427 BPF_ALU64_IMM(BPF_LSH, BPF_REG_7, 32), \
428 BPF_ALU64_IMM(BPF_ARSH, BPF_REG_7, 32)
429
430static struct bpf_test tests[] = {
431#define FILL_ARRAY
432#include <verifier/tests.h>
433#undef FILL_ARRAY
434};
435
436static int probe_filter_length(const struct bpf_insn *fp)
437{
438 int len;
439
440 for (len = MAX_INSNS - 1; len > 0; --len)
441 if (fp[len].code != 0 || fp[len].imm != 0)
442 break;
443 return len + 1;
444}
445
446static bool skip_unsupported_map(enum bpf_map_type map_type)
447{
448 if (!bpf_probe_map_type(map_type, 0)) {
449 printf("SKIP (unsupported map type %d)\n", map_type);
450 skips++;
451 return true;
452 }
453 return false;
454}
455
456static int __create_map(uint32_t type, uint32_t size_key,
457 uint32_t size_value, uint32_t max_elem,
458 uint32_t extra_flags)
459{
460 int fd;
461
462 fd = bpf_create_map(type, size_key, size_value, max_elem,
463 (type == BPF_MAP_TYPE_HASH ?
464 BPF_F_NO_PREALLOC : 0) | extra_flags);
465 if (fd < 0) {
466 if (skip_unsupported_map(type))
467 return -1;
468 printf("Failed to create hash map '%s'!\n", strerror(errno));
469 }
470
471 return fd;
472}
473
474static int create_map(uint32_t type, uint32_t size_key,
475 uint32_t size_value, uint32_t max_elem)
476{
477 return __create_map(type, size_key, size_value, max_elem, 0);
478}
479
480static void update_map(int fd, int index)
481{
482 struct test_val value = {
483 .index = (6 + 1) * sizeof(int),
484 .foo[6] = 0xabcdef12,
485 };
486
487 assert(!bpf_map_update_elem(fd, &index, &value, 0));
488}
489
490static int create_prog_dummy_simple(enum bpf_prog_type prog_type, int ret)
491{
492 struct bpf_insn prog[] = {
493 BPF_MOV64_IMM(BPF_REG_0, ret),
494 BPF_EXIT_INSN(),
495 };
496
497 return bpf_load_program(prog_type, prog,
498 ARRAY_SIZE(prog), "GPL", 0, NULL, 0);
499}
500
501static int create_prog_dummy_loop(enum bpf_prog_type prog_type, int mfd,
502 int idx, int ret)
503{
504 struct bpf_insn prog[] = {
505 BPF_MOV64_IMM(BPF_REG_3, idx),
506 BPF_LD_MAP_FD(BPF_REG_2, mfd),
507 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
508 BPF_FUNC_tail_call),
509 BPF_MOV64_IMM(BPF_REG_0, ret),
510 BPF_EXIT_INSN(),
511 };
512
513 return bpf_load_program(prog_type, prog,
514 ARRAY_SIZE(prog), "GPL", 0, NULL, 0);
515}
516
517static int create_prog_array(enum bpf_prog_type prog_type, uint32_t max_elem,
518 int p1key, int p2key, int p3key)
519{
520 int mfd, p1fd, p2fd, p3fd;
521
522 mfd = bpf_create_map(BPF_MAP_TYPE_PROG_ARRAY, sizeof(int),
523 sizeof(int), max_elem, 0);
524 if (mfd < 0) {
525 if (skip_unsupported_map(BPF_MAP_TYPE_PROG_ARRAY))
526 return -1;
527 printf("Failed to create prog array '%s'!\n", strerror(errno));
528 return -1;
529 }
530
531 p1fd = create_prog_dummy_simple(prog_type, 42);
532 p2fd = create_prog_dummy_loop(prog_type, mfd, p2key, 41);
533 p3fd = create_prog_dummy_simple(prog_type, 24);
534 if (p1fd < 0 || p2fd < 0 || p3fd < 0)
535 goto err;
536 if (bpf_map_update_elem(mfd, &p1key, &p1fd, BPF_ANY) < 0)
537 goto err;
538 if (bpf_map_update_elem(mfd, &p2key, &p2fd, BPF_ANY) < 0)
539 goto err;
540 if (bpf_map_update_elem(mfd, &p3key, &p3fd, BPF_ANY) < 0) {
541err:
542 close(mfd);
543 mfd = -1;
544 }
545 close(p3fd);
546 close(p2fd);
547 close(p1fd);
548 return mfd;
549}
550
551static int create_map_in_map(void)
552{
553 int inner_map_fd, outer_map_fd;
554
555 inner_map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
556 sizeof(int), 1, 0);
557 if (inner_map_fd < 0) {
558 if (skip_unsupported_map(BPF_MAP_TYPE_ARRAY))
559 return -1;
560 printf("Failed to create array '%s'!\n", strerror(errno));
561 return inner_map_fd;
562 }
563
564 outer_map_fd = bpf_create_map_in_map(BPF_MAP_TYPE_ARRAY_OF_MAPS, NULL,
565 sizeof(int), inner_map_fd, 1, 0);
566 if (outer_map_fd < 0) {
567 if (skip_unsupported_map(BPF_MAP_TYPE_ARRAY_OF_MAPS))
568 return -1;
569 printf("Failed to create array of maps '%s'!\n",
570 strerror(errno));
571 }
572
573 close(inner_map_fd);
574
575 return outer_map_fd;
576}
577
578static int create_cgroup_storage(bool percpu)
579{
580 enum bpf_map_type type = percpu ? BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE :
581 BPF_MAP_TYPE_CGROUP_STORAGE;
582 int fd;
583
584 fd = bpf_create_map(type, sizeof(struct bpf_cgroup_storage_key),
585 TEST_DATA_LEN, 0, 0);
586 if (fd < 0) {
587 if (skip_unsupported_map(type))
588 return -1;
589 printf("Failed to create cgroup storage '%s'!\n",
590 strerror(errno));
591 }
592
593 return fd;
594}
595
596/* struct bpf_spin_lock {
597 * int val;
598 * };
599 * struct val {
600 * int cnt;
601 * struct bpf_spin_lock l;
602 * };
603 */
604static const char btf_str_sec[] = "\0bpf_spin_lock\0val\0cnt\0l";
605static __u32 btf_raw_types[] = {
606 /* int */
607 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
608 /* struct bpf_spin_lock */ /* [2] */
609 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 1), 4),
610 BTF_MEMBER_ENC(15, 1, 0), /* int val; */
611 /* struct val */ /* [3] */
612 BTF_TYPE_ENC(15, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 2), 8),
613 BTF_MEMBER_ENC(19, 1, 0), /* int cnt; */
614 BTF_MEMBER_ENC(23, 2, 32),/* struct bpf_spin_lock l; */
615};
616
617static int load_btf(void)
618{
619 struct btf_header hdr = {
620 .magic = BTF_MAGIC,
621 .version = BTF_VERSION,
622 .hdr_len = sizeof(struct btf_header),
623 .type_len = sizeof(btf_raw_types),
624 .str_off = sizeof(btf_raw_types),
625 .str_len = sizeof(btf_str_sec),
626 };
627 void *ptr, *raw_btf;
628 int btf_fd;
629
630 ptr = raw_btf = malloc(sizeof(hdr) + sizeof(btf_raw_types) +
631 sizeof(btf_str_sec));
632
633 memcpy(ptr, &hdr, sizeof(hdr));
634 ptr += sizeof(hdr);
635 memcpy(ptr, btf_raw_types, hdr.type_len);
636 ptr += hdr.type_len;
637 memcpy(ptr, btf_str_sec, hdr.str_len);
638 ptr += hdr.str_len;
639
640 btf_fd = bpf_load_btf(raw_btf, ptr - raw_btf, 0, 0, 0);
641 free(raw_btf);
642 if (btf_fd < 0)
643 return -1;
644 return btf_fd;
645}
646
647static int create_map_spin_lock(void)
648{
649 struct bpf_create_map_attr attr = {
650 .name = "test_map",
651 .map_type = BPF_MAP_TYPE_ARRAY,
652 .key_size = 4,
653 .value_size = 8,
654 .max_entries = 1,
655 .btf_key_type_id = 1,
656 .btf_value_type_id = 3,
657 };
658 int fd, btf_fd;
659
660 btf_fd = load_btf();
661 if (btf_fd < 0)
662 return -1;
663 attr.btf_fd = btf_fd;
664 fd = bpf_create_map_xattr(&attr);
665 if (fd < 0)
666 printf("Failed to create map with spin_lock\n");
667 return fd;
668}
669
670static int create_sk_storage_map(void)
671{
672 struct bpf_create_map_attr attr = {
673 .name = "test_map",
674 .map_type = BPF_MAP_TYPE_SK_STORAGE,
675 .key_size = 4,
676 .value_size = 8,
677 .max_entries = 0,
678 .map_flags = BPF_F_NO_PREALLOC,
679 .btf_key_type_id = 1,
680 .btf_value_type_id = 3,
681 };
682 int fd, btf_fd;
683
684 btf_fd = load_btf();
685 if (btf_fd < 0)
686 return -1;
687 attr.btf_fd = btf_fd;
688 fd = bpf_create_map_xattr(&attr);
689 close(attr.btf_fd);
690 if (fd < 0)
691 printf("Failed to create sk_storage_map\n");
692 return fd;
693}
694
695static char bpf_vlog[UINT_MAX >> 8];
696
697static void do_test_fixup(struct bpf_test *test, enum bpf_prog_type prog_type,
698 struct bpf_insn *prog, int *map_fds)
699{
700 int *fixup_map_hash_8b = test->fixup_map_hash_8b;
701 int *fixup_map_hash_48b = test->fixup_map_hash_48b;
702 int *fixup_map_hash_16b = test->fixup_map_hash_16b;
703 int *fixup_map_array_48b = test->fixup_map_array_48b;
704 int *fixup_map_sockmap = test->fixup_map_sockmap;
705 int *fixup_map_sockhash = test->fixup_map_sockhash;
706 int *fixup_map_xskmap = test->fixup_map_xskmap;
707 int *fixup_map_stacktrace = test->fixup_map_stacktrace;
708 int *fixup_prog1 = test->fixup_prog1;
709 int *fixup_prog2 = test->fixup_prog2;
710 int *fixup_map_in_map = test->fixup_map_in_map;
711 int *fixup_cgroup_storage = test->fixup_cgroup_storage;
712 int *fixup_percpu_cgroup_storage = test->fixup_percpu_cgroup_storage;
713 int *fixup_map_spin_lock = test->fixup_map_spin_lock;
714 int *fixup_map_array_ro = test->fixup_map_array_ro;
715 int *fixup_map_array_wo = test->fixup_map_array_wo;
716 int *fixup_map_array_small = test->fixup_map_array_small;
717 int *fixup_sk_storage_map = test->fixup_sk_storage_map;
718 int *fixup_map_event_output = test->fixup_map_event_output;
719 int *fixup_map_reuseport_array = test->fixup_map_reuseport_array;
720 int *fixup_map_ringbuf = test->fixup_map_ringbuf;
721
722 if (test->fill_helper) {
723 test->fill_insns = calloc(MAX_TEST_INSNS, sizeof(struct bpf_insn));
724 test->fill_helper(test);
725 }
726
727 /* Allocating HTs with 1 elem is fine here, since we only test
728 * for verifier and not do a runtime lookup, so the only thing
729 * that really matters is value size in this case.
730 */
731 if (*fixup_map_hash_8b) {
732 map_fds[0] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
733 sizeof(long long), 1);
734 do {
735 prog[*fixup_map_hash_8b].imm = map_fds[0];
736 fixup_map_hash_8b++;
737 } while (*fixup_map_hash_8b);
738 }
739
740 if (*fixup_map_hash_48b) {
741 map_fds[1] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
742 sizeof(struct test_val), 1);
743 do {
744 prog[*fixup_map_hash_48b].imm = map_fds[1];
745 fixup_map_hash_48b++;
746 } while (*fixup_map_hash_48b);
747 }
748
749 if (*fixup_map_hash_16b) {
750 map_fds[2] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
751 sizeof(struct other_val), 1);
752 do {
753 prog[*fixup_map_hash_16b].imm = map_fds[2];
754 fixup_map_hash_16b++;
755 } while (*fixup_map_hash_16b);
756 }
757
758 if (*fixup_map_array_48b) {
759 map_fds[3] = create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
760 sizeof(struct test_val), 1);
761 update_map(map_fds[3], 0);
762 do {
763 prog[*fixup_map_array_48b].imm = map_fds[3];
764 fixup_map_array_48b++;
765 } while (*fixup_map_array_48b);
766 }
767
768 if (*fixup_prog1) {
769 map_fds[4] = create_prog_array(prog_type, 4, 0, 1, 2);
770 do {
771 prog[*fixup_prog1].imm = map_fds[4];
772 fixup_prog1++;
773 } while (*fixup_prog1);
774 }
775
776 if (*fixup_prog2) {
777 map_fds[5] = create_prog_array(prog_type, 8, 7, 1, 2);
778 do {
779 prog[*fixup_prog2].imm = map_fds[5];
780 fixup_prog2++;
781 } while (*fixup_prog2);
782 }
783
784 if (*fixup_map_in_map) {
785 map_fds[6] = create_map_in_map();
786 do {
787 prog[*fixup_map_in_map].imm = map_fds[6];
788 fixup_map_in_map++;
789 } while (*fixup_map_in_map);
790 }
791
792 if (*fixup_cgroup_storage) {
793 map_fds[7] = create_cgroup_storage(false);
794 do {
795 prog[*fixup_cgroup_storage].imm = map_fds[7];
796 fixup_cgroup_storage++;
797 } while (*fixup_cgroup_storage);
798 }
799
800 if (*fixup_percpu_cgroup_storage) {
801 map_fds[8] = create_cgroup_storage(true);
802 do {
803 prog[*fixup_percpu_cgroup_storage].imm = map_fds[8];
804 fixup_percpu_cgroup_storage++;
805 } while (*fixup_percpu_cgroup_storage);
806 }
807 if (*fixup_map_sockmap) {
808 map_fds[9] = create_map(BPF_MAP_TYPE_SOCKMAP, sizeof(int),
809 sizeof(int), 1);
810 do {
811 prog[*fixup_map_sockmap].imm = map_fds[9];
812 fixup_map_sockmap++;
813 } while (*fixup_map_sockmap);
814 }
815 if (*fixup_map_sockhash) {
816 map_fds[10] = create_map(BPF_MAP_TYPE_SOCKHASH, sizeof(int),
817 sizeof(int), 1);
818 do {
819 prog[*fixup_map_sockhash].imm = map_fds[10];
820 fixup_map_sockhash++;
821 } while (*fixup_map_sockhash);
822 }
823 if (*fixup_map_xskmap) {
824 map_fds[11] = create_map(BPF_MAP_TYPE_XSKMAP, sizeof(int),
825 sizeof(int), 1);
826 do {
827 prog[*fixup_map_xskmap].imm = map_fds[11];
828 fixup_map_xskmap++;
829 } while (*fixup_map_xskmap);
830 }
831 if (*fixup_map_stacktrace) {
832 map_fds[12] = create_map(BPF_MAP_TYPE_STACK_TRACE, sizeof(u32),
833 sizeof(u64), 1);
834 do {
835 prog[*fixup_map_stacktrace].imm = map_fds[12];
836 fixup_map_stacktrace++;
837 } while (*fixup_map_stacktrace);
838 }
839 if (*fixup_map_spin_lock) {
840 map_fds[13] = create_map_spin_lock();
841 do {
842 prog[*fixup_map_spin_lock].imm = map_fds[13];
843 fixup_map_spin_lock++;
844 } while (*fixup_map_spin_lock);
845 }
846 if (*fixup_map_array_ro) {
847 map_fds[14] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
848 sizeof(struct test_val), 1,
849 BPF_F_RDONLY_PROG);
850 update_map(map_fds[14], 0);
851 do {
852 prog[*fixup_map_array_ro].imm = map_fds[14];
853 fixup_map_array_ro++;
854 } while (*fixup_map_array_ro);
855 }
856 if (*fixup_map_array_wo) {
857 map_fds[15] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
858 sizeof(struct test_val), 1,
859 BPF_F_WRONLY_PROG);
860 update_map(map_fds[15], 0);
861 do {
862 prog[*fixup_map_array_wo].imm = map_fds[15];
863 fixup_map_array_wo++;
864 } while (*fixup_map_array_wo);
865 }
866 if (*fixup_map_array_small) {
867 map_fds[16] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
868 1, 1, 0);
869 update_map(map_fds[16], 0);
870 do {
871 prog[*fixup_map_array_small].imm = map_fds[16];
872 fixup_map_array_small++;
873 } while (*fixup_map_array_small);
874 }
875 if (*fixup_sk_storage_map) {
876 map_fds[17] = create_sk_storage_map();
877 do {
878 prog[*fixup_sk_storage_map].imm = map_fds[17];
879 fixup_sk_storage_map++;
880 } while (*fixup_sk_storage_map);
881 }
882 if (*fixup_map_event_output) {
883 map_fds[18] = __create_map(BPF_MAP_TYPE_PERF_EVENT_ARRAY,
884 sizeof(int), sizeof(int), 1, 0);
885 do {
886 prog[*fixup_map_event_output].imm = map_fds[18];
887 fixup_map_event_output++;
888 } while (*fixup_map_event_output);
889 }
890 if (*fixup_map_reuseport_array) {
891 map_fds[19] = __create_map(BPF_MAP_TYPE_REUSEPORT_SOCKARRAY,
892 sizeof(u32), sizeof(u64), 1, 0);
893 do {
894 prog[*fixup_map_reuseport_array].imm = map_fds[19];
895 fixup_map_reuseport_array++;
896 } while (*fixup_map_reuseport_array);
897 }
898 if (*fixup_map_ringbuf) {
899 map_fds[20] = create_map(BPF_MAP_TYPE_RINGBUF, 0,
900 0, 4096);
901 do {
902 prog[*fixup_map_ringbuf].imm = map_fds[20];
903 fixup_map_ringbuf++;
904 } while (*fixup_map_ringbuf);
905 }
906}
907
908struct libcap {
909 struct __user_cap_header_struct hdr;
910 struct __user_cap_data_struct data[2];
911};
912
913static int set_admin(bool admin)
914{
915 cap_t caps;
916 /* need CAP_BPF, CAP_NET_ADMIN, CAP_PERFMON to load progs */
917 const cap_value_t cap_net_admin = CAP_NET_ADMIN;
918 const cap_value_t cap_sys_admin = CAP_SYS_ADMIN;
919 struct libcap *cap;
920 int ret = -1;
921
922 caps = cap_get_proc();
923 if (!caps) {
924 perror("cap_get_proc");
925 return -1;
926 }
927 cap = (struct libcap *)caps;
928 if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap_sys_admin, CAP_CLEAR)) {
929 perror("cap_set_flag clear admin");
930 goto out;
931 }
932 if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap_net_admin,
933 admin ? CAP_SET : CAP_CLEAR)) {
934 perror("cap_set_flag set_or_clear net");
935 goto out;
936 }
937 /* libcap is likely old and simply ignores CAP_BPF and CAP_PERFMON,
938 * so update effective bits manually
939 */
940 if (admin) {
941 cap->data[1].effective |= 1 << (38 /* CAP_PERFMON */ - 32);
942 cap->data[1].effective |= 1 << (39 /* CAP_BPF */ - 32);
943 } else {
944 cap->data[1].effective &= ~(1 << (38 - 32));
945 cap->data[1].effective &= ~(1 << (39 - 32));
946 }
947 if (cap_set_proc(caps)) {
948 perror("cap_set_proc");
949 goto out;
950 }
951 ret = 0;
952out:
953 if (cap_free(caps))
954 perror("cap_free");
955 return ret;
956}
957
958static int do_prog_test_run(int fd_prog, bool unpriv, uint32_t expected_val,
959 void *data, size_t size_data)
960{
961 __u8 tmp[TEST_DATA_LEN << 2];
962 __u32 size_tmp = sizeof(tmp);
963 uint32_t retval;
964 int err, saved_errno;
965
966 if (unpriv)
967 set_admin(true);
968 err = bpf_prog_test_run(fd_prog, 1, data, size_data,
969 tmp, &size_tmp, &retval, NULL);
970 saved_errno = errno;
971
972 if (unpriv)
973 set_admin(false);
974
975 if (err) {
976 switch (saved_errno) {
977 case 524/*ENOTSUPP*/:
978 printf("Did not run the program (not supported) ");
979 return 0;
980 case EPERM:
981 if (unpriv) {
982 printf("Did not run the program (no permission) ");
983 return 0;
984 }
985 /* fallthrough; */
986 default:
987 printf("FAIL: Unexpected bpf_prog_test_run error (%s) ",
988 strerror(saved_errno));
989 return err;
990 }
991 }
992
993 if (retval != expected_val &&
994 expected_val != POINTER_VALUE) {
995 printf("FAIL retval %d != %d ", retval, expected_val);
996 return 1;
997 }
998
999 return 0;
1000}
1001
1002/* Returns true if every part of exp (tab-separated) appears in log, in order.
1003 *
1004 * If exp is an empty string, returns true.
1005 */
1006static bool cmp_str_seq(const char *log, const char *exp)
1007{
1008 char needle[200];
1009 const char *p, *q;
1010 int len;
1011
1012 do {
1013 if (!strlen(exp))
1014 break;
1015 p = strchr(exp, '\t');
1016 if (!p)
1017 p = exp + strlen(exp);
1018
1019 len = p - exp;
1020 if (len >= sizeof(needle) || !len) {
1021 printf("FAIL\nTestcase bug\n");
1022 return false;
1023 }
1024 strncpy(needle, exp, len);
1025 needle[len] = 0;
1026 q = strstr(log, needle);
1027 if (!q) {
1028 printf("FAIL\nUnexpected verifier log!\n"
1029 "EXP: %s\nRES:\n", needle);
1030 return false;
1031 }
1032 log = q + len;
1033 exp = p + 1;
1034 } while (*p);
1035 return true;
1036}
1037
1038static void do_test_single(struct bpf_test *test, bool unpriv,
1039 int *passes, int *errors)
1040{
1041 int fd_prog, expected_ret, alignment_prevented_execution;
1042 int prog_len, prog_type = test->prog_type;
1043 struct bpf_insn *prog = test->insns;
1044 struct bpf_load_program_attr attr;
1045 int run_errs, run_successes;
1046 int map_fds[MAX_NR_MAPS];
1047 const char *expected_err;
1048 int saved_errno;
1049 int fixup_skips;
1050 __u32 pflags;
1051 int i, err;
1052
1053 for (i = 0; i < MAX_NR_MAPS; i++)
1054 map_fds[i] = -1;
1055
1056 if (!prog_type)
1057 prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1058 fixup_skips = skips;
1059 do_test_fixup(test, prog_type, prog, map_fds);
1060 if (test->fill_insns) {
1061 prog = test->fill_insns;
1062 prog_len = test->prog_len;
1063 } else {
1064 prog_len = probe_filter_length(prog);
1065 }
1066 /* If there were some map skips during fixup due to missing bpf
1067 * features, skip this test.
1068 */
1069 if (fixup_skips != skips)
1070 return;
1071
1072 pflags = BPF_F_TEST_RND_HI32;
1073 if (test->flags & F_LOAD_WITH_STRICT_ALIGNMENT)
1074 pflags |= BPF_F_STRICT_ALIGNMENT;
1075 if (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS)
1076 pflags |= BPF_F_ANY_ALIGNMENT;
1077 if (test->flags & ~3)
1078 pflags |= test->flags;
1079
1080 expected_ret = unpriv && test->result_unpriv != UNDEF ?
1081 test->result_unpriv : test->result;
1082 expected_err = unpriv && test->errstr_unpriv ?
1083 test->errstr_unpriv : test->errstr;
1084 memset(&attr, 0, sizeof(attr));
1085 attr.prog_type = prog_type;
1086 attr.expected_attach_type = test->expected_attach_type;
1087 attr.insns = prog;
1088 attr.insns_cnt = prog_len;
1089 attr.license = "GPL";
1090 if (verbose)
1091 attr.log_level = 1;
1092 else if (expected_ret == VERBOSE_ACCEPT)
1093 attr.log_level = 2;
1094 else
1095 attr.log_level = 4;
1096 attr.prog_flags = pflags;
1097
1098 if (prog_type == BPF_PROG_TYPE_TRACING && test->kfunc) {
1099 attr.attach_btf_id = libbpf_find_vmlinux_btf_id(test->kfunc,
1100 attr.expected_attach_type);
1101 if (attr.attach_btf_id < 0) {
1102 printf("FAIL\nFailed to find BTF ID for '%s'!\n",
1103 test->kfunc);
1104 (*errors)++;
1105 return;
1106 }
1107 }
1108
1109 fd_prog = bpf_load_program_xattr(&attr, bpf_vlog, sizeof(bpf_vlog));
1110 saved_errno = errno;
1111
1112 /* BPF_PROG_TYPE_TRACING requires more setup and
1113 * bpf_probe_prog_type won't give correct answer
1114 */
1115 if (fd_prog < 0 && prog_type != BPF_PROG_TYPE_TRACING &&
1116 !bpf_probe_prog_type(prog_type, 0)) {
1117 printf("SKIP (unsupported program type %d)\n", prog_type);
1118 skips++;
1119 goto close_fds;
1120 }
1121
1122 alignment_prevented_execution = 0;
1123
1124 if (expected_ret == ACCEPT || expected_ret == VERBOSE_ACCEPT) {
1125 if (fd_prog < 0) {
1126 printf("FAIL\nFailed to load prog '%s'!\n",
1127 strerror(saved_errno));
1128 goto fail_log;
1129 }
1130#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
1131 if (fd_prog >= 0 &&
1132 (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS))
1133 alignment_prevented_execution = 1;
1134#endif
1135 if (expected_ret == VERBOSE_ACCEPT && !cmp_str_seq(bpf_vlog, expected_err)) {
1136 goto fail_log;
1137 }
1138 } else {
1139 if (fd_prog >= 0) {
1140 printf("FAIL\nUnexpected success to load!\n");
1141 goto fail_log;
1142 }
1143 if (!expected_err || !cmp_str_seq(bpf_vlog, expected_err)) {
1144 printf("FAIL\nUnexpected error message!\n\tEXP: %s\n\tRES: %s\n",
1145 expected_err, bpf_vlog);
1146 goto fail_log;
1147 }
1148 }
1149
1150 if (!unpriv && test->insn_processed) {
1151 uint32_t insn_processed;
1152 char *proc;
1153
1154 proc = strstr(bpf_vlog, "processed ");
1155 insn_processed = atoi(proc + 10);
1156 if (test->insn_processed != insn_processed) {
1157 printf("FAIL\nUnexpected insn_processed %u vs %u\n",
1158 insn_processed, test->insn_processed);
1159 goto fail_log;
1160 }
1161 }
1162
1163 if (verbose)
1164 printf(", verifier log:\n%s", bpf_vlog);
1165
1166 run_errs = 0;
1167 run_successes = 0;
1168 if (!alignment_prevented_execution && fd_prog >= 0 && test->runs >= 0) {
1169 uint32_t expected_val;
1170 int i;
1171
1172 if (!test->runs)
1173 test->runs = 1;
1174
1175 for (i = 0; i < test->runs; i++) {
1176 if (unpriv && test->retvals[i].retval_unpriv)
1177 expected_val = test->retvals[i].retval_unpriv;
1178 else
1179 expected_val = test->retvals[i].retval;
1180
1181 err = do_prog_test_run(fd_prog, unpriv, expected_val,
1182 test->retvals[i].data,
1183 sizeof(test->retvals[i].data));
1184 if (err) {
1185 printf("(run %d/%d) ", i + 1, test->runs);
1186 run_errs++;
1187 } else {
1188 run_successes++;
1189 }
1190 }
1191 }
1192
1193 if (!run_errs) {
1194 (*passes)++;
1195 if (run_successes > 1)
1196 printf("%d cases ", run_successes);
1197 printf("OK");
1198 if (alignment_prevented_execution)
1199 printf(" (NOTE: not executed due to unknown alignment)");
1200 printf("\n");
1201 } else {
1202 printf("\n");
1203 goto fail_log;
1204 }
1205close_fds:
1206 if (test->fill_insns)
1207 free(test->fill_insns);
1208 close(fd_prog);
1209 for (i = 0; i < MAX_NR_MAPS; i++)
1210 close(map_fds[i]);
1211 sched_yield();
1212 return;
1213fail_log:
1214 (*errors)++;
1215 printf("%s", bpf_vlog);
1216 goto close_fds;
1217}
1218
1219static bool is_admin(void)
1220{
1221 cap_flag_value_t net_priv = CAP_CLEAR;
1222 bool perfmon_priv = false;
1223 bool bpf_priv = false;
1224 struct libcap *cap;
1225 cap_t caps;
1226
1227#ifdef CAP_IS_SUPPORTED
1228 if (!CAP_IS_SUPPORTED(CAP_SETFCAP)) {
1229 perror("cap_get_flag");
1230 return false;
1231 }
1232#endif
1233 caps = cap_get_proc();
1234 if (!caps) {
1235 perror("cap_get_proc");
1236 return false;
1237 }
1238 cap = (struct libcap *)caps;
1239 bpf_priv = cap->data[1].effective & (1 << (39/* CAP_BPF */ - 32));
1240 perfmon_priv = cap->data[1].effective & (1 << (38/* CAP_PERFMON */ - 32));
1241 if (cap_get_flag(caps, CAP_NET_ADMIN, CAP_EFFECTIVE, &net_priv))
1242 perror("cap_get_flag NET");
1243 if (cap_free(caps))
1244 perror("cap_free");
1245 return bpf_priv && perfmon_priv && net_priv == CAP_SET;
1246}
1247
1248static void get_unpriv_disabled()
1249{
1250 char buf[2];
1251 FILE *fd;
1252
1253 fd = fopen("/proc/sys/"UNPRIV_SYSCTL, "r");
1254 if (!fd) {
1255 perror("fopen /proc/sys/"UNPRIV_SYSCTL);
1256 unpriv_disabled = true;
1257 return;
1258 }
1259 if (fgets(buf, 2, fd) == buf && atoi(buf))
1260 unpriv_disabled = true;
1261 fclose(fd);
1262}
1263
1264static bool test_as_unpriv(struct bpf_test *test)
1265{
1266#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
1267 /* Some architectures have strict alignment requirements. In
1268 * that case, the BPF verifier detects if a program has
1269 * unaligned accesses and rejects them. A user can pass
1270 * BPF_F_ANY_ALIGNMENT to a program to override this
1271 * check. That, however, will only work when a privileged user
1272 * loads a program. An unprivileged user loading a program
1273 * with this flag will be rejected prior entering the
1274 * verifier.
1275 */
1276 if (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS)
1277 return false;
1278#endif
1279 return !test->prog_type ||
1280 test->prog_type == BPF_PROG_TYPE_SOCKET_FILTER ||
1281 test->prog_type == BPF_PROG_TYPE_CGROUP_SKB;
1282}
1283
1284static int do_test(bool unpriv, unsigned int from, unsigned int to)
1285{
1286 int i, passes = 0, errors = 0;
1287
1288 for (i = from; i < to; i++) {
1289 struct bpf_test *test = &tests[i];
1290
1291 /* Program types that are not supported by non-root we
1292 * skip right away.
1293 */
1294 if (test_as_unpriv(test) && unpriv_disabled) {
1295 printf("#%d/u %s SKIP\n", i, test->descr);
1296 skips++;
1297 } else if (test_as_unpriv(test)) {
1298 if (!unpriv)
1299 set_admin(false);
1300 printf("#%d/u %s ", i, test->descr);
1301 do_test_single(test, true, &passes, &errors);
1302 if (!unpriv)
1303 set_admin(true);
1304 }
1305
1306 if (unpriv) {
1307 printf("#%d/p %s SKIP\n", i, test->descr);
1308 skips++;
1309 } else {
1310 printf("#%d/p %s ", i, test->descr);
1311 do_test_single(test, false, &passes, &errors);
1312 }
1313 }
1314
1315 printf("Summary: %d PASSED, %d SKIPPED, %d FAILED\n", passes,
1316 skips, errors);
1317 return errors ? EXIT_FAILURE : EXIT_SUCCESS;
1318}
1319
1320int main(int argc, char **argv)
1321{
1322 unsigned int from = 0, to = ARRAY_SIZE(tests);
1323 bool unpriv = !is_admin();
1324 int arg = 1;
1325
1326 if (argc > 1 && strcmp(argv[1], "-v") == 0) {
1327 arg++;
1328 verbose = true;
1329 argc--;
1330 }
1331
1332 if (argc == 3) {
1333 unsigned int l = atoi(argv[arg]);
1334 unsigned int u = atoi(argv[arg + 1]);
1335
1336 if (l < to && u < to) {
1337 from = l;
1338 to = u + 1;
1339 }
1340 } else if (argc == 2) {
1341 unsigned int t = atoi(argv[arg]);
1342
1343 if (t < to) {
1344 from = t;
1345 to = t + 1;
1346 }
1347 }
1348
1349 get_unpriv_disabled();
1350 if (unpriv && unpriv_disabled) {
1351 printf("Cannot run as unprivileged user with sysctl %s.\n",
1352 UNPRIV_SYSCTL);
1353 return EXIT_FAILURE;
1354 }
1355
1356 bpf_semi_rand_init();
1357 return do_test(unpriv, from, to);
1358}