git: d3643c9efe78 - main - join: use getline() instead of fgetln()

From: Warner Losh <imp_at_FreeBSD.org>
Date: Fri, 19 Apr 2024 21:52:43 UTC
The branch main has been updated by imp:

URL: https://cgit.FreeBSD.org/src/commit/?id=d3643c9efe7806c17c11251acd299f70b112c596

commit d3643c9efe7806c17c11251acd299f70b112c596
Author:     Martin Tournoij <martin@arp242.net>
AuthorDate: 2024-04-19 21:11:30 +0000
Commit:     Warner Losh <imp@FreeBSD.org>
CommitDate: 2024-04-19 21:52:22 +0000

    join: use getline() instead of fgetln()
    
    This replaces fgetln() with getline(). The main reason for this is
    portability, making things easier for people who want to compile these
    tools on non-FreeBSD systems.
    
    I appreciate that's probably not the top concern for FreeBSD base tools,
    but fgetln() is impossible to port to most platforms, as concurrent
    access is essentially impossible to implement fully correct without the
    line buffer on the FILE struct. Other than this, many generic FreeBSD
    tools compile fairly cleanly on Linux with a few small changes.
    
    Most uses of fgetln() pre-date getline() support (added in 2009 with
    69099ba2ec8b), and there's been some previous patches (ee3ca711a898
    8c98e6b1a7f3 1a2a4fc8ce1b) for other tools.
    
    Obtained from:  https://github.com/dcantrell/bsdutils and
                    https://github.com/chimera-linux/chimerautils
    Signed-off-by: Martin Tournoij <martin@arp242.net>
    Reviewed by: imp
    Pull Request: https://github.com/freebsd/freebsd-src/pull/893
---
 usr.bin/join/join.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)

diff --git a/usr.bin/join/join.c b/usr.bin/join/join.c
index b1be8cd81690..79469cdc52db 100644
--- a/usr.bin/join/join.c
+++ b/usr.bin/join/join.c
@@ -262,9 +262,10 @@ static void
 slurp(INPUT *F)
 {
 	LINE *lp, *lastlp, tmp;
-	size_t len;
+	size_t blen = 0;
+	ssize_t len;
 	int cnt;
-	char *bp, *fieldp;
+	char *bp, *buf = NULL, *fieldp;
 
 	/*
 	 * Read all of the lines from an input file that have the same
@@ -307,21 +308,21 @@ slurp(INPUT *F)
 			F->pushbool = 0;
 			continue;
 		}
-		if ((bp = fgetln(F->fp, &len)) == NULL)
+		if ((len = getline(&buf, &blen, F->fp)) < 0) {
+			free(buf);
 			return;
-		if (lp->linealloc <= len + 1) {
+		}
+		if (lp->linealloc <= (size_t)(len + 1)) {
 			lp->linealloc += MAX(100, len + 1 - lp->linealloc);
 			if ((lp->line =
 			    realloc(lp->line, lp->linealloc)) == NULL)
 				err(1, NULL);
 		}
-		memmove(lp->line, bp, len);
+		memmove(lp->line, buf, len);
 
 		/* Replace trailing newline, if it exists. */
-		if (bp[len - 1] == '\n')
+		if (buf[len - 1] == '\n')
 			lp->line[len - 1] = '\0';
-		else
-			lp->line[len] = '\0';
 		bp = lp->line;
 
 		/* Split the line into fields, allocate space as necessary. */
@@ -345,6 +346,7 @@ slurp(INPUT *F)
 			break;
 		}
 	}
+	free(buf);
 }
 
 static char *