Module Name:    src
Committed By:   rillig
Date:           Sun Aug  9 09:26:21 UTC 2020

Modified Files:
        src/usr.bin/make: main.c

Log Message:
make(1): avoid undefined behavior in Cmd_Exec

Iterating the command output backwards was dangerous since at the end,
the pointer cp pointed outside of the array.  Even without dereferencing
this pointer, this already invokes undefined behavior (C11, 6.5.6p8).
Don't risk anything.  Iterating forwards is probably faster anyway, since
it is more common.


To generate a diff of this commit:
cvs rdiff -u -r1.299 -r1.300 src/usr.bin/make/main.c

Please note that diffs are not public domain; they are subject to the
copyright notices on the relevant files.

Modified files:

Index: src/usr.bin/make/main.c
diff -u src/usr.bin/make/main.c:1.299 src/usr.bin/make/main.c:1.300
--- src/usr.bin/make/main.c:1.299	Sun Aug  9 09:07:54 2020
+++ src/usr.bin/make/main.c	Sun Aug  9 09:26:21 2020
@@ -1,4 +1,4 @@
-/*	$NetBSD: main.c,v 1.299 2020/08/09 09:07:54 rillig Exp $	*/
+/*	$NetBSD: main.c,v 1.300 2020/08/09 09:26:21 rillig Exp $	*/
 
 /*
  * Copyright (c) 1988, 1989, 1990, 1993
@@ -69,7 +69,7 @@
  */
 
 #ifndef MAKE_NATIVE
-static char rcsid[] = "$NetBSD: main.c,v 1.299 2020/08/09 09:07:54 rillig Exp $";
+static char rcsid[] = "$NetBSD: main.c,v 1.300 2020/08/09 09:26:21 rillig Exp $";
 #else
 #include <sys/cdefs.h>
 #ifndef lint
@@ -81,7 +81,7 @@ __COPYRIGHT("@(#) Copyright (c) 1988, 19
 #if 0
 static char sccsid[] = "@(#)main.c	8.3 (Berkeley) 3/19/94";
 #else
-__RCSID("$NetBSD: main.c,v 1.299 2020/08/09 09:07:54 rillig Exp $");
+__RCSID("$NetBSD: main.c,v 1.300 2020/08/09 09:26:21 rillig Exp $");
 #endif
 #endif /* not lint */
 #endif
@@ -1699,14 +1699,11 @@ Cmd_Exec(const char *cmd, const char **e
 	    *errfmt = "\"%s\" returned non-zero status";
 
 	/* Convert newlines to spaces.  A final newline is just stripped */
-	cp = &res[res_len];
-	if (res_len > 0 && *--cp == '\n')
-	    *cp-- = '\0';
-	while (cp >= res) {
+	if (res_len > 0 && res[res_len - 1] == '\n')
+	    res[res_len - 1] = '\0';
+	for (cp = res; *cp != '\0'; cp++)
 	    if (*cp == '\n')
 		*cp = ' ';
-	    cp--;
-	}
 	break;
     }
     return res;

Reply via email to