From b061d24916fb9a14da37a3f2a05cb80dc65cfd38 Mon Sep 17 00:00:00 2001
From: Paul Eggert <eggert@cs.ucla.edu>
Date: Mon, 5 Dec 2022 14:16:45 -0800
Subject: [PATCH] backport: grep: bug backref in last of multiple patterns

---
 src/dfasearch.c | 25 ++++++++++++-------------
 tests/backref   |  8 ++++++++
 2 files changed, 20 insertions(+), 13 deletions(-)

diff --git a/src/dfasearch.c b/src/dfasearch.c
index d6afa8d..2d0e861 100644
--- a/src/dfasearch.c
+++ b/src/dfasearch.c
@@ -267,20 +267,19 @@ GEAcompile (char *pattern, size_t size, reg_syntax_t syntax_bits,
   if (compilation_failed)
     exit (EXIT_TROUBLE);
 
-  if (prev <= patlim)
+  if (patlim < prev)
+    buflen--;
+  else if (pattern < prev)
     {
-      if (pattern < prev)
-        {
-          ptrdiff_t prevlen = patlim - prev;
-          buf = xrealloc (buf, buflen + prevlen);
-          memcpy (buf + buflen, prev, prevlen);
-          buflen += prevlen;
-        }
-      else
-        {
-          buf = pattern;
-          buflen = size;
-        }
+      ptrdiff_t prevlen = patlim - prev;
+      buf = xrealloc (buf, buflen + prevlen);
+      memcpy (buf + buflen, prev, prevlen);
+      buflen += prevlen;
+    }
+  else
+    {
+      buf = pattern;
+      buflen = size;
     }
 
   /* In the match_words and match_lines cases, we use a different pattern
diff --git a/tests/backref b/tests/backref
index 947981b..5cc3060 100755
--- a/tests/backref
+++ b/tests/backref
@@ -43,4 +43,12 @@ if test $? -ne 2 ; then
         failures=1
 fi
 
+# https://bugs.gnu.org/36148#13
+echo 'Total failed: 2 (1 ignored)' |
+    grep -e '^Total failed: 0$' -e '^Total failed: \([0-9]*\) (\1 ignored)$'
+if test $? -ne 1 ; then
+        echo "Backref: Multiple -e test, test #5 failed"
+        failures=1
+fi
+
 Exit $failures
-- 
2.30.1 (Apple Git-130)

