shithub: scc

Download patch

ref: 58b406cf181a732417b57119b9da46836a2b3ada
parent: fef98680b811aac701fc7d4b7babb3d4f7993c95
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Mon Oct 15 09:30:07 EDT 2018

[lib/c] Allocate buffers in stdio by demand

Don't allocate buffers for FILEs before they are used.

--- a/lib/c/__getc.c
+++ b/lib/c/__getc.c
@@ -22,6 +22,14 @@
 		return EOF;
 	}
 
+	if (fp->buf == NULL) {
+		if ((fp->buf = malloc(BUFSIZ)) == NULL) {
+			errno = ENOMEM;
+			return NULL;
+		}
+		fp->flags |= _IOALLOC;
+	}
+
 	if ((cnt = _read(fp->fd, fp->buf, fp->len)) <= 0) {
 		fp->flags |= (cnt == 0) ? _IOEOF : _IOERR;
 		return EOF;
--- a/lib/c/__putc.c
+++ b/lib/c/__putc.c
@@ -45,6 +45,14 @@
 		return EOF;
 	}
 
+	if (fp->buf == NULL) {
+		if ((fp->buf = malloc(BUFSIZ)) == NULL) {
+			errno = ENOMEM;
+			return NULL;
+		}
+		fp->flags |= _IOALLOC;
+	}
+
 	if (first) {
 		if (atexit(cleanup)) {
 			fp->flags |= _IOERR;
--- a/lib/c/_fpopen.c
+++ b/lib/c/_fpopen.c
@@ -56,14 +56,7 @@
 	if ((fd = _open(fname, flags)) < 0)
 		return NULL;
 
-	if (fp->buf == NULL) {
-		if ((fp->buf = malloc(BUFSIZ)) == NULL) {
-			_close(fd);
-			errno = ENOMEM;
-			return NULL;
-		}
-		fp->flags |= _IOALLOC;
-	}
+	fp->buf = NULL;
 	fp->fd = fd;
 
 	if (!bin)
--- a/lib/c/stdio.c
+++ b/lib/c/stdio.c
@@ -1,12 +1,9 @@
 #include <stdio.h>
 
-static unsigned char inbuf[BUFSIZ];
-static unsigned char outbuf[BUFSIZ];
-
 FILE __iob[FOPEN_MAX] = {
 	{
 		.fd = 0,
-		.buf = inbuf,
+		.buf = NULL,
 		.len = BUFSIZ,
 		.flags = _IOREAD,
 		.lp = inbuf,
@@ -15,7 +12,7 @@
 	},
 	{
 		.fd = 1,
-		.buf = outbuf,
+		.buf = NULL,
 		.len = BUFSIZ,
 		.flags = _IOWRITE | _IOLBF,
 		.lp = outbuf,