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 #ifndef ENOTSUPP
51 #define ENOTSUPP 524
52 #endif
53 
54 #define MAX_INSNS	BPF_MAXINSNS
55 #define MAX_TEST_INSNS	1000000
56 #define MAX_FIXUPS	8
57 #define MAX_NR_MAPS	21
58 #define MAX_TEST_RUNS	8
59 #define POINTER_VALUE	0xcafe4all
60 #define TEST_DATA_LEN	64
61 
62 #define F_NEEDS_EFFICIENT_UNALIGNED_ACCESS	(1 << 0)
63 #define F_LOAD_WITH_STRICT_ALIGNMENT		(1 << 1)
64 
65 #define UNPRIV_SYSCTL "kernel/unprivileged_bpf_disabled"
66 static bool unpriv_disabled = false;
67 static int skips;
68 static bool verbose = false;
69 
70 struct bpf_test {
71 	const char *descr;
72 	struct bpf_insn	insns[MAX_INSNS];
73 	struct bpf_insn	*fill_insns;
74 	int fixup_map_hash_8b[MAX_FIXUPS];
75 	int fixup_map_hash_48b[MAX_FIXUPS];
76 	int fixup_map_hash_16b[MAX_FIXUPS];
77 	int fixup_map_array_48b[MAX_FIXUPS];
78 	int fixup_map_sockmap[MAX_FIXUPS];
79 	int fixup_map_sockhash[MAX_FIXUPS];
80 	int fixup_map_xskmap[MAX_FIXUPS];
81 	int fixup_map_stacktrace[MAX_FIXUPS];
82 	int fixup_prog1[MAX_FIXUPS];
83 	int fixup_prog2[MAX_FIXUPS];
84 	int fixup_map_in_map[MAX_FIXUPS];
85 	int fixup_cgroup_storage[MAX_FIXUPS];
86 	int fixup_percpu_cgroup_storage[MAX_FIXUPS];
87 	int fixup_map_spin_lock[MAX_FIXUPS];
88 	int fixup_map_array_ro[MAX_FIXUPS];
89 	int fixup_map_array_wo[MAX_FIXUPS];
90 	int fixup_map_array_small[MAX_FIXUPS];
91 	int fixup_sk_storage_map[MAX_FIXUPS];
92 	int fixup_map_event_output[MAX_FIXUPS];
93 	int fixup_map_reuseport_array[MAX_FIXUPS];
94 	int fixup_map_ringbuf[MAX_FIXUPS];
95 	int fixup_map_timer[MAX_FIXUPS];
96 	/* Expected verifier log output for result REJECT or VERBOSE_ACCEPT.
97 	 * Can be a tab-separated sequence of expected strings. An empty string
98 	 * means no log verification.
99 	 */
100 	const char *errstr;
101 	const char *errstr_unpriv;
102 	uint32_t insn_processed;
103 	int prog_len;
104 	enum {
105 		UNDEF,
106 		ACCEPT,
107 		REJECT,
108 		VERBOSE_ACCEPT,
109 	} result, result_unpriv;
110 	enum bpf_prog_type prog_type;
111 	uint8_t flags;
112 	void (*fill_helper)(struct bpf_test *self);
113 	int runs;
114 #define bpf_testdata_struct_t					\
115 	struct {						\
116 		uint32_t retval, retval_unpriv;			\
117 		union {						\
118 			__u8 data[TEST_DATA_LEN];		\
119 			__u64 data64[TEST_DATA_LEN / 8];	\
120 		};						\
121 	}
122 	union {
123 		bpf_testdata_struct_t;
124 		bpf_testdata_struct_t retvals[MAX_TEST_RUNS];
125 	};
126 	enum bpf_attach_type expected_attach_type;
127 	const char *kfunc;
128 };
129 
130 /* Note we want this to be 64 bit aligned so that the end of our array is
131  * actually the end of the structure.
132  */
133 #define MAX_ENTRIES 11
134 
135 struct test_val {
136 	unsigned int index;
137 	int foo[MAX_ENTRIES];
138 };
139 
140 struct other_val {
141 	long long foo;
142 	long long bar;
143 };
144 
145 static void bpf_fill_ld_abs_vlan_push_pop(struct bpf_test *self)
146 {
147 	/* test: {skb->data[0], vlan_push} x 51 + {skb->data[0], vlan_pop} x 51 */
148 #define PUSH_CNT 51
149 	/* jump range is limited to 16 bit. PUSH_CNT of ld_abs needs room */
150 	unsigned int len = (1 << 15) - PUSH_CNT * 2 * 5 * 6;
151 	struct bpf_insn *insn = self->fill_insns;
152 	int i = 0, j, k = 0;
153 
154 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
155 loop:
156 	for (j = 0; j < PUSH_CNT; j++) {
157 		insn[i++] = BPF_LD_ABS(BPF_B, 0);
158 		/* jump to error label */
159 		insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
160 		i++;
161 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
162 		insn[i++] = BPF_MOV64_IMM(BPF_REG_2, 1);
163 		insn[i++] = BPF_MOV64_IMM(BPF_REG_3, 2);
164 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
165 					 BPF_FUNC_skb_vlan_push),
166 		insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
167 		i++;
168 	}
169 
170 	for (j = 0; j < PUSH_CNT; j++) {
171 		insn[i++] = BPF_LD_ABS(BPF_B, 0);
172 		insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
173 		i++;
174 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
175 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
176 					 BPF_FUNC_skb_vlan_pop),
177 		insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
178 		i++;
179 	}
180 	if (++k < 5)
181 		goto loop;
182 
183 	for (; i < len - 3; i++)
184 		insn[i] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0xbef);
185 	insn[len - 3] = BPF_JMP_A(1);
186 	/* error label */
187 	insn[len - 2] = BPF_MOV32_IMM(BPF_REG_0, 0);
188 	insn[len - 1] = BPF_EXIT_INSN();
189 	self->prog_len = len;
190 }
191 
192 static void bpf_fill_jump_around_ld_abs(struct bpf_test *self)
193 {
194 	struct bpf_insn *insn = self->fill_insns;
195 	/* jump range is limited to 16 bit. every ld_abs is replaced by 6 insns,
196 	 * but on arches like arm, ppc etc, there will be one BPF_ZEXT inserted
197 	 * to extend the error value of the inlined ld_abs sequence which then
198 	 * contains 7 insns. so, set the dividend to 7 so the testcase could
199 	 * work on all arches.
200 	 */
201 	unsigned int len = (1 << 15) / 7;
202 	int i = 0;
203 
204 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
205 	insn[i++] = BPF_LD_ABS(BPF_B, 0);
206 	insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 10, len - i - 2);
207 	i++;
208 	while (i < len - 1)
209 		insn[i++] = BPF_LD_ABS(BPF_B, 1);
210 	insn[i] = BPF_EXIT_INSN();
211 	self->prog_len = i + 1;
212 }
213 
214 static void bpf_fill_rand_ld_dw(struct bpf_test *self)
215 {
216 	struct bpf_insn *insn = self->fill_insns;
217 	uint64_t res = 0;
218 	int i = 0;
219 
220 	insn[i++] = BPF_MOV32_IMM(BPF_REG_0, 0);
221 	while (i < self->retval) {
222 		uint64_t val = bpf_semi_rand_get();
223 		struct bpf_insn tmp[2] = { BPF_LD_IMM64(BPF_REG_1, val) };
224 
225 		res ^= val;
226 		insn[i++] = tmp[0];
227 		insn[i++] = tmp[1];
228 		insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
229 	}
230 	insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_0);
231 	insn[i++] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 32);
232 	insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
233 	insn[i] = BPF_EXIT_INSN();
234 	self->prog_len = i + 1;
235 	res ^= (res >> 32);
236 	self->retval = (uint32_t)res;
237 }
238 
239 #define MAX_JMP_SEQ 8192
240 
241 /* test the sequence of 8k jumps */
242 static void bpf_fill_scale1(struct bpf_test *self)
243 {
244 	struct bpf_insn *insn = self->fill_insns;
245 	int i = 0, k = 0;
246 
247 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
248 	/* test to check that the long sequence of jumps is acceptable */
249 	while (k++ < MAX_JMP_SEQ) {
250 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
251 					 BPF_FUNC_get_prandom_u32);
252 		insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
253 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
254 		insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
255 					-8 * (k % 64 + 1));
256 	}
257 	/* is_state_visited() doesn't allocate state for pruning for every jump.
258 	 * Hence multiply jmps by 4 to accommodate that heuristic
259 	 */
260 	while (i < MAX_TEST_INSNS - MAX_JMP_SEQ * 4)
261 		insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
262 	insn[i] = BPF_EXIT_INSN();
263 	self->prog_len = i + 1;
264 	self->retval = 42;
265 }
266 
267 /* test the sequence of 8k jumps in inner most function (function depth 8)*/
268 static void bpf_fill_scale2(struct bpf_test *self)
269 {
270 	struct bpf_insn *insn = self->fill_insns;
271 	int i = 0, k = 0;
272 
273 #define FUNC_NEST 7
274 	for (k = 0; k < FUNC_NEST; k++) {
275 		insn[i++] = BPF_CALL_REL(1);
276 		insn[i++] = BPF_EXIT_INSN();
277 	}
278 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
279 	/* test to check that the long sequence of jumps is acceptable */
280 	k = 0;
281 	while (k++ < MAX_JMP_SEQ) {
282 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
283 					 BPF_FUNC_get_prandom_u32);
284 		insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
285 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
286 		insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
287 					-8 * (k % (64 - 4 * FUNC_NEST) + 1));
288 	}
289 	while (i < MAX_TEST_INSNS - MAX_JMP_SEQ * 4)
290 		insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
291 	insn[i] = BPF_EXIT_INSN();
292 	self->prog_len = i + 1;
293 	self->retval = 42;
294 }
295 
296 static void bpf_fill_scale(struct bpf_test *self)
297 {
298 	switch (self->retval) {
299 	case 1:
300 		return bpf_fill_scale1(self);
301 	case 2:
302 		return bpf_fill_scale2(self);
303 	default:
304 		self->prog_len = 0;
305 		break;
306 	}
307 }
308 
309 static int bpf_fill_torturous_jumps_insn_1(struct bpf_insn *insn)
310 {
311 	unsigned int len = 259, hlen = 128;
312 	int i;
313 
314 	insn[0] = BPF_EMIT_CALL(BPF_FUNC_get_prandom_u32);
315 	for (i = 1; i <= hlen; i++) {
316 		insn[i]        = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, i, hlen);
317 		insn[i + hlen] = BPF_JMP_A(hlen - i);
318 	}
319 	insn[len - 2] = BPF_MOV64_IMM(BPF_REG_0, 1);
320 	insn[len - 1] = BPF_EXIT_INSN();
321 
322 	return len;
323 }
324 
325 static int bpf_fill_torturous_jumps_insn_2(struct bpf_insn *insn)
326 {
327 	unsigned int len = 4100, jmp_off = 2048;
328 	int i, j;
329 
330 	insn[0] = BPF_EMIT_CALL(BPF_FUNC_get_prandom_u32);
331 	for (i = 1; i <= jmp_off; i++) {
332 		insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, i, jmp_off);
333 	}
334 	insn[i++] = BPF_JMP_A(jmp_off);
335 	for (; i <= jmp_off * 2 + 1; i+=16) {
336 		for (j = 0; j < 16; j++) {
337 			insn[i + j] = BPF_JMP_A(16 - j - 1);
338 		}
339 	}
340 
341 	insn[len - 2] = BPF_MOV64_IMM(BPF_REG_0, 2);
342 	insn[len - 1] = BPF_EXIT_INSN();
343 
344 	return len;
345 }
346 
347 static void bpf_fill_torturous_jumps(struct bpf_test *self)
348 {
349 	struct bpf_insn *insn = self->fill_insns;
350 	int i = 0;
351 
352 	switch (self->retval) {
353 	case 1:
354 		self->prog_len = bpf_fill_torturous_jumps_insn_1(insn);
355 		return;
356 	case 2:
357 		self->prog_len = bpf_fill_torturous_jumps_insn_2(insn);
358 		return;
359 	case 3:
360 		/* main */
361 		insn[i++] = BPF_RAW_INSN(BPF_JMP|BPF_CALL, 0, 1, 0, 4);
362 		insn[i++] = BPF_RAW_INSN(BPF_JMP|BPF_CALL, 0, 1, 0, 262);
363 		insn[i++] = BPF_ST_MEM(BPF_B, BPF_REG_10, -32, 0);
364 		insn[i++] = BPF_MOV64_IMM(BPF_REG_0, 3);
365 		insn[i++] = BPF_EXIT_INSN();
366 
367 		/* subprog 1 */
368 		i += bpf_fill_torturous_jumps_insn_1(insn + i);
369 
370 		/* subprog 2 */
371 		i += bpf_fill_torturous_jumps_insn_2(insn + i);
372 
373 		self->prog_len = i;
374 		return;
375 	default:
376 		self->prog_len = 0;
377 		break;
378 	}
379 }
380 
381 /* BPF_SK_LOOKUP contains 13 instructions, if you need to fix up maps */
382 #define BPF_SK_LOOKUP(func)						\
383 	/* struct bpf_sock_tuple tuple = {} */				\
384 	BPF_MOV64_IMM(BPF_REG_2, 0),					\
385 	BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_2, -8),			\
386 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -16),		\
387 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -24),		\
388 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -32),		\
389 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -40),		\
390 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -48),		\
391 	/* sk = func(ctx, &tuple, sizeof tuple, 0, 0) */		\
392 	BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),				\
393 	BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -48),				\
394 	BPF_MOV64_IMM(BPF_REG_3, sizeof(struct bpf_sock_tuple)),	\
395 	BPF_MOV64_IMM(BPF_REG_4, 0),					\
396 	BPF_MOV64_IMM(BPF_REG_5, 0),					\
397 	BPF_EMIT_CALL(BPF_FUNC_ ## func)
398 
399 /* BPF_DIRECT_PKT_R2 contains 7 instructions, it initializes default return
400  * value into 0 and does necessary preparation for direct packet access
401  * through r2. The allowed access range is 8 bytes.
402  */
403 #define BPF_DIRECT_PKT_R2						\
404 	BPF_MOV64_IMM(BPF_REG_0, 0),					\
405 	BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,			\
406 		    offsetof(struct __sk_buff, data)),			\
407 	BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,			\
408 		    offsetof(struct __sk_buff, data_end)),		\
409 	BPF_MOV64_REG(BPF_REG_4, BPF_REG_2),				\
410 	BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 8),				\
411 	BPF_JMP_REG(BPF_JLE, BPF_REG_4, BPF_REG_3, 1),			\
412 	BPF_EXIT_INSN()
413 
414 /* BPF_RAND_UEXT_R7 contains 4 instructions, it initializes R7 into a random
415  * positive u32, and zero-extend it into 64-bit.
416  */
417 #define BPF_RAND_UEXT_R7						\
418 	BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,			\
419 		     BPF_FUNC_get_prandom_u32),				\
420 	BPF_MOV64_REG(BPF_REG_7, BPF_REG_0),				\
421 	BPF_ALU64_IMM(BPF_LSH, BPF_REG_7, 33),				\
422 	BPF_ALU64_IMM(BPF_RSH, BPF_REG_7, 33)
423 
424 /* BPF_RAND_SEXT_R7 contains 5 instructions, it initializes R7 into a random
425  * negative u32, and sign-extend it into 64-bit.
426  */
427 #define BPF_RAND_SEXT_R7						\
428 	BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,			\
429 		     BPF_FUNC_get_prandom_u32),				\
430 	BPF_MOV64_REG(BPF_REG_7, BPF_REG_0),				\
431 	BPF_ALU64_IMM(BPF_OR, BPF_REG_7, 0x80000000),			\
432 	BPF_ALU64_IMM(BPF_LSH, BPF_REG_7, 32),				\
433 	BPF_ALU64_IMM(BPF_ARSH, BPF_REG_7, 32)
434 
435 static struct bpf_test tests[] = {
436 #define FILL_ARRAY
437 #include <verifier/tests.h>
438 #undef FILL_ARRAY
439 };
440 
441 static int probe_filter_length(const struct bpf_insn *fp)
442 {
443 	int len;
444 
445 	for (len = MAX_INSNS - 1; len > 0; --len)
446 		if (fp[len].code != 0 || fp[len].imm != 0)
447 			break;
448 	return len + 1;
449 }
450 
451 static bool skip_unsupported_map(enum bpf_map_type map_type)
452 {
453 	if (!bpf_probe_map_type(map_type, 0)) {
454 		printf("SKIP (unsupported map type %d)\n", map_type);
455 		skips++;
456 		return true;
457 	}
458 	return false;
459 }
460 
461 static int __create_map(uint32_t type, uint32_t size_key,
462 			uint32_t size_value, uint32_t max_elem,
463 			uint32_t extra_flags)
464 {
465 	int fd;
466 
467 	fd = bpf_create_map(type, size_key, size_value, max_elem,
468 			    (type == BPF_MAP_TYPE_HASH ?
469 			     BPF_F_NO_PREALLOC : 0) | extra_flags);
470 	if (fd < 0) {
471 		if (skip_unsupported_map(type))
472 			return -1;
473 		printf("Failed to create hash map '%s'!\n", strerror(errno));
474 	}
475 
476 	return fd;
477 }
478 
479 static int create_map(uint32_t type, uint32_t size_key,
480 		      uint32_t size_value, uint32_t max_elem)
481 {
482 	return __create_map(type, size_key, size_value, max_elem, 0);
483 }
484 
485 static void update_map(int fd, int index)
486 {
487 	struct test_val value = {
488 		.index = (6 + 1) * sizeof(int),
489 		.foo[6] = 0xabcdef12,
490 	};
491 
492 	assert(!bpf_map_update_elem(fd, &index, &value, 0));
493 }
494 
495 static int create_prog_dummy_simple(enum bpf_prog_type prog_type, int ret)
496 {
497 	struct bpf_insn prog[] = {
498 		BPF_MOV64_IMM(BPF_REG_0, ret),
499 		BPF_EXIT_INSN(),
500 	};
501 
502 	return bpf_load_program(prog_type, prog,
503 				ARRAY_SIZE(prog), "GPL", 0, NULL, 0);
504 }
505 
506 static int create_prog_dummy_loop(enum bpf_prog_type prog_type, int mfd,
507 				  int idx, int ret)
508 {
509 	struct bpf_insn prog[] = {
510 		BPF_MOV64_IMM(BPF_REG_3, idx),
511 		BPF_LD_MAP_FD(BPF_REG_2, mfd),
512 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
513 			     BPF_FUNC_tail_call),
514 		BPF_MOV64_IMM(BPF_REG_0, ret),
515 		BPF_EXIT_INSN(),
516 	};
517 
518 	return bpf_load_program(prog_type, prog,
519 				ARRAY_SIZE(prog), "GPL", 0, NULL, 0);
520 }
521 
522 static int create_prog_array(enum bpf_prog_type prog_type, uint32_t max_elem,
523 			     int p1key, int p2key, int p3key)
524 {
525 	int mfd, p1fd, p2fd, p3fd;
526 
527 	mfd = bpf_create_map(BPF_MAP_TYPE_PROG_ARRAY, sizeof(int),
528 			     sizeof(int), max_elem, 0);
529 	if (mfd < 0) {
530 		if (skip_unsupported_map(BPF_MAP_TYPE_PROG_ARRAY))
531 			return -1;
532 		printf("Failed to create prog array '%s'!\n", strerror(errno));
533 		return -1;
534 	}
535 
536 	p1fd = create_prog_dummy_simple(prog_type, 42);
537 	p2fd = create_prog_dummy_loop(prog_type, mfd, p2key, 41);
538 	p3fd = create_prog_dummy_simple(prog_type, 24);
539 	if (p1fd < 0 || p2fd < 0 || p3fd < 0)
540 		goto err;
541 	if (bpf_map_update_elem(mfd, &p1key, &p1fd, BPF_ANY) < 0)
542 		goto err;
543 	if (bpf_map_update_elem(mfd, &p2key, &p2fd, BPF_ANY) < 0)
544 		goto err;
545 	if (bpf_map_update_elem(mfd, &p3key, &p3fd, BPF_ANY) < 0) {
546 err:
547 		close(mfd);
548 		mfd = -1;
549 	}
550 	close(p3fd);
551 	close(p2fd);
552 	close(p1fd);
553 	return mfd;
554 }
555 
556 static int create_map_in_map(void)
557 {
558 	int inner_map_fd, outer_map_fd;
559 
560 	inner_map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
561 				      sizeof(int), 1, 0);
562 	if (inner_map_fd < 0) {
563 		if (skip_unsupported_map(BPF_MAP_TYPE_ARRAY))
564 			return -1;
565 		printf("Failed to create array '%s'!\n", strerror(errno));
566 		return inner_map_fd;
567 	}
568 
569 	outer_map_fd = bpf_create_map_in_map(BPF_MAP_TYPE_ARRAY_OF_MAPS, NULL,
570 					     sizeof(int), inner_map_fd, 1, 0);
571 	if (outer_map_fd < 0) {
572 		if (skip_unsupported_map(BPF_MAP_TYPE_ARRAY_OF_MAPS))
573 			return -1;
574 		printf("Failed to create array of maps '%s'!\n",
575 		       strerror(errno));
576 	}
577 
578 	close(inner_map_fd);
579 
580 	return outer_map_fd;
581 }
582 
583 static int create_cgroup_storage(bool percpu)
584 {
585 	enum bpf_map_type type = percpu ? BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE :
586 		BPF_MAP_TYPE_CGROUP_STORAGE;
587 	int fd;
588 
589 	fd = bpf_create_map(type, sizeof(struct bpf_cgroup_storage_key),
590 			    TEST_DATA_LEN, 0, 0);
591 	if (fd < 0) {
592 		if (skip_unsupported_map(type))
593 			return -1;
594 		printf("Failed to create cgroup storage '%s'!\n",
595 		       strerror(errno));
596 	}
597 
598 	return fd;
599 }
600 
601 /* struct bpf_spin_lock {
602  *   int val;
603  * };
604  * struct val {
605  *   int cnt;
606  *   struct bpf_spin_lock l;
607  * };
608  * struct bpf_timer {
609  *   __u64 :64;
610  *   __u64 :64;
611  * } __attribute__((aligned(8)));
612  * struct timer {
613  *   struct bpf_timer t;
614  * };
615  */
616 static const char btf_str_sec[] = "\0bpf_spin_lock\0val\0cnt\0l\0bpf_timer\0timer\0t";
617 static __u32 btf_raw_types[] = {
618 	/* int */
619 	BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
620 	/* struct bpf_spin_lock */                      /* [2] */
621 	BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 1), 4),
622 	BTF_MEMBER_ENC(15, 1, 0), /* int val; */
623 	/* struct val */                                /* [3] */
624 	BTF_TYPE_ENC(15, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 2), 8),
625 	BTF_MEMBER_ENC(19, 1, 0), /* int cnt; */
626 	BTF_MEMBER_ENC(23, 2, 32),/* struct bpf_spin_lock l; */
627 	/* struct bpf_timer */                          /* [4] */
628 	BTF_TYPE_ENC(25, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0), 16),
629 	/* struct timer */                              /* [5] */
630 	BTF_TYPE_ENC(35, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 1), 16),
631 	BTF_MEMBER_ENC(41, 4, 0), /* struct bpf_timer t; */
632 };
633 
634 static int load_btf(void)
635 {
636 	struct btf_header hdr = {
637 		.magic = BTF_MAGIC,
638 		.version = BTF_VERSION,
639 		.hdr_len = sizeof(struct btf_header),
640 		.type_len = sizeof(btf_raw_types),
641 		.str_off = sizeof(btf_raw_types),
642 		.str_len = sizeof(btf_str_sec),
643 	};
644 	void *ptr, *raw_btf;
645 	int btf_fd;
646 
647 	ptr = raw_btf = malloc(sizeof(hdr) + sizeof(btf_raw_types) +
648 			       sizeof(btf_str_sec));
649 
650 	memcpy(ptr, &hdr, sizeof(hdr));
651 	ptr += sizeof(hdr);
652 	memcpy(ptr, btf_raw_types, hdr.type_len);
653 	ptr += hdr.type_len;
654 	memcpy(ptr, btf_str_sec, hdr.str_len);
655 	ptr += hdr.str_len;
656 
657 	btf_fd = bpf_load_btf(raw_btf, ptr - raw_btf, 0, 0, 0);
658 	free(raw_btf);
659 	if (btf_fd < 0)
660 		return -1;
661 	return btf_fd;
662 }
663 
664 static int create_map_spin_lock(void)
665 {
666 	struct bpf_create_map_attr attr = {
667 		.name = "test_map",
668 		.map_type = BPF_MAP_TYPE_ARRAY,
669 		.key_size = 4,
670 		.value_size = 8,
671 		.max_entries = 1,
672 		.btf_key_type_id = 1,
673 		.btf_value_type_id = 3,
674 	};
675 	int fd, btf_fd;
676 
677 	btf_fd = load_btf();
678 	if (btf_fd < 0)
679 		return -1;
680 	attr.btf_fd = btf_fd;
681 	fd = bpf_create_map_xattr(&attr);
682 	if (fd < 0)
683 		printf("Failed to create map with spin_lock\n");
684 	return fd;
685 }
686 
687 static int create_sk_storage_map(void)
688 {
689 	struct bpf_create_map_attr attr = {
690 		.name = "test_map",
691 		.map_type = BPF_MAP_TYPE_SK_STORAGE,
692 		.key_size = 4,
693 		.value_size = 8,
694 		.max_entries = 0,
695 		.map_flags = BPF_F_NO_PREALLOC,
696 		.btf_key_type_id = 1,
697 		.btf_value_type_id = 3,
698 	};
699 	int fd, btf_fd;
700 
701 	btf_fd = load_btf();
702 	if (btf_fd < 0)
703 		return -1;
704 	attr.btf_fd = btf_fd;
705 	fd = bpf_create_map_xattr(&attr);
706 	close(attr.btf_fd);
707 	if (fd < 0)
708 		printf("Failed to create sk_storage_map\n");
709 	return fd;
710 }
711 
712 static int create_map_timer(void)
713 {
714 	struct bpf_create_map_attr attr = {
715 		.name = "test_map",
716 		.map_type = BPF_MAP_TYPE_ARRAY,
717 		.key_size = 4,
718 		.value_size = 16,
719 		.max_entries = 1,
720 		.btf_key_type_id = 1,
721 		.btf_value_type_id = 5,
722 	};
723 	int fd, btf_fd;
724 
725 	btf_fd = load_btf();
726 	if (btf_fd < 0)
727 		return -1;
728 	attr.btf_fd = btf_fd;
729 	fd = bpf_create_map_xattr(&attr);
730 	if (fd < 0)
731 		printf("Failed to create map with timer\n");
732 	return fd;
733 }
734 
735 static char bpf_vlog[UINT_MAX >> 8];
736 
737 static void do_test_fixup(struct bpf_test *test, enum bpf_prog_type prog_type,
738 			  struct bpf_insn *prog, int *map_fds)
739 {
740 	int *fixup_map_hash_8b = test->fixup_map_hash_8b;
741 	int *fixup_map_hash_48b = test->fixup_map_hash_48b;
742 	int *fixup_map_hash_16b = test->fixup_map_hash_16b;
743 	int *fixup_map_array_48b = test->fixup_map_array_48b;
744 	int *fixup_map_sockmap = test->fixup_map_sockmap;
745 	int *fixup_map_sockhash = test->fixup_map_sockhash;
746 	int *fixup_map_xskmap = test->fixup_map_xskmap;
747 	int *fixup_map_stacktrace = test->fixup_map_stacktrace;
748 	int *fixup_prog1 = test->fixup_prog1;
749 	int *fixup_prog2 = test->fixup_prog2;
750 	int *fixup_map_in_map = test->fixup_map_in_map;
751 	int *fixup_cgroup_storage = test->fixup_cgroup_storage;
752 	int *fixup_percpu_cgroup_storage = test->fixup_percpu_cgroup_storage;
753 	int *fixup_map_spin_lock = test->fixup_map_spin_lock;
754 	int *fixup_map_array_ro = test->fixup_map_array_ro;
755 	int *fixup_map_array_wo = test->fixup_map_array_wo;
756 	int *fixup_map_array_small = test->fixup_map_array_small;
757 	int *fixup_sk_storage_map = test->fixup_sk_storage_map;
758 	int *fixup_map_event_output = test->fixup_map_event_output;
759 	int *fixup_map_reuseport_array = test->fixup_map_reuseport_array;
760 	int *fixup_map_ringbuf = test->fixup_map_ringbuf;
761 	int *fixup_map_timer = test->fixup_map_timer;
762 
763 	if (test->fill_helper) {
764 		test->fill_insns = calloc(MAX_TEST_INSNS, sizeof(struct bpf_insn));
765 		test->fill_helper(test);
766 	}
767 
768 	/* Allocating HTs with 1 elem is fine here, since we only test
769 	 * for verifier and not do a runtime lookup, so the only thing
770 	 * that really matters is value size in this case.
771 	 */
772 	if (*fixup_map_hash_8b) {
773 		map_fds[0] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
774 					sizeof(long long), 1);
775 		do {
776 			prog[*fixup_map_hash_8b].imm = map_fds[0];
777 			fixup_map_hash_8b++;
778 		} while (*fixup_map_hash_8b);
779 	}
780 
781 	if (*fixup_map_hash_48b) {
782 		map_fds[1] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
783 					sizeof(struct test_val), 1);
784 		do {
785 			prog[*fixup_map_hash_48b].imm = map_fds[1];
786 			fixup_map_hash_48b++;
787 		} while (*fixup_map_hash_48b);
788 	}
789 
790 	if (*fixup_map_hash_16b) {
791 		map_fds[2] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
792 					sizeof(struct other_val), 1);
793 		do {
794 			prog[*fixup_map_hash_16b].imm = map_fds[2];
795 			fixup_map_hash_16b++;
796 		} while (*fixup_map_hash_16b);
797 	}
798 
799 	if (*fixup_map_array_48b) {
800 		map_fds[3] = create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
801 					sizeof(struct test_val), 1);
802 		update_map(map_fds[3], 0);
803 		do {
804 			prog[*fixup_map_array_48b].imm = map_fds[3];
805 			fixup_map_array_48b++;
806 		} while (*fixup_map_array_48b);
807 	}
808 
809 	if (*fixup_prog1) {
810 		map_fds[4] = create_prog_array(prog_type, 4, 0, 1, 2);
811 		do {
812 			prog[*fixup_prog1].imm = map_fds[4];
813 			fixup_prog1++;
814 		} while (*fixup_prog1);
815 	}
816 
817 	if (*fixup_prog2) {
818 		map_fds[5] = create_prog_array(prog_type, 8, 7, 1, 2);
819 		do {
820 			prog[*fixup_prog2].imm = map_fds[5];
821 			fixup_prog2++;
822 		} while (*fixup_prog2);
823 	}
824 
825 	if (*fixup_map_in_map) {
826 		map_fds[6] = create_map_in_map();
827 		do {
828 			prog[*fixup_map_in_map].imm = map_fds[6];
829 			fixup_map_in_map++;
830 		} while (*fixup_map_in_map);
831 	}
832 
833 	if (*fixup_cgroup_storage) {
834 		map_fds[7] = create_cgroup_storage(false);
835 		do {
836 			prog[*fixup_cgroup_storage].imm = map_fds[7];
837 			fixup_cgroup_storage++;
838 		} while (*fixup_cgroup_storage);
839 	}
840 
841 	if (*fixup_percpu_cgroup_storage) {
842 		map_fds[8] = create_cgroup_storage(true);
843 		do {
844 			prog[*fixup_percpu_cgroup_storage].imm = map_fds[8];
845 			fixup_percpu_cgroup_storage++;
846 		} while (*fixup_percpu_cgroup_storage);
847 	}
848 	if (*fixup_map_sockmap) {
849 		map_fds[9] = create_map(BPF_MAP_TYPE_SOCKMAP, sizeof(int),
850 					sizeof(int), 1);
851 		do {
852 			prog[*fixup_map_sockmap].imm = map_fds[9];
853 			fixup_map_sockmap++;
854 		} while (*fixup_map_sockmap);
855 	}
856 	if (*fixup_map_sockhash) {
857 		map_fds[10] = create_map(BPF_MAP_TYPE_SOCKHASH, sizeof(int),
858 					sizeof(int), 1);
859 		do {
860 			prog[*fixup_map_sockhash].imm = map_fds[10];
861 			fixup_map_sockhash++;
862 		} while (*fixup_map_sockhash);
863 	}
864 	if (*fixup_map_xskmap) {
865 		map_fds[11] = create_map(BPF_MAP_TYPE_XSKMAP, sizeof(int),
866 					sizeof(int), 1);
867 		do {
868 			prog[*fixup_map_xskmap].imm = map_fds[11];
869 			fixup_map_xskmap++;
870 		} while (*fixup_map_xskmap);
871 	}
872 	if (*fixup_map_stacktrace) {
873 		map_fds[12] = create_map(BPF_MAP_TYPE_STACK_TRACE, sizeof(u32),
874 					 sizeof(u64), 1);
875 		do {
876 			prog[*fixup_map_stacktrace].imm = map_fds[12];
877 			fixup_map_stacktrace++;
878 		} while (*fixup_map_stacktrace);
879 	}
880 	if (*fixup_map_spin_lock) {
881 		map_fds[13] = create_map_spin_lock();
882 		do {
883 			prog[*fixup_map_spin_lock].imm = map_fds[13];
884 			fixup_map_spin_lock++;
885 		} while (*fixup_map_spin_lock);
886 	}
887 	if (*fixup_map_array_ro) {
888 		map_fds[14] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
889 					   sizeof(struct test_val), 1,
890 					   BPF_F_RDONLY_PROG);
891 		update_map(map_fds[14], 0);
892 		do {
893 			prog[*fixup_map_array_ro].imm = map_fds[14];
894 			fixup_map_array_ro++;
895 		} while (*fixup_map_array_ro);
896 	}
897 	if (*fixup_map_array_wo) {
898 		map_fds[15] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
899 					   sizeof(struct test_val), 1,
900 					   BPF_F_WRONLY_PROG);
901 		update_map(map_fds[15], 0);
902 		do {
903 			prog[*fixup_map_array_wo].imm = map_fds[15];
904 			fixup_map_array_wo++;
905 		} while (*fixup_map_array_wo);
906 	}
907 	if (*fixup_map_array_small) {
908 		map_fds[16] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
909 					   1, 1, 0);
910 		update_map(map_fds[16], 0);
911 		do {
912 			prog[*fixup_map_array_small].imm = map_fds[16];
913 			fixup_map_array_small++;
914 		} while (*fixup_map_array_small);
915 	}
916 	if (*fixup_sk_storage_map) {
917 		map_fds[17] = create_sk_storage_map();
918 		do {
919 			prog[*fixup_sk_storage_map].imm = map_fds[17];
920 			fixup_sk_storage_map++;
921 		} while (*fixup_sk_storage_map);
922 	}
923 	if (*fixup_map_event_output) {
924 		map_fds[18] = __create_map(BPF_MAP_TYPE_PERF_EVENT_ARRAY,
925 					   sizeof(int), sizeof(int), 1, 0);
926 		do {
927 			prog[*fixup_map_event_output].imm = map_fds[18];
928 			fixup_map_event_output++;
929 		} while (*fixup_map_event_output);
930 	}
931 	if (*fixup_map_reuseport_array) {
932 		map_fds[19] = __create_map(BPF_MAP_TYPE_REUSEPORT_SOCKARRAY,
933 					   sizeof(u32), sizeof(u64), 1, 0);
934 		do {
935 			prog[*fixup_map_reuseport_array].imm = map_fds[19];
936 			fixup_map_reuseport_array++;
937 		} while (*fixup_map_reuseport_array);
938 	}
939 	if (*fixup_map_ringbuf) {
940 		map_fds[20] = create_map(BPF_MAP_TYPE_RINGBUF, 0,
941 					   0, 4096);
942 		do {
943 			prog[*fixup_map_ringbuf].imm = map_fds[20];
944 			fixup_map_ringbuf++;
945 		} while (*fixup_map_ringbuf);
946 	}
947 	if (*fixup_map_timer) {
948 		map_fds[21] = create_map_timer();
949 		do {
950 			prog[*fixup_map_timer].imm = map_fds[21];
951 			fixup_map_timer++;
952 		} while (*fixup_map_timer);
953 	}
954 }
955 
956 struct libcap {
957 	struct __user_cap_header_struct hdr;
958 	struct __user_cap_data_struct data[2];
959 };
960 
961 static int set_admin(bool admin)
962 {
963 	cap_t caps;
964 	/* need CAP_BPF, CAP_NET_ADMIN, CAP_PERFMON to load progs */
965 	const cap_value_t cap_net_admin = CAP_NET_ADMIN;
966 	const cap_value_t cap_sys_admin = CAP_SYS_ADMIN;
967 	struct libcap *cap;
968 	int ret = -1;
969 
970 	caps = cap_get_proc();
971 	if (!caps) {
972 		perror("cap_get_proc");
973 		return -1;
974 	}
975 	cap = (struct libcap *)caps;
976 	if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap_sys_admin, CAP_CLEAR)) {
977 		perror("cap_set_flag clear admin");
978 		goto out;
979 	}
980 	if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap_net_admin,
981 				admin ? CAP_SET : CAP_CLEAR)) {
982 		perror("cap_set_flag set_or_clear net");
983 		goto out;
984 	}
985 	/* libcap is likely old and simply ignores CAP_BPF and CAP_PERFMON,
986 	 * so update effective bits manually
987 	 */
988 	if (admin) {
989 		cap->data[1].effective |= 1 << (38 /* CAP_PERFMON */ - 32);
990 		cap->data[1].effective |= 1 << (39 /* CAP_BPF */ - 32);
991 	} else {
992 		cap->data[1].effective &= ~(1 << (38 - 32));
993 		cap->data[1].effective &= ~(1 << (39 - 32));
994 	}
995 	if (cap_set_proc(caps)) {
996 		perror("cap_set_proc");
997 		goto out;
998 	}
999 	ret = 0;
1000 out:
1001 	if (cap_free(caps))
1002 		perror("cap_free");
1003 	return ret;
1004 }
1005 
1006 static int do_prog_test_run(int fd_prog, bool unpriv, uint32_t expected_val,
1007 			    void *data, size_t size_data)
1008 {
1009 	__u8 tmp[TEST_DATA_LEN << 2];
1010 	__u32 size_tmp = sizeof(tmp);
1011 	uint32_t retval;
1012 	int err, saved_errno;
1013 
1014 	if (unpriv)
1015 		set_admin(true);
1016 	err = bpf_prog_test_run(fd_prog, 1, data, size_data,
1017 				tmp, &size_tmp, &retval, NULL);
1018 	saved_errno = errno;
1019 
1020 	if (unpriv)
1021 		set_admin(false);
1022 
1023 	if (err) {
1024 		switch (saved_errno) {
1025 		case ENOTSUPP:
1026 			printf("Did not run the program (not supported) ");
1027 			return 0;
1028 		case EPERM:
1029 			if (unpriv) {
1030 				printf("Did not run the program (no permission) ");
1031 				return 0;
1032 			}
1033 			/* fallthrough; */
1034 		default:
1035 			printf("FAIL: Unexpected bpf_prog_test_run error (%s) ",
1036 				strerror(saved_errno));
1037 			return err;
1038 		}
1039 	}
1040 
1041 	if (retval != expected_val &&
1042 	    expected_val != POINTER_VALUE) {
1043 		printf("FAIL retval %d != %d ", retval, expected_val);
1044 		return 1;
1045 	}
1046 
1047 	return 0;
1048 }
1049 
1050 /* Returns true if every part of exp (tab-separated) appears in log, in order.
1051  *
1052  * If exp is an empty string, returns true.
1053  */
1054 static bool cmp_str_seq(const char *log, const char *exp)
1055 {
1056 	char needle[200];
1057 	const char *p, *q;
1058 	int len;
1059 
1060 	do {
1061 		if (!strlen(exp))
1062 			break;
1063 		p = strchr(exp, '\t');
1064 		if (!p)
1065 			p = exp + strlen(exp);
1066 
1067 		len = p - exp;
1068 		if (len >= sizeof(needle) || !len) {
1069 			printf("FAIL\nTestcase bug\n");
1070 			return false;
1071 		}
1072 		strncpy(needle, exp, len);
1073 		needle[len] = 0;
1074 		q = strstr(log, needle);
1075 		if (!q) {
1076 			printf("FAIL\nUnexpected verifier log!\n"
1077 			       "EXP: %s\nRES:\n", needle);
1078 			return false;
1079 		}
1080 		log = q + len;
1081 		exp = p + 1;
1082 	} while (*p);
1083 	return true;
1084 }
1085 
1086 static void do_test_single(struct bpf_test *test, bool unpriv,
1087 			   int *passes, int *errors)
1088 {
1089 	int fd_prog, expected_ret, alignment_prevented_execution;
1090 	int prog_len, prog_type = test->prog_type;
1091 	struct bpf_insn *prog = test->insns;
1092 	struct bpf_load_program_attr attr;
1093 	int run_errs, run_successes;
1094 	int map_fds[MAX_NR_MAPS];
1095 	const char *expected_err;
1096 	int saved_errno;
1097 	int fixup_skips;
1098 	__u32 pflags;
1099 	int i, err;
1100 
1101 	for (i = 0; i < MAX_NR_MAPS; i++)
1102 		map_fds[i] = -1;
1103 
1104 	if (!prog_type)
1105 		prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
1106 	fixup_skips = skips;
1107 	do_test_fixup(test, prog_type, prog, map_fds);
1108 	if (test->fill_insns) {
1109 		prog = test->fill_insns;
1110 		prog_len = test->prog_len;
1111 	} else {
1112 		prog_len = probe_filter_length(prog);
1113 	}
1114 	/* If there were some map skips during fixup due to missing bpf
1115 	 * features, skip this test.
1116 	 */
1117 	if (fixup_skips != skips)
1118 		return;
1119 
1120 	pflags = BPF_F_TEST_RND_HI32;
1121 	if (test->flags & F_LOAD_WITH_STRICT_ALIGNMENT)
1122 		pflags |= BPF_F_STRICT_ALIGNMENT;
1123 	if (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS)
1124 		pflags |= BPF_F_ANY_ALIGNMENT;
1125 	if (test->flags & ~3)
1126 		pflags |= test->flags;
1127 
1128 	expected_ret = unpriv && test->result_unpriv != UNDEF ?
1129 		       test->result_unpriv : test->result;
1130 	expected_err = unpriv && test->errstr_unpriv ?
1131 		       test->errstr_unpriv : test->errstr;
1132 	memset(&attr, 0, sizeof(attr));
1133 	attr.prog_type = prog_type;
1134 	attr.expected_attach_type = test->expected_attach_type;
1135 	attr.insns = prog;
1136 	attr.insns_cnt = prog_len;
1137 	attr.license = "GPL";
1138 	if (verbose)
1139 		attr.log_level = 1;
1140 	else if (expected_ret == VERBOSE_ACCEPT)
1141 		attr.log_level = 2;
1142 	else
1143 		attr.log_level = 4;
1144 	attr.prog_flags = pflags;
1145 
1146 	if (prog_type == BPF_PROG_TYPE_TRACING && test->kfunc) {
1147 		attr.attach_btf_id = libbpf_find_vmlinux_btf_id(test->kfunc,
1148 						attr.expected_attach_type);
1149 		if (attr.attach_btf_id < 0) {
1150 			printf("FAIL\nFailed to find BTF ID for '%s'!\n",
1151 				test->kfunc);
1152 			(*errors)++;
1153 			return;
1154 		}
1155 	}
1156 
1157 	fd_prog = bpf_load_program_xattr(&attr, bpf_vlog, sizeof(bpf_vlog));
1158 	saved_errno = errno;
1159 
1160 	/* BPF_PROG_TYPE_TRACING requires more setup and
1161 	 * bpf_probe_prog_type won't give correct answer
1162 	 */
1163 	if (fd_prog < 0 && prog_type != BPF_PROG_TYPE_TRACING &&
1164 	    !bpf_probe_prog_type(prog_type, 0)) {
1165 		printf("SKIP (unsupported program type %d)\n", prog_type);
1166 		skips++;
1167 		goto close_fds;
1168 	}
1169 
1170 	if (fd_prog < 0 && saved_errno == ENOTSUPP) {
1171 		printf("SKIP (program uses an unsupported feature)\n");
1172 		skips++;
1173 		goto close_fds;
1174 	}
1175 
1176 	alignment_prevented_execution = 0;
1177 
1178 	if (expected_ret == ACCEPT || expected_ret == VERBOSE_ACCEPT) {
1179 		if (fd_prog < 0) {
1180 			printf("FAIL\nFailed to load prog '%s'!\n",
1181 			       strerror(saved_errno));
1182 			goto fail_log;
1183 		}
1184 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
1185 		if (fd_prog >= 0 &&
1186 		    (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS))
1187 			alignment_prevented_execution = 1;
1188 #endif
1189 		if (expected_ret == VERBOSE_ACCEPT && !cmp_str_seq(bpf_vlog, expected_err)) {
1190 			goto fail_log;
1191 		}
1192 	} else {
1193 		if (fd_prog >= 0) {
1194 			printf("FAIL\nUnexpected success to load!\n");
1195 			goto fail_log;
1196 		}
1197 		if (!expected_err || !cmp_str_seq(bpf_vlog, expected_err)) {
1198 			printf("FAIL\nUnexpected error message!\n\tEXP: %s\n\tRES: %s\n",
1199 			      expected_err, bpf_vlog);
1200 			goto fail_log;
1201 		}
1202 	}
1203 
1204 	if (!unpriv && test->insn_processed) {
1205 		uint32_t insn_processed;
1206 		char *proc;
1207 
1208 		proc = strstr(bpf_vlog, "processed ");
1209 		insn_processed = atoi(proc + 10);
1210 		if (test->insn_processed != insn_processed) {
1211 			printf("FAIL\nUnexpected insn_processed %u vs %u\n",
1212 			       insn_processed, test->insn_processed);
1213 			goto fail_log;
1214 		}
1215 	}
1216 
1217 	if (verbose)
1218 		printf(", verifier log:\n%s", bpf_vlog);
1219 
1220 	run_errs = 0;
1221 	run_successes = 0;
1222 	if (!alignment_prevented_execution && fd_prog >= 0 && test->runs >= 0) {
1223 		uint32_t expected_val;
1224 		int i;
1225 
1226 		if (!test->runs)
1227 			test->runs = 1;
1228 
1229 		for (i = 0; i < test->runs; i++) {
1230 			if (unpriv && test->retvals[i].retval_unpriv)
1231 				expected_val = test->retvals[i].retval_unpriv;
1232 			else
1233 				expected_val = test->retvals[i].retval;
1234 
1235 			err = do_prog_test_run(fd_prog, unpriv, expected_val,
1236 					       test->retvals[i].data,
1237 					       sizeof(test->retvals[i].data));
1238 			if (err) {
1239 				printf("(run %d/%d) ", i + 1, test->runs);
1240 				run_errs++;
1241 			} else {
1242 				run_successes++;
1243 			}
1244 		}
1245 	}
1246 
1247 	if (!run_errs) {
1248 		(*passes)++;
1249 		if (run_successes > 1)
1250 			printf("%d cases ", run_successes);
1251 		printf("OK");
1252 		if (alignment_prevented_execution)
1253 			printf(" (NOTE: not executed due to unknown alignment)");
1254 		printf("\n");
1255 	} else {
1256 		printf("\n");
1257 		goto fail_log;
1258 	}
1259 close_fds:
1260 	if (test->fill_insns)
1261 		free(test->fill_insns);
1262 	close(fd_prog);
1263 	for (i = 0; i < MAX_NR_MAPS; i++)
1264 		close(map_fds[i]);
1265 	sched_yield();
1266 	return;
1267 fail_log:
1268 	(*errors)++;
1269 	printf("%s", bpf_vlog);
1270 	goto close_fds;
1271 }
1272 
1273 static bool is_admin(void)
1274 {
1275 	cap_flag_value_t net_priv = CAP_CLEAR;
1276 	bool perfmon_priv = false;
1277 	bool bpf_priv = false;
1278 	struct libcap *cap;
1279 	cap_t caps;
1280 
1281 #ifdef CAP_IS_SUPPORTED
1282 	if (!CAP_IS_SUPPORTED(CAP_SETFCAP)) {
1283 		perror("cap_get_flag");
1284 		return false;
1285 	}
1286 #endif
1287 	caps = cap_get_proc();
1288 	if (!caps) {
1289 		perror("cap_get_proc");
1290 		return false;
1291 	}
1292 	cap = (struct libcap *)caps;
1293 	bpf_priv = cap->data[1].effective & (1 << (39/* CAP_BPF */ - 32));
1294 	perfmon_priv = cap->data[1].effective & (1 << (38/* CAP_PERFMON */ - 32));
1295 	if (cap_get_flag(caps, CAP_NET_ADMIN, CAP_EFFECTIVE, &net_priv))
1296 		perror("cap_get_flag NET");
1297 	if (cap_free(caps))
1298 		perror("cap_free");
1299 	return bpf_priv && perfmon_priv && net_priv == CAP_SET;
1300 }
1301 
1302 static void get_unpriv_disabled()
1303 {
1304 	char buf[2];
1305 	FILE *fd;
1306 
1307 	fd = fopen("/proc/sys/"UNPRIV_SYSCTL, "r");
1308 	if (!fd) {
1309 		perror("fopen /proc/sys/"UNPRIV_SYSCTL);
1310 		unpriv_disabled = true;
1311 		return;
1312 	}
1313 	if (fgets(buf, 2, fd) == buf && atoi(buf))
1314 		unpriv_disabled = true;
1315 	fclose(fd);
1316 }
1317 
1318 static bool test_as_unpriv(struct bpf_test *test)
1319 {
1320 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
1321 	/* Some architectures have strict alignment requirements. In
1322 	 * that case, the BPF verifier detects if a program has
1323 	 * unaligned accesses and rejects them. A user can pass
1324 	 * BPF_F_ANY_ALIGNMENT to a program to override this
1325 	 * check. That, however, will only work when a privileged user
1326 	 * loads a program. An unprivileged user loading a program
1327 	 * with this flag will be rejected prior entering the
1328 	 * verifier.
1329 	 */
1330 	if (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS)
1331 		return false;
1332 #endif
1333 	return !test->prog_type ||
1334 	       test->prog_type == BPF_PROG_TYPE_SOCKET_FILTER ||
1335 	       test->prog_type == BPF_PROG_TYPE_CGROUP_SKB;
1336 }
1337 
1338 static int do_test(bool unpriv, unsigned int from, unsigned int to)
1339 {
1340 	int i, passes = 0, errors = 0;
1341 
1342 	for (i = from; i < to; i++) {
1343 		struct bpf_test *test = &tests[i];
1344 
1345 		/* Program types that are not supported by non-root we
1346 		 * skip right away.
1347 		 */
1348 		if (test_as_unpriv(test) && unpriv_disabled) {
1349 			printf("#%d/u %s SKIP\n", i, test->descr);
1350 			skips++;
1351 		} else if (test_as_unpriv(test)) {
1352 			if (!unpriv)
1353 				set_admin(false);
1354 			printf("#%d/u %s ", i, test->descr);
1355 			do_test_single(test, true, &passes, &errors);
1356 			if (!unpriv)
1357 				set_admin(true);
1358 		}
1359 
1360 		if (unpriv) {
1361 			printf("#%d/p %s SKIP\n", i, test->descr);
1362 			skips++;
1363 		} else {
1364 			printf("#%d/p %s ", i, test->descr);
1365 			do_test_single(test, false, &passes, &errors);
1366 		}
1367 	}
1368 
1369 	printf("Summary: %d PASSED, %d SKIPPED, %d FAILED\n", passes,
1370 	       skips, errors);
1371 	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
1372 }
1373 
1374 int main(int argc, char **argv)
1375 {
1376 	unsigned int from = 0, to = ARRAY_SIZE(tests);
1377 	bool unpriv = !is_admin();
1378 	int arg = 1;
1379 
1380 	if (argc > 1 && strcmp(argv[1], "-v") == 0) {
1381 		arg++;
1382 		verbose = true;
1383 		argc--;
1384 	}
1385 
1386 	if (argc == 3) {
1387 		unsigned int l = atoi(argv[arg]);
1388 		unsigned int u = atoi(argv[arg + 1]);
1389 
1390 		if (l < to && u < to) {
1391 			from = l;
1392 			to   = u + 1;
1393 		}
1394 	} else if (argc == 2) {
1395 		unsigned int t = atoi(argv[arg]);
1396 
1397 		if (t < to) {
1398 			from = t;
1399 			to   = t + 1;
1400 		}
1401 	}
1402 
1403 	get_unpriv_disabled();
1404 	if (unpriv && unpriv_disabled) {
1405 		printf("Cannot run as unprivileged user with sysctl %s.\n",
1406 		       UNPRIV_SYSCTL);
1407 		return EXIT_FAILURE;
1408 	}
1409 
1410 	bpf_semi_rand_init();
1411 	return do_test(unpriv, from, to);
1412 }
1413