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