xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/clone/clone09.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2017 Oracle and/or its affiliates. All Rights Reserved.
4  */
5 
6 #define _GNU_SOURCE
7 #include <stdlib.h>
8 #include <errno.h>
9 
10 #include "tst_test.h"
11 #include "clone_platform.h"
12 #include "lapi/syscalls.h"
13 #include "lapi/sched.h"
14 
15 static void *child_stack;
16 static int sysctl_net = -1;
17 static int sysctl_net_new = -1;
18 static const char sysctl_path[] = "/proc/sys/net/ipv4/conf/lo/tag";
19 static const char sysctl_path_def[] = "/proc/sys/net/ipv4/conf/default/tag";
20 static int flags = CLONE_NEWNET | CLONE_VM | SIGCHLD;
21 
setup(void)22 static void setup(void)
23 {
24 	child_stack = SAFE_MALLOC(CHILD_STACK_SIZE);
25 }
26 
cleanup(void)27 static void cleanup(void)
28 {
29 	if (sysctl_net != -1)
30 		SAFE_FILE_PRINTF(sysctl_path, "%d", sysctl_net);
31 
32 	free(child_stack);
33 }
34 
newnet(void * arg LTP_ATTRIBUTE_UNUSED)35 static int newnet(void *arg LTP_ATTRIBUTE_UNUSED)
36 {
37 	SAFE_FILE_SCANF(sysctl_path, "%d", &sysctl_net_new);
38 	tst_syscall(__NR_exit, 0);
39 	return 0;
40 }
41 
clone_child(void)42 static long clone_child(void)
43 {
44 	TEST(ltp_clone(flags, newnet, NULL, CHILD_STACK_SIZE, child_stack));
45 
46 	if (TST_RET == -1 && TST_ERR == EINVAL)
47 		tst_brk(TCONF, "CONFIG_NET_NS was disabled");
48 
49 	if (TST_RET == -1)
50 		tst_brk(TBROK | TTERRNO, "clone(CLONE_NEWNET) failed");
51 
52 	return TST_RET;
53 }
54 
do_test(void)55 static void do_test(void)
56 {
57 	int def_val;
58 
59 	tst_res(TINFO, "create clone in a new netns with 'CLONE_NEWNET' flag");
60 
61 	SAFE_FILE_SCANF(sysctl_path, "%d", &sysctl_net);
62 	SAFE_FILE_PRINTF(sysctl_path, "%d", sysctl_net + 1);
63 
64 	clone_child();
65 	tst_reap_children();
66 
67 	if (sysctl_net_new == (sysctl_net + 1)) {
68 		tst_res(TFAIL, "sysctl params equal: %s=%d",
69 			sysctl_path, sysctl_net_new);
70 	}
71 
72 	SAFE_FILE_SCANF(sysctl_path_def, "%d", &def_val);
73 
74 	if (sysctl_net_new != def_val) {
75 		tst_res(TFAIL, "netns param init to non-default value %d",
76 			sysctl_net_new);
77 	}
78 
79 	/* restore previous value */
80 	SAFE_FILE_PRINTF(sysctl_path, "%d", sysctl_net);
81 
82 	tst_res(TPASS, "sysctl params differ in new netns");
83 }
84 
85 static struct tst_test test = {
86 	.test_all = do_test,
87 	.setup = setup,
88 	.cleanup = cleanup,
89 	.needs_root = 1,
90 };
91