Skip to content

Const validation rejects references that might be dangling (but could actually be valid at run-time) #63197

Open
@axos88

Description

Apparently it's undefined behaviour to use:

const gpio: &RegisterBlock = unsafe { (& (*lpc176x5x::GPIO::ptr())) };

but not undefined to use:

fn x() {
  let gpio: &RegisterBlock = unsafe { (& (*lpc176x5x::GPIO::ptr())) };
  (...)
}

with:

    pub const fn ptr() -> *const gpio::RegisterBlock {
        0x2009_c000 as *const _
    }

Error message is:

error[E0080]: it is undefined behavior to use this value
  --> src/rtos.rs:27:1
   |
27 | const gpio: &RegisterBlock = unsafe { (& (*lpc176x5x::GPIO::ptr())) };
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered dangling reference (created from integer)
   |
   = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior

This is happening on in an embedded envrionment, where there is no MMU, and access to that address is correct.
I'm not sure why it would be undefined to use it as a const, but not undefined to use it as a variable value?
Perpahs it has something to do with the borrow checker not being able to track mutable and unmutable references to that value, but this is an immutable access, so it should be fine?

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language team, which will review and decide on the PR/issue.needs-rfcThis change is large or controversial enough that it should have an RFC accepted before doing it.requires-nightlyThis issue requires a nightly compiler in some way.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions