git: 91af1b8001d3 - stable/13 - sed: Fix handling of an empty pattern space

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Tue, 14 Jan 2025 14:43:48 UTC
The branch stable/13 has been updated by markj:

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

commit 91af1b8001d34a1563d861f1da81deaa121adca8
Author:     Mohamed Akram <mohd.akram@outlook.com>
AuthorDate: 2024-12-23 19:06:09 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2025-01-14 14:43:05 +0000

    sed: Fix handling of an empty pattern space
    
    Add a regression test.
    
    PR:             271791
    Obtained from:  OpenBSD (1.38 millert)
    MFC after:      2 weeks
    
    (cherry picked from commit 5982237f1e5a30b6b7d67b307b4d3685b00718bf)
---
 usr.bin/sed/process.c          | 10 ++++------
 usr.bin/sed/tests/sed2_test.sh | 14 ++++++++++++++
 2 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/usr.bin/sed/process.c b/usr.bin/sed/process.c
index 3d88096ffb77..945db462a601 100644
--- a/usr.bin/sed/process.c
+++ b/usr.bin/sed/process.c
@@ -439,14 +439,12 @@ substitute(struct s_command *cp)
 		 * and at the end of the line, terminate.
 		 */
 		if (match[0].rm_so == match[0].rm_eo) {
-			if (*s == '\0' || *s == '\n')
-				slen = -1;
-			else
-				slen--;
-			if (*s != '\0') {
+			if (slen > 0) {
 			 	cspace(&SS, s++, 1, APPEND);
+				slen--;
 				le++;
-			}
+			} else
+				slen = -1;
 			lastempty = 1;
 		} else
 			lastempty = 0;
diff --git a/usr.bin/sed/tests/sed2_test.sh b/usr.bin/sed/tests/sed2_test.sh
index f50619612561..0b849b1ea132 100755
--- a/usr.bin/sed/tests/sed2_test.sh
+++ b/usr.bin/sed/tests/sed2_test.sh
@@ -159,6 +159,19 @@ minus_e_body()
 	atf_check -o 'inline:--\nab\n' sed    $'1 i\\\n--' a
 }
 
+atf_test_case command_D
+command_D_head()
+{
+	atf_set "descr" "Test handling of an empty pattern space"
+}
+command_D_body()
+{
+	printf "hello\n\nworld\n" > a
+
+	atf_check -o file:a sed -e 's/^//;P;D' a
+	atf_check -o file:a sed -e 's/^//;$!N;P;D' a
+}
+
 atf_init_test_cases()
 {
 	atf_add_test_case inplace_command_q
@@ -169,4 +182,5 @@ atf_init_test_cases()
 	atf_add_test_case hex_subst
 	atf_add_test_case bracket_y
 	atf_add_test_case minus_e
+	atf_add_test_case command_D
 }