1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Wayne Boyer, International Business Machines Corp., 2001
4 * Copyright (c) 2019 SUSE LLC <mdoucha@suse.cz>
5 */
6
7 /*
8 * Test Description:
9 * Testcase to check that fsync(2) sets errno correctly.
10 * 1. Call fsync() on a pipe(fd), and expect EINVAL.
11 * 2. Call fsync() on a socket(fd), and expect EINVAL.
12 * 3. Call fsync() on a closed fd, and test for EBADF.
13 * 4. Call fsync() on an invalid fd, and test for EBADF.
14 * 5. Call fsync() on a fifo(fd), and expect EINVAL.
15 */
16
17 #include <unistd.h>
18 #include <errno.h>
19 #include "tst_test.h"
20
21 #define FIFO_PATH "fifo"
22
23 static int fifo_rfd, fifo_wfd;
24 static int pipe_fd[2];
25 static int sock_fd, bad_fd = -1;
26
27 static const struct test_case {
28 int *fd;
29 int error;
30 } testcase_list[] = {
31 /* EINVAL - fsync() on pipe should not succeed. */
32 {&pipe_fd[1], EINVAL},
33 /* EINVAL - fsync() on socket should not succeed. */
34 {&sock_fd, EINVAL},
35 /* EBADF - fd is closed */
36 {&pipe_fd[0], EBADF},
37 /* EBADF - fd is invalid (-1) */
38 {&bad_fd, EBADF},
39 /* EINVAL - fsync() on fifo should not succeed. */
40 {&fifo_wfd, EINVAL},
41 };
42
setup(void)43 static void setup(void)
44 {
45 SAFE_MKFIFO(FIFO_PATH, 0644);
46 SAFE_PIPE(pipe_fd);
47
48 // FIFO must be opened for reading first, otherwise
49 // open(fifo, O_WRONLY) will block.
50 fifo_rfd = SAFE_OPEN(FIFO_PATH, O_RDONLY | O_NONBLOCK);
51 fifo_wfd = SAFE_OPEN(FIFO_PATH, O_WRONLY);
52 sock_fd = SAFE_SOCKET(AF_UNIX, SOCK_STREAM, 0);
53
54 // Do not open any file descriptors after this line unless you close
55 // them before the next test run.
56 SAFE_CLOSE(pipe_fd[0]);
57 }
58
test_fsync(unsigned int n)59 static void test_fsync(unsigned int n)
60 {
61 const struct test_case *tc = testcase_list + n;
62
63 TEST(fsync(*tc->fd));
64
65 if (TST_RET != -1) {
66 tst_res(TFAIL, "fsync() returned unexpected value %ld",
67 TST_RET);
68 } else if (TST_ERR != tc->error) {
69 tst_res(TFAIL | TTERRNO, "fsync(): unexpected error");
70 } else {
71 tst_res(TPASS | TTERRNO, "fsync() failed as expected");
72 }
73 }
74
cleanup(void)75 static void cleanup(void)
76 {
77 SAFE_CLOSE(fifo_wfd);
78 SAFE_CLOSE(fifo_rfd);
79 SAFE_CLOSE(pipe_fd[1]);
80 SAFE_CLOSE(sock_fd);
81 }
82
83 static struct tst_test test = {
84 .test = test_fsync,
85 .tcnt = ARRAY_SIZE(testcase_list),
86 .needs_tmpdir = 1,
87 .setup = setup,
88 .cleanup = cleanup
89 };
90