Linux Audio

Check our new training course

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