xref: /linux/tools/testing/selftests/bpf/test_loader.c (revision 78ee02a966ad76966be516ed3d56860d7a58fe7e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
3 #include <linux/capability.h>
4 #include <stdlib.h>
5 #include <test_progs.h>
6 #include <bpf/btf.h>
7 
8 #include "autoconf_helper.h"
9 #include "disasm_helpers.h"
10 #include "unpriv_helpers.h"
11 #include "cap_helpers.h"
12 #include "jit_disasm_helpers.h"
13 
14 #define str_has_pfx(str, pfx) \
15 	(strncmp(str, pfx, __builtin_constant_p(pfx) ? sizeof(pfx) - 1 : strlen(pfx)) == 0)
16 
17 #define TEST_LOADER_LOG_BUF_SZ 2097152
18 
19 #define TEST_TAG_EXPECT_FAILURE "comment:test_expect_failure"
20 #define TEST_TAG_EXPECT_SUCCESS "comment:test_expect_success"
21 #define TEST_TAG_EXPECT_MSG_PFX "comment:test_expect_msg="
22 #define TEST_TAG_EXPECT_NOT_MSG_PFX "comment:test_expect_not_msg="
23 #define TEST_TAG_EXPECT_XLATED_PFX "comment:test_expect_xlated="
24 #define TEST_TAG_EXPECT_FAILURE_UNPRIV "comment:test_expect_failure_unpriv"
25 #define TEST_TAG_EXPECT_SUCCESS_UNPRIV "comment:test_expect_success_unpriv"
26 #define TEST_TAG_EXPECT_MSG_PFX_UNPRIV "comment:test_expect_msg_unpriv="
27 #define TEST_TAG_EXPECT_NOT_MSG_PFX_UNPRIV "comment:test_expect_not_msg_unpriv="
28 #define TEST_TAG_EXPECT_XLATED_PFX_UNPRIV "comment:test_expect_xlated_unpriv="
29 #define TEST_TAG_LOG_LEVEL_PFX "comment:test_log_level="
30 #define TEST_TAG_PROG_FLAGS_PFX "comment:test_prog_flags="
31 #define TEST_TAG_DESCRIPTION_PFX "comment:test_description="
32 #define TEST_TAG_RETVAL_PFX "comment:test_retval="
33 #define TEST_TAG_RETVAL_PFX_UNPRIV "comment:test_retval_unpriv="
34 #define TEST_TAG_AUXILIARY "comment:test_auxiliary"
35 #define TEST_TAG_AUXILIARY_UNPRIV "comment:test_auxiliary_unpriv"
36 #define TEST_BTF_PATH "comment:test_btf_path="
37 #define TEST_TAG_ARCH "comment:test_arch="
38 #define TEST_TAG_JITED_PFX "comment:test_jited="
39 #define TEST_TAG_JITED_PFX_UNPRIV "comment:test_jited_unpriv="
40 #define TEST_TAG_CAPS_UNPRIV "comment:test_caps_unpriv="
41 #define TEST_TAG_LOAD_MODE_PFX "comment:load_mode="
42 #define TEST_TAG_EXPECT_STDERR_PFX "comment:test_expect_stderr="
43 #define TEST_TAG_EXPECT_STDERR_PFX_UNPRIV "comment:test_expect_stderr_unpriv="
44 #define TEST_TAG_EXPECT_STDOUT_PFX "comment:test_expect_stdout="
45 #define TEST_TAG_EXPECT_STDOUT_PFX_UNPRIV "comment:test_expect_stdout_unpriv="
46 #define TEST_TAG_LINEAR_SIZE "comment:test_linear_size="
47 
48 /* Warning: duplicated in bpf_misc.h */
49 #define POINTER_VALUE	0xbadcafe
50 #define TEST_DATA_LEN	64
51 
52 #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
53 #define EFFICIENT_UNALIGNED_ACCESS 1
54 #else
55 #define EFFICIENT_UNALIGNED_ACCESS 0
56 #endif
57 
58 static int sysctl_unpriv_disabled = -1;
59 
60 enum mode {
61 	PRIV = 1,
62 	UNPRIV = 2
63 };
64 
65 enum load_mode {
66 	JITED		= 1 << 0,
67 	NO_JITED	= 1 << 1,
68 };
69 
70 struct test_subspec {
71 	char *name;
72 	char *description;
73 	bool expect_failure;
74 	struct expected_msgs expect_msgs;
75 	struct expected_msgs expect_xlated;
76 	struct expected_msgs jited;
77 	struct expected_msgs stderr;
78 	struct expected_msgs stdout;
79 	int retval;
80 	bool execute;
81 	__u64 caps;
82 };
83 
84 struct test_spec {
85 	const char *prog_name;
86 	struct test_subspec priv;
87 	struct test_subspec unpriv;
88 	const char *btf_custom_path;
89 	int log_level;
90 	int prog_flags;
91 	int mode_mask;
92 	int arch_mask;
93 	int load_mask;
94 	int linear_sz;
95 	bool auxiliary;
96 	bool valid;
97 };
98 
99 static int tester_init(struct test_loader *tester)
100 {
101 	if (!tester->log_buf) {
102 		tester->log_buf_sz = TEST_LOADER_LOG_BUF_SZ;
103 		tester->log_buf = calloc(tester->log_buf_sz, 1);
104 		if (!ASSERT_OK_PTR(tester->log_buf, "tester_log_buf"))
105 			return -ENOMEM;
106 	}
107 
108 	return 0;
109 }
110 
111 void test_loader_fini(struct test_loader *tester)
112 {
113 	if (!tester)
114 		return;
115 
116 	free(tester->log_buf);
117 }
118 
119 static void free_msgs(struct expected_msgs *msgs)
120 {
121 	int i;
122 
123 	for (i = 0; i < msgs->cnt; i++)
124 		if (msgs->patterns[i].is_regex)
125 			regfree(&msgs->patterns[i].regex);
126 	free(msgs->patterns);
127 	msgs->patterns = NULL;
128 	msgs->cnt = 0;
129 }
130 
131 static void free_test_spec(struct test_spec *spec)
132 {
133 	/* Deallocate expect_msgs arrays. */
134 	free_msgs(&spec->priv.expect_msgs);
135 	free_msgs(&spec->unpriv.expect_msgs);
136 	free_msgs(&spec->priv.expect_xlated);
137 	free_msgs(&spec->unpriv.expect_xlated);
138 	free_msgs(&spec->priv.jited);
139 	free_msgs(&spec->unpriv.jited);
140 	free_msgs(&spec->unpriv.stderr);
141 	free_msgs(&spec->priv.stderr);
142 	free_msgs(&spec->unpriv.stdout);
143 	free_msgs(&spec->priv.stdout);
144 
145 	free(spec->priv.name);
146 	free(spec->priv.description);
147 	free(spec->unpriv.name);
148 	free(spec->unpriv.description);
149 	spec->priv.name = NULL;
150 	spec->priv.description = NULL;
151 	spec->unpriv.name = NULL;
152 	spec->unpriv.description = NULL;
153 }
154 
155 /* Compiles regular expression matching pattern.
156  * Pattern has a special syntax:
157  *
158  *   pattern := (<verbatim text> | regex)*
159  *   regex := "{{" <posix extended regular expression> "}}"
160  *
161  * In other words, pattern is a verbatim text with inclusion
162  * of regular expressions enclosed in "{{" "}}" pairs.
163  * For example, pattern "foo{{[0-9]+}}" matches strings like
164  * "foo0", "foo007", etc.
165  */
166 static int compile_regex(const char *pattern, regex_t *regex)
167 {
168 	char err_buf[256], buf[256] = {}, *ptr, *buf_end;
169 	const char *original_pattern = pattern;
170 	bool in_regex = false;
171 	int err;
172 
173 	buf_end = buf + sizeof(buf);
174 	ptr = buf;
175 	while (*pattern && ptr < buf_end - 2) {
176 		if (!in_regex && str_has_pfx(pattern, "{{")) {
177 			in_regex = true;
178 			pattern += 2;
179 			continue;
180 		}
181 		if (in_regex && str_has_pfx(pattern, "}}")) {
182 			in_regex = false;
183 			pattern += 2;
184 			continue;
185 		}
186 		if (in_regex) {
187 			*ptr++ = *pattern++;
188 			continue;
189 		}
190 		/* list of characters that need escaping for extended posix regex */
191 		if (strchr(".[]\\()*+?{}|^$", *pattern)) {
192 			*ptr++ = '\\';
193 			*ptr++ = *pattern++;
194 			continue;
195 		}
196 		*ptr++ = *pattern++;
197 	}
198 	if (*pattern) {
199 		PRINT_FAIL("Regexp too long: '%s'\n", original_pattern);
200 		return -EINVAL;
201 	}
202 	if (in_regex) {
203 		PRINT_FAIL("Regexp has open '{{' but no closing '}}': '%s'\n", original_pattern);
204 		return -EINVAL;
205 	}
206 	err = regcomp(regex, buf, REG_EXTENDED | REG_NEWLINE);
207 	if (err != 0) {
208 		regerror(err, regex, err_buf, sizeof(err_buf));
209 		PRINT_FAIL("Regexp compilation error in '%s': '%s'\n", buf, err_buf);
210 		return -EINVAL;
211 	}
212 	return 0;
213 }
214 
215 static int __push_msg(const char *pattern, bool on_next_line, bool negative,
216 		      struct expected_msgs *msgs)
217 {
218 	struct expect_msg *msg;
219 	void *tmp;
220 	int err;
221 
222 	tmp = realloc(msgs->patterns,
223 		      (1 + msgs->cnt) * sizeof(struct expect_msg));
224 	if (!tmp) {
225 		ASSERT_FAIL("failed to realloc memory for messages\n");
226 		return -ENOMEM;
227 	}
228 	msgs->patterns = tmp;
229 	msg = &msgs->patterns[msgs->cnt];
230 	msg->on_next_line = on_next_line;
231 	msg->substr = pattern;
232 	msg->negative = negative;
233 	msg->is_regex = false;
234 	if (strstr(pattern, "{{")) {
235 		err = compile_regex(pattern, &msg->regex);
236 		if (err)
237 			return err;
238 		msg->is_regex = true;
239 	}
240 	msgs->cnt += 1;
241 	return 0;
242 }
243 
244 static int clone_msgs(struct expected_msgs *from, struct expected_msgs *to)
245 {
246 	struct expect_msg *msg;
247 	int i, err;
248 
249 	for (i = 0; i < from->cnt; i++) {
250 		msg = &from->patterns[i];
251 		err = __push_msg(msg->substr, msg->on_next_line, msg->negative, to);
252 		if (err)
253 			return err;
254 	}
255 	return 0;
256 }
257 
258 static int push_msg(const char *substr, bool negative, struct expected_msgs *msgs)
259 {
260 	return __push_msg(substr, false, negative, msgs);
261 }
262 
263 static int push_disasm_msg(const char *regex_str, bool *on_next_line, struct expected_msgs *msgs)
264 {
265 	int err;
266 
267 	if (strcmp(regex_str, "...") == 0) {
268 		*on_next_line = false;
269 		return 0;
270 	}
271 	err = __push_msg(regex_str, *on_next_line, false, msgs);
272 	if (err)
273 		return err;
274 	*on_next_line = true;
275 	return 0;
276 }
277 
278 static int parse_int(const char *str, int *val, const char *name)
279 {
280 	char *end;
281 	long tmp;
282 
283 	errno = 0;
284 	if (str_has_pfx(str, "0x"))
285 		tmp = strtol(str + 2, &end, 16);
286 	else
287 		tmp = strtol(str, &end, 10);
288 	if (errno || end[0] != '\0') {
289 		PRINT_FAIL("failed to parse %s from '%s'\n", name, str);
290 		return -EINVAL;
291 	}
292 	*val = tmp;
293 	return 0;
294 }
295 
296 static int parse_caps(const char *str, __u64 *val, const char *name)
297 {
298 	int cap_flag = 0;
299 	char *token = NULL, *saveptr = NULL;
300 
301 	char *str_cpy = strdup(str);
302 	if (str_cpy == NULL) {
303 		PRINT_FAIL("Memory allocation failed\n");
304 		return -EINVAL;
305 	}
306 
307 	token = strtok_r(str_cpy, "|", &saveptr);
308 	while (token != NULL) {
309 		errno = 0;
310 		if (!strncmp("CAP_", token, sizeof("CAP_") - 1)) {
311 			PRINT_FAIL("define %s constant in bpf_misc.h, failed to parse caps\n", token);
312 			return -EINVAL;
313 		}
314 		cap_flag = strtol(token, NULL, 10);
315 		if (!cap_flag || errno) {
316 			PRINT_FAIL("failed to parse caps %s\n", name);
317 			return -EINVAL;
318 		}
319 		*val |= (1ULL << cap_flag);
320 		token = strtok_r(NULL, "|", &saveptr);
321 	}
322 
323 	free(str_cpy);
324 	return 0;
325 }
326 
327 static int parse_retval(const char *str, int *val, const char *name)
328 {
329 	/*
330 	 * INT_MIN is defined as (-INT_MAX -1), i.e. it doesn't expand to a
331 	 * single int and cannot be parsed with strtol, so we handle it
332 	 * separately here. In addition, it expands to different expressions in
333 	 * different compilers so we use a prefixed _INT_MIN instead.
334 	 */
335 	if (strcmp(str, "_INT_MIN") == 0) {
336 		*val = INT_MIN;
337 		return 0;
338 	}
339 
340 	return parse_int(str, val, name);
341 }
342 
343 static void update_flags(int *flags, int flag, bool clear)
344 {
345 	if (clear)
346 		*flags &= ~flag;
347 	else
348 		*flags |= flag;
349 }
350 
351 /* Matches a string of form '<pfx>[^=]=.*' and returns it's suffix.
352  * Used to parse btf_decl_tag values.
353  * Such values require unique prefix because compiler does not add
354  * same __attribute__((btf_decl_tag(...))) twice.
355  * Test suite uses two-component tags for such cases:
356  *
357  *   <pfx> __COUNTER__ '='
358  *
359  * For example, two consecutive __msg tags '__msg("foo") __msg("foo")'
360  * would be encoded as:
361  *
362  *   [18] DECL_TAG 'comment:test_expect_msg=0=foo' type_id=15 component_idx=-1
363  *   [19] DECL_TAG 'comment:test_expect_msg=1=foo' type_id=15 component_idx=-1
364  *
365  * And the purpose of this function is to extract 'foo' from the above.
366  */
367 static const char *skip_dynamic_pfx(const char *s, const char *pfx)
368 {
369 	const char *msg;
370 
371 	if (strncmp(s, pfx, strlen(pfx)) != 0)
372 		return NULL;
373 	msg = s + strlen(pfx);
374 	msg = strchr(msg, '=');
375 	if (!msg)
376 		return NULL;
377 	return msg + 1;
378 }
379 
380 enum arch {
381 	ARCH_UNKNOWN	= 0x1,
382 	ARCH_X86_64	= 0x2,
383 	ARCH_ARM64	= 0x4,
384 	ARCH_RISCV64	= 0x8,
385 	ARCH_S390X	= 0x10,
386 };
387 
388 static int get_current_arch(void)
389 {
390 #if defined(__x86_64__)
391 	return ARCH_X86_64;
392 #elif defined(__aarch64__)
393 	return ARCH_ARM64;
394 #elif defined(__riscv) && __riscv_xlen == 64
395 	return ARCH_RISCV64;
396 #elif defined(__s390x__)
397 	return ARCH_S390X;
398 #endif
399 	return ARCH_UNKNOWN;
400 }
401 
402 /* Uses btf_decl_tag attributes to describe the expected test
403  * behavior, see bpf_misc.h for detailed description of each attribute
404  * and attribute combinations.
405  */
406 static int parse_test_spec(struct test_loader *tester,
407 			   struct bpf_object *obj,
408 			   struct bpf_program *prog,
409 			   struct test_spec *spec)
410 {
411 	const char *description = NULL;
412 	bool has_unpriv_result = false;
413 	bool has_unpriv_retval = false;
414 	bool unpriv_xlated_on_next_line = true;
415 	bool xlated_on_next_line = true;
416 	bool unpriv_jit_on_next_line;
417 	bool jit_on_next_line;
418 	bool stderr_on_next_line = true;
419 	bool unpriv_stderr_on_next_line = true;
420 	bool stdout_on_next_line = true;
421 	bool unpriv_stdout_on_next_line = true;
422 	bool collect_jit = false;
423 	int func_id, i, err = 0;
424 	u32 arch_mask = 0;
425 	u32 load_mask = 0;
426 	struct btf *btf;
427 	enum arch arch;
428 
429 	memset(spec, 0, sizeof(*spec));
430 
431 	spec->prog_name = bpf_program__name(prog);
432 	spec->prog_flags = testing_prog_flags();
433 
434 	btf = bpf_object__btf(obj);
435 	if (!btf) {
436 		ASSERT_FAIL("BPF object has no BTF");
437 		return -EINVAL;
438 	}
439 
440 	func_id = btf__find_by_name_kind(btf, spec->prog_name, BTF_KIND_FUNC);
441 	if (func_id < 0) {
442 		ASSERT_FAIL("failed to find FUNC BTF type for '%s'", spec->prog_name);
443 		return -EINVAL;
444 	}
445 
446 	for (i = 1; i < btf__type_cnt(btf); i++) {
447 		const char *s, *val, *msg;
448 		const struct btf_type *t;
449 		bool clear;
450 		int flags;
451 
452 		t = btf__type_by_id(btf, i);
453 		if (!btf_is_decl_tag(t))
454 			continue;
455 
456 		if (t->type != func_id || btf_decl_tag(t)->component_idx != -1)
457 			continue;
458 
459 		s = btf__str_by_offset(btf, t->name_off);
460 		if (str_has_pfx(s, TEST_TAG_DESCRIPTION_PFX)) {
461 			description = s + sizeof(TEST_TAG_DESCRIPTION_PFX) - 1;
462 		} else if (strcmp(s, TEST_TAG_EXPECT_FAILURE) == 0) {
463 			spec->priv.expect_failure = true;
464 			spec->mode_mask |= PRIV;
465 		} else if (strcmp(s, TEST_TAG_EXPECT_SUCCESS) == 0) {
466 			spec->priv.expect_failure = false;
467 			spec->mode_mask |= PRIV;
468 		} else if (strcmp(s, TEST_TAG_EXPECT_FAILURE_UNPRIV) == 0) {
469 			spec->unpriv.expect_failure = true;
470 			spec->mode_mask |= UNPRIV;
471 			has_unpriv_result = true;
472 		} else if (strcmp(s, TEST_TAG_EXPECT_SUCCESS_UNPRIV) == 0) {
473 			spec->unpriv.expect_failure = false;
474 			spec->mode_mask |= UNPRIV;
475 			has_unpriv_result = true;
476 		} else if (strcmp(s, TEST_TAG_AUXILIARY) == 0) {
477 			spec->auxiliary = true;
478 			spec->mode_mask |= PRIV;
479 		} else if (strcmp(s, TEST_TAG_AUXILIARY_UNPRIV) == 0) {
480 			spec->auxiliary = true;
481 			spec->mode_mask |= UNPRIV;
482 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_MSG_PFX))) {
483 			err = push_msg(msg, false, &spec->priv.expect_msgs);
484 			if (err)
485 				goto cleanup;
486 			spec->mode_mask |= PRIV;
487 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_NOT_MSG_PFX))) {
488 			err = push_msg(msg, true, &spec->priv.expect_msgs);
489 			if (err)
490 				goto cleanup;
491 			spec->mode_mask |= PRIV;
492 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_MSG_PFX_UNPRIV))) {
493 			err = push_msg(msg, false, &spec->unpriv.expect_msgs);
494 			if (err)
495 				goto cleanup;
496 			spec->mode_mask |= UNPRIV;
497 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_NOT_MSG_PFX_UNPRIV))) {
498 			err = push_msg(msg, true, &spec->unpriv.expect_msgs);
499 			if (err)
500 				goto cleanup;
501 			spec->mode_mask |= UNPRIV;
502 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_JITED_PFX))) {
503 			if (arch_mask == 0) {
504 				PRINT_FAIL("__jited used before __arch_*");
505 				goto cleanup;
506 			}
507 			if (collect_jit) {
508 				err = push_disasm_msg(msg, &jit_on_next_line,
509 						      &spec->priv.jited);
510 				if (err)
511 					goto cleanup;
512 				spec->mode_mask |= PRIV;
513 			}
514 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_JITED_PFX_UNPRIV))) {
515 			if (arch_mask == 0) {
516 				PRINT_FAIL("__unpriv_jited used before __arch_*");
517 				goto cleanup;
518 			}
519 			if (collect_jit) {
520 				err = push_disasm_msg(msg, &unpriv_jit_on_next_line,
521 						      &spec->unpriv.jited);
522 				if (err)
523 					goto cleanup;
524 				spec->mode_mask |= UNPRIV;
525 			}
526 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_XLATED_PFX))) {
527 			err = push_disasm_msg(msg, &xlated_on_next_line,
528 					      &spec->priv.expect_xlated);
529 			if (err)
530 				goto cleanup;
531 			spec->mode_mask |= PRIV;
532 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_XLATED_PFX_UNPRIV))) {
533 			err = push_disasm_msg(msg, &unpriv_xlated_on_next_line,
534 					      &spec->unpriv.expect_xlated);
535 			if (err)
536 				goto cleanup;
537 			spec->mode_mask |= UNPRIV;
538 		} else if (str_has_pfx(s, TEST_TAG_RETVAL_PFX)) {
539 			val = s + sizeof(TEST_TAG_RETVAL_PFX) - 1;
540 			err = parse_retval(val, &spec->priv.retval, "__retval");
541 			if (err)
542 				goto cleanup;
543 			spec->priv.execute = true;
544 			spec->mode_mask |= PRIV;
545 		} else if (str_has_pfx(s, TEST_TAG_RETVAL_PFX_UNPRIV)) {
546 			val = s + sizeof(TEST_TAG_RETVAL_PFX_UNPRIV) - 1;
547 			err = parse_retval(val, &spec->unpriv.retval, "__retval_unpriv");
548 			if (err)
549 				goto cleanup;
550 			spec->mode_mask |= UNPRIV;
551 			spec->unpriv.execute = true;
552 			has_unpriv_retval = true;
553 		} else if (str_has_pfx(s, TEST_TAG_LOG_LEVEL_PFX)) {
554 			val = s + sizeof(TEST_TAG_LOG_LEVEL_PFX) - 1;
555 			err = parse_int(val, &spec->log_level, "test log level");
556 			if (err)
557 				goto cleanup;
558 		} else if (str_has_pfx(s, TEST_TAG_PROG_FLAGS_PFX)) {
559 			val = s + sizeof(TEST_TAG_PROG_FLAGS_PFX) - 1;
560 
561 			clear = val[0] == '!';
562 			if (clear)
563 				val++;
564 
565 			if (strcmp(val, "BPF_F_STRICT_ALIGNMENT") == 0) {
566 				update_flags(&spec->prog_flags, BPF_F_STRICT_ALIGNMENT, clear);
567 			} else if (strcmp(val, "BPF_F_ANY_ALIGNMENT") == 0) {
568 				update_flags(&spec->prog_flags, BPF_F_ANY_ALIGNMENT, clear);
569 			} else if (strcmp(val, "BPF_F_TEST_RND_HI32") == 0) {
570 				update_flags(&spec->prog_flags, BPF_F_TEST_RND_HI32, clear);
571 			} else if (strcmp(val, "BPF_F_TEST_STATE_FREQ") == 0) {
572 				update_flags(&spec->prog_flags, BPF_F_TEST_STATE_FREQ, clear);
573 			} else if (strcmp(val, "BPF_F_SLEEPABLE") == 0) {
574 				update_flags(&spec->prog_flags, BPF_F_SLEEPABLE, clear);
575 			} else if (strcmp(val, "BPF_F_XDP_HAS_FRAGS") == 0) {
576 				update_flags(&spec->prog_flags, BPF_F_XDP_HAS_FRAGS, clear);
577 			} else if (strcmp(val, "BPF_F_TEST_REG_INVARIANTS") == 0) {
578 				update_flags(&spec->prog_flags, BPF_F_TEST_REG_INVARIANTS, clear);
579 			} else /* assume numeric value */ {
580 				err = parse_int(val, &flags, "test prog flags");
581 				if (err)
582 					goto cleanup;
583 				update_flags(&spec->prog_flags, flags, clear);
584 			}
585 		} else if (str_has_pfx(s, TEST_TAG_ARCH)) {
586 			val = s + sizeof(TEST_TAG_ARCH) - 1;
587 			if (strcmp(val, "X86_64") == 0) {
588 				arch = ARCH_X86_64;
589 			} else if (strcmp(val, "ARM64") == 0) {
590 				arch = ARCH_ARM64;
591 			} else if (strcmp(val, "RISCV64") == 0) {
592 				arch = ARCH_RISCV64;
593 			} else if (strcmp(val, "s390x") == 0) {
594 				arch = ARCH_S390X;
595 			} else {
596 				PRINT_FAIL("bad arch spec: '%s'\n", val);
597 				err = -EINVAL;
598 				goto cleanup;
599 			}
600 			arch_mask |= arch;
601 			collect_jit = get_current_arch() == arch;
602 			unpriv_jit_on_next_line = true;
603 			jit_on_next_line = true;
604 		} else if (str_has_pfx(s, TEST_BTF_PATH)) {
605 			spec->btf_custom_path = s + sizeof(TEST_BTF_PATH) - 1;
606 		} else if (str_has_pfx(s, TEST_TAG_CAPS_UNPRIV)) {
607 			val = s + sizeof(TEST_TAG_CAPS_UNPRIV) - 1;
608 			err = parse_caps(val, &spec->unpriv.caps, "test caps");
609 			if (err)
610 				goto cleanup;
611 			spec->mode_mask |= UNPRIV;
612 		} else if (str_has_pfx(s, TEST_TAG_LOAD_MODE_PFX)) {
613 			val = s + sizeof(TEST_TAG_LOAD_MODE_PFX) - 1;
614 			if (strcmp(val, "jited") == 0) {
615 				load_mask = JITED;
616 			} else if (strcmp(val, "no_jited") == 0) {
617 				load_mask = NO_JITED;
618 			} else {
619 				PRINT_FAIL("bad load spec: '%s'", val);
620 				err = -EINVAL;
621 				goto cleanup;
622 			}
623 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_STDERR_PFX))) {
624 			err = push_disasm_msg(msg, &stderr_on_next_line,
625 					      &spec->priv.stderr);
626 			if (err)
627 				goto cleanup;
628 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_STDERR_PFX_UNPRIV))) {
629 			err = push_disasm_msg(msg, &unpriv_stderr_on_next_line,
630 					      &spec->unpriv.stderr);
631 			if (err)
632 				goto cleanup;
633 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_STDOUT_PFX))) {
634 			err = push_disasm_msg(msg, &stdout_on_next_line,
635 					      &spec->priv.stdout);
636 			if (err)
637 				goto cleanup;
638 		} else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_STDOUT_PFX_UNPRIV))) {
639 			err = push_disasm_msg(msg, &unpriv_stdout_on_next_line,
640 					      &spec->unpriv.stdout);
641 			if (err)
642 				goto cleanup;
643 		} else if (str_has_pfx(s, TEST_TAG_LINEAR_SIZE)) {
644 			switch (bpf_program__type(prog)) {
645 			case BPF_PROG_TYPE_SCHED_ACT:
646 			case BPF_PROG_TYPE_SCHED_CLS:
647 			case BPF_PROG_TYPE_CGROUP_SKB:
648 				val = s + sizeof(TEST_TAG_LINEAR_SIZE) - 1;
649 				err = parse_int(val, &spec->linear_sz, "test linear size");
650 				if (err)
651 					goto cleanup;
652 				break;
653 			default:
654 				PRINT_FAIL("__linear_size for unsupported program type");
655 				err = -EINVAL;
656 				goto cleanup;
657 			}
658 		}
659 	}
660 
661 	spec->arch_mask = arch_mask ?: -1;
662 	spec->load_mask = load_mask ?: (JITED | NO_JITED);
663 
664 	if (spec->mode_mask == 0)
665 		spec->mode_mask = PRIV;
666 
667 	if (spec->mode_mask & PRIV) {
668 		spec->priv.name = strdup(spec->prog_name);
669 		if (!spec->priv.name) {
670 			PRINT_FAIL("failed to allocate memory for priv.name\n");
671 			err = -ENOMEM;
672 			goto cleanup;
673 		}
674 
675 		if (description) {
676 			spec->priv.description = strdup(description);
677 			if (!spec->priv.description) {
678 				PRINT_FAIL("failed to allocate memory for priv.description\n");
679 				err = -ENOMEM;
680 				goto cleanup;
681 			}
682 		}
683 	}
684 
685 	if (spec->mode_mask & UNPRIV) {
686 		int name_len = strlen(spec->prog_name);
687 		const char *suffix = " @unpriv";
688 		int suffix_len = strlen(suffix);
689 		char *name;
690 
691 		name = malloc(name_len + suffix_len + 1);
692 		if (!name) {
693 			PRINT_FAIL("failed to allocate memory for unpriv.name\n");
694 			err = -ENOMEM;
695 			goto cleanup;
696 		}
697 
698 		strcpy(name, spec->prog_name);
699 		strcpy(&name[name_len], suffix);
700 		spec->unpriv.name = name;
701 
702 		if (description) {
703 			int descr_len = strlen(description);
704 			char *descr;
705 
706 			descr = malloc(descr_len + suffix_len + 1);
707 			if (!descr) {
708 				PRINT_FAIL("failed to allocate memory for unpriv.description\n");
709 				err = -ENOMEM;
710 				goto cleanup;
711 			}
712 
713 			strcpy(descr, description);
714 			strcpy(&descr[descr_len], suffix);
715 			spec->unpriv.description = descr;
716 		}
717 	}
718 
719 	if (spec->mode_mask & (PRIV | UNPRIV)) {
720 		if (!has_unpriv_result)
721 			spec->unpriv.expect_failure = spec->priv.expect_failure;
722 
723 		if (!has_unpriv_retval) {
724 			spec->unpriv.retval = spec->priv.retval;
725 			spec->unpriv.execute = spec->priv.execute;
726 		}
727 
728 		if (spec->unpriv.expect_msgs.cnt == 0)
729 			clone_msgs(&spec->priv.expect_msgs, &spec->unpriv.expect_msgs);
730 		if (spec->unpriv.expect_xlated.cnt == 0)
731 			clone_msgs(&spec->priv.expect_xlated, &spec->unpriv.expect_xlated);
732 		if (spec->unpriv.jited.cnt == 0)
733 			clone_msgs(&spec->priv.jited, &spec->unpriv.jited);
734 		if (spec->unpriv.stderr.cnt == 0)
735 			clone_msgs(&spec->priv.stderr, &spec->unpriv.stderr);
736 		if (spec->unpriv.stdout.cnt == 0)
737 			clone_msgs(&spec->priv.stdout, &spec->unpriv.stdout);
738 	}
739 
740 	spec->valid = true;
741 
742 	return 0;
743 
744 cleanup:
745 	free_test_spec(spec);
746 	return err;
747 }
748 
749 static void prepare_case(struct test_loader *tester,
750 			 struct test_spec *spec,
751 			 struct bpf_object *obj,
752 			 struct bpf_program *prog)
753 {
754 	int min_log_level = 0, prog_flags;
755 
756 	if (env.verbosity > VERBOSE_NONE)
757 		min_log_level = 1;
758 	if (env.verbosity > VERBOSE_VERY)
759 		min_log_level = 2;
760 
761 	bpf_program__set_log_buf(prog, tester->log_buf, tester->log_buf_sz);
762 
763 	/* Make sure we set at least minimal log level, unless test requires
764 	 * even higher level already. Make sure to preserve independent log
765 	 * level 4 (verifier stats), though.
766 	 */
767 	if ((spec->log_level & 3) < min_log_level)
768 		bpf_program__set_log_level(prog, (spec->log_level & 4) | min_log_level);
769 	else
770 		bpf_program__set_log_level(prog, spec->log_level);
771 
772 	prog_flags = bpf_program__flags(prog);
773 	bpf_program__set_flags(prog, prog_flags | spec->prog_flags);
774 
775 	tester->log_buf[0] = '\0';
776 }
777 
778 static void emit_verifier_log(const char *log_buf, bool force)
779 {
780 	if (!force && env.verbosity == VERBOSE_NONE)
781 		return;
782 	fprintf(stdout, "VERIFIER LOG:\n=============\n%s=============\n", log_buf);
783 }
784 
785 static void emit_xlated(const char *xlated, bool force)
786 {
787 	if (!force && env.verbosity == VERBOSE_NONE)
788 		return;
789 	fprintf(stdout, "XLATED:\n=============\n%s=============\n", xlated);
790 }
791 
792 static void emit_jited(const char *jited, bool force)
793 {
794 	if (!force && env.verbosity == VERBOSE_NONE)
795 		return;
796 	fprintf(stdout, "JITED:\n=============\n%s=============\n", jited);
797 }
798 
799 static void emit_stderr(const char *stderr, bool force)
800 {
801 	if (!force && env.verbosity == VERBOSE_NONE)
802 		return;
803 	fprintf(stdout, "STDERR:\n=============\n%s=============\n", stderr);
804 }
805 
806 static void emit_stdout(const char *bpf_stdout, bool force)
807 {
808 	if (!force && env.verbosity == VERBOSE_NONE)
809 		return;
810 	fprintf(stdout, "STDOUT:\n=============\n%s=============\n", bpf_stdout);
811 }
812 
813 static const char *match_msg(struct expect_msg *msg, const char **log)
814 {
815 	const char *match = NULL;
816 	regmatch_t reg_match[1];
817 	int err;
818 
819 	if (!msg->is_regex) {
820 		match = strstr(*log, msg->substr);
821 		if (match)
822 			*log = match + strlen(msg->substr);
823 	} else {
824 		err = regexec(&msg->regex, *log, 1, reg_match, 0);
825 		if (err == 0) {
826 			match = *log + reg_match[0].rm_so;
827 			*log += reg_match[0].rm_eo;
828 		}
829 	}
830 	return match;
831 }
832 
833 static int count_lines(const char *start, const char *end)
834 {
835 	const char *tmp;
836 	int n = 0;
837 
838 	for (tmp = start; tmp < end; ++tmp)
839 		if (*tmp == '\n')
840 			n++;
841 	return n;
842 }
843 
844 struct match {
845 	const char *start;
846 	const char *end;
847 	int line;
848 };
849 
850 /*
851  * Positive messages are matched sequentially, each next message
852  * is looked for starting from the end of a previous matched one.
853  */
854 static void match_positive_msgs(const char *log, struct expected_msgs *msgs, struct match *matches)
855 {
856 	const char *prev_match;
857 	int i, line;
858 
859 	prev_match = log;
860 	line = 0;
861 	for (i = 0; i < msgs->cnt; i++) {
862 		struct expect_msg *msg = &msgs->patterns[i];
863 		const char *match = NULL;
864 
865 		if (msg->negative)
866 			continue;
867 
868 		match = match_msg(msg, &log);
869 		if (match) {
870 			line += count_lines(prev_match, match);
871 			matches[i].start = match;
872 			matches[i].end   = log;
873 			matches[i].line  = line;
874 			prev_match = match;
875 		}
876 	}
877 }
878 
879 /*
880  * Each negative messages N located between positive messages P1 and P2
881  * is matched in the span P1.end .. P2.start. Consequently, negative messages
882  * are unordered within the span.
883  */
884 static void match_negative_msgs(const char *log, struct expected_msgs *msgs, struct match *matches)
885 {
886 	const char *start = log, *end, *next, *match;
887 	const char *log_end = log + strlen(log);
888 	int i, j, next_positive;
889 
890 	for (i = 0; i < msgs->cnt; i++) {
891 		struct expect_msg *msg = &msgs->patterns[i];
892 
893 		/* positive message bumps span start */
894 		if (!msg->negative) {
895 			start = matches[i].end ?: start;
896 			continue;
897 		}
898 
899 		/* count stride of negative patterns and adjust span end */
900 		end = log_end;
901 		for (next_positive = i + 1; next_positive < msgs->cnt; next_positive++) {
902 			if (!msgs->patterns[next_positive].negative) {
903 				end = matches[next_positive].start;
904 				break;
905 			}
906 		}
907 
908 		/* try matching negative messages within identified span */
909 		for (j = i; j < next_positive; j++) {
910 			next = start;
911 			match = match_msg(msg, &next);
912 			if (match && next <= end) {
913 				matches[j].start = match;
914 				matches[j].end = next;
915 			}
916 		}
917 
918 		/* -1 to account for i++ */
919 		i = next_positive - 1;
920 	}
921 }
922 
923 void validate_msgs(const char *log_buf, struct expected_msgs *msgs,
924 		   void (*emit_fn)(const char *buf, bool force))
925 {
926 	struct match matches[msgs->cnt];
927 	struct match *prev_match = NULL;
928 	int i, j;
929 
930 	memset(matches, 0, sizeof(*matches) * msgs->cnt);
931 	match_positive_msgs(log_buf, msgs, matches);
932 	match_negative_msgs(log_buf, msgs, matches);
933 
934 	for (i = 0; i < msgs->cnt; i++) {
935 		struct expect_msg *msg = &msgs->patterns[i];
936 		struct match *match = &matches[i];
937 		const char *pat_status;
938 		bool unexpected;
939 		bool wrong_line;
940 		bool no_match;
941 
942 		no_match   = !msg->negative && !match->start;
943 		wrong_line = !msg->negative &&
944 			     msg->on_next_line &&
945 			     prev_match && prev_match->line + 1 != match->line;
946 		unexpected = msg->negative && match->start;
947 		if (no_match || wrong_line || unexpected) {
948 			PRINT_FAIL("expect_msg\n");
949 			if (env.verbosity == VERBOSE_NONE)
950 				emit_fn(log_buf, true /*force*/);
951 			for (j = 0; j <= i; j++) {
952 				msg = &msgs->patterns[j];
953 				if (j < i)
954 					pat_status = "MATCHED   ";
955 				else if (wrong_line)
956 					pat_status = "WRONG LINE";
957 				else if (no_match)
958 					pat_status = "EXPECTED  ";
959 				else
960 					pat_status = "UNEXPECTED";
961 				msg = &msgs->patterns[j];
962 				fprintf(stderr, "%s %s: '%s'\n",
963 					pat_status,
964 					msg->is_regex ? " REGEX" : "SUBSTR",
965 					msg->substr);
966 			}
967 			if (wrong_line) {
968 				fprintf(stderr,
969 					"expecting match at line %d, actual match is at line %d\n",
970 					prev_match->line + 1, match->line);
971 			}
972 			break;
973 		}
974 
975 		if (!msg->negative)
976 			prev_match = match;
977 	}
978 }
979 
980 struct cap_state {
981 	__u64 old_caps;
982 	bool initialized;
983 };
984 
985 static int drop_capabilities(struct cap_state *caps)
986 {
987 	const __u64 caps_to_drop = (1ULL << CAP_SYS_ADMIN | 1ULL << CAP_NET_ADMIN |
988 				    1ULL << CAP_PERFMON   | 1ULL << CAP_BPF);
989 	int err;
990 
991 	err = cap_disable_effective(caps_to_drop, &caps->old_caps);
992 	if (err) {
993 		PRINT_FAIL("failed to drop capabilities: %i, %s\n", err, strerror(-err));
994 		return err;
995 	}
996 
997 	caps->initialized = true;
998 	return 0;
999 }
1000 
1001 static int restore_capabilities(struct cap_state *caps)
1002 {
1003 	int err;
1004 
1005 	if (!caps->initialized)
1006 		return 0;
1007 
1008 	err = cap_enable_effective(caps->old_caps, NULL);
1009 	if (err)
1010 		PRINT_FAIL("failed to restore capabilities: %i, %s\n", err, strerror(-err));
1011 	caps->initialized = false;
1012 	return err;
1013 }
1014 
1015 static bool can_execute_unpriv(struct test_loader *tester, struct test_spec *spec)
1016 {
1017 	if (sysctl_unpriv_disabled < 0)
1018 		sysctl_unpriv_disabled = get_unpriv_disabled() ? 1 : 0;
1019 	if (sysctl_unpriv_disabled)
1020 		return false;
1021 	if ((spec->prog_flags & BPF_F_ANY_ALIGNMENT) && !EFFICIENT_UNALIGNED_ACCESS)
1022 		return false;
1023 	return true;
1024 }
1025 
1026 static bool is_unpriv_capable_map(struct bpf_map *map)
1027 {
1028 	enum bpf_map_type type;
1029 	__u32 flags;
1030 
1031 	type = bpf_map__type(map);
1032 
1033 	switch (type) {
1034 	case BPF_MAP_TYPE_HASH:
1035 	case BPF_MAP_TYPE_PERCPU_HASH:
1036 	case BPF_MAP_TYPE_HASH_OF_MAPS:
1037 		flags = bpf_map__map_flags(map);
1038 		return !(flags & BPF_F_ZERO_SEED);
1039 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1040 	case BPF_MAP_TYPE_ARRAY:
1041 	case BPF_MAP_TYPE_RINGBUF:
1042 	case BPF_MAP_TYPE_PROG_ARRAY:
1043 	case BPF_MAP_TYPE_CGROUP_ARRAY:
1044 	case BPF_MAP_TYPE_PERCPU_ARRAY:
1045 	case BPF_MAP_TYPE_USER_RINGBUF:
1046 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1047 	case BPF_MAP_TYPE_CGROUP_STORAGE:
1048 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1049 		return true;
1050 	default:
1051 		return false;
1052 	}
1053 }
1054 
1055 static int do_prog_test_run(int fd_prog, int *retval, bool empty_opts, int linear_sz)
1056 {
1057 	__u8 tmp_out[TEST_DATA_LEN << 2] = {};
1058 	__u8 tmp_in[TEST_DATA_LEN] = {};
1059 	struct __sk_buff ctx = {};
1060 	int err, saved_errno;
1061 	LIBBPF_OPTS(bpf_test_run_opts, topts,
1062 		.data_in = tmp_in,
1063 		.data_size_in = sizeof(tmp_in),
1064 		.data_out = tmp_out,
1065 		.data_size_out = sizeof(tmp_out),
1066 		.repeat = 1,
1067 	);
1068 
1069 	if (linear_sz) {
1070 		ctx.data_end = linear_sz;
1071 		topts.ctx_in = &ctx;
1072 		topts.ctx_size_in = sizeof(ctx);
1073 	}
1074 
1075 	if (empty_opts) {
1076 		memset(&topts, 0, sizeof(struct bpf_test_run_opts));
1077 		topts.sz = sizeof(struct bpf_test_run_opts);
1078 	}
1079 	err = bpf_prog_test_run_opts(fd_prog, &topts);
1080 	saved_errno = errno;
1081 
1082 	if (err) {
1083 		PRINT_FAIL("FAIL: Unexpected bpf_prog_test_run error: %d (%s) ",
1084 			   saved_errno, strerror(saved_errno));
1085 		return err;
1086 	}
1087 
1088 	ASSERT_OK(0, "bpf_prog_test_run");
1089 	*retval = topts.retval;
1090 
1091 	return 0;
1092 }
1093 
1094 static bool should_do_test_run(struct test_spec *spec, struct test_subspec *subspec)
1095 {
1096 	if (!subspec->execute)
1097 		return false;
1098 
1099 	if (subspec->expect_failure)
1100 		return false;
1101 
1102 	if ((spec->prog_flags & BPF_F_ANY_ALIGNMENT) && !EFFICIENT_UNALIGNED_ACCESS) {
1103 		if (env.verbosity != VERBOSE_NONE)
1104 			printf("alignment prevents execution\n");
1105 		return false;
1106 	}
1107 
1108 	return true;
1109 }
1110 
1111 /* Get a disassembly of BPF program after verifier applies all rewrites */
1112 static int get_xlated_program_text(int prog_fd, char *text, size_t text_sz)
1113 {
1114 	struct bpf_insn *insn_start = NULL, *insn, *insn_end;
1115 	__u32 insns_cnt = 0, i;
1116 	char buf[64];
1117 	FILE *out = NULL;
1118 	int err;
1119 
1120 	err = get_xlated_program(prog_fd, &insn_start, &insns_cnt);
1121 	if (!ASSERT_OK(err, "get_xlated_program"))
1122 		goto out;
1123 	out = fmemopen(text, text_sz, "w");
1124 	if (!ASSERT_OK_PTR(out, "open_memstream"))
1125 		goto out;
1126 	insn_end = insn_start + insns_cnt;
1127 	insn = insn_start;
1128 	while (insn < insn_end) {
1129 		i = insn - insn_start;
1130 		insn = disasm_insn(insn, buf, sizeof(buf));
1131 		fprintf(out, "%d: %s\n", i, buf);
1132 	}
1133 	fflush(out);
1134 
1135 out:
1136 	free(insn_start);
1137 	if (out)
1138 		fclose(out);
1139 	return err;
1140 }
1141 
1142 /* Read the bpf stream corresponding to the stream_id */
1143 static int get_stream(int stream_id, int prog_fd, char *text, size_t text_sz)
1144 {
1145 	LIBBPF_OPTS(bpf_prog_stream_read_opts, ropts);
1146 	int ret;
1147 
1148 	ret = bpf_prog_stream_read(prog_fd, stream_id, text, text_sz, &ropts);
1149 	ASSERT_GT(ret, 0, "stream read");
1150 	text[ret] = '\0';
1151 
1152 	return ret;
1153 }
1154 
1155 /* this function is forced noinline and has short generic name to look better
1156  * in test_progs output (in case of a failure)
1157  */
1158 static noinline
1159 void run_subtest(struct test_loader *tester,
1160 		 struct bpf_object_open_opts *open_opts,
1161 		 const void *obj_bytes,
1162 		 size_t obj_byte_cnt,
1163 		 struct test_spec *specs,
1164 		 struct test_spec *spec,
1165 		 bool unpriv)
1166 {
1167 	struct test_subspec *subspec = unpriv ? &spec->unpriv : &spec->priv;
1168 	int current_runtime = is_jit_enabled() ? JITED : NO_JITED;
1169 	struct bpf_program *tprog = NULL, *tprog_iter;
1170 	struct bpf_link *link, *links[32] = {};
1171 	struct test_spec *spec_iter;
1172 	struct cap_state caps = {};
1173 	struct bpf_object *tobj;
1174 	struct bpf_map *map;
1175 	int retval, err, i;
1176 	int links_cnt = 0;
1177 	bool should_load;
1178 
1179 	if (!test__start_subtest_with_desc(subspec->name, subspec->description))
1180 		return;
1181 
1182 	if ((get_current_arch() & spec->arch_mask) == 0) {
1183 		test__skip();
1184 		return;
1185 	}
1186 
1187 	if ((current_runtime & spec->load_mask) == 0) {
1188 		test__skip();
1189 		return;
1190 	}
1191 
1192 	if (unpriv) {
1193 		if (!can_execute_unpriv(tester, spec)) {
1194 			test__skip();
1195 			test__end_subtest();
1196 			return;
1197 		}
1198 		if (drop_capabilities(&caps)) {
1199 			test__end_subtest();
1200 			return;
1201 		}
1202 		if (subspec->caps) {
1203 			err = cap_enable_effective(subspec->caps, NULL);
1204 			if (err) {
1205 				PRINT_FAIL("failed to set capabilities: %i, %s\n", err, strerror(-err));
1206 				goto subtest_cleanup;
1207 			}
1208 		}
1209 	}
1210 
1211 	/* Implicitly reset to NULL if next test case doesn't specify */
1212 	open_opts->btf_custom_path = spec->btf_custom_path;
1213 
1214 	tobj = bpf_object__open_mem(obj_bytes, obj_byte_cnt, open_opts);
1215 	if (!ASSERT_OK_PTR(tobj, "obj_open_mem")) /* shouldn't happen */
1216 		goto subtest_cleanup;
1217 
1218 	i = 0;
1219 	bpf_object__for_each_program(tprog_iter, tobj) {
1220 		spec_iter = &specs[i++];
1221 		should_load = false;
1222 
1223 		if (spec_iter->valid) {
1224 			if (strcmp(bpf_program__name(tprog_iter), spec->prog_name) == 0) {
1225 				tprog = tprog_iter;
1226 				should_load = true;
1227 			}
1228 
1229 			if (spec_iter->auxiliary &&
1230 			    spec_iter->mode_mask & (unpriv ? UNPRIV : PRIV))
1231 				should_load = true;
1232 		}
1233 
1234 		bpf_program__set_autoload(tprog_iter, should_load);
1235 	}
1236 
1237 	prepare_case(tester, spec, tobj, tprog);
1238 
1239 	/* By default bpf_object__load() automatically creates all
1240 	 * maps declared in the skeleton. Some map types are only
1241 	 * allowed in priv mode. Disable autoload for such maps in
1242 	 * unpriv mode.
1243 	 */
1244 	bpf_object__for_each_map(map, tobj)
1245 		bpf_map__set_autocreate(map, !unpriv || is_unpriv_capable_map(map));
1246 
1247 	err = bpf_object__load(tobj);
1248 	if (subspec->expect_failure) {
1249 		if (!ASSERT_ERR(err, "unexpected_load_success")) {
1250 			emit_verifier_log(tester->log_buf, false /*force*/);
1251 			goto tobj_cleanup;
1252 		}
1253 	} else {
1254 		if (!ASSERT_OK(err, "unexpected_load_failure")) {
1255 			emit_verifier_log(tester->log_buf, true /*force*/);
1256 			goto tobj_cleanup;
1257 		}
1258 	}
1259 	emit_verifier_log(tester->log_buf, false /*force*/);
1260 	validate_msgs(tester->log_buf, &subspec->expect_msgs, emit_verifier_log);
1261 
1262 	/* Restore capabilities because the kernel will silently ignore requests
1263 	 * for program info (such as xlated program text) if we are not
1264 	 * bpf-capable. Also, for some reason test_verifier executes programs
1265 	 * with all capabilities restored. Do the same here.
1266 	 */
1267 	if (restore_capabilities(&caps))
1268 		goto tobj_cleanup;
1269 
1270 	if (subspec->expect_xlated.cnt) {
1271 		err = get_xlated_program_text(bpf_program__fd(tprog),
1272 					      tester->log_buf, tester->log_buf_sz);
1273 		if (err)
1274 			goto tobj_cleanup;
1275 		emit_xlated(tester->log_buf, false /*force*/);
1276 		validate_msgs(tester->log_buf, &subspec->expect_xlated, emit_xlated);
1277 	}
1278 
1279 	if (subspec->jited.cnt) {
1280 		err = get_jited_program_text(bpf_program__fd(tprog),
1281 					     tester->log_buf, tester->log_buf_sz);
1282 		if (err == -EOPNOTSUPP) {
1283 			printf("%s:SKIP: jited programs disassembly is not supported,\n", __func__);
1284 			printf("%s:SKIP: tests are built w/o LLVM development libs\n", __func__);
1285 			test__skip();
1286 			goto tobj_cleanup;
1287 		}
1288 		if (!ASSERT_EQ(err, 0, "get_jited_program_text"))
1289 			goto tobj_cleanup;
1290 		emit_jited(tester->log_buf, false /*force*/);
1291 		validate_msgs(tester->log_buf, &subspec->jited, emit_jited);
1292 	}
1293 
1294 	if (should_do_test_run(spec, subspec)) {
1295 		/* Do bpf_map__attach_struct_ops() for each struct_ops map.
1296 		 * This should trigger bpf_struct_ops->reg callback on kernel side.
1297 		 */
1298 		bpf_object__for_each_map(map, tobj) {
1299 			if (!bpf_map__autocreate(map) ||
1300 			    bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
1301 				continue;
1302 			if (links_cnt >= ARRAY_SIZE(links)) {
1303 				PRINT_FAIL("too many struct_ops maps");
1304 				goto tobj_cleanup;
1305 			}
1306 			link = bpf_map__attach_struct_ops(map);
1307 			if (!link) {
1308 				PRINT_FAIL("bpf_map__attach_struct_ops failed for map %s: err=%d\n",
1309 					   bpf_map__name(map), -errno);
1310 				goto tobj_cleanup;
1311 			}
1312 			links[links_cnt++] = link;
1313 		}
1314 
1315 		if (tester->pre_execution_cb) {
1316 			err = tester->pre_execution_cb(tobj);
1317 			if (err) {
1318 				PRINT_FAIL("pre_execution_cb failed: %d\n", err);
1319 				goto tobj_cleanup;
1320 			}
1321 		}
1322 
1323 		err = do_prog_test_run(bpf_program__fd(tprog), &retval,
1324 				       bpf_program__type(tprog) == BPF_PROG_TYPE_SYSCALL ? true : false,
1325 				       spec->linear_sz);
1326 		if (!err && retval != subspec->retval && subspec->retval != POINTER_VALUE) {
1327 			PRINT_FAIL("Unexpected retval: %d != %d\n", retval, subspec->retval);
1328 			goto tobj_cleanup;
1329 		}
1330 
1331 		if (subspec->stderr.cnt) {
1332 			err = get_stream(2, bpf_program__fd(tprog),
1333 					 tester->log_buf, tester->log_buf_sz);
1334 			if (err <= 0) {
1335 				PRINT_FAIL("Unexpected retval from get_stream(): %d, errno = %d\n",
1336 					   err, errno);
1337 				goto tobj_cleanup;
1338 			}
1339 			emit_stderr(tester->log_buf, false /*force*/);
1340 			validate_msgs(tester->log_buf, &subspec->stderr, emit_stderr);
1341 		}
1342 
1343 		if (subspec->stdout.cnt) {
1344 			err = get_stream(1, bpf_program__fd(tprog),
1345 					 tester->log_buf, tester->log_buf_sz);
1346 			if (err <= 0) {
1347 				PRINT_FAIL("Unexpected retval from get_stream(): %d, errno = %d\n",
1348 					   err, errno);
1349 				goto tobj_cleanup;
1350 			}
1351 			emit_stdout(tester->log_buf, false /*force*/);
1352 			validate_msgs(tester->log_buf, &subspec->stdout, emit_stdout);
1353 		}
1354 
1355 		/* redo bpf_map__attach_struct_ops for each test */
1356 		while (links_cnt > 0)
1357 			bpf_link__destroy(links[--links_cnt]);
1358 	}
1359 
1360 tobj_cleanup:
1361 	while (links_cnt > 0)
1362 		bpf_link__destroy(links[--links_cnt]);
1363 	bpf_object__close(tobj);
1364 subtest_cleanup:
1365 	test__end_subtest();
1366 	restore_capabilities(&caps);
1367 }
1368 
1369 static void process_subtest(struct test_loader *tester,
1370 			    const char *skel_name,
1371 			    skel_elf_bytes_fn elf_bytes_factory)
1372 {
1373 	LIBBPF_OPTS(bpf_object_open_opts, open_opts, .object_name = skel_name);
1374 	struct test_spec *specs = NULL;
1375 	struct bpf_object *obj = NULL;
1376 	struct bpf_program *prog;
1377 	const void *obj_bytes;
1378 	int err, i, nr_progs;
1379 	size_t obj_byte_cnt;
1380 
1381 	if (tester_init(tester) < 0)
1382 		return; /* failed to initialize tester */
1383 
1384 	obj_bytes = elf_bytes_factory(&obj_byte_cnt);
1385 	obj = bpf_object__open_mem(obj_bytes, obj_byte_cnt, &open_opts);
1386 	if (!ASSERT_OK_PTR(obj, "obj_open_mem"))
1387 		return;
1388 
1389 	nr_progs = 0;
1390 	bpf_object__for_each_program(prog, obj)
1391 		++nr_progs;
1392 
1393 	specs = calloc(nr_progs, sizeof(struct test_spec));
1394 	if (!ASSERT_OK_PTR(specs, "specs_alloc"))
1395 		return;
1396 
1397 	i = 0;
1398 	bpf_object__for_each_program(prog, obj) {
1399 		/* ignore tests for which  we can't derive test specification */
1400 		err = parse_test_spec(tester, obj, prog, &specs[i++]);
1401 		if (err)
1402 			PRINT_FAIL("Can't parse test spec for program '%s'\n",
1403 				   bpf_program__name(prog));
1404 	}
1405 
1406 	i = 0;
1407 	bpf_object__for_each_program(prog, obj) {
1408 		struct test_spec *spec = &specs[i++];
1409 
1410 		if (!spec->valid || spec->auxiliary)
1411 			continue;
1412 
1413 		if (spec->mode_mask & PRIV)
1414 			run_subtest(tester, &open_opts, obj_bytes, obj_byte_cnt,
1415 				    specs, spec, false);
1416 		if (spec->mode_mask & UNPRIV)
1417 			run_subtest(tester, &open_opts, obj_bytes, obj_byte_cnt,
1418 				    specs, spec, true);
1419 
1420 	}
1421 
1422 	for (i = 0; i < nr_progs; ++i)
1423 		free_test_spec(&specs[i]);
1424 	free(specs);
1425 	bpf_object__close(obj);
1426 }
1427 
1428 void test_loader__run_subtests(struct test_loader *tester,
1429 			       const char *skel_name,
1430 			       skel_elf_bytes_fn elf_bytes_factory)
1431 {
1432 	/* see comment in run_subtest() for why we do this function nesting */
1433 	process_subtest(tester, skel_name, elf_bytes_factory);
1434 }
1435