nalgebra icon indicating copy to clipboard operation
nalgebra copied to clipboard

fix: resolve Miri UB in SMatrix decompositions

Open pandashark opened this issue 9 months ago • 0 comments

Summary

Fixes #1520

Rewrites array_axcpy and array_axc in blas_uninit.rs to use raw pointers instead of slice references, fixing Miri-detected undefined behavior when decompositions run on SMatrix (stack-allocated via ArrayStorage).

Root cause: The previous code obtained &mut [T] / &[T] via as_mut_slice_unchecked() / as_slice_unchecked() on column views from columns_range_pair_mut(). When both views derived from the same underlying ArrayStorage, these references aliased the same allocation, violating Rust's aliasing rules. Miri flagged this under both Stacked Borrows and Tree Borrows.

Fix: Use ptr_mut() / ptr() with ptr::read / ptr::write to avoid creating references that trigger Stacked Borrows retags. Raw pointer accesses do not push tags onto the borrow stack, so they cannot invalidate sibling borrows.

See root cause analysis comment for full details.

What Changed

  • src/base/uninit.rs — Added init_ptr and assume_init_read to InitStatus trait for raw pointer operations on potentially-uninitialized memory
  • src/base/blas_uninit.rs — Rewrote array_axcpy/array_axc to use raw pointers; axcpy_uninit now uses ptr()/ptr_mut() instead of as_slice_unchecked()/as_mut_slice_unchecked(); added // SAFETY documentation to gemv_uninit and gemm_uninit
  • tests/linalg/miri_smatrix.rs — 11 regression tests covering all major SMatrix decompositions (Cholesky, LU, FullPivLU, QR, ColPivQR, Hessenberg, Schur, SymmetricTridiagonal, SymmetricEigen, Bidiagonal, SVD)

Verification

Check Result
Miri (Tree Borrows) 11/11 pass
Full test suite 563 pass, 1 pre-existing trybuild failure
Clippy Clean
no_std build Passes

Known Limitation: Deeper Stacked Borrows Issue

Under Stacked Borrows (but not Tree Borrows), a second, separate UB exists in the view creation system. When rows_range_mut is called on a MatrixViewMut, the macro at matrix_view.rs:819 performs &mut self.data which triggers a Unique retag that invalidates pointers derived from the parent ArrayStorage. This affects all code paths through columns_range_pair_mut + sub-view creation, regardless of this fix.

Under Tree Borrows (the likely successor aliasing model), this is not a violation. This is a separate architectural concern that would require changes to the view infrastructure and should be tracked independently.

Test Plan

  • [x] cargo +nightly miri test miri_smatrix passes under Tree Borrows
  • [x] cargo test — full suite passes (563/564, 1 pre-existing trybuild)
  • [x] cargo clippy — clean
  • [x] cargo build --no-default-features — no_std builds

pandashark avatar Feb 18 '26 18:02 pandashark