1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2019 FUJITSU LIMITED. All rights reserved.
4 * Author: Jinhui Huang <[email protected]>
5 */
6
7 /*\
8 * [Description]
9 *
10 * Check various errnos for pwritev2(2).
11 *
12 * - pwritev2() fails and sets errno to EINVAL if iov_len is invalid.
13 * - pwritev2() fails and sets errno to EINVAL if the vector count iovcnt is
14 * less than zero.
15 * - pwritev2() fails and sets errno to EOPNOTSUPP if flag is invalid.
16 * - pwritev2() fails and sets errno to EFAULT when writing data from invalid
17 * address.
18 * - pwritev2() fails and sets errno to EBADF if file descriptor is invalid.
19 * - pwritev2() fails and sets errno to EBADF if file descriptor is open for
20 * reading.
21 * - pwritev2() fails and sets errno to ESPIPE if fd is associated with a pipe.
22 */
23
24 #define _GNU_SOURCE
25 #include <sys/uio.h>
26 #include <unistd.h>
27
28 #include "tst_test.h"
29 #include "lapi/pwritev2.h"
30
31 #define CHUNK 64
32
33 static int fd1;
34 static int fd2;
35 static int fd3 = -1;
36 static int fd4[2];
37
38 static char buf[CHUNK];
39
40 static struct iovec wr_iovec1[] = {
41 {buf, -1},
42 };
43
44 static struct iovec wr_iovec2[] = {
45 {buf, CHUNK},
46 };
47
48 static struct iovec wr_iovec3[] = {
49 {NULL, CHUNK},
50 };
51
52 static struct tcase {
53 int *fd;
54 struct iovec *name;
55 int count;
56 off_t offset;
57 int flag;
58 int exp_err;
59 } tcases[] = {
60 {&fd1, wr_iovec1, 1, 0, 0, EINVAL},
61 {&fd1, wr_iovec2, -1, 0, 0, EINVAL},
62 {&fd1, wr_iovec2, 1, 1, -1, EOPNOTSUPP},
63 {&fd1, wr_iovec3, 1, 0, 0, EFAULT},
64 {&fd3, wr_iovec2, 1, 0, 0, EBADF},
65 {&fd2, wr_iovec2, 1, 0, 0, EBADF},
66 {&fd4[0], wr_iovec2, 1, 0, 0, ESPIPE},
67 };
68
verify_pwritev2(unsigned int n)69 static void verify_pwritev2(unsigned int n)
70 {
71 struct tcase *tc = &tcases[n];
72
73 TEST(pwritev2(*tc->fd, tc->name, tc->count, tc->offset, tc->flag));
74
75 if (TST_RET == 0) {
76 tst_res(TFAIL, "pwritev2() succeeded unexpectedly");
77 return;
78 }
79
80 if (TST_ERR == tc->exp_err) {
81 tst_res(TPASS | TTERRNO, "pwritev2() failed as expected");
82 return;
83 }
84
85 tst_res(TFAIL | TTERRNO, "pwritev2() failed unexpectedly, expected %s",
86 tst_strerrno(tc->exp_err));
87 }
88
setup(void)89 static void setup(void)
90 {
91 fd1 = SAFE_OPEN("file1", O_RDWR | O_CREAT, 0644);
92 SAFE_FTRUNCATE(fd1, getpagesize());
93 fd2 = SAFE_OPEN("file2", O_RDONLY | O_CREAT, 0644);
94 SAFE_PIPE(fd4);
95
96 wr_iovec3[0].iov_base = tst_get_bad_addr(NULL);
97 }
98
cleanup(void)99 static void cleanup(void)
100 {
101 if (fd1 > 0)
102 SAFE_CLOSE(fd1);
103
104 if (fd2 > 0)
105 SAFE_CLOSE(fd2);
106
107 if (fd4[0] > 0)
108 SAFE_CLOSE(fd4[0]);
109
110 if (fd4[1] > 0)
111 SAFE_CLOSE(fd4[1]);
112 }
113
114 static struct tst_test test = {
115 .tcnt = ARRAY_SIZE(tcases),
116 .setup = setup,
117 .cleanup = cleanup,
118 .test = verify_pwritev2,
119 .needs_tmpdir = 1,
120 };
121