rust-lang / rust-lang/rust

`impl Deref for &Extern` shouldn't be allowed

Open
#149,231 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug F-extern_types F-sized_hierarchy T-libs T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

The following code compiles, but probably shouldn't.

#![feature(extern_types)]

unsafe extern "C" {
    type Extern;
}

impl std::ops::Deref for &Extern {
    type Target = i32;
    fn deref(&self) -> &i32 { &1 }
}

This doesn't overlap with the existing Deref impl for references, since the T: ?Sized bound desugars to T: MetaSized, and Extern doesn't implement MetaSized.

As a result, we can write some goofy-looking code such as the following, which compiles without errors:

#![feature(extern_types)]

use std::ops::Deref;
use std::pin::Pin;

unsafe extern "C" {
    type Extern;
}

impl Deref for &mut Extern {
    type Target = i32;
    fn deref(&self) -> &i32 { &1 }
}

fn make_extern() -> &'static mut Extern {
    // Suppose that this allocates and leaks an Extern on the heap
    unsafe { &mut *(1 as *mut Extern) }
}

fn main() {
    let r: &'static mut Extern = make_extern();
    // This is allowed because &mut Extern dereferences to i32,
    // which is Unpin
    let p: Pin<&'static mut Extern> = Pin::new(r);
}

I am unable to actually cause UB with this weirdness, but I wouldn't be surprised if there's some code that assumes that references implement Deref sanely.

Meta

Reproducible on the playground with version 1.93.0-nightly (2025-11-22 94b49fd998d6723e0a92)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the two examples on the reported Rust nightly version, then investigate how Deref implementations for references to extern types interact with the existing reference impl, MetaSized, and Pin::new. The work is complete when the intended behavior is decided and covered by regression tests showing whether these impls should be accepted.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.