git: 4e609121a764 - stable/13 - sed: fix commandline-given expression when -e is not used

From: Kyle Evans <kevans_at_FreeBSD.org>
Date: Fri, 22 Nov 2024 04:53:51 UTC
The branch stable/13 has been updated by kevans:

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

commit 4e609121a764b103dd2d07630441d1c4cd76bbdd
Author:     Martin Cracauer <cracauer@FreeBSD.org>
AuthorDate: 2024-11-07 03:40:02 +0000
Commit:     Kyle Evans <kevans@FreeBSD.org>
CommitDate: 2024-11-22 04:53:43 +0000

    sed: fix commandline-given expression when -e is not used
    
    Make explicit sed commands (first on commandline) behave the same
    as those given with -e.
    
    Without this patch the following two commands behave differently,
    the second one being wrong:
    echo ab | sed -e $'1 i\\\n--'
    echo ab | sed $'1 i\\\n--'
    
    Reviewed by:    0mp, des, kevans
    Sponsored by:   Klara, Inc.
    
    (cherry picked from commit 0552fdc62caf034397ffd5b07dfbad853aef5aa8)
---
 usr.bin/sed/main.c             | 10 +++++-----
 usr.bin/sed/tests/sed2_test.sh | 13 +++++++++++++
 2 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/usr.bin/sed/main.c b/usr.bin/sed/main.c
index efa28b5e7239..1632b823cc69 100644
--- a/usr.bin/sed/main.c
+++ b/usr.bin/sed/main.c
@@ -148,10 +148,8 @@ main(int argc, char *argv[])
 			break;
 		case 'e':
 			eflag = 1;
-			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
-				err(1, "malloc");
-			strcpy(temp_arg, optarg);
-			strcat(temp_arg, "\n");
+			if (asprintf(&temp_arg, "%s\n", optarg) == -1)
+				err(1, "asprintf");
 			add_compunit(CU_STRING, temp_arg);
 			break;
 		case 'f':
@@ -184,7 +182,9 @@ main(int argc, char *argv[])
 
 	/* First usage case; script is the first arg */
 	if (!eflag && !fflag && *argv) {
-		add_compunit(CU_STRING, *argv);
+		if (asprintf(&temp_arg, "%s\n", *argv) == -1)
+			err(1, "asprintf");
+		add_compunit(CU_STRING, temp_arg);
 		argv++;
 	}
 
diff --git a/usr.bin/sed/tests/sed2_test.sh b/usr.bin/sed/tests/sed2_test.sh
index a7408b2560a7..f50619612561 100755
--- a/usr.bin/sed/tests/sed2_test.sh
+++ b/usr.bin/sed/tests/sed2_test.sh
@@ -147,6 +147,18 @@ bracket_y_body()
 	    echo 'bra[ke]' | sed 'y[\[][ct['
 }
 
+atf_test_case minus_e
+minus_e_head()
+{
+	atf_set "descr" "Verify that -e and implicit arg do the same thing"
+}
+minus_e_body()
+{
+	printf "ab\n" > a
+	atf_check -o 'inline:--\nab\n' sed -e $'1 i\\\n--' a
+	atf_check -o 'inline:--\nab\n' sed    $'1 i\\\n--' a
+}
+
 atf_init_test_cases()
 {
 	atf_add_test_case inplace_command_q
@@ -156,4 +168,5 @@ atf_init_test_cases()
 	atf_add_test_case commands_on_stdin
 	atf_add_test_case hex_subst
 	atf_add_test_case bracket_y
+	atf_add_test_case minus_e
 }