Skip to content

const_heap feature can be used to leak mutable memory into final value of constant #129233

Open
@RalfJung

Description

@RalfJung

Consider this code:

#![feature(core_intrinsics)]
#![feature(const_heap)]
#![feature(const_mut_refs)]
use std::intrinsics;

const BAR: *mut i32 = unsafe { intrinsics::const_allocate(4, 4) as *mut i32 };

fn main() {}

This code is problematic because when BAR is used multiple times in the program, it will always point to the same global allocation, violating the idea that consts behave as-if their initializer is inlined everywhere they are used. Furthermore, under our current interning strategy this allocation will end up being immutable in the runtime phase of the program, so writing it is UB, which could be quite surprising.

We have a safety net in the interner that catches this problem, but the safety net has a big gaping hole around shared references with interior mutability, and can hence easily be circumvented:

#![feature(core_intrinsics)]
#![feature(const_heap)]
#![feature(const_mut_refs, const_refs_to_cell)]

use std::intrinsics;
use std::cell::Cell;

const BAR: *mut i32 = unsafe {
    let launder = &*(intrinsics::const_allocate(4, 4) as *const Cell<i32>);
    launder as *const _ as *mut i32
};

fn main() {}

The gaping hole in the safety net is needed due to #121610 and rust-lang/unsafe-code-guidelines#493; also see the description of #128543 for more context.

This seems like a pretty major blocker for the const_heap feature, unless we want to just declare this UB "ex machina".

Cc @rust-lang/wg-const-eval
(Not something to be discussed any time soon, I am filing this because tidy forced me to have an issue number for the ICE that ensues from this mutable-ref-escape-prevention-bypass.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-bugCategory: This is a bug.F-const_heap`#[feature(const_heap)]`F-const_mut_refs`#![feature(const_mut_refs)]`F-core_intrinsicsIssue in the "core intrinsics" for internal usage only.P-lowLow priorityrequires-incomplete-featuresThis issue requires the use of incomplete features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions