1 /* SPDX-License-Identifier: GPL-2.0 */
2 
3 #ifndef _CLONE3_SELFTESTS_H
4 #define _CLONE3_SELFTESTS_H
5 
6 #define _GNU_SOURCE
7 #include <sched.h>
8 #include <linux/sched.h>
9 #include <linux/types.h>
10 #include <stdint.h>
11 #include <syscall.h>
12 #include <sys/wait.h>
13 
14 #include "../kselftest.h"
15 
16 #define ptr_to_u64(ptr) ((__u64)((uintptr_t)(ptr)))
17 
18 #ifndef CLONE_INTO_CGROUP
19 #define CLONE_INTO_CGROUP 0x200000000ULL /* Clone into a specific cgroup given the right permissions. */
20 #endif
21 
22 #ifndef CLONE_ARGS_SIZE_VER0
23 #define CLONE_ARGS_SIZE_VER0 64
24 #endif
25 
26 #ifndef __NR_clone3
27 #define __NR_clone3 -1
28 struct clone_args {
29 	__aligned_u64 flags;
30 	__aligned_u64 pidfd;
31 	__aligned_u64 child_tid;
32 	__aligned_u64 parent_tid;
33 	__aligned_u64 exit_signal;
34 	__aligned_u64 stack;
35 	__aligned_u64 stack_size;
36 	__aligned_u64 tls;
37 #define CLONE_ARGS_SIZE_VER1 80
38 	__aligned_u64 set_tid;
39 	__aligned_u64 set_tid_size;
40 #define CLONE_ARGS_SIZE_VER2 88
41 	__aligned_u64 cgroup;
42 };
43 #endif /* __NR_clone3 */
44 
45 static pid_t sys_clone3(struct clone_args *args, size_t size)
46 {
47 	fflush(stdout);
48 	fflush(stderr);
49 	return syscall(__NR_clone3, args, size);
50 }
51 
52 static inline void test_clone3_supported(void)
53 {
54 	pid_t pid;
55 	struct clone_args args = {};
56 
57 	if (__NR_clone3 < 0)
58 		ksft_exit_skip("clone3() syscall is not supported\n");
59 
60 	/* Set to something that will always cause EINVAL. */
61 	args.exit_signal = -1;
62 	pid = sys_clone3(&args, sizeof(args));
63 	if (!pid)
64 		exit(EXIT_SUCCESS);
65 
66 	if (pid > 0) {
67 		wait(NULL);
68 		ksft_exit_fail_msg(
69 			"Managed to create child process with invalid exit_signal\n");
70 	}
71 
72 	if (errno == ENOSYS)
73 		ksft_exit_skip("clone3() syscall is not supported\n");
74 
75 	ksft_print_msg("clone3() syscall supported\n");
76 }
77 
78 #endif /* _CLONE3_SELFTESTS_H */
79