1 #define _GNU_SOURCE
2 
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <signal.h>
6 #include <limits.h>
7 #include <unistd.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <fcntl.h>
11 
12 #include <linux/unistd.h>
13 #include <linux/kcmp.h>
14 
15 #include <sys/syscall.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/wait.h>
19 
20 #include "../kselftest.h"
21 
22 static long sys_kcmp(int pid1, int pid2, int type, int fd1, int fd2)
23 {
24 	return syscall(__NR_kcmp, pid1, pid2, type, fd1, fd2);
25 }
26 
27 int main(int argc, char **argv)
28 {
29 	const char kpath[] = "kcmp-test-file";
30 	int pid1, pid2;
31 	int fd1, fd2;
32 	int status;
33 
34 	fd1 = open(kpath, O_RDWR | O_CREAT | O_TRUNC, 0644);
35 	pid1 = getpid();
36 
37 	if (fd1 < 0) {
38 		perror("Can't create file");
39 		ksft_exit_fail();
40 	}
41 
42 	pid2 = fork();
43 	if (pid2 < 0) {
44 		perror("fork failed");
45 		ksft_exit_fail();
46 	}
47 
48 	if (!pid2) {
49 		int pid2 = getpid();
50 		int ret;
51 
52 		fd2 = open(kpath, O_RDWR, 0644);
53 		if (fd2 < 0) {
54 			perror("Can't open file");
55 			ksft_exit_fail();
56 		}
57 
58 		/* An example of output and arguments */
59 		printf("pid1: %6d pid2: %6d FD: %2ld FILES: %2ld VM: %2ld "
60 		       "FS: %2ld SIGHAND: %2ld IO: %2ld SYSVSEM: %2ld "
61 		       "INV: %2ld\n",
62 		       pid1, pid2,
63 		       sys_kcmp(pid1, pid2, KCMP_FILE,		fd1, fd2),
64 		       sys_kcmp(pid1, pid2, KCMP_FILES,		0, 0),
65 		       sys_kcmp(pid1, pid2, KCMP_VM,		0, 0),
66 		       sys_kcmp(pid1, pid2, KCMP_FS,		0, 0),
67 		       sys_kcmp(pid1, pid2, KCMP_SIGHAND,	0, 0),
68 		       sys_kcmp(pid1, pid2, KCMP_IO,		0, 0),
69 		       sys_kcmp(pid1, pid2, KCMP_SYSVSEM,	0, 0),
70 
71 			/* This one should fail */
72 		       sys_kcmp(pid1, pid2, KCMP_TYPES + 1,	0, 0));
73 
74 		/* This one should return same fd */
75 		ret = sys_kcmp(pid1, pid2, KCMP_FILE, fd1, fd1);
76 		if (ret) {
77 			printf("FAIL: 0 expected but %d returned (%s)\n",
78 				ret, strerror(errno));
79 			ksft_inc_fail_cnt();
80 			ret = -1;
81 		} else {
82 			printf("PASS: 0 returned as expected\n");
83 			ksft_inc_pass_cnt();
84 		}
85 
86 		/* Compare with self */
87 		ret = sys_kcmp(pid1, pid1, KCMP_VM, 0, 0);
88 		if (ret) {
89 			printf("FAIL: 0 expected but %d returned (%s)\n",
90 				ret, strerror(errno));
91 			ksft_inc_fail_cnt();
92 			ret = -1;
93 		} else {
94 			printf("PASS: 0 returned as expected\n");
95 			ksft_inc_pass_cnt();
96 		}
97 
98 		ksft_print_cnts();
99 
100 		if (ret)
101 			ksft_exit_fail();
102 		else
103 			ksft_exit_pass();
104 	}
105 
106 	waitpid(pid2, &status, P_ALL);
107 
108 	return ksft_exit_pass();
109 }
110