From 75a18a60b40f87dd4d081bc75931c9f93de7b82c Mon Sep 17 00:00:00 2001 From: Ron Yorston Date: Sun, 2 Jun 2024 19:36:03 +0100 Subject: make: ensure sufficient space in line buffer When using fgets(3) to read a line into a buffer it's necessary to ensure at least two characters are available in the buffer. Otherwise the read fails. (At least, it did when pdpmake was built using MSYS2 on Windows.) Adds 16 bytes to the 32-bit build. (GitHub pdpmake issue 44) --- miscutils/make.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/miscutils/make.c b/miscutils/make.c index 8394c4e7b..bcba080fe 100644 --- a/miscutils/make.c +++ b/miscutils/make.c @@ -1627,23 +1627,24 @@ make_fgets(char *s, int size, FILE *fd) static char * readline(FILE *fd) { - char *p, *str; + char *p, *str = NULL; int pos = 0; - int len = 256; - - str = xmalloc(len); + int len = 0; for (;;) { - if (make_fgets(str + pos, len - pos, fd) == NULL) { + // We need room for at least one character and a NUL terminator + if (len - pos > 1 && + make_fgets(str + pos, len - pos, fd) == NULL) { if (pos) return str; free(str); return NULL; // EOF } - if ((p = strchr(str + pos, '\n')) == NULL) { + if (len - pos < 2 || (p = strchr(str + pos, '\n')) == NULL) { // Need more room - pos = len - 1; + if (len) + pos = len - 1; len += 256; str = xrealloc(str, len); continue; -- cgit v1.2.3-55-g6feb