rust-lang / rust-lang/rust

Tracking Issue for the enum discriminant check (part of -Z ub-checks)

Open
#143,087 2 comments 0 reactions 1 assignee View on GitHub

@1c3t3a is already working on this.

Since Jun 27, 2025.

C-tracking-issue
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

What is this?

We recently added checks for valid enum discriminants to -Zub-checks (PR #141759). This currently sanitizes (in dbg-builds) for a pattern where an invalid enum is created. As an example the following code:

#[repr(u8)]
enum Foo {
  A = 0,
  B = 1
}
...
let foo = unsafe { std::mem::transmute::<_, Foo>(3_u8) };

Would result in the following runtime panic:

trying to construct an enum from an invalid value 0x3

While this is nice and helpful, most people don't transmute to invalid enum values. A much more common place where this can happen is when interacting with other languages. E.g. with C(++):

#[repr(C)]
enum Foo {
  A,
  B,
}

unsafe extern "C" {
    fn get_foo() -> *const Foo;
}
...
let foo = unsafe { *get_foo() };

The current check is not sufficient here and wouldn't catch the invalid value. So one goal is to extend the check to catch such cases.

Another improvement we would like to do is a better debug message for when this fails. At the moment this just tells the invalid runtime discriminant value that was used to create this enum. It would be helpful to have more information here.

Steps
  • Extend the check to union reads
  • Extend the check to pointer reads
  • Improve the error message with information about the enum type that we tried to construct
  • Improve the error message with information about the valid values that can be used to construct this enum
Implementation history

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.