From 869e8e3d61cad86b1cfcb4594f3124e2c3e4bc50 Mon Sep 17 00:00:00 2001
From: Hugo van der Sanden <hv@crypt.org>
Date: Sat, 11 Apr 2020 14:10:24 +0100
Subject: [PATCH] study_chunk: do not rewrite for trie while enframed

gh16947: the outer frame may be in the middle of looking at the part
of the program we would rewrite. Let the outer frame deal with it.
---
 regcomp.c  | 7 ++++---
 t/re/pat.t | 9 ++++++++-
 2 files changed, 12 insertions(+), 4 deletions(-)

diff --git a/regcomp.c b/regcomp.c
index 5e0f37599c8c..9275bc5ac9b7 100644
--- a/regcomp.c
+++ b/regcomp.c
@@ -4804,9 +4804,10 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
 		    }
 		}
 
-                if (PERL_ENABLE_TRIE_OPTIMISATION &&
-                        OP( startbranch ) == BRANCH )
-                {
+                if (PERL_ENABLE_TRIE_OPTIMISATION
+                    && OP(startbranch) == BRANCH
+                    && !frame
+                ) {
 		/* demq.
 
                    Assuming this was/is a branch we are dealing with: 'scan'
diff --git a/t/re/pat.t b/t/re/pat.t
index 4c7ca6f9e0b8..5a6e1daaf0ea 100644
--- a/t/re/pat.t
+++ b/t/re/pat.t
@@ -24,7 +24,7 @@ BEGIN {
 
 skip_all_without_unicode_tables();
 
-plan tests => 1017;  # Update this when adding/deleting tests.
+plan tests => 1018;  # Update this when adding/deleting tests.
 
 run_tests() unless caller;
 
@@ -2252,6 +2252,13 @@ SKIP:
         ok($result, "regexp correctly matched");
     }
 
+    # gh16947: test regexp corruption
+    {
+        fresh_perl_is(q{
+            'xy' =~ /x(?0)|x(?|y|y)/ && print 'ok'
+        }, 'ok', {}, 'gh16947: test regexp corruption');
+    }
+
 } # End of sub run_tests
 
 1;