78f1eb
From 7e5b390a008ccad094a39c350f385d58e8a5102a Mon Sep 17 00:00:00 2001
78f1eb
From: Karl Williamson <khw@cpan.org>
78f1eb
Date: Fri, 3 May 2019 13:57:47 -0600
78f1eb
Subject: [PATCH] Remove undefined behavior from IV shifting
78f1eb
MIME-Version: 1.0
78f1eb
Content-Type: text/plain; charset=UTF-8
78f1eb
Content-Transfer-Encoding: 8bit
78f1eb
78f1eb
It is undefined behavior to shift a negative integer to the left.  This
78f1eb
commit avoids that by treating the value as unsigned, then casting back
78f1eb
to integer for return.
78f1eb
78f1eb
Petr Písař: Ported to 5.30.0 from
78f1eb
814735a391b874af8f00eaf89469e5ec7f38cd4aa.
78f1eb
78f1eb
Signed-off-by: Petr Písař <ppisar@redhat.com>
78f1eb
---
78f1eb
 asan_ignore |  5 -----
78f1eb
 pp.c        | 21 ++++++++++++++++++++-
78f1eb
 2 files changed, 20 insertions(+), 6 deletions(-)
78f1eb
78f1eb
diff --git a/asan_ignore b/asan_ignore
78f1eb
index e0f5685..f520546 100644
78f1eb
--- a/asan_ignore
78f1eb
+++ b/asan_ignore
78f1eb
@@ -18,11 +18,6 @@
78f1eb
 
78f1eb
 fun:Perl_pp_i_*
78f1eb
 
78f1eb
-# Perl's << is defined as using the underlying C's << operator, with the
78f1eb
-# same undefined behaviour for shifts greater than the word size.
78f1eb
-# (UVs normally, IVs with 'use integer')
78f1eb
-
78f1eb
-fun:Perl_pp_left_shift
78f1eb
 
78f1eb
 # this function numifies the field width in eg printf "%10f".
78f1eb
 # It has its own overflow detection, so don't warn about it
78f1eb
diff --git a/pp.c b/pp.c
78f1eb
index 7afb090..3ca04e1 100644
78f1eb
--- a/pp.c
78f1eb
+++ b/pp.c
78f1eb
@@ -1991,10 +1991,29 @@ static IV S_iv_shift(IV iv, int shift, bool left)
78f1eb
        shift = -shift;
78f1eb
        left = !left;
78f1eb
    }
78f1eb
+
78f1eb
    if (UNLIKELY(shift >= IV_BITS)) {
78f1eb
        return iv < 0 && !left ? -1 : 0;
78f1eb
    }
78f1eb
-   return left ? iv << shift : iv >> shift;
78f1eb
+   /* For left shifts, perl 5 has chosen to treat the value as unsigned for
78f1eb
+    * the * purposes of shifting, then cast back to signed.  This is very
78f1eb
+    * different from perl 6:
78f1eb
+    *
78f1eb
+    * $ perl6 -e 'say -2 +< 5'
78f1eb
+    * -64
78f1eb
+    *
78f1eb
+    * $ ./perl -le 'print -2 << 5'
78f1eb
+    * 18446744073709551552
78f1eb
+    * */
78f1eb
+   if (left) {
78f1eb
+       if (iv == IV_MIN) { /* Casting this to a UV is undefined behavior */
78f1eb
+           return 0;
78f1eb
+       }
78f1eb
+       return (IV) (((UV) iv) << shift);
78f1eb
+   }
78f1eb
+
78f1eb
+   /* Here is right shift */
78f1eb
+   return iv >> shift;
78f1eb
 }
78f1eb
 
78f1eb
 #define UV_LEFT_SHIFT(uv, shift) S_uv_shift(uv, shift, TRUE)
78f1eb
-- 
78f1eb
2.20.1
78f1eb