From 0d4185f30e360b078d663acd8f4dfda95fe2aae9 Mon Sep 17 00:00:00 2001 From: akr Date: Fri, 17 Oct 2014 09:49:28 +0000 Subject: * Avoid undefined behaviors found by gcc -fsanitize=undefined. gcc (Debian 4.9.1-16) 4.9.1 * string.c (rb_str_sum): Avoid undefined behavior. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@47997 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 7 +++++++ string.c | 4 +++- test/ruby/test_string.rb | 4 +++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index b5dd1f2ea8..5db122c023 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,10 @@ +Fri Oct 17 17:50:10 2014 Tanaka Akira + + * Avoid undefined behaviors found by gcc -fsanitize=undefined. + gcc (Debian 4.9.1-16) 4.9.1 + + * string.c (rb_str_sum): Avoid undefined behavior. + Fri Oct 17 17:43:50 2014 Tanaka Akira * Avoid undefined behaviors found by gcc -fsanitize=undefined. diff --git a/string.c b/string.c index c2501f99b1..b433a21446 100644 --- a/string.c +++ b/string.c @@ -7571,7 +7571,7 @@ rb_str_ord(VALUE s) * * Returns a basic n-bit checksum of the characters in str, * where n is the optional Fixnum parameter, defaulting - * to 16. The result is simply the sum of the binary value of each character in + * to 16. The result is simply the sum of the binary value of each byte in * str modulo 2**n - 1. This is not a particularly good * checksum. */ @@ -7592,6 +7592,8 @@ rb_str_sum(int argc, VALUE *argv, VALUE str) else { rb_scan_args(argc, argv, "01", &vbits); bits = NUM2INT(vbits); + if (bits < 0) + bits = 0; } ptr = p = RSTRING_PTR(str); len = RSTRING_LEN(str); diff --git a/test/ruby/test_string.rb b/test/ruby/test_string.rb index d82d2bc59e..543c1389bd 100644 --- a/test/ruby/test_string.rb +++ b/test/ruby/test_string.rb @@ -1584,6 +1584,8 @@ class TestString < Test::Unit::TestCase assert_equal(16, n.sum(17)) n[0] = 2.chr assert_not_equal(15, n.sum) + assert_equal(17, n.sum(0)) + assert_equal(17, n.sum(-1)) end def check_sum(str, bits=16) @@ -1598,7 +1600,7 @@ class TestString < Test::Unit::TestCase assert_equal(294, "abc".sum) check_sum("abc") check_sum("\x80") - 0.upto(70) {|bits| + -3.upto(70) {|bits| check_sum("xyz", bits) } end -- cgit v1.2.3