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