xref: /linux/tools/testing/selftests/bpf/test_verifier.c (revision 0d97dacc46d9af2daba1af224747d452bd988365)
1 /*
2  * Testsuite for eBPF verifier
3  *
4  * Copyright (c) 2014 PLUMgrid, http://plumgrid.com
5  * Copyright (c) 2017 Facebook
6  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of version 2 of the GNU General Public
10  * License as published by the Free Software Foundation.
11  */
12 
13 #include <endian.h>
14 #include <asm/types.h>
15 #include <linux/types.h>
16 #include <stdint.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <errno.h>
21 #include <string.h>
22 #include <stddef.h>
23 #include <stdbool.h>
24 #include <sched.h>
25 #include <limits.h>
26 #include <assert.h>
27 
28 #include <sys/capability.h>
29 
30 #include <linux/unistd.h>
31 #include <linux/filter.h>
32 #include <linux/bpf_perf_event.h>
33 #include <linux/bpf.h>
34 #include <linux/if_ether.h>
35 #include <linux/btf.h>
36 
37 #include <bpf/bpf.h>
38 #include <bpf/libbpf.h>
39 
40 #ifdef HAVE_GENHDR
41 # include "autoconf.h"
42 #else
43 # if defined(__i386) || defined(__x86_64) || defined(__s390x__) || defined(__aarch64__)
44 #  define CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS 1
45 # endif
46 #endif
47 #include "bpf_rlimit.h"
48 #include "bpf_rand.h"
49 #include "bpf_util.h"
50 #include "test_btf.h"
51 #include "../../../include/linux/filter.h"
52 
53 #define MAX_INSNS	BPF_MAXINSNS
54 #define MAX_TEST_INSNS	1000000
55 #define MAX_FIXUPS	8
56 #define MAX_NR_MAPS	18
57 #define MAX_TEST_RUNS	8
58 #define POINTER_VALUE	0xcafe4all
59 #define TEST_DATA_LEN	64
60 
61 #define F_NEEDS_EFFICIENT_UNALIGNED_ACCESS	(1 << 0)
62 #define F_LOAD_WITH_STRICT_ALIGNMENT		(1 << 1)
63 
64 #define UNPRIV_SYSCTL "kernel/unprivileged_bpf_disabled"
65 static bool unpriv_disabled = false;
66 static int skips;
67 
68 struct bpf_test {
69 	const char *descr;
70 	struct bpf_insn	insns[MAX_INSNS];
71 	struct bpf_insn	*fill_insns;
72 	int fixup_map_hash_8b[MAX_FIXUPS];
73 	int fixup_map_hash_48b[MAX_FIXUPS];
74 	int fixup_map_hash_16b[MAX_FIXUPS];
75 	int fixup_map_array_48b[MAX_FIXUPS];
76 	int fixup_map_sockmap[MAX_FIXUPS];
77 	int fixup_map_sockhash[MAX_FIXUPS];
78 	int fixup_map_xskmap[MAX_FIXUPS];
79 	int fixup_map_stacktrace[MAX_FIXUPS];
80 	int fixup_prog1[MAX_FIXUPS];
81 	int fixup_prog2[MAX_FIXUPS];
82 	int fixup_map_in_map[MAX_FIXUPS];
83 	int fixup_cgroup_storage[MAX_FIXUPS];
84 	int fixup_percpu_cgroup_storage[MAX_FIXUPS];
85 	int fixup_map_spin_lock[MAX_FIXUPS];
86 	int fixup_map_array_ro[MAX_FIXUPS];
87 	int fixup_map_array_wo[MAX_FIXUPS];
88 	int fixup_map_array_small[MAX_FIXUPS];
89 	int fixup_sk_storage_map[MAX_FIXUPS];
90 	const char *errstr;
91 	const char *errstr_unpriv;
92 	uint32_t retval, retval_unpriv, insn_processed;
93 	int prog_len;
94 	enum {
95 		UNDEF,
96 		ACCEPT,
97 		REJECT
98 	} result, result_unpriv;
99 	enum bpf_prog_type prog_type;
100 	uint8_t flags;
101 	__u8 data[TEST_DATA_LEN];
102 	void (*fill_helper)(struct bpf_test *self);
103 	uint8_t runs;
104 	struct {
105 		uint32_t retval, retval_unpriv;
106 		union {
107 			__u8 data[TEST_DATA_LEN];
108 			__u64 data64[TEST_DATA_LEN / 8];
109 		};
110 	} retvals[MAX_TEST_RUNS];
111 };
112 
113 /* Note we want this to be 64 bit aligned so that the end of our array is
114  * actually the end of the structure.
115  */
116 #define MAX_ENTRIES 11
117 
118 struct test_val {
119 	unsigned int index;
120 	int foo[MAX_ENTRIES];
121 };
122 
123 struct other_val {
124 	long long foo;
125 	long long bar;
126 };
127 
128 static void bpf_fill_ld_abs_vlan_push_pop(struct bpf_test *self)
129 {
130 	/* test: {skb->data[0], vlan_push} x 51 + {skb->data[0], vlan_pop} x 51 */
131 #define PUSH_CNT 51
132 	/* jump range is limited to 16 bit. PUSH_CNT of ld_abs needs room */
133 	unsigned int len = (1 << 15) - PUSH_CNT * 2 * 5 * 6;
134 	struct bpf_insn *insn = self->fill_insns;
135 	int i = 0, j, k = 0;
136 
137 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
138 loop:
139 	for (j = 0; j < PUSH_CNT; j++) {
140 		insn[i++] = BPF_LD_ABS(BPF_B, 0);
141 		/* jump to error label */
142 		insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
143 		i++;
144 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
145 		insn[i++] = BPF_MOV64_IMM(BPF_REG_2, 1);
146 		insn[i++] = BPF_MOV64_IMM(BPF_REG_3, 2);
147 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
148 					 BPF_FUNC_skb_vlan_push),
149 		insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
150 		i++;
151 	}
152 
153 	for (j = 0; j < PUSH_CNT; j++) {
154 		insn[i++] = BPF_LD_ABS(BPF_B, 0);
155 		insn[i] = BPF_JMP32_IMM(BPF_JNE, BPF_REG_0, 0x34, len - i - 3);
156 		i++;
157 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
158 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
159 					 BPF_FUNC_skb_vlan_pop),
160 		insn[i] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, len - i - 3);
161 		i++;
162 	}
163 	if (++k < 5)
164 		goto loop;
165 
166 	for (; i < len - 3; i++)
167 		insn[i] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 0xbef);
168 	insn[len - 3] = BPF_JMP_A(1);
169 	/* error label */
170 	insn[len - 2] = BPF_MOV32_IMM(BPF_REG_0, 0);
171 	insn[len - 1] = BPF_EXIT_INSN();
172 	self->prog_len = len;
173 }
174 
175 static void bpf_fill_jump_around_ld_abs(struct bpf_test *self)
176 {
177 	struct bpf_insn *insn = self->fill_insns;
178 	/* jump range is limited to 16 bit. every ld_abs is replaced by 6 insns,
179 	 * but on arches like arm, ppc etc, there will be one BPF_ZEXT inserted
180 	 * to extend the error value of the inlined ld_abs sequence which then
181 	 * contains 7 insns. so, set the dividend to 7 so the testcase could
182 	 * work on all arches.
183 	 */
184 	unsigned int len = (1 << 15) / 7;
185 	int i = 0;
186 
187 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
188 	insn[i++] = BPF_LD_ABS(BPF_B, 0);
189 	insn[i] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 10, len - i - 2);
190 	i++;
191 	while (i < len - 1)
192 		insn[i++] = BPF_LD_ABS(BPF_B, 1);
193 	insn[i] = BPF_EXIT_INSN();
194 	self->prog_len = i + 1;
195 }
196 
197 static void bpf_fill_rand_ld_dw(struct bpf_test *self)
198 {
199 	struct bpf_insn *insn = self->fill_insns;
200 	uint64_t res = 0;
201 	int i = 0;
202 
203 	insn[i++] = BPF_MOV32_IMM(BPF_REG_0, 0);
204 	while (i < self->retval) {
205 		uint64_t val = bpf_semi_rand_get();
206 		struct bpf_insn tmp[2] = { BPF_LD_IMM64(BPF_REG_1, val) };
207 
208 		res ^= val;
209 		insn[i++] = tmp[0];
210 		insn[i++] = tmp[1];
211 		insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
212 	}
213 	insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_0);
214 	insn[i++] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_1, 32);
215 	insn[i++] = BPF_ALU64_REG(BPF_XOR, BPF_REG_0, BPF_REG_1);
216 	insn[i] = BPF_EXIT_INSN();
217 	self->prog_len = i + 1;
218 	res ^= (res >> 32);
219 	self->retval = (uint32_t)res;
220 }
221 
222 #define MAX_JMP_SEQ 8192
223 
224 /* test the sequence of 8k jumps */
225 static void bpf_fill_scale1(struct bpf_test *self)
226 {
227 	struct bpf_insn *insn = self->fill_insns;
228 	int i = 0, k = 0;
229 
230 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
231 	/* test to check that the long sequence of jumps is acceptable */
232 	while (k++ < MAX_JMP_SEQ) {
233 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
234 					 BPF_FUNC_get_prandom_u32);
235 		insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
236 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
237 		insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
238 					-8 * (k % 64 + 1));
239 	}
240 	/* every jump adds 1 step to insn_processed, so to stay exactly
241 	 * within 1m limit add MAX_TEST_INSNS - MAX_JMP_SEQ - 1 MOVs and 1 EXIT
242 	 */
243 	while (i < MAX_TEST_INSNS - MAX_JMP_SEQ - 1)
244 		insn[i++] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_0, 42);
245 	insn[i] = BPF_EXIT_INSN();
246 	self->prog_len = i + 1;
247 	self->retval = 42;
248 }
249 
250 /* test the sequence of 8k jumps in inner most function (function depth 8)*/
251 static void bpf_fill_scale2(struct bpf_test *self)
252 {
253 	struct bpf_insn *insn = self->fill_insns;
254 	int i = 0, k = 0;
255 
256 #define FUNC_NEST 7
257 	for (k = 0; k < FUNC_NEST; k++) {
258 		insn[i++] = BPF_CALL_REL(1);
259 		insn[i++] = BPF_EXIT_INSN();
260 	}
261 	insn[i++] = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
262 	/* test to check that the long sequence of jumps is acceptable */
263 	k = 0;
264 	while (k++ < MAX_JMP_SEQ) {
265 		insn[i++] = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
266 					 BPF_FUNC_get_prandom_u32);
267 		insn[i++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, bpf_semi_rand_get(), 2);
268 		insn[i++] = BPF_MOV64_REG(BPF_REG_1, BPF_REG_10);
269 		insn[i++] = BPF_STX_MEM(BPF_DW, BPF_REG_1, BPF_REG_6,
270 					-8 * (k % (64 - 4 * FUNC_NEST) + 1));
271 	}
272 	/* every jump adds 1 step to insn_processed, so to stay exactly
273 	 * within 1m limit add MAX_TEST_INSNS - MAX_JMP_SEQ - 1 MOVs and 1 EXIT
274 	 */
275 	while (i < MAX_TEST_INSNS - MAX_JMP_SEQ - 1)
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 
637 	if (test->fill_helper) {
638 		test->fill_insns = calloc(MAX_TEST_INSNS, sizeof(struct bpf_insn));
639 		test->fill_helper(test);
640 	}
641 
642 	/* Allocating HTs with 1 elem is fine here, since we only test
643 	 * for verifier and not do a runtime lookup, so the only thing
644 	 * that really matters is value size in this case.
645 	 */
646 	if (*fixup_map_hash_8b) {
647 		map_fds[0] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
648 					sizeof(long long), 1);
649 		do {
650 			prog[*fixup_map_hash_8b].imm = map_fds[0];
651 			fixup_map_hash_8b++;
652 		} while (*fixup_map_hash_8b);
653 	}
654 
655 	if (*fixup_map_hash_48b) {
656 		map_fds[1] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
657 					sizeof(struct test_val), 1);
658 		do {
659 			prog[*fixup_map_hash_48b].imm = map_fds[1];
660 			fixup_map_hash_48b++;
661 		} while (*fixup_map_hash_48b);
662 	}
663 
664 	if (*fixup_map_hash_16b) {
665 		map_fds[2] = create_map(BPF_MAP_TYPE_HASH, sizeof(long long),
666 					sizeof(struct other_val), 1);
667 		do {
668 			prog[*fixup_map_hash_16b].imm = map_fds[2];
669 			fixup_map_hash_16b++;
670 		} while (*fixup_map_hash_16b);
671 	}
672 
673 	if (*fixup_map_array_48b) {
674 		map_fds[3] = create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
675 					sizeof(struct test_val), 1);
676 		update_map(map_fds[3], 0);
677 		do {
678 			prog[*fixup_map_array_48b].imm = map_fds[3];
679 			fixup_map_array_48b++;
680 		} while (*fixup_map_array_48b);
681 	}
682 
683 	if (*fixup_prog1) {
684 		map_fds[4] = create_prog_array(prog_type, 4, 0);
685 		do {
686 			prog[*fixup_prog1].imm = map_fds[4];
687 			fixup_prog1++;
688 		} while (*fixup_prog1);
689 	}
690 
691 	if (*fixup_prog2) {
692 		map_fds[5] = create_prog_array(prog_type, 8, 7);
693 		do {
694 			prog[*fixup_prog2].imm = map_fds[5];
695 			fixup_prog2++;
696 		} while (*fixup_prog2);
697 	}
698 
699 	if (*fixup_map_in_map) {
700 		map_fds[6] = create_map_in_map();
701 		do {
702 			prog[*fixup_map_in_map].imm = map_fds[6];
703 			fixup_map_in_map++;
704 		} while (*fixup_map_in_map);
705 	}
706 
707 	if (*fixup_cgroup_storage) {
708 		map_fds[7] = create_cgroup_storage(false);
709 		do {
710 			prog[*fixup_cgroup_storage].imm = map_fds[7];
711 			fixup_cgroup_storage++;
712 		} while (*fixup_cgroup_storage);
713 	}
714 
715 	if (*fixup_percpu_cgroup_storage) {
716 		map_fds[8] = create_cgroup_storage(true);
717 		do {
718 			prog[*fixup_percpu_cgroup_storage].imm = map_fds[8];
719 			fixup_percpu_cgroup_storage++;
720 		} while (*fixup_percpu_cgroup_storage);
721 	}
722 	if (*fixup_map_sockmap) {
723 		map_fds[9] = create_map(BPF_MAP_TYPE_SOCKMAP, sizeof(int),
724 					sizeof(int), 1);
725 		do {
726 			prog[*fixup_map_sockmap].imm = map_fds[9];
727 			fixup_map_sockmap++;
728 		} while (*fixup_map_sockmap);
729 	}
730 	if (*fixup_map_sockhash) {
731 		map_fds[10] = create_map(BPF_MAP_TYPE_SOCKHASH, sizeof(int),
732 					sizeof(int), 1);
733 		do {
734 			prog[*fixup_map_sockhash].imm = map_fds[10];
735 			fixup_map_sockhash++;
736 		} while (*fixup_map_sockhash);
737 	}
738 	if (*fixup_map_xskmap) {
739 		map_fds[11] = create_map(BPF_MAP_TYPE_XSKMAP, sizeof(int),
740 					sizeof(int), 1);
741 		do {
742 			prog[*fixup_map_xskmap].imm = map_fds[11];
743 			fixup_map_xskmap++;
744 		} while (*fixup_map_xskmap);
745 	}
746 	if (*fixup_map_stacktrace) {
747 		map_fds[12] = create_map(BPF_MAP_TYPE_STACK_TRACE, sizeof(u32),
748 					 sizeof(u64), 1);
749 		do {
750 			prog[*fixup_map_stacktrace].imm = map_fds[12];
751 			fixup_map_stacktrace++;
752 		} while (*fixup_map_stacktrace);
753 	}
754 	if (*fixup_map_spin_lock) {
755 		map_fds[13] = create_map_spin_lock();
756 		do {
757 			prog[*fixup_map_spin_lock].imm = map_fds[13];
758 			fixup_map_spin_lock++;
759 		} while (*fixup_map_spin_lock);
760 	}
761 	if (*fixup_map_array_ro) {
762 		map_fds[14] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
763 					   sizeof(struct test_val), 1,
764 					   BPF_F_RDONLY_PROG);
765 		update_map(map_fds[14], 0);
766 		do {
767 			prog[*fixup_map_array_ro].imm = map_fds[14];
768 			fixup_map_array_ro++;
769 		} while (*fixup_map_array_ro);
770 	}
771 	if (*fixup_map_array_wo) {
772 		map_fds[15] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
773 					   sizeof(struct test_val), 1,
774 					   BPF_F_WRONLY_PROG);
775 		update_map(map_fds[15], 0);
776 		do {
777 			prog[*fixup_map_array_wo].imm = map_fds[15];
778 			fixup_map_array_wo++;
779 		} while (*fixup_map_array_wo);
780 	}
781 	if (*fixup_map_array_small) {
782 		map_fds[16] = __create_map(BPF_MAP_TYPE_ARRAY, sizeof(int),
783 					   1, 1, 0);
784 		update_map(map_fds[16], 0);
785 		do {
786 			prog[*fixup_map_array_small].imm = map_fds[16];
787 			fixup_map_array_small++;
788 		} while (*fixup_map_array_small);
789 	}
790 	if (*fixup_sk_storage_map) {
791 		map_fds[17] = create_sk_storage_map();
792 		do {
793 			prog[*fixup_sk_storage_map].imm = map_fds[17];
794 			fixup_sk_storage_map++;
795 		} while (*fixup_sk_storage_map);
796 	}
797 }
798 
799 static int set_admin(bool admin)
800 {
801 	cap_t caps;
802 	const cap_value_t cap_val = CAP_SYS_ADMIN;
803 	int ret = -1;
804 
805 	caps = cap_get_proc();
806 	if (!caps) {
807 		perror("cap_get_proc");
808 		return -1;
809 	}
810 	if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &cap_val,
811 				admin ? CAP_SET : CAP_CLEAR)) {
812 		perror("cap_set_flag");
813 		goto out;
814 	}
815 	if (cap_set_proc(caps)) {
816 		perror("cap_set_proc");
817 		goto out;
818 	}
819 	ret = 0;
820 out:
821 	if (cap_free(caps))
822 		perror("cap_free");
823 	return ret;
824 }
825 
826 static int do_prog_test_run(int fd_prog, bool unpriv, uint32_t expected_val,
827 			    void *data, size_t size_data)
828 {
829 	__u8 tmp[TEST_DATA_LEN << 2];
830 	__u32 size_tmp = sizeof(tmp);
831 	uint32_t retval;
832 	int err;
833 
834 	if (unpriv)
835 		set_admin(true);
836 	err = bpf_prog_test_run(fd_prog, 1, data, size_data,
837 				tmp, &size_tmp, &retval, NULL);
838 	if (unpriv)
839 		set_admin(false);
840 	if (err && errno != 524/*ENOTSUPP*/ && errno != EPERM) {
841 		printf("Unexpected bpf_prog_test_run error ");
842 		return err;
843 	}
844 	if (!err && retval != expected_val &&
845 	    expected_val != POINTER_VALUE) {
846 		printf("FAIL retval %d != %d ", retval, expected_val);
847 		return 1;
848 	}
849 
850 	return 0;
851 }
852 
853 static void do_test_single(struct bpf_test *test, bool unpriv,
854 			   int *passes, int *errors)
855 {
856 	int fd_prog, expected_ret, alignment_prevented_execution;
857 	int prog_len, prog_type = test->prog_type;
858 	struct bpf_insn *prog = test->insns;
859 	int run_errs, run_successes;
860 	int map_fds[MAX_NR_MAPS];
861 	const char *expected_err;
862 	int fixup_skips;
863 	__u32 pflags;
864 	int i, err;
865 
866 	for (i = 0; i < MAX_NR_MAPS; i++)
867 		map_fds[i] = -1;
868 
869 	if (!prog_type)
870 		prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
871 	fixup_skips = skips;
872 	do_test_fixup(test, prog_type, prog, map_fds);
873 	if (test->fill_insns) {
874 		prog = test->fill_insns;
875 		prog_len = test->prog_len;
876 	} else {
877 		prog_len = probe_filter_length(prog);
878 	}
879 	/* If there were some map skips during fixup due to missing bpf
880 	 * features, skip this test.
881 	 */
882 	if (fixup_skips != skips)
883 		return;
884 
885 	pflags = BPF_F_TEST_RND_HI32;
886 	if (test->flags & F_LOAD_WITH_STRICT_ALIGNMENT)
887 		pflags |= BPF_F_STRICT_ALIGNMENT;
888 	if (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS)
889 		pflags |= BPF_F_ANY_ALIGNMENT;
890 	fd_prog = bpf_verify_program(prog_type, prog, prog_len, pflags,
891 				     "GPL", 0, bpf_vlog, sizeof(bpf_vlog), 4);
892 	if (fd_prog < 0 && !bpf_probe_prog_type(prog_type, 0)) {
893 		printf("SKIP (unsupported program type %d)\n", prog_type);
894 		skips++;
895 		goto close_fds;
896 	}
897 
898 	expected_ret = unpriv && test->result_unpriv != UNDEF ?
899 		       test->result_unpriv : test->result;
900 	expected_err = unpriv && test->errstr_unpriv ?
901 		       test->errstr_unpriv : test->errstr;
902 
903 	alignment_prevented_execution = 0;
904 
905 	if (expected_ret == ACCEPT) {
906 		if (fd_prog < 0) {
907 			printf("FAIL\nFailed to load prog '%s'!\n",
908 			       strerror(errno));
909 			goto fail_log;
910 		}
911 #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
912 		if (fd_prog >= 0 &&
913 		    (test->flags & F_NEEDS_EFFICIENT_UNALIGNED_ACCESS))
914 			alignment_prevented_execution = 1;
915 #endif
916 	} else {
917 		if (fd_prog >= 0) {
918 			printf("FAIL\nUnexpected success to load!\n");
919 			goto fail_log;
920 		}
921 		if (!strstr(bpf_vlog, expected_err)) {
922 			printf("FAIL\nUnexpected error message!\n\tEXP: %s\n\tRES: %s\n",
923 			      expected_err, bpf_vlog);
924 			goto fail_log;
925 		}
926 	}
927 
928 	if (test->insn_processed) {
929 		uint32_t insn_processed;
930 		char *proc;
931 
932 		proc = strstr(bpf_vlog, "processed ");
933 		insn_processed = atoi(proc + 10);
934 		if (test->insn_processed != insn_processed) {
935 			printf("FAIL\nUnexpected insn_processed %u vs %u\n",
936 			       insn_processed, test->insn_processed);
937 			goto fail_log;
938 		}
939 	}
940 
941 	run_errs = 0;
942 	run_successes = 0;
943 	if (!alignment_prevented_execution && fd_prog >= 0) {
944 		uint32_t expected_val;
945 		int i;
946 
947 		if (!test->runs) {
948 			expected_val = unpriv && test->retval_unpriv ?
949 				test->retval_unpriv : test->retval;
950 
951 			err = do_prog_test_run(fd_prog, unpriv, expected_val,
952 					       test->data, sizeof(test->data));
953 			if (err)
954 				run_errs++;
955 			else
956 				run_successes++;
957 		}
958 
959 		for (i = 0; i < test->runs; i++) {
960 			if (unpriv && test->retvals[i].retval_unpriv)
961 				expected_val = test->retvals[i].retval_unpriv;
962 			else
963 				expected_val = test->retvals[i].retval;
964 
965 			err = do_prog_test_run(fd_prog, unpriv, expected_val,
966 					       test->retvals[i].data,
967 					       sizeof(test->retvals[i].data));
968 			if (err) {
969 				printf("(run %d/%d) ", i + 1, test->runs);
970 				run_errs++;
971 			} else {
972 				run_successes++;
973 			}
974 		}
975 	}
976 
977 	if (!run_errs) {
978 		(*passes)++;
979 		if (run_successes > 1)
980 			printf("%d cases ", run_successes);
981 		printf("OK");
982 		if (alignment_prevented_execution)
983 			printf(" (NOTE: not executed due to unknown alignment)");
984 		printf("\n");
985 	} else {
986 		printf("\n");
987 		goto fail_log;
988 	}
989 close_fds:
990 	if (test->fill_insns)
991 		free(test->fill_insns);
992 	close(fd_prog);
993 	for (i = 0; i < MAX_NR_MAPS; i++)
994 		close(map_fds[i]);
995 	sched_yield();
996 	return;
997 fail_log:
998 	(*errors)++;
999 	printf("%s", bpf_vlog);
1000 	goto close_fds;
1001 }
1002 
1003 static bool is_admin(void)
1004 {
1005 	cap_t caps;
1006 	cap_flag_value_t sysadmin = CAP_CLEAR;
1007 	const cap_value_t cap_val = CAP_SYS_ADMIN;
1008 
1009 #ifdef CAP_IS_SUPPORTED
1010 	if (!CAP_IS_SUPPORTED(CAP_SETFCAP)) {
1011 		perror("cap_get_flag");
1012 		return false;
1013 	}
1014 #endif
1015 	caps = cap_get_proc();
1016 	if (!caps) {
1017 		perror("cap_get_proc");
1018 		return false;
1019 	}
1020 	if (cap_get_flag(caps, cap_val, CAP_EFFECTIVE, &sysadmin))
1021 		perror("cap_get_flag");
1022 	if (cap_free(caps))
1023 		perror("cap_free");
1024 	return (sysadmin == CAP_SET);
1025 }
1026 
1027 static void get_unpriv_disabled()
1028 {
1029 	char buf[2];
1030 	FILE *fd;
1031 
1032 	fd = fopen("/proc/sys/"UNPRIV_SYSCTL, "r");
1033 	if (!fd) {
1034 		perror("fopen /proc/sys/"UNPRIV_SYSCTL);
1035 		unpriv_disabled = true;
1036 		return;
1037 	}
1038 	if (fgets(buf, 2, fd) == buf && atoi(buf))
1039 		unpriv_disabled = true;
1040 	fclose(fd);
1041 }
1042 
1043 static bool test_as_unpriv(struct bpf_test *test)
1044 {
1045 	return !test->prog_type ||
1046 	       test->prog_type == BPF_PROG_TYPE_SOCKET_FILTER ||
1047 	       test->prog_type == BPF_PROG_TYPE_CGROUP_SKB;
1048 }
1049 
1050 static int do_test(bool unpriv, unsigned int from, unsigned int to)
1051 {
1052 	int i, passes = 0, errors = 0;
1053 
1054 	for (i = from; i < to; i++) {
1055 		struct bpf_test *test = &tests[i];
1056 
1057 		/* Program types that are not supported by non-root we
1058 		 * skip right away.
1059 		 */
1060 		if (test_as_unpriv(test) && unpriv_disabled) {
1061 			printf("#%d/u %s SKIP\n", i, test->descr);
1062 			skips++;
1063 		} else if (test_as_unpriv(test)) {
1064 			if (!unpriv)
1065 				set_admin(false);
1066 			printf("#%d/u %s ", i, test->descr);
1067 			do_test_single(test, true, &passes, &errors);
1068 			if (!unpriv)
1069 				set_admin(true);
1070 		}
1071 
1072 		if (unpriv) {
1073 			printf("#%d/p %s SKIP\n", i, test->descr);
1074 			skips++;
1075 		} else {
1076 			printf("#%d/p %s ", i, test->descr);
1077 			do_test_single(test, false, &passes, &errors);
1078 		}
1079 	}
1080 
1081 	printf("Summary: %d PASSED, %d SKIPPED, %d FAILED\n", passes,
1082 	       skips, errors);
1083 	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
1084 }
1085 
1086 int main(int argc, char **argv)
1087 {
1088 	unsigned int from = 0, to = ARRAY_SIZE(tests);
1089 	bool unpriv = !is_admin();
1090 
1091 	if (argc == 3) {
1092 		unsigned int l = atoi(argv[argc - 2]);
1093 		unsigned int u = atoi(argv[argc - 1]);
1094 
1095 		if (l < to && u < to) {
1096 			from = l;
1097 			to   = u + 1;
1098 		}
1099 	} else if (argc == 2) {
1100 		unsigned int t = atoi(argv[argc - 1]);
1101 
1102 		if (t < to) {
1103 			from = t;
1104 			to   = t + 1;
1105 		}
1106 	}
1107 
1108 	get_unpriv_disabled();
1109 	if (unpriv && unpriv_disabled) {
1110 		printf("Cannot run as unprivileged user with sysctl %s.\n",
1111 		       UNPRIV_SYSCTL);
1112 		return EXIT_FAILURE;
1113 	}
1114 
1115 	bpf_semi_rand_init();
1116 	return do_test(unpriv, from, to);
1117 }
1118