Skip to content

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

Open
@1c3t3a

Description

@1c3t3a

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

Metadata

Metadata

Assignees

Labels

C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFC

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions