1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2021 Facebook */
3 #define _GNU_SOURCE
4 #include <sched.h>
5 #include <test_progs.h>
6 #include <time.h>
7 #include <sys/mman.h>
8 #include <sys/syscall.h>
9 #include "fexit_sleep.lskel.h"
10 
11 static int do_sleep(void *skel)
12 {
13 	struct fexit_sleep_lskel *fexit_skel = skel;
14 	struct timespec ts1 = { .tv_nsec = 1 };
15 	struct timespec ts2 = { .tv_sec = 10 };
16 
17 	fexit_skel->bss->pid = getpid();
18 	(void)syscall(__NR_nanosleep, &ts1, NULL);
19 	(void)syscall(__NR_nanosleep, &ts2, NULL);
20 	return 0;
21 }
22 
23 #define STACK_SIZE (1024 * 1024)
24 static char child_stack[STACK_SIZE];
25 
26 void test_fexit_sleep(void)
27 {
28 	struct fexit_sleep_lskel *fexit_skel = NULL;
29 	int wstatus, duration = 0;
30 	pid_t cpid;
31 	int err, fexit_cnt;
32 
33 	fexit_skel = fexit_sleep_lskel__open_and_load();
34 	if (CHECK(!fexit_skel, "fexit_skel_load", "fexit skeleton failed\n"))
35 		goto cleanup;
36 
37 	err = fexit_sleep_lskel__attach(fexit_skel);
38 	if (CHECK(err, "fexit_attach", "fexit attach failed: %d\n", err))
39 		goto cleanup;
40 
41 	cpid = clone(do_sleep, child_stack + STACK_SIZE, CLONE_FILES | SIGCHLD, fexit_skel);
42 	if (CHECK(cpid == -1, "clone", "%s\n", strerror(errno)))
43 		goto cleanup;
44 
45 	/* wait until first sys_nanosleep ends and second sys_nanosleep starts */
46 	while (READ_ONCE(fexit_skel->bss->fentry_cnt) != 2);
47 	fexit_cnt = READ_ONCE(fexit_skel->bss->fexit_cnt);
48 	if (CHECK(fexit_cnt != 1, "fexit_cnt", "%d", fexit_cnt))
49 		goto cleanup;
50 
51 	/* close progs and detach them. That will trigger two nop5->jmp5 rewrites
52 	 * in the trampolines to skip nanosleep_fexit prog.
53 	 * The nanosleep_fentry prog will get detached first.
54 	 * The nanosleep_fexit prog will get detached second.
55 	 * Detaching will trigger freeing of both progs JITed images.
56 	 * There will be two dying bpf_tramp_image-s, but only the initial
57 	 * bpf_tramp_image (with both _fentry and _fexit progs will be stuck
58 	 * waiting for percpu_ref_kill to confirm). The other one
59 	 * will be freed quickly.
60 	 */
61 	close(fexit_skel->progs.nanosleep_fentry.prog_fd);
62 	close(fexit_skel->progs.nanosleep_fexit.prog_fd);
63 	fexit_sleep_lskel__detach(fexit_skel);
64 
65 	/* kill the thread to unwind sys_nanosleep stack through the trampoline */
66 	kill(cpid, 9);
67 
68 	if (CHECK(waitpid(cpid, &wstatus, 0) == -1, "waitpid", "%s\n", strerror(errno)))
69 		goto cleanup;
70 	if (CHECK(WEXITSTATUS(wstatus) != 0, "exitstatus", "failed"))
71 		goto cleanup;
72 
73 	/* The bypassed nanosleep_fexit prog shouldn't have executed.
74 	 * Unlike progs the maps were not freed and directly accessible.
75 	 */
76 	fexit_cnt = READ_ONCE(fexit_skel->bss->fexit_cnt);
77 	if (CHECK(fexit_cnt != 1, "fexit_cnt", "%d", fexit_cnt))
78 		goto cleanup;
79 
80 cleanup:
81 	fexit_sleep_lskel__destroy(fexit_skel);
82 }
83