From 7c83923be37aac2cdfe53bce1974bf917084c784 Mon Sep 17 00:00:00 2001 From: Matt Brubeck Date: Wed, 20 Mar 2024 11:30:13 -0700 Subject: [PATCH 1/2] Fix UB on out-of-bounds insert() Fixes #343. --- src/lib.rs | 9 +++++---- src/tests.rs | 7 +++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index cadb5d8..1ea3deb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1372,13 +1372,14 @@ impl SmallVec { } let mut ptr = ptr.as_ptr(); let len = *len_ptr; + if index > len { + panic!("index exceeds length"); + } + // SAFETY: add is UB if index > len, but we panicked first ptr = ptr.add(index); if index < len { + // Shift element to the right of `index`. ptr::copy(ptr, ptr.add(1), len - index); - } else if index == len { - // No elements need shifting. - } else { - panic!("index exceeds length"); } *len_ptr = len + 1; ptr::write(ptr, element); diff --git a/src/tests.rs b/src/tests.rs index 1de0a0d..f53100c 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -1049,3 +1049,10 @@ fn max_swap_remove() { let mut sv: SmallVec<[i32; 2]> = smallvec![0]; sv.swap_remove(usize::MAX); } + +#[test] +#[should_panic] +fn test_insert_out_of_bounds() { + let mut v: SmallVec<[i32; 4]> = SmallVec::new(); + v.insert(10, 6); +} From 0f3aacb99ccfe0cbbf0bb83ecf736f67339ce8ae Mon Sep 17 00:00:00 2001 From: Matt Brubeck Date: Wed, 20 Mar 2024 11:33:06 -0700 Subject: [PATCH 2/2] Bump version to 1.13.2 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 71189f1..ae2a9fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "smallvec" -version = "1.13.1" +version = "1.13.2" edition = "2018" authors = ["The Servo Project Developers"] license = "MIT OR Apache-2.0"