1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2020 Facebook */
3 #include <test_progs.h>
4 #include "test_subprogs.skel.h"
5 #include "test_subprogs_unused.skel.h"
6 
7 struct toggler_ctx {
8 	int fd;
9 	bool stop;
10 };
11 
toggle_jit_harden(void * arg)12 static void *toggle_jit_harden(void *arg)
13 {
14 	struct toggler_ctx *ctx = arg;
15 	char two = '2';
16 	char zero = '0';
17 
18 	while (!ctx->stop) {
19 		lseek(ctx->fd, SEEK_SET, 0);
20 		write(ctx->fd, &two, sizeof(two));
21 		lseek(ctx->fd, SEEK_SET, 0);
22 		write(ctx->fd, &zero, sizeof(zero));
23 	}
24 
25 	return NULL;
26 }
27 
test_subprogs_with_jit_harden_toggling(void)28 static void test_subprogs_with_jit_harden_toggling(void)
29 {
30 	struct toggler_ctx ctx;
31 	pthread_t toggler;
32 	int err;
33 	unsigned int i, loop = 10;
34 
35 	ctx.fd = open("/proc/sys/net/core/bpf_jit_harden", O_RDWR);
36 	if (!ASSERT_GE(ctx.fd, 0, "open bpf_jit_harden"))
37 		return;
38 
39 	ctx.stop = false;
40 	err = pthread_create(&toggler, NULL, toggle_jit_harden, &ctx);
41 	if (!ASSERT_OK(err, "new toggler"))
42 		goto out;
43 
44 	/* Make toggler thread to run */
45 	usleep(1);
46 
47 	for (i = 0; i < loop; i++) {
48 		struct test_subprogs *skel = test_subprogs__open_and_load();
49 
50 		if (!ASSERT_OK_PTR(skel, "skel open"))
51 			break;
52 		test_subprogs__destroy(skel);
53 	}
54 
55 	ctx.stop = true;
56 	pthread_join(toggler, NULL);
57 out:
58 	close(ctx.fd);
59 }
60 
test_subprogs_alone(void)61 static void test_subprogs_alone(void)
62 {
63 	struct test_subprogs *skel;
64 	struct test_subprogs_unused *skel2;
65 	int err;
66 
67 	skel = test_subprogs__open_and_load();
68 	if (!ASSERT_OK_PTR(skel, "skel_open"))
69 		return;
70 
71 	err = test_subprogs__attach(skel);
72 	if (!ASSERT_OK(err, "skel attach"))
73 		goto cleanup;
74 
75 	usleep(1);
76 
77 	ASSERT_EQ(skel->bss->res1, 12, "res1");
78 	ASSERT_EQ(skel->bss->res2, 17, "res2");
79 	ASSERT_EQ(skel->bss->res3, 19, "res3");
80 	ASSERT_EQ(skel->bss->res4, 36, "res4");
81 
82 	skel2 = test_subprogs_unused__open_and_load();
83 	ASSERT_OK_PTR(skel2, "unused_progs_skel");
84 	test_subprogs_unused__destroy(skel2);
85 
86 cleanup:
87 	test_subprogs__destroy(skel);
88 }
89 
test_subprogs(void)90 void test_subprogs(void)
91 {
92 	if (test__start_subtest("subprogs_alone"))
93 		test_subprogs_alone();
94 	if (test__start_subtest("subprogs_and_jit_harden"))
95 		test_subprogs_with_jit_harden_toggling();
96 }
97