-/* $OpenBSD: fvwrite.c,v 1.21 2023/10/06 16:41:02 millert Exp $ */
+/* $OpenBSD: fvwrite.c,v 1.22 2024/04/28 14:28:02 millert Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
* SUCH DAMAGE.
*/
+#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
}
if (fp->_flags & __SNBF) {
/*
- * Unbuffered: write up to BUFSIZ bytes at a time.
+ * Unbuffered: write up to INT_MAX bytes at a time, to not
+ * truncate the value of len if it is greater than 2^31 bytes.
*/
do {
GETIOV(;);
- w = (*fp->_write)(fp->_cookie, p, MIN(len, BUFSIZ));
+ w = (*fp->_write)(fp->_cookie, p, MIN(len, INT_MAX));
if (w <= 0)
goto err;
p += w;
/*
* Fully buffered: fill partially full buffer, if any,
* and then flush. If there is no partial buffer, write
- * one _bf._size byte chunk directly (without copying).
+ * entire payload directly (without copying) up to a
+ * multiple of the buffer size.
*
* String output is a special case: write as many bytes
* as fit, but pretend we wrote everything. This makes
if (__sflush(fp))
goto err;
} else if (len >= (w = fp->_bf._size)) {
- /* write directly */
+ /*
+ * Write directly up to INT_MAX or greatest
+ * multiple of buffer size (whichever is
+ * smaller), keeping in the memory buffer the
+ * remaining part of payload that is smaller
+ * than buffer size.
+ */
+ if (w != 0)
+ w = MIN(w * (len / w), INT_MAX);
w = (*fp->_write)(fp->_cookie, p, w);
if (w <= 0)
goto err;