`CoerceShared` can violate privacy
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.2k
- PR merge metrics
- PR metrics pending
Description
The CoerceShared trait can be implemented to allow coercing from a local type to a foreign type. (Notably, the foreign crate does not need to use feature(reborrow) at all.) This allows creating an instance of that foreign type without going through public API, which can be used to violate invariants of the type.
As an example, the following code compiles and causes a null pointer dereference at run time.
dep/src/lib.rs:
use std::marker::PhantomData;
// SAFETY invariant: the pointer is valid as &'a i32
#[derive(Clone, Copy)]
pub struct MyRef<'a>((*const i32, PhantomData<&'a ()>));
// Note: This needs to be a tuple nested inside, since CoerceShared currently requires exactly 1 field
impl<'a> MyRef<'a> {
pub fn new(r: &'a i32) -> Self {
MyRef((r, PhantomData))
}
pub fn to_ref(self) -> &'a i32 {
unsafe { &*self.0.0 }
}
}
src/main.rs:
#![feature(reborrow)]
use std::marker::{CoerceShared, PhantomData, Reborrow};
use std::ptr;
use dep::MyRef;
#[expect(dead_code)]
struct MyMut<'a>((*const i32, PhantomData<&'a ()>));
impl Reborrow for MyMut<'_> {}
impl<'a> CoerceShared<MyRef<'a>> for MyMut<'a> {}
fn main() {
let my_mut = MyMut((ptr::null(), PhantomData));
let my_ref: MyRef<'_> = my_mut;
println!("{}", my_ref.to_ref());
}
cc @aapoalas
Meta
rustc --version --verbose:
rustc 1.97.0-nightly (ff9a9ea07 2026-05-13)
binary: rustc
commit-hash: ff9a9ea07bdc74e9555126464b02be8ff277f521
commit-date: 2026-05-13
host: aarch64-apple-darwin
release: 1.97.0-nightly
LLVM version: 22.1.4
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the two-crate example from dep/src/lib.rs and src/main.rs with the nightly rustc version shown. Read the CoerceShared and Reborrow definitions and related compiler tests; done means the demonstrated foreign-type construction can no longer violate the type's stated pointer invariant, with a regression test covering the case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers, security
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100