From ac06d4d104b540d7f09f6194b006905dab4622a2 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Wed, 6 Nov 2024 10:02:02 -0800 Subject: [PATCH] Fix xsparse.c big heap allocation bugs MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * scripts/xsparse.c (expand_sparse): Read into auto buffer, not heap. The heap code was wrong for two reasons: it called malloc just once in the try-again loop, and even when it succeeded it could have left so few bytes available in the heap that later stdio calls could fail. Reading into the auto buffer might be a bit slower but speed is not an issue here and it’s better to be simple. --- scripts/xsparse.c | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/scripts/xsparse.c b/scripts/xsparse.c index 625b04d9..8559d105 100644 --- a/scripts/xsparse.c +++ b/scripts/xsparse.c @@ -281,19 +281,6 @@ static void expand_sparse (FILE *sfp, int ofd) { size_t i; - off_t max_numbytes = 0; - size_t maxbytes; - char *buffer; - - for (i = 0; i < sparse_map_size; i++) - if (max_numbytes < sparse_map[i].numbytes) - max_numbytes = sparse_map[i].numbytes; - - maxbytes = max_numbytes < SIZE_MAX ? max_numbytes : SIZE_MAX; - - for (buffer = malloc (maxbytes); !buffer; maxbytes /= 2) - if (maxbytes == 0) - die (1, "not enough memory"); for (i = 0; i < sparse_map_size; i++) { @@ -310,7 +297,8 @@ expand_sparse (FILE *sfp, int ofd) die (1, "lseek error (%d)", errno); while (size) { - size_t rdsize = (size < maxbytes) ? size : maxbytes; + char buffer[BUFSIZ]; + size_t rdsize = size < BUFSIZ ? size : BUFSIZ; if (rdsize != fread (buffer, 1, rdsize, sfp)) die (1, "read error (%d)", errno); if (0 <= ofd) @@ -323,7 +311,6 @@ expand_sparse (FILE *sfp, int ofd) } } } - free (buffer); } static void -- 2.47.3