xref: /netbsd-src/lib/libc/stdio/fvwrite.c (revision 046528e7dc5fcb249abb6905c9a02d81c4ced0d0)
1 /*	$NetBSD: fvwrite.c,v 1.31 2024/03/29 22:39:41 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Chris Torek.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #if defined(LIBC_SCCS) && !defined(lint)
37 #if 0
38 static char sccsid[] = "@(#)fvwrite.c	8.1 (Berkeley) 6/4/93";
39 #else
40 __RCSID("$NetBSD: fvwrite.c,v 1.31 2024/03/29 22:39:41 christos Exp $");
41 #endif
42 #endif /* LIBC_SCCS and not lint */
43 
44 #include <assert.h>
45 #include <stddef.h>
46 #include <errno.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include "reentrant.h"
51 #include "local.h"
52 #include "fvwrite.h"
53 
54 /*
55  * Write some memory regions.  Return zero on success, EOF on error.
56  *
57  * This routine is large and unsightly, but most of the ugliness due
58  * to the three different kinds of output buffering is handled here.
59  */
60 int
__sfvwrite(FILE * fp,struct __suio * uio)61 __sfvwrite(FILE *fp, struct __suio *uio)
62 {
63 	size_t len;
64 	char *p;
65 	struct __siov *iov;
66 	int s;
67 	ssize_t w;
68 	char *nl;
69 	size_t nlknown, nldist;
70 
71 	_DIAGASSERT(fp != NULL);
72 	_DIAGASSERT(uio != NULL);
73 
74 	if ((ssize_t)uio->uio_resid < 0) {
75 		errno = EINVAL;
76 		return EOF;
77 	}
78 	if (uio->uio_resid == 0)
79 		return 0;
80 	/* make sure we can write */
81 	if (cantwrite(fp)) {
82 		errno = EBADF;
83 		return EOF;
84 	}
85 
86 #define	MIN(a, b) ((a) < (b) ? (a) : (b))
87 #define	COPY(n)	  (void)memcpy(fp->_p, p, (size_t)(n))
88 
89 	iov = uio->uio_iov;
90 	p = iov->iov_base;
91 	len = iov->iov_len;
92 	iov++;
93 #define GETIOV(extra_work) \
94 	while (len == 0) { \
95 		extra_work; \
96 		p = iov->iov_base; \
97 		len = iov->iov_len; \
98 		iov++; \
99 	}
100 	if (fp->_flags & __SNBF) {
101 		/*
102 		 * Unbuffered: write up to INT_MAX bytes at a time, to not
103 		 * truncate the value of len if it is greater than 2^31 bytes.
104 		 */
105 		do {
106 			GETIOV(;);
107 			w = (*fp->_write)(fp->_cookie, p, MIN(len, INT_MAX));
108 			if (w <= 0)
109 				goto err;
110 			p += w;
111 			len -= w;
112 		} while ((uio->uio_resid -= w) != 0);
113 	} else if ((fp->_flags & __SLBF) == 0) {
114 		/*
115 		 * Fully buffered: fill partially full buffer, if any,
116 		 * and then flush.  If there is no partial buffer, write
117 		 * entire payload directly (without copying) up to a multiple
118 		 * of the buffer size.
119 		 *
120 		 * String output is a special case: write as many bytes
121 		 * as fit, but pretend we wrote everything.  This makes
122 		 * snprintf() return the number of bytes needed, rather
123 		 * than the number used, and avoids its write function
124 		 * (so that the write function can be invalid).
125 		 */
126 		do {
127 			GETIOV(;);
128 			if ((fp->_flags & (__SALC | __SSTR)) ==
129 			    (__SALC | __SSTR) && (size_t)fp->_w < len) {
130 				ptrdiff_t blen = fp->_p - fp->_bf._base;
131 				unsigned char *_base;
132 				int _size;
133 
134 				/* Allocate space exponentially. */
135 				_size = fp->_bf._size;
136 				do {
137 					_size = (_size << 1) + 1;
138 				} while ((size_t)_size < blen + len);
139 				_base = realloc(fp->_bf._base,
140 				    (size_t)(_size + 1));
141 				if (_base == NULL)
142 					goto err;
143 				fp->_w += _size - fp->_bf._size;
144 				fp->_bf._base = _base;
145 				fp->_bf._size = _size;
146 				fp->_p = _base + blen;
147 			}
148 			w = fp->_w;
149 			if (fp->_flags & __SSTR) {
150 				if (len < (size_t)w)
151 					w = len;
152 				COPY(w);	/* copy MIN(fp->_w,len), */
153 				fp->_w -= (int)w;
154 				fp->_p += w;
155 				w = len;	/* but pretend copied all */
156 			} else if (fp->_p > fp->_bf._base && len > (size_t)w) {
157 				/* fill and flush */
158 				COPY(w);
159 				/* fp->_w -= w; */ /* unneeded */
160 				fp->_p += w;
161 				if (fflush(fp))
162 					goto err;
163 			} else if (len >= (size_t)(w = fp->_bf._size)) {
164 				/*
165 				 * write directly up to INT_MAX or greatest
166 				 * multiple of buffer size (whatever is
167 				 * smaller), keeping in the memory buffer the
168 				 * remaining part of payload that is smaller
169 				 * than buffer size.
170 				 */
171 				if (w != 0)
172 					w = MIN(w * (len / w), INT_MAX);
173 				w = (*fp->_write)(fp->_cookie, p, (size_t)w);
174 				if (w <= 0)
175 					goto err;
176 			} else {
177 				/* fill and done */
178 				w = len;
179 				COPY(w);
180 				fp->_w -= (int)w;
181 				fp->_p += w;
182 			}
183 			p += w;
184 			len -= w;
185 		} while ((uio->uio_resid -= w) != 0);
186 	} else {
187 		/*
188 		 * Line buffered: like fully buffered, but we
189 		 * must check for newlines.  Compute the distance
190 		 * to the first newline (including the newline),
191 		 * or `infinity' if there is none, then pretend
192 		 * that the amount to write is MIN(len,nldist).
193 		 */
194 		nlknown = 0;
195 		nldist = 0;	/* XXX just to keep gcc happy */
196 		do {
197 			GETIOV(nlknown = 0);
198 			if (!nlknown) {
199 				nl = memchr(p, '\n', len);
200 				nldist = nl ? (size_t)(nl + 1 - p) : len + 1;
201 				nlknown = 1;
202 			}
203 			s = (int)MIN(len, nldist);
204 			w = fp->_w + fp->_bf._size;
205 			if (fp->_p > fp->_bf._base && s > w) {
206 				COPY(w);
207 				/* fp->_w -= w; */
208 				fp->_p += w;
209 				if (fflush(fp))
210 					goto err;
211 			} else if (s >= (w = fp->_bf._size)) {
212 				w = (*fp->_write)(fp->_cookie, p, (size_t)w);
213 				if (w <= 0)
214 				 	goto err;
215 			} else {
216 				w = s;
217 				COPY(w);
218 				fp->_w -= (int)w;
219 				fp->_p += w;
220 			}
221 			if ((nldist -= w) == 0) {
222 				/* copied the newline: flush and forget */
223 				if (fflush(fp))
224 					goto err;
225 				nlknown = 0;
226 			}
227 			p += w;
228 			len -= w;
229 		} while ((uio->uio_resid -= w) != 0);
230 	}
231 	return 0;
232 
233 err:
234 	fp->_flags |= __SERR;
235 	return EOF;
236 }
237