1 /* Write data into multiple buffers. Base implementation for pwritev
2 and pwritev64.
3 Copyright (C) 2017-2022 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
19
20 #include <unistd.h>
21 #include <sys/uio.h>
22 #include <sys/param.h>
23 #include <errno.h>
24 #include <malloc.h>
25
26 #include <ldsodefs.h>
27 #include <libc-pointer-arith.h>
28
29 /* Write data pointed by the buffers described by IOVEC, which is a
30 vector of COUNT 'struct iovec's, to file descriptor FD at the given
31 position OFFSET without change the file pointer. The data is
32 written in the order specified. Operates just like 'write' (see
33 <unistd.h>) except that the data are taken from IOVEC instead of a
34 contiguous buffer. */
35 ssize_t
PWRITEV(int fd,const struct iovec * vector,int count,OFF_T offset)36 PWRITEV (int fd, const struct iovec *vector, int count, OFF_T offset)
37 {
38 /* Find the total number of bytes to be read. */
39 size_t bytes = 0;
40 for (int i = 0; i < count; ++i)
41 {
42 /* Check for ssize_t overflow. */
43 if (SSIZE_MAX - bytes < vector[i].iov_len)
44 {
45 __set_errno (EINVAL);
46 return -1;
47 }
48 bytes += vector[i].iov_len;
49 }
50
51 /* Allocate a temporary buffer to hold the data. It could be done with a
52 stack allocation, but due limitations on some system (Linux with
53 O_DIRECT) it aligns the buffer to pagesize. A possible optimization
54 would be querying if the syscall would impose any alignment constraint,
55 but 1. it is system specific (not meant in generic implementation), and
56 2. it would make the implementation more complex, and 3. it will require
57 another syscall (fcntl). */
58 void *buffer = __mmap (NULL, bytes, PROT_READ | PROT_WRITE,
59 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
60 if (__glibc_unlikely (buffer == MAP_FAILED))
61 return -1;
62
63 /* Copy the data from BUFFER into the memory specified by VECTOR. */
64 char *ptr = buffer;
65 for (int i = 0; i < count; ++i)
66 ptr = __mempcpy ((void *) ptr, (void *) vector[i].iov_base,
67 vector[i].iov_len);
68
69 ssize_t ret = PWRITE (fd, buffer, bytes, offset);
70
71 __munmap (buffer, bytes);
72
73 return ret;
74 }
75