From b257aad239f2075ff66fae08c0a19dd0c27976ac Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Tue, 1 Feb 2022 17:49:21 -0500 Subject: [PATCH] Fix Miri complaints with -Zmiri-tag-raw-pointers Miri does not check all of Stacked Borrows (the prototype aliasing model for Rust) without -Zmiri-tag-raw-pointers. This enables the check in CI, and makes a few adjustments to fix places where pointers were invalidated by construction or use of a mutable reference. --- .github/workflows/main.yml | 2 ++ src/lib.rs | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 6baaaea..fec61b3 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -61,6 +61,8 @@ jobs: - name: miri if: matrix.toolchain == 'nightly' run: bash ./scripts/run_miri.sh + env: + MIRIFLAGS: '-Zmiri-tag-raw-pointers' - name: fuzz if: env.DO_FUZZ == '1' diff --git a/src/lib.rs b/src/lib.rs index 1699a71..d721789 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -392,8 +392,11 @@ impl<'a, T: 'a + Array> Drop for Drain<'a, T> { let start = source_vec.len(); let tail = self.tail_start; if tail != start { - let src = source_vec.as_ptr().add(tail); - let dst = source_vec.as_mut_ptr().add(start); + // as_mut_ptr creates a &mut, invalidating other pointers. + // This pattern avoids calling it with a pointer already present. + let ptr = source_vec.as_mut_ptr(); + let src = ptr.add(tail); + let dst = ptr.add(start); ptr::copy(src, dst, self.tail_len); } source_vec.set_len(start + self.tail_len); @@ -813,13 +816,14 @@ impl SmallVec { unsafe { self.set_len(start); - let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); + let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start); Drain { tail_start: end, tail_len: len - end, iter: range_slice.iter(), - vec: NonNull::from(self), + // Since self is a &mut, passing it to a function would invalidate the slice iterator. + vec: NonNull::new_unchecked(self as *mut _), } } } @@ -1112,6 +1116,10 @@ impl SmallVec { len: old_len + lower_size_bound, }; + // The set_len above invalidates the previous pointers, so we must re-create them. + let start = self.as_mut_ptr(); + let ptr = start.add(index); + while num_added < lower_size_bound { let element = match iter.next() { Some(x) => x,