xref: /linux/tools/testing/selftests/bpf/test_verifier.c (revision 1375dc4a4579d5e767dd8c2d2abcd929ff59d0a7)
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	19
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"
62 static bool unpriv_disabled = false;
63 static int skips;
64 
65 struct bpf_test {
66 	const char *descr;
67 	struct bpf_insn	insns[MAX_INSNS];
68 	struct bpf_insn	*fill_insns;
69 	int fixup_map_hash_8b[MAX_FIXUPS];
70 	int fixup_map_hash_48b[MAX_FIXUPS];
71 	int fixup_map_hash_16b[MAX_FIXUPS];
72 	int fixup_map_array_48b[MAX_FIXUPS];
73 	int fixup_map_sockmap[MAX_FIXUPS];
74 	int fixup_map_sockhash[MAX_FIXUPS];
75 	int fixup_map_xskmap[MAX_FIXUPS];
76 	int fixup_map_stacktrace[MAX_FIXUPS];
77 	int fixup_prog1[MAX_FIXUPS];
78 	int fixup_prog2[MAX_FIXUPS];
79 	int fixup_map_in_map[MAX_FIXUPS];
80 	int fixup_cgroup_storage[MAX_FIXUPS];
81 	int fixup_percpu_cgroup_storage[MAX_FIXUPS];
82 	int fixup_map_spin_lock[MAX_FIXUPS];
83 	int fixup_map_array_ro[MAX_FIXUPS];
84 	int fixup_map_array_wo[MAX_FIXUPS];
85 	int fixup_map_array_small[MAX_FIXUPS];
86 	int fixup_sk_storage_map[MAX_FIXUPS];
87 	int fixup_map_event_output[MAX_FIXUPS];
88 	const char *errstr;
89 	const char *errstr_unpriv;
90 	uint32_t insn_processed;
91 	int prog_len;
92 	enum {
93 		UNDEF,
94 		ACCEPT,
95 		REJECT
96 	} result, result_unpriv;
97 	enum bpf_prog_type prog_type;
98 	uint8_t flags;
99 	void (*fill_helper)(struct bpf_test *self);
100 	uint8_t runs;
101 #define bpf_testdata_struct_t					\
102 	struct {						\
103 		uint32_t retval, retval_unpriv;			\
104 		union {						\
105 			__u8 data[TEST_DATA_LEN];		\
106 			__u64 data64[TEST_DATA_LEN / 8];	\
107 		};						\
108 	}
109 	union {
110 		bpf_testdata_struct_t;
111 		bpf_testdata_struct_t retvals[MAX_TEST_RUNS];
112 	};
113 	enum bpf_attach_type expected_attach_type;
114 };
115 
116 /* Note we want this to be 64 bit aligned so that the end of our array is
117  * actually the end of the structure.
118  */
119 #define MAX_ENTRIES 11
120 
121 struct test_val {
122 	unsigned int index;
123 	int foo[MAX_ENTRIES];
124 };
125 
126 struct other_val {
127 	long long foo;
128 	long long bar;
129 };
130 
131 static void bpf_fill_ld_abs_vlan_push_pop(struct bpf_test *self)
132 {
133 	/* test: {skb->data[0], vlan_push} x 51 + {skb->data[0], vlan_pop} x 51 */
134 #define PUSH_CNT 51
135 	/* jump range is limited to 16 bit. PUSH_CNT of ld_abs needs room */
136 	unsigned int len = (1 << 15) - PUSH_CNT * 2 * 5 * 6;
137 	struct bpf_insn *insn = self->fill_insns;
138 	int i = 0, j, k = 0;
139 
140 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
141 loop:
142 	for (j = 0; j < PUSH_CNT; j++) {
143 		insn[i++] = BPF_LD_ABS(BPF_B, 0);
144 		/* jump to error label */
145 		insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
146 		i++;
147 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
148 		insn[i++] = BPF_MOV64_IMM(BPF_REG_2, 1);
149 		insn[i++] = BPF_MOV64_IMM(BPF_REG_3, 2);
150 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
151 					 BPF_FUNC_skb_vlan_push),
152 		insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
153 		i++;
154 	}
155 
156 	for (j = 0; j < PUSH_CNT; j++) {
157 		insn[i++] = BPF_LD_ABS(BPF_B, 0);
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_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
162 					 BPF_FUNC_skb_vlan_pop),
163 		insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
164 		i++;
165 	}
166 	if (++k < 5)
167 		goto loop;
168 
169 	for (; i < len - 3; i++)
170 		insn[i] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0xbef);
171 	insn[len - 3] = BPF_JMP_A(1);
172 	/* error label */
173 	insn[len - 2] = BPF_MOV32_IMM(BPF_REG_0, 0);
174 	insn[len - 1] = BPF_EXIT_INSN();
175 	self->prog_len = len;
176 }
177 
178 static void bpf_fill_jump_around_ld_abs(struct bpf_test *self)
179 {
180 	struct bpf_insn *insn = self->fill_insns;
181 	/* jump range is limited to 16 bit. every ld_abs is replaced by 6 insns,
182 	 * but on arches like arm, ppc etc, there will be one BPF_ZEXT inserted
183 	 * to extend the error value of the inlined ld_abs sequence which then
184 	 * contains 7 insns. so, set the dividend to 7 so the testcase could
185 	 * work on all arches.
186 	 */
187 	unsigned int len = (1 << 15) / 7;
188 	int i = 0;
189 
190 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
191 	insn[i++] = BPF_LD_ABS(BPF_B, 0);
192 	insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 10, len - i - 2);
193 	i++;
194 	while (i < len - 1)
195 		insn[i++] = BPF_LD_ABS(BPF_B, 1);
196 	insn[i] = BPF_EXIT_INSN();
197 	self->prog_len = i + 1;
198 }
199 
200 static void bpf_fill_rand_ld_dw(struct bpf_test *self)
201 {
202 	struct bpf_insn *insn = self->fill_insns;
203 	uint64_t res = 0;
204 	int i = 0;
205 
206 	insn[i++] = BPF_MOV32_IMM(BPF_REG_0, 0);
207 	while (i < self->retval) {
208 		uint64_t val = bpf_semi_rand_get();
209 		struct bpf_insn tmp[2] = { BPF_LD_IMM64(BPF_REG_1, val) };
210 
211 		res ^= val;
212 		insn[i++] = tmp[0];
213 		insn[i++] = tmp[1];
214 		insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
215 	}
216 	insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_0);
217 	insn[i++] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 32);
218 	insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
219 	insn[i] = BPF_EXIT_INSN();
220 	self->prog_len = i + 1;
221 	res ^= (res >> 32);
222 	self->retval = (uint32_t)res;
223 }
224 
225 #define MAX_JMP_SEQ 8192
226 
227 /* test the sequence of 8k jumps */
228 static void bpf_fill_scale1(struct bpf_test *self)
229 {
230 	struct bpf_insn *insn = self->fill_insns;
231 	int i = 0, k = 0;
232 
233 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
234 	/* test to check that the long sequence of jumps is acceptable */
235 	while (k++ < MAX_JMP_SEQ) {
236 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
237 					 BPF_FUNC_get_prandom_u32);
238 		insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
239 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
240 		insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
241 					-8 * (k % 64 + 1));
242 	}
243 	/* is_state_visited() doesn't allocate state for pruning for every jump.
244 	 * Hence multiply jmps by 4 to accommodate that heuristic
245 	 */
246 	while (i < MAX_TEST_INSNS - MAX_JMP_SEQ * 4)
247 		insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
248 	insn[i] = BPF_EXIT_INSN();
249 	self->prog_len = i + 1;
250 	self->retval = 42;
251 }
252 
253 /* test the sequence of 8k jumps in inner most function (function depth 8)*/
254 static void bpf_fill_scale2(struct bpf_test *self)
255 {
256 	struct bpf_insn *insn = self->fill_insns;
257 	int i = 0, k = 0;
258 
259 #define FUNC_NEST 7
260 	for (k = 0; k < FUNC_NEST; k++) {
261 		insn[i++] = BPF_CALL_REL(1);
262 		insn[i++] = BPF_EXIT_INSN();
263 	}
264 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
265 	/* test to check that the long sequence of jumps is acceptable */
266 	k = 0;
267 	while (k++ < MAX_JMP_SEQ) {
268 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
269 					 BPF_FUNC_get_prandom_u32);
270 		insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
271 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
272 		insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
273 					-8 * (k % (64 - 4 * FUNC_NEST) + 1));
274 	}
275 	while (i < MAX_TEST_INSNS - MAX_JMP_SEQ * 4)
276 		insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
277 	insn[i] = BPF_EXIT_INSN();
278 	self->prog_len = i + 1;
279 	self->retval = 42;
280 }
281 
282 static void bpf_fill_scale(struct bpf_test *self)
283 {
284 	switch (self->retval) {
285 	case 1:
286 		return bpf_fill_scale1(self);
287 	case 2:
288 		return bpf_fill_scale2(self);
289 	default:
290 		self->prog_len = 0;
291 		break;
292 	}
293 }
294 
295 /* BPF_SK_LOOKUP contains 13 instructions, if you need to fix up maps */
296 #define BPF_SK_LOOKUP(func)						\
297 	/* struct bpf_sock_tuple tuple = {} */				\
298 	BPF_MOV64_IMM(BPF_REG_2, 0),					\
299 	BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_2, -8),			\
300 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -16),		\
301 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -24),		\
302 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -32),		\
303 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -40),		\
304 	BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_2, -48),		\
305 	/* sk = func(ctx, &tuple, sizeof tuple, 0, 0) */		\
306 	BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),				\
307 	BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -48),				\
308 	BPF_MOV64_IMM(BPF_REG_3, sizeof(struct bpf_sock_tuple)),	\
309 	BPF_MOV64_IMM(BPF_REG_4, 0),					\
310 	BPF_MOV64_IMM(BPF_REG_5, 0),					\
311 	BPF_EMIT_CALL(BPF_FUNC_ ## func)
312 
313 /* BPF_DIRECT_PKT_R2 contains 7 instructions, it initializes default return
314  * value into 0 and does necessary preparation for direct packet access
315  * through r2. The allowed access range is 8 bytes.
316  */
317 #define BPF_DIRECT_PKT_R2						\
318 	BPF_MOV64_IMM(BPF_REG_0, 0),					\
319 	BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1,			\
320 		    offsetof(struct __sk_buff, data)),			\
321 	BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1,			\
322 		    offsetof(struct __sk_buff, data_end)),		\
323 	BPF_MOV64_REG(BPF_REG_4, BPF_REG_2),				\
324 	BPF_ALU64_IMM(BPF_ADD, BPF_REG_4, 8),				\
325 	BPF_JMP_REG(BPF_JLE, BPF_REG_4, BPF_REG_3, 1),			\
326 	BPF_EXIT_INSN()
327 
328 /* BPF_RAND_UEXT_R7 contains 4 instructions, it initializes R7 into a random
329  * positive u32, and zero-extend it into 64-bit.
330  */
331 #define BPF_RAND_UEXT_R7						\
332 	BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,			\
333 		     BPF_FUNC_get_prandom_u32),				\
334 	BPF_MOV64_REG(BPF_REG_7, BPF_REG_0),				\
335 	BPF_ALU64_IMM(BPF_LSH, BPF_REG_7, 33),				\
336 	BPF_ALU64_IMM(BPF_RSH, BPF_REG_7, 33)
337 
338 /* BPF_RAND_SEXT_R7 contains 5 instructions, it initializes R7 into a random
339  * negative u32, and sign-extend it into 64-bit.
340  */
341 #define BPF_RAND_SEXT_R7						\
342 	BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,			\
343 		     BPF_FUNC_get_prandom_u32),				\
344 	BPF_MOV64_REG(BPF_REG_7, BPF_REG_0),				\
345 	BPF_ALU64_IMM(BPF_OR, BPF_REG_7, 0x80000000),			\
346 	BPF_ALU64_IMM(BPF_LSH, BPF_REG_7, 32),				\
347 	BPF_ALU64_IMM(BPF_ARSH, BPF_REG_7, 32)
348 
349 static struct bpf_test tests[] = {
350 #define FILL_ARRAY
351 #include <verifier/tests.h>
352 #undef FILL_ARRAY
353 };
354 
355 static int probe_filter_length(const struct bpf_insn *fp)
356 {
357 	int len;
358 
359 	for (len = MAX_INSNS - 1; len > 0; --len)
360 		if (fp[len].code != 0 || fp[len].imm != 0)
361 			break;
362 	return len + 1;
363 }
364 
365 static bool skip_unsupported_map(enum bpf_map_type map_type)
366 {
367 	if (!bpf_probe_map_type(map_type, 0)) {
368 		printf("SKIP (unsupported map type %d)\n", map_type);
369 		skips++;
370 		return true;
371 	}
372 	return false;
373 }
374 
375 static int __create_map(uint32_t type, uint32_t size_key,
376 			uint32_t size_value, uint32_t max_elem,
377 			uint32_t extra_flags)
378 {
379 	int fd;
380 
381 	fd = bpf_create_map(type, size_key, size_value, max_elem,
382 			    (type == BPF_MAP_TYPE_HASH ?
383 			     BPF_F_NO_PREALLOC : 0) | extra_flags);
384 	if (fd < 0) {
385 		if (skip_unsupported_map(type))
386 			return -1;
387 		printf("Failed to create hash map '%s'!\n", strerror(errno));
388 	}
389 
390 	return fd;
391 }
392 
393 static int create_map(uint32_t type, uint32_t size_key,
394 		      uint32_t size_value, uint32_t max_elem)
395 {
396 	return __create_map(type, size_key, size_value, max_elem, 0);
397 }
398 
399 static void update_map(int fd, int index)
400 {
401 	struct test_val value = {
402 		.index = (6 + 1) * sizeof(int),
403 		.foo[6] = 0xabcdef12,
404 	};
405 
406 	assert(!bpf_map_update_elem(fd, &index, &value, 0));
407 }
408 
409 static int create_prog_dummy1(enum bpf_prog_type prog_type)
410 {
411 	struct bpf_insn prog[] = {
412 		BPF_MOV64_IMM(BPF_REG_0, 42),
413 		BPF_EXIT_INSN(),
414 	};
415 
416 	return bpf_load_program(prog_type, prog,
417 				ARRAY_SIZE(prog), "GPL", 0, NULL, 0);
418 }
419 
420 static int create_prog_dummy2(enum bpf_prog_type prog_type, int mfd, int idx)
421 {
422 	struct bpf_insn prog[] = {
423 		BPF_MOV64_IMM(BPF_REG_3, idx),
424 		BPF_LD_MAP_FD(BPF_REG_2, mfd),
425 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
426 			     BPF_FUNC_tail_call),
427 		BPF_MOV64_IMM(BPF_REG_0, 41),
428 		BPF_EXIT_INSN(),
429 	};
430 
431 	return bpf_load_program(prog_type, prog,
432 				ARRAY_SIZE(prog), "GPL", 0, NULL, 0);
433 }
434 
435 static int create_prog_array(enum bpf_prog_type prog_type, uint32_t max_elem,
436 			     int p1key)
437 {
438 	int p2key = 1;
439 	int mfd, p1fd, p2fd;
440 
441 	mfd = bpf_create_map(BPF_MAP_TYPE_PROG_ARRAY, sizeof(int),
442 			     sizeof(int), max_elem, 0);
443 	if (mfd < 0) {
444 		if (skip_unsupported_map(BPF_MAP_TYPE_PROG_ARRAY))
445 			return -1;
446 		printf("Failed to create prog array '%s'!\n", strerror(errno));
447 		return -1;
448 	}
449 
450 	p1fd = create_prog_dummy1(prog_type);
451 	p2fd = create_prog_dummy2(prog_type, mfd, p2key);
452 	if (p1fd < 0 || p2fd < 0)
453 		goto out;
454 	if (bpf_map_update_elem(mfd, &p1key, &p1fd, BPF_ANY) < 0)
455 		goto out;
456 	if (bpf_map_update_elem(mfd, &p2key, &p2fd, BPF_ANY) < 0)
457 		goto out;
458 	close(p2fd);
459 	close(p1fd);
460 
461 	return mfd;
462 out:
463 	close(p2fd);
464 	close(p1fd);
465 	close(mfd);
466 	return -1;
467 }
468 
469 static int create_map_in_map(void)
470 {
471 	int inner_map_fd, outer_map_fd;
472 
473 	inner_map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
474 				      sizeof(int), 1, 0);
475 	if (inner_map_fd < 0) {
476 		if (skip_unsupported_map(BPF_MAP_TYPE_ARRAY))
477 			return -1;
478 		printf("Failed to create array '%s'!\n", strerror(errno));
479 		return inner_map_fd;
480 	}
481 
482 	outer_map_fd = bpf_create_map_in_map(BPF_MAP_TYPE_ARRAY_OF_MAPS, NULL,
483 					     sizeof(int), inner_map_fd, 1, 0);
484 	if (outer_map_fd < 0) {
485 		if (skip_unsupported_map(BPF_MAP_TYPE_ARRAY_OF_MAPS))
486 			return -1;
487 		printf("Failed to create array of maps '%s'!\n",
488 		       strerror(errno));
489 	}
490 
491 	close(inner_map_fd);
492 
493 	return outer_map_fd;
494 }
495 
496 static int create_cgroup_storage(bool percpu)
497 {
498 	enum bpf_map_type type = percpu ? BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE :
499 		BPF_MAP_TYPE_CGROUP_STORAGE;
500 	int fd;
501 
502 	fd = bpf_create_map(type, sizeof(struct bpf_cgroup_storage_key),
503 			    TEST_DATA_LEN, 0, 0);
504 	if (fd < 0) {
505 		if (skip_unsupported_map(type))
506 			return -1;
507 		printf("Failed to create cgroup storage '%s'!\n",
508 		       strerror(errno));
509 	}
510 
511 	return fd;
512 }
513 
514 /* struct bpf_spin_lock {
515  *   int val;
516  * };
517  * struct val {
518  *   int cnt;
519  *   struct bpf_spin_lock l;
520  * };
521  */
522 static const char btf_str_sec[] = "\0bpf_spin_lock\0val\0cnt\0l";
523 static __u32 btf_raw_types[] = {
524 	/* int */
525 	BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
526 	/* struct bpf_spin_lock */                      /* [2] */
527 	BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 1), 4),
528 	BTF_MEMBER_ENC(15, 1, 0), /* int val; */
529 	/* struct val */                                /* [3] */
530 	BTF_TYPE_ENC(15, BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 2), 8),
531 	BTF_MEMBER_ENC(19, 1, 0), /* int cnt; */
532 	BTF_MEMBER_ENC(23, 2, 32),/* struct bpf_spin_lock l; */
533 };
534 
535 static int load_btf(void)
536 {
537 	struct btf_header hdr = {
538 		.magic = BTF_MAGIC,
539 		.version = BTF_VERSION,
540 		.hdr_len = sizeof(struct btf_header),
541 		.type_len = sizeof(btf_raw_types),
542 		.str_off = sizeof(btf_raw_types),
543 		.str_len = sizeof(btf_str_sec),
544 	};
545 	void *ptr, *raw_btf;
546 	int btf_fd;
547 
548 	ptr = raw_btf = malloc(sizeof(hdr) + sizeof(btf_raw_types) +
549 			       sizeof(btf_str_sec));
550 
551 	memcpy(ptr, &hdr, sizeof(hdr));
552 	ptr += sizeof(hdr);
553 	memcpy(ptr, btf_raw_types, hdr.type_len);
554 	ptr += hdr.type_len;
555 	memcpy(ptr, btf_str_sec, hdr.str_len);
556 	ptr += hdr.str_len;
557 
558 	btf_fd = bpf_load_btf(raw_btf, ptr - raw_btf, 0, 0, 0);
559 	free(raw_btf);
560 	if (btf_fd < 0)
561 		return -1;
562 	return btf_fd;
563 }
564 
565 static int create_map_spin_lock(void)
566 {
567 	struct bpf_create_map_attr attr = {
568 		.name = "test_map",
569 		.map_type = BPF_MAP_TYPE_ARRAY,
570 		.key_size = 4,
571 		.value_size = 8,
572 		.max_entries = 1,
573 		.btf_key_type_id = 1,
574 		.btf_value_type_id = 3,
575 	};
576 	int fd, btf_fd;
577 
578 	btf_fd = load_btf();
579 	if (btf_fd < 0)
580 		return -1;
581 	attr.btf_fd = btf_fd;
582 	fd = bpf_create_map_xattr(&attr);
583 	if (fd < 0)
584 		printf("Failed to create map with spin_lock\n");
585 	return fd;
586 }
587 
588 static int create_sk_storage_map(void)
589 {
590 	struct bpf_create_map_attr attr = {
591 		.name = "test_map",
592 		.map_type = BPF_MAP_TYPE_SK_STORAGE,
593 		.key_size = 4,
594 		.value_size = 8,
595 		.max_entries = 0,
596 		.map_flags = BPF_F_NO_PREALLOC,
597 		.btf_key_type_id = 1,
598 		.btf_value_type_id = 3,
599 	};
600 	int fd, btf_fd;
601 
602 	btf_fd = load_btf();
603 	if (btf_fd < 0)
604 		return -1;
605 	attr.btf_fd = btf_fd;
606 	fd = bpf_create_map_xattr(&attr);
607 	close(attr.btf_fd);
608 	if (fd < 0)
609 		printf("Failed to create sk_storage_map\n");
610 	return fd;
611 }
612 
613 static char bpf_vlog[UINT_MAX >> 8];
614 
615 static void do_test_fixup(struct bpf_test *test, enum bpf_prog_type prog_type,
616 			  struct bpf_insn *prog, int *map_fds)
617 {
618 	int *fixup_map_hash_8b = test->fixup_map_hash_8b;
619 	int *fixup_map_hash_48b = test->fixup_map_hash_48b;
620 	int *fixup_map_hash_16b = test->fixup_map_hash_16b;
621 	int *fixup_map_array_48b = test->fixup_map_array_48b;
622 	int *fixup_map_sockmap = test->fixup_map_sockmap;
623 	int *fixup_map_sockhash = test->fixup_map_sockhash;
624 	int *fixup_map_xskmap = test->fixup_map_xskmap;
625 	int *fixup_map_stacktrace = test->fixup_map_stacktrace;
626 	int *fixup_prog1 = test->fixup_prog1;
627 	int *fixup_prog2 = test->fixup_prog2;
628 	int *fixup_map_in_map = test->fixup_map_in_map;
629 	int *fixup_cgroup_storage = test->fixup_cgroup_storage;
630 	int *fixup_percpu_cgroup_storage = test->fixup_percpu_cgroup_storage;
631 	int *fixup_map_spin_lock = test->fixup_map_spin_lock;
632 	int *fixup_map_array_ro = test->fixup_map_array_ro;
633 	int *fixup_map_array_wo = test->fixup_map_array_wo;
634 	int *fixup_map_array_small = test->fixup_map_array_small;
635 	int *fixup_sk_storage_map = test->fixup_sk_storage_map;
636 	int *fixup_map_event_output = test->fixup_map_event_output;
637 
638 	if (test->fill_helper) {
639 		test->fill_insns = calloc(MAX_TEST_INSNS, sizeof(struct bpf_insn));
640 		test->fill_helper(test);
641 	}
642 
643 	/* Allocating HTs with 1 elem is fine here, since we only test
644 	 * for verifier and not do a runtime lookup, so the only thing
645 	 * that really matters is value size in this case.
646 	 */
647 	if (*fixup_map_hash_8b) {
648 		map_fds[0] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
649 					sizeof(long long), 1);
650 		do {
651 			prog[*fixup_map_hash_8b].imm = map_fds[0];
652 			fixup_map_hash_8b++;
653 		} while (*fixup_map_hash_8b);
654 	}
655 
656 	if (*fixup_map_hash_48b) {
657 		map_fds[1] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
658 					sizeof(struct test_val), 1);
659 		do {
660 			prog[*fixup_map_hash_48b].imm = map_fds[1];
661 			fixup_map_hash_48b++;
662 		} while (*fixup_map_hash_48b);
663 	}
664 
665 	if (*fixup_map_hash_16b) {
666 		map_fds[2] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
667 					sizeof(struct other_val), 1);
668 		do {
669 			prog[*fixup_map_hash_16b].imm = map_fds[2];
670 			fixup_map_hash_16b++;
671 		} while (*fixup_map_hash_16b);
672 	}
673 
674 	if (*fixup_map_array_48b) {
675 		map_fds[3] = create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
676 					sizeof(struct test_val), 1);
677 		update_map(map_fds[3], 0);
678 		do {
679 			prog[*fixup_map_array_48b].imm = map_fds[3];
680 			fixup_map_array_48b++;
681 		} while (*fixup_map_array_48b);
682 	}
683 
684 	if (*fixup_prog1) {
685 		map_fds[4] = create_prog_array(prog_type, 4, 0);
686 		do {
687 			prog[*fixup_prog1].imm = map_fds[4];
688 			fixup_prog1++;
689 		} while (*fixup_prog1);
690 	}
691 
692 	if (*fixup_prog2) {
693 		map_fds[5] = create_prog_array(prog_type, 8, 7);
694 		do {
695 			prog[*fixup_prog2].imm = map_fds[5];
696 			fixup_prog2++;
697 		} while (*fixup_prog2);
698 	}
699 
700 	if (*fixup_map_in_map) {
701 		map_fds[6] = create_map_in_map();
702 		do {
703 			prog[*fixup_map_in_map].imm = map_fds[6];
704 			fixup_map_in_map++;
705 		} while (*fixup_map_in_map);
706 	}
707 
708 	if (*fixup_cgroup_storage) {
709 		map_fds[7] = create_cgroup_storage(false);
710 		do {
711 			prog[*fixup_cgroup_storage].imm = map_fds[7];
712 			fixup_cgroup_storage++;
713 		} while (*fixup_cgroup_storage);
714 	}
715 
716 	if (*fixup_percpu_cgroup_storage) {
717 		map_fds[8] = create_cgroup_storage(true);
718 		do {
719 			prog[*fixup_percpu_cgroup_storage].imm = map_fds[8];
720 			fixup_percpu_cgroup_storage++;
721 		} while (*fixup_percpu_cgroup_storage);
722 	}
723 	if (*fixup_map_sockmap) {
724 		map_fds[9] = create_map(BPF_MAP_TYPE_SOCKMAP, sizeof(int),
725 					sizeof(int), 1);
726 		do {
727 			prog[*fixup_map_sockmap].imm = map_fds[9];
728 			fixup_map_sockmap++;
729 		} while (*fixup_map_sockmap);
730 	}
731 	if (*fixup_map_sockhash) {
732 		map_fds[10] = create_map(BPF_MAP_TYPE_SOCKHASH, sizeof(int),
733 					sizeof(int), 1);
734 		do {
735 			prog[*fixup_map_sockhash].imm = map_fds[10];
736 			fixup_map_sockhash++;
737 		} while (*fixup_map_sockhash);
738 	}
739 	if (*fixup_map_xskmap) {
740 		map_fds[11] = create_map(BPF_MAP_TYPE_XSKMAP, sizeof(int),
741 					sizeof(int), 1);
742 		do {
743 			prog[*fixup_map_xskmap].imm = map_fds[11];
744 			fixup_map_xskmap++;
745 		} while (*fixup_map_xskmap);
746 	}
747 	if (*fixup_map_stacktrace) {
748 		map_fds[12] = create_map(BPF_MAP_TYPE_STACK_TRACE, sizeof(u32),
749 					 sizeof(u64), 1);
750 		do {
751 			prog[*fixup_map_stacktrace].imm = map_fds[12];
752 			fixup_map_stacktrace++;
753 		} while (*fixup_map_stacktrace);
754 	}
755 	if (*fixup_map_spin_lock) {
756 		map_fds[13] = create_map_spin_lock();
757 		do {
758 			prog[*fixup_map_spin_lock].imm = map_fds[13];
759 			fixup_map_spin_lock++;
760 		} while (*fixup_map_spin_lock);
761 	}
762 	if (*fixup_map_array_ro) {
763 		map_fds[14] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
764 					   sizeof(struct test_val), 1,
765 					   BPF_F_RDONLY_PROG);
766 		update_map(map_fds[14], 0);
767 		do {
768 			prog[*fixup_map_array_ro].imm = map_fds[14];
769 			fixup_map_array_ro++;
770 		} while (*fixup_map_array_ro);
771 	}
772 	if (*fixup_map_array_wo) {
773 		map_fds[15] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
774 					   sizeof(struct test_val), 1,
775 					   BPF_F_WRONLY_PROG);
776 		update_map(map_fds[15], 0);
777 		do {
778 			prog[*fixup_map_array_wo].imm = map_fds[15];
779 			fixup_map_array_wo++;
780 		} while (*fixup_map_array_wo);
781 	}
782 	if (*fixup_map_array_small) {
783 		map_fds[16] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
784 					   1, 1, 0);
785 		update_map(map_fds[16], 0);
786 		do {
787 			prog[*fixup_map_array_small].imm = map_fds[16];
788 			fixup_map_array_small++;
789 		} while (*fixup_map_array_small);
790 	}
791 	if (*fixup_sk_storage_map) {
792 		map_fds[17] = create_sk_storage_map();
793 		do {
794 			prog[*fixup_sk_storage_map].imm = map_fds[17];
795 			fixup_sk_storage_map++;
796 		} while (*fixup_sk_storage_map);
797 	}
798 	if (*fixup_map_event_output) {
799 		map_fds[18] = __create_map(BPF_MAP_TYPE_PERF_EVENT_ARRAY,
800 					   sizeof(int), sizeof(int), 1, 0);
801 		do {
802 			prog[*fixup_map_event_output].imm = map_fds[18];
803 			fixup_map_event_output++;
804 		} while (*fixup_map_event_output);
805 	}
806 }
807 
808 static int set_admin(bool admin)
809 {
810 	cap_t caps;
811 	const cap_value_t cap_val = CAP_SYS_ADMIN;
812 	int ret = -1;
813 
814 	caps = cap_get_proc();
815 	if (!caps) {
816 		perror("cap_get_proc");
817 		return -1;
818 	}
819 	if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap_val,
820 				admin ? CAP_SET : CAP_CLEAR)) {
821 		perror("cap_set_flag");
822 		goto out;
823 	}
824 	if (cap_set_proc(caps)) {
825 		perror("cap_set_proc");
826 		goto out;
827 	}
828 	ret = 0;
829 out:
830 	if (cap_free(caps))
831 		perror("cap_free");
832 	return ret;
833 }
834 
835 static int do_prog_test_run(int fd_prog, bool unpriv, uint32_t expected_val,
836 			    void *data, size_t size_data)
837 {
838 	__u8 tmp[TEST_DATA_LEN << 2];
839 	__u32 size_tmp = sizeof(tmp);
840 	uint32_t retval;
841 	int err;
842 
843 	if (unpriv)
844 		set_admin(true);
845 	err = bpf_prog_test_run(fd_prog, 1, data, size_data,
846 				tmp, &size_tmp, &retval, NULL);
847 	if (unpriv)
848 		set_admin(false);
849 	if (err && errno != 524/*ENOTSUPP*/ && errno != EPERM) {
850 		printf("Unexpected bpf_prog_test_run error ");
851 		return err;
852 	}
853 	if (!err && retval != expected_val &&
854 	    expected_val != POINTER_VALUE) {
855 		printf("FAIL retval %d != %d ", retval, expected_val);
856 		return 1;
857 	}
858 
859 	return 0;
860 }
861 
862 static void do_test_single(struct bpf_test *test, bool unpriv,
863 			   int *passes, int *errors)
864 {
865 	int fd_prog, expected_ret, alignment_prevented_execution;
866 	int prog_len, prog_type = test->prog_type;
867 	struct bpf_insn *prog = test->insns;
868 	struct bpf_load_program_attr attr;
869 	int run_errs, run_successes;
870 	int map_fds[MAX_NR_MAPS];
871 	const char *expected_err;
872 	int fixup_skips;
873 	__u32 pflags;
874 	int i, err;
875 
876 	for (i = 0; i < MAX_NR_MAPS; i++)
877 		map_fds[i] = -1;
878 
879 	if (!prog_type)
880 		prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
881 	fixup_skips = skips;
882 	do_test_fixup(test, prog_type, prog, map_fds);
883 	if (test->fill_insns) {
884 		prog = test->fill_insns;
885 		prog_len = test->prog_len;
886 	} else {
887 		prog_len = probe_filter_length(prog);
888 	}
889 	/* If there were some map skips during fixup due to missing bpf
890 	 * features, skip this test.
891 	 */
892 	if (fixup_skips != skips)
893 		return;
894 
895 	pflags = BPF_F_TEST_RND_HI32;
896 	if (test->flags & F_LOAD_WITH_STRICT_ALIGNMENT)
897 		pflags |= BPF_F_STRICT_ALIGNMENT;
898 	if (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS)
899 		pflags |= BPF_F_ANY_ALIGNMENT;
900 
901 	memset(&attr, 0, sizeof(attr));
902 	attr.prog_type = prog_type;
903 	attr.expected_attach_type = test->expected_attach_type;
904 	attr.insns = prog;
905 	attr.insns_cnt = prog_len;
906 	attr.license = "GPL";
907 	attr.log_level = 4;
908 	attr.prog_flags = pflags;
909 
910 	fd_prog = bpf_load_program_xattr(&attr, bpf_vlog, sizeof(bpf_vlog));
911 	if (fd_prog < 0 && !bpf_probe_prog_type(prog_type, 0)) {
912 		printf("SKIP (unsupported program type %d)\n", prog_type);
913 		skips++;
914 		goto close_fds;
915 	}
916 
917 	expected_ret = unpriv && test->result_unpriv != UNDEF ?
918 		       test->result_unpriv : test->result;
919 	expected_err = unpriv && test->errstr_unpriv ?
920 		       test->errstr_unpriv : test->errstr;
921 
922 	alignment_prevented_execution = 0;
923 
924 	if (expected_ret == ACCEPT) {
925 		if (fd_prog < 0) {
926 			printf("FAIL\nFailed to load prog '%s'!\n",
927 			       strerror(errno));
928 			goto fail_log;
929 		}
930 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
931 		if (fd_prog >= 0 &&
932 		    (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS))
933 			alignment_prevented_execution = 1;
934 #endif
935 	} else {
936 		if (fd_prog >= 0) {
937 			printf("FAIL\nUnexpected success to load!\n");
938 			goto fail_log;
939 		}
940 		if (!expected_err || !strstr(bpf_vlog, expected_err)) {
941 			printf("FAIL\nUnexpected error message!\n\tEXP: %s\n\tRES: %s\n",
942 			      expected_err, bpf_vlog);
943 			goto fail_log;
944 		}
945 	}
946 
947 	if (test->insn_processed) {
948 		uint32_t insn_processed;
949 		char *proc;
950 
951 		proc = strstr(bpf_vlog, "processed ");
952 		insn_processed = atoi(proc + 10);
953 		if (test->insn_processed != insn_processed) {
954 			printf("FAIL\nUnexpected insn_processed %u vs %u\n",
955 			       insn_processed, test->insn_processed);
956 			goto fail_log;
957 		}
958 	}
959 
960 	run_errs = 0;
961 	run_successes = 0;
962 	if (!alignment_prevented_execution && fd_prog >= 0) {
963 		uint32_t expected_val;
964 		int i;
965 
966 		if (!test->runs)
967 			test->runs = 1;
968 
969 		for (i = 0; i < test->runs; i++) {
970 			if (unpriv && test->retvals[i].retval_unpriv)
971 				expected_val = test->retvals[i].retval_unpriv;
972 			else
973 				expected_val = test->retvals[i].retval;
974 
975 			err = do_prog_test_run(fd_prog, unpriv, expected_val,
976 					       test->retvals[i].data,
977 					       sizeof(test->retvals[i].data));
978 			if (err) {
979 				printf("(run %d/%d) ", i + 1, test->runs);
980 				run_errs++;
981 			} else {
982 				run_successes++;
983 			}
984 		}
985 	}
986 
987 	if (!run_errs) {
988 		(*passes)++;
989 		if (run_successes > 1)
990 			printf("%d cases ", run_successes);
991 		printf("OK");
992 		if (alignment_prevented_execution)
993 			printf(" (NOTE: not executed due to unknown alignment)");
994 		printf("\n");
995 	} else {
996 		printf("\n");
997 		goto fail_log;
998 	}
999 close_fds:
1000 	if (test->fill_insns)
1001 		free(test->fill_insns);
1002 	close(fd_prog);
1003 	for (i = 0; i < MAX_NR_MAPS; i++)
1004 		close(map_fds[i]);
1005 	sched_yield();
1006 	return;
1007 fail_log:
1008 	(*errors)++;
1009 	printf("%s", bpf_vlog);
1010 	goto close_fds;
1011 }
1012 
1013 static bool is_admin(void)
1014 {
1015 	cap_t caps;
1016 	cap_flag_value_t sysadmin = CAP_CLEAR;
1017 	const cap_value_t cap_val = CAP_SYS_ADMIN;
1018 
1019 #ifdef CAP_IS_SUPPORTED
1020 	if (!CAP_IS_SUPPORTED(CAP_SETFCAP)) {
1021 		perror("cap_get_flag");
1022 		return false;
1023 	}
1024 #endif
1025 	caps = cap_get_proc();
1026 	if (!caps) {
1027 		perror("cap_get_proc");
1028 		return false;
1029 	}
1030 	if (cap_get_flag(caps, cap_val, CAP_EFFECTIVE, &sysadmin))
1031 		perror("cap_get_flag");
1032 	if (cap_free(caps))
1033 		perror("cap_free");
1034 	return (sysadmin == CAP_SET);
1035 }
1036 
1037 static void get_unpriv_disabled()
1038 {
1039 	char buf[2];
1040 	FILE *fd;
1041 
1042 	fd = fopen("/proc/sys/"UNPRIV_SYSCTL, "r");
1043 	if (!fd) {
1044 		perror("fopen /proc/sys/"UNPRIV_SYSCTL);
1045 		unpriv_disabled = true;
1046 		return;
1047 	}
1048 	if (fgets(buf, 2, fd) == buf && atoi(buf))
1049 		unpriv_disabled = true;
1050 	fclose(fd);
1051 }
1052 
1053 static bool test_as_unpriv(struct bpf_test *test)
1054 {
1055 	return !test->prog_type ||
1056 	       test->prog_type == BPF_PROG_TYPE_SOCKET_FILTER ||
1057 	       test->prog_type == BPF_PROG_TYPE_CGROUP_SKB;
1058 }
1059 
1060 static int do_test(bool unpriv, unsigned int from, unsigned int to)
1061 {
1062 	int i, passes = 0, errors = 0;
1063 
1064 	for (i = from; i < to; i++) {
1065 		struct bpf_test *test = &tests[i];
1066 
1067 		/* Program types that are not supported by non-root we
1068 		 * skip right away.
1069 		 */
1070 		if (test_as_unpriv(test) && unpriv_disabled) {
1071 			printf("#%d/u %s SKIP\n", i, test->descr);
1072 			skips++;
1073 		} else if (test_as_unpriv(test)) {
1074 			if (!unpriv)
1075 				set_admin(false);
1076 			printf("#%d/u %s ", i, test->descr);
1077 			do_test_single(test, true, &passes, &errors);
1078 			if (!unpriv)
1079 				set_admin(true);
1080 		}
1081 
1082 		if (unpriv) {
1083 			printf("#%d/p %s SKIP\n", i, test->descr);
1084 			skips++;
1085 		} else {
1086 			printf("#%d/p %s ", i, test->descr);
1087 			do_test_single(test, false, &passes, &errors);
1088 		}
1089 	}
1090 
1091 	printf("Summary: %d PASSED, %d SKIPPED, %d FAILED\n", passes,
1092 	       skips, errors);
1093 	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
1094 }
1095 
1096 int main(int argc, char **argv)
1097 {
1098 	unsigned int from = 0, to = ARRAY_SIZE(tests);
1099 	bool unpriv = !is_admin();
1100 
1101 	if (argc == 3) {
1102 		unsigned int l = atoi(argv[argc - 2]);
1103 		unsigned int u = atoi(argv[argc - 1]);
1104 
1105 		if (l < to && u < to) {
1106 			from = l;
1107 			to   = u + 1;
1108 		}
1109 	} else if (argc == 2) {
1110 		unsigned int t = atoi(argv[argc - 1]);
1111 
1112 		if (t < to) {
1113 			from = t;
1114 			to   = t + 1;
1115 		}
1116 	}
1117 
1118 	get_unpriv_disabled();
1119 	if (unpriv && unpriv_disabled) {
1120 		printf("Cannot run as unprivileged user with sysctl %s.\n",
1121 		       UNPRIV_SYSCTL);
1122 		return EXIT_FAILURE;
1123 	}
1124 
1125 	bpf_semi_rand_init();
1126 	return do_test(unpriv, from, to);
1127 }
1128