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