1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Copyright (c) 2022 FUJITSU LIMITED. All rights reserved.
4 * Author: Yang Xu <xuyang2018.jy@fujitsu.com>
5 */
6
7/*\
8 * [Description]
9 *
10 * Basic pidfd_getfd() test:
11 *
12 * - the close-on-exec flag is set on the file descriptor returned by
13 *   pidfd_getfd
14 * - use kcmp to check whether a file descriptor idx1 in the process pid1
15 *   refers to the same open file description as file descriptor idx2 in
16 *   the process pid2
17 */
18
19#include <unistd.h>
20#include <stdlib.h>
21#include <stdio.h>
22#include "tst_test.h"
23#include "lapi/kcmp.h"
24#include "tst_safe_macros.h"
25#include "lapi/pidfd.h"
26
27#define TESTFILE "testfile"
28
29static int fds[2] = {-1, -1};
30static int pidfd = -1;
31
32static void do_child(void)
33{
34	int fd;
35
36	SAFE_CLOSE(fds[0]);
37	fd = SAFE_CREAT(TESTFILE, 0644);
38	SAFE_WRITE(SAFE_WRITE_ALL, fds[1], &fd, sizeof(fd));
39	TST_CHECKPOINT_WAIT(0);
40	SAFE_CLOSE(fd);
41	SAFE_CLOSE(fds[1]);
42	exit(0);
43}
44
45static void run(void)
46{
47	int flag, pid, targetfd, remotefd;
48
49	SAFE_PIPE(fds);
50	pid = SAFE_FORK();
51	if (!pid)
52		do_child();
53
54	SAFE_CLOSE(fds[1]);
55	TST_PROCESS_STATE_WAIT(pid, 'S', 0);
56
57	pidfd = SAFE_PIDFD_OPEN(pid, 0);
58	SAFE_READ(1, fds[0], &targetfd, sizeof(targetfd));
59	TST_EXP_FD_SILENT(pidfd_getfd(pidfd, targetfd, 0),
60		"pidfd_getfd(%d, %d , 0)", pidfd, targetfd);
61
62	remotefd = TST_RET;
63	flag = SAFE_FCNTL(remotefd, F_GETFD);
64	if (!(flag & FD_CLOEXEC))
65		tst_res(TFAIL, "pidfd_getfd() didn't set close-on-exec flag");
66
67	TST_EXP_VAL_SILENT(kcmp(getpid(), pid, KCMP_FILE, remotefd, targetfd), 0);
68
69	tst_res(TPASS, "pidfd_getfd(%d, %d, 0) passed", pidfd, targetfd);
70
71	TST_CHECKPOINT_WAKE(0);
72	SAFE_CLOSE(remotefd);
73	SAFE_CLOSE(pidfd);
74	SAFE_CLOSE(fds[0]);
75	tst_reap_children();
76}
77
78static void setup(void)
79{
80	pidfd_open_supported();
81	pidfd_getfd_supported();
82}
83
84static void cleanup(void)
85{
86	if (fds[0] > -1)
87		SAFE_CLOSE(fds[0]);
88	if (fds[1] > -1)
89		SAFE_CLOSE(fds[1]);
90	if (pidfd > -1)
91		SAFE_CLOSE(pidfd);
92}
93
94static struct tst_test test = {
95	.needs_root = 1,
96	.needs_checkpoints = 1,
97	.forks_child = 1,
98	.setup = setup,
99	.cleanup = cleanup,
100	.test_all = run,
101};
102