Commit 7011e422bf for perl

commit 7011e422bfc52c23012fa570aefaee202afd3a57
Author: Richard Leach <rich+perl@hyphen-dash-hyphen.info>
Date:   Thu Nov 12 10:11:37 2026 +0000

    S_flatten_inner_branches: explicitly check for overflow

    Oversized offsets were expected to trigger reparsing as BRANCHJ, but that
    didn't happen. (That was either a bug in this function or an expectation
    that changed when parts of the regex engine moved to 32 bit.)

diff --git a/regcomp.c b/regcomp.c
index a817b14852..55a44c3246 100644
--- a/regcomp.c
+++ b/regcomp.c
@@ -3102,10 +3102,8 @@ S_flatten_inner_branches(pTHX_ RExC_state_t *pRExC_state, regnode *first_outer_b
          * branch contents) that could corrupt the regex if flattened. */
         regnode *last_inner_br = first_inner_br;
          /* Note: This loop could check if flattening has a good chance of
-         * building bigger tries, or would result in offsets > U16_MAX, but
-         * with the anticipated move to 32 bit offsets, it shouldn't matter.
-         * If this code does create oversized offsets in the meantime, the
-         * surrounding code will reparse using BRANCHJ. */
+         * building bigger tries, but with the anticipated move to 32 bit
+         * offsets, it shouldn't matter. */
         bool unsafe = false;
         while (1) {
             regnode *inner_content = S_content_head(aTHX_ last_inner_br);
@@ -3130,6 +3128,12 @@ S_flatten_inner_branches(pTHX_ RExC_state_t *pRExC_state, regnode *first_outer_b
             prev_outer_br = outer_br; outer_br = outer_successor; continue;
         }

+        /* Flattening links regnodes in the inner branch directly to *ender.
+         * Skip this outer branch if the offsets would overflow. */
+        if (ender - outer_br > U16_MAX) {
+            prev_outer_br = outer_br; outer_br = outer_successor; continue;
+        }
+
         /* By this point, there is an inner BRANCH and it seems safe to
          * flatten it. This is done by manipulating regnode offsets. */
         const regnode_offset last_inner_off      = REGNODE_OFFSET(last_inner_br);
diff --git a/t/re/pat.t b/t/re/pat.t
index bb0e7d7613..9daecbaef4 100644
--- a/t/re/pat.t
+++ b/t/re/pat.t
@@ -28,7 +28,7 @@ skip_all_without_unicode_tables();
 my $has_locales = locales_enabled('LC_CTYPE');
 my $utf8_locale = find_utf8_ctype_locale();

-plan tests => 6822 + 6 * $Config{uvsize};  # Update when adding/deleting tests.
+plan tests => 6823 + 6 * $Config{uvsize};  # Update when adding/deleting tests.

 run_tests() unless caller;

@@ -3483,6 +3483,14 @@ PROG
         PROG
     }

+    {
+        fresh_perl_is(<<~'PROG', "ok", {}, "flattened branches don't overflow U16_MAX offset");
+        my $b = "b" x 150000;
+        my $c = "c" x 150000;
+        print "ok" if "1a" =~ /^(?:(?:\da|$b)|$c)/;
+        PROG
+    }
+
 } # End of sub run_tests

 1;