1 /* Copyright (C) 1991-2022 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
17
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <string.h>
21 #include <limits.h>
22 #include <stdbool.h>
23 #include <sys/param.h>
24 #include <sys/uio.h>
25 #include <errno.h>
26
27
28 static void
ifree(char ** ptrp)29 ifree (char **ptrp)
30 {
31 free (*ptrp);
32 }
33
34 /* Read data from file descriptor FD, and put the result in the
35 buffers described by VECTOR, which is a vector of COUNT 'struct iovec's.
36 The buffers are filled in the order specified.
37 Operates just like 'read' (see <unistd.h>) except that data are
38 put in VECTOR instead of a contiguous buffer. */
39 ssize_t
__readv(int fd,const struct iovec * vector,int count)40 __readv (int fd, const struct iovec *vector, int count)
41 {
42 /* Find the total number of bytes to be read. */
43 size_t bytes = 0;
44 for (int i = 0; i < count; ++i)
45 {
46 /* Check for ssize_t overflow. */
47 if (SSIZE_MAX - bytes < vector[i].iov_len)
48 {
49 __set_errno (EINVAL);
50 return -1;
51 }
52 bytes += vector[i].iov_len;
53 }
54
55 /* Allocate a temporary buffer to hold the data. We should normally
56 use alloca since it's faster and does not require synchronization
57 with other threads. But we cannot if the amount of memory
58 required is too large. */
59 char *buffer;
60 char *malloced_buffer __attribute__ ((__cleanup__ (ifree))) = NULL;
61 if (__libc_use_alloca (bytes))
62 buffer = (char *) __alloca (bytes);
63 else
64 {
65 malloced_buffer = buffer = (char *) malloc (bytes);
66 if (buffer == NULL)
67 return -1;
68 }
69
70 /* Read the data. */
71 ssize_t bytes_read = __read (fd, buffer, bytes);
72 if (bytes_read < 0)
73 return -1;
74
75 /* Copy the data from BUFFER into the memory specified by VECTOR. */
76 bytes = bytes_read;
77 for (int i = 0; i < count; ++i)
78 {
79 size_t copy = MIN (vector[i].iov_len, bytes);
80
81 (void) memcpy ((void *) vector[i].iov_base, (void *) buffer, copy);
82
83 buffer += copy;
84 bytes -= copy;
85 if (bytes == 0)
86 break;
87 }
88
89 return bytes_read;
90 }
91 libc_hidden_def (__readv)
92 weak_alias (__readv, readv)
93