cgmath icon indicating copy to clipboard operation
cgmath copied to clipboard

Soundness issue: Matrix2/Matrix3/Matrix4 swap_columns can trigger UB in Safe Rust when a == b

Open yilin0518 opened this issue 8 months ago • 2 comments

Hello, I found a soundness issue in cgmath 0.18.0 affecting three implementations of swap_columns.

Summary

Matrix2::swap_columns, Matrix3::swap_columns, and Matrix4::swap_columns all use:

unsafe { ptr::swap(&mut self[a], &mut self[b]) };

When a == b, this creates two overlapping mutable references to the same location through a Safe API call, violating Rust aliasing guarantees and triggering UB under Miri.

Why this is unsound:

  • Caller uses only Safe Rust.
  • Passing equal indices is allowed by the function signature.
  • Equal indices cause aliased &mut borrows.
  • Miri reports UB (Stacked Borrows violation) in std::ptr::swap, with backtrace into each corresponding swap_columns implementation.

Minimal PoCs (Safe Rust):

  • Matrix2:
use cgmath::{Matrix, Matrix2};

fn main() {
    let mut m = Matrix2::new(1.0, 2.0, 3.0, 4.0);
    m.swap_columns(0, 0);
}
  • Matrix3:
use cgmath::{Matrix, Matrix3};

fn main() {
    let mut m = Matrix3::new(
        1.0, 2.0, 3.0,
        4.0, 5.0, 6.0,
        7.0, 8.0, 9.0,
    );
    m.swap_columns(1, 1);
}
  • Matrix4:
use cgmath::{Matrix, Matrix4};

fn main() {
    let mut m = Matrix4::new(
        1.0, 2.0, 3.0, 4.0,
        5.0, 6.0, 7.0, 8.0,
        9.0, 10.0, 11.0, 12.0,
        13.0, 14.0, 15.0, 16.0,
    );
    m.swap_columns(2, 2);
}

Miri report:

  • Matrix2:
error: Undefined Behavior: attempting a read access using <281> at alloc120[0x0], but that tag does not exist in the borrow stack for this location
    --> /home/yilin/.rustup/toolchains/nightly-2025-12-06-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:1308:9
     |
1308 |         copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
     |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this error occurs as part of an access at alloc120[0x0..0x10]
     |
     = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
     = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
help: <281> was created by a SharedReadWrite retag at offsets [0x0..0x10]
    --> src/main.rs:9:5
     |
   9 |     m.swap_columns(0, 0);
     |     ^^^^^^^^^^^^^^^^^^^^
help: <281> was later invalidated at offsets [0x0..0x20] by a Unique retag
    --> src/main.rs:9:5
     |
   9 |     m.swap_columns(0, 0);
     |     ^^^^^^^^^^^^^^^^^^^^
     = note: BACKTRACE (of the first span):
     = note: inside `std::ptr::swap::<cgmath::Vector2<f64>>` at /home/yilin/.rustup/toolchains/nightly-2025-12-06-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:1308:9: 1308:52
     = note: inside `<cgmath::Matrix2<f64> as cgmath::Matrix>::swap_columns` at /home/yilin/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/cgmath-0.18.0/src/matrix.rs:583:18: 583:55
note: inside `main`
    --> src/main.rs:9:5
     |
   9 |     m.swap_columns(0, 0);
     |     ^^^^^^^^^^^^^^^^^^^^

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to 1 previous error

The miri report of Matirx3 and Matrix4 are same to Matrix2.

Suggested fix:

A minimal safe fix is to return early when indices are equal:

if a == b {
    return;
}
unsafe { ptr::swap(&mut self[a], &mut self[b]) };

This should be applied consistently to all three implementations.

Thanks for maintaining cgmath.

yilin0518 avatar Mar 11 '26 07:03 yilin0518

@aloucks @kvark it looks like this crate is not getting any maintenance. Should we publish an advisory to make that official?

djc avatar Jun 01 '26 13:06 djc

Scope clarification on @yilin0518's report above: this isn't limited to a == b. swap_columns is UB for any two indices, including genuinely distinct ones, and the same pattern is reachable through entirely ordinary API use that never calls swap_columns/swap_elements by name at all.

1. swap_columns itself is UB for distinct indices, not just a == b:

use cgmath::{Matrix, Matrix2};

fn main() {
    let mut m = Matrix2::new(1.0, 2.0, 3.0, 4.0);
    m.swap_columns(0, 1); // distinct indices -- not the reported a==b case
}
error: Undefined Behavior: attempting a read access using <614> at alloc226[0x0], but that tag does not exist in the borrow stack for this location
    --> .../core/src/ptr/mod.rs:1327:9
     |
1327 |         copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
     |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this error occurs as part of an access at alloc226[0x0..0x10]
     = note: stack backtrace:
             0: std::ptr::swap::<cgmath::Vector2<f64>>
             1: <cgmath::Matrix2<f64> as cgmath::Matrix>::swap_columns
                 at .../cgmath-0.18.0/src/matrix.rs:583:18: 583:55
             2: main

2. It's reachable without ever calling swap_columns/swap_elements by name. Matrix2::transpose_self() (and the Matrix3/Matrix4 equivalents) calls swap_elements internally, which has the identical unsafe { ptr::swap(...) } shape:

use cgmath::{Matrix2, SquareMatrix};

fn main() {
    let mut m = Matrix2::new(1.0, 2.0, 3.0, 4.0);
    m.transpose_self();
}
error: Undefined Behavior: attempting a read access using <636> at alloc226[0x8], but that tag does not exist in the borrow stack for this location
    --> .../core/src/ptr/mod.rs:1327:9
     = note: stack backtrace:
             0: std::ptr::swap::<f64>
             1: <cgmath::Matrix2<f64> as cgmath::Matrix>::swap_elements
                 at .../cgmath-0.18.0/src/matrix.rs:590:18: 590:65
             2: <cgmath::Matrix2<f64> as cgmath::SquareMatrix>::transpose_self
                 at .../cgmath-0.18.0/src/matrix.rs:625:9: 625:43
             3: main

3. Array::swap_elements (src/structure.rs:78) has the same shape and is separately confirmed — not just by inspection: Vector4::new(1.,2.,3.,4.).swap_elements(0, 2) aborts with the identical ptr::swap backtrace, just through structure.rs:78 instead of matrix.rs:590.

4. Repro #1 (distinct-index swap_columns) is confirmed on Matrix3 and Matrix4 too, not just Matrix2 — Matrix3::new(...).swap_columns(0, 2) and Matrix4::new(...).swap_columns(1, 3) both abort with the identical ptr::swap backtrace through their own swap_columns. Not extrapolated from Matrix2 alone.

All three run with:

$ rustc +nightly --version
rustc 1.98.0-nightly (54333ff07 2026-05-22)
$ cargo +nightly miri --version
miri 0.1.0 (54333ff079 2026-05-22)
$ cargo +nightly miri run

Practical implications for the fix:

  1. The minimal if a == b { return; } guard (as suggested above) closes the reported PoC but not repro #1 — distinct indices still hit the aliasing violation, guard or no guard.
  2. Matrix::swap_elements and Array::swap_elements aren't mentioned in the original report, but swap_elements is what transpose_self actually calls, and both have the identical pattern.
  3. A read-into-temp-then-write-back rewrite (no unsafe, no aliasing &muts ever constructed) closes all of the above at once, independent of index equality — happy to expand on the exact shape if useful.

I ran into this doing a from-scratch Miri sweep on a source-compatible fork (cgmath-next, unaffiliated with this project, built for exactly this kind of gap). Linking in case the repro detail or fix shape is useful here — not asking anyone to adopt the fork:

Thanks to @yilin0518 for the original report and clean Miri output — this is scope clarification on top of that finding, not a separate issue.

kent-tokyo avatar Aug 16 '26 09:08 kent-tokyo