1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2021 Facebook */
3 #include <test_progs.h>
4 #include "test_legacy_printk.skel.h"
5 
execute_one_variant(bool legacy)6 static int execute_one_variant(bool legacy)
7 {
8 	struct test_legacy_printk *skel;
9 	int err, zero = 0, my_pid = getpid(), res, map_fd;
10 
11 	skel = test_legacy_printk__open();
12 	if (!ASSERT_OK_PTR(skel, "skel_open"))
13 		return -errno;
14 
15 	bpf_program__set_autoload(skel->progs.handle_legacy, legacy);
16 	bpf_program__set_autoload(skel->progs.handle_modern, !legacy);
17 
18 	err = test_legacy_printk__load(skel);
19 	/* no ASSERT_OK, we expect one of two variants can fail here */
20 	if (err)
21 		goto err_out;
22 
23 	if (legacy) {
24 		map_fd = bpf_map__fd(skel->maps.my_pid_map);
25 		err = bpf_map_update_elem(map_fd, &zero, &my_pid, BPF_ANY);
26 		if (!ASSERT_OK(err, "my_pid_map_update"))
27 			goto err_out;
28 		err = bpf_map_lookup_elem(map_fd, &zero, &res);
29 	} else {
30 		skel->bss->my_pid_var = my_pid;
31 	}
32 
33 	err = test_legacy_printk__attach(skel);
34 	if (!ASSERT_OK(err, "skel_attach"))
35 		goto err_out;
36 
37 	usleep(1); /* trigger */
38 
39 	if (legacy) {
40 		map_fd = bpf_map__fd(skel->maps.res_map);
41 		err = bpf_map_lookup_elem(map_fd, &zero, &res);
42 		if (!ASSERT_OK(err, "res_map_lookup"))
43 			goto err_out;
44 	} else {
45 		res = skel->bss->res_var;
46 	}
47 
48 	if (!ASSERT_GT(res, 0, "res")) {
49 		err = -EINVAL;
50 		goto err_out;
51 	}
52 
53 err_out:
54 	test_legacy_printk__destroy(skel);
55 	return err;
56 }
57 
test_legacy_printk(void)58 void test_legacy_printk(void)
59 {
60 	/* legacy variant should work everywhere */
61 	ASSERT_OK(execute_one_variant(true /* legacy */), "legacy_case");
62 
63 	/* execute modern variant, can fail the load on old kernels */
64 	execute_one_variant(false);
65 }
66