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