Blob Blame History Raw
From 4e0fb37303b72ed9d38949139c304abdb73e223e Mon Sep 17 00:00:00 2001
From: Aaron Crane <arc@cpan.org>
Date: Tue, 24 Jan 2017 23:39:40 +0000
Subject: [PATCH] RT#130624: heap-use-after-free in 4-arg substr
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Ported to 5.24.1:

commit 41b1e858a075694f88057b9514f5fc78c80b5355
Author: Aaron Crane <arc@cpan.org>
Date:   Tue Jan 24 23:39:40 2017 +0000

    RT#130624: heap-use-after-free in 4-arg substr

Signed-off-by: Petr Písař <ppisar@redhat.com>
---
 pp.c          |  4 +++-
 t/op/substr.t | 14 +++++++++++++-
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/pp.c b/pp.c
index 334b353..aa6cff0 100644
--- a/pp.c
+++ b/pp.c
@@ -3462,8 +3462,10 @@ PP(pp_substr)
 	tmps = SvPV_force_nomg(sv, curlen);
 	if (DO_UTF8(repl_sv) && repl_len) {
 	    if (!DO_UTF8(sv)) {
+                /* Upgrade the dest, and recalculate tmps in case the buffer
+                 * got reallocated; curlen may also have been changed */
 		sv_utf8_upgrade_nomg(sv);
-		curlen = SvCUR(sv);
+		tmps = SvPV_nomg(sv, curlen);
 	    }
 	}
 	else if (DO_UTF8(sv))
diff --git a/t/op/substr.t b/t/op/substr.t
index 01c36a9..f9fee48 100644
--- a/t/op/substr.t
+++ b/t/op/substr.t
@@ -22,7 +22,7 @@ $SIG{__WARN__} = sub {
      }
 };
 
-plan(389);
+plan(391);
 
 run_tests() unless caller;
 
@@ -872,3 +872,15 @@ is($destroyed, 1, 'Timely scalar destruction with lvalue substr');
 
 # failed with ASAN
 fresh_perl_is('$0 = "/usr/bin/perl"; substr($0, 0, 0, $0)', '', {}, "(perl #129340) substr() with source in target");
+
+
+# [perl #130624] - heap-use-after-free, observable under asan
+{
+    my $x = "\xE9zzzz";
+    my $y = "\x{100}";
+    my $z = substr $x, 0, 1, $y;
+    is $z, "\xE9",        "RT#130624: heap-use-after-free in 4-arg substr (ret)";
+    is $x, "\x{100}zzzz", "RT#130624: heap-use-after-free in 4-arg substr (targ)";
+}
+
+
-- 
2.7.4