From 00823dd92335c3bb478c65d884e19a71f4e8d153 Mon Sep 17 00:00:00 2001 From: "HyeonGyu Lee (Vazrupe)" Date: Thu, 26 Sep 2019 12:45:47 +0900 Subject: [PATCH] Fix panic when using negative int for bytes() Fixes #1401 --- Cargo.lock | 1 + tests/snippets/basic_types.py | 6 ++++++ vm/src/obj/objbyteinner.rs | 4 +++- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 1dc6544601..02c6349b6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1221,6 +1221,7 @@ dependencies = [ "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", "js-sys 0.3.27 (registry+https://github.com/rust-lang/crates.io-index)", + "num-bigint 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", "rustpython-compiler 0.1.0", "rustpython-parser 0.1.0", diff --git a/tests/snippets/basic_types.py b/tests/snippets/basic_types.py index 006669b3f3..77d15e9697 100644 --- a/tests/snippets/basic_types.py +++ b/tests/snippets/basic_types.py @@ -1,3 +1,6 @@ +from testutils import assert_raises + + # Spec: https://docs.python.org/2/library/types.html print(None) # TypeType @@ -36,6 +39,9 @@ except TypeError: pass +with assert_raises(ValueError): + bytes(-1) + a = bytearray([1, 2, 3]) # assert a[1] == 2 diff --git a/vm/src/obj/objbyteinner.rs b/vm/src/obj/objbyteinner.rs index 4545c931b3..fe69b4420b 100644 --- a/vm/src/obj/objbyteinner.rs +++ b/vm/src/obj/objbyteinner.rs @@ -117,7 +117,9 @@ impl ByteInnerNewOptions { let value = if let OptionalArg::Present(ival) = self.val_option { match_class!(match ival.clone() { i @ PyInt => { - let size = objint::get_value(&i.into_object()).to_usize().unwrap(); + let size = objint::get_value(&i.into_object()) + .to_usize() + .ok_or_else(|| vm.new_value_error("negative count".to_string()))?; Ok(vec![0; size]) } _l @ PyString => {