Skip to content

Functions in const declarations ignore lifetimes, mutability, violate memory safety #22382

@lilyball

Description

@lilyball
Contributor

Functions defined inside of const declarations seem to ignore all lifetimes and mutability. This allows for massively violating the safety guarantees of Rust:

// Let's try moving out of a reference
const MOVE: fn(&String) -> String = {
    fn broken(x: &String) -> String {
        return *x
    }
    broken
};

// How about mutating an immutable vector?
const MUTATE: fn(&Vec<String>) = {
    fn broken(x: &Vec<String>) {
        x.push(format!("this is broken"));
    }
    broken
};

// Returning local references?
struct DropString {
    inner: String
}
impl Drop for DropString {
    fn drop(&mut self) {
        self.inner.clear();
        self.inner.push_str("dropped");
    }
}
const LOCAL_REF: fn() -> &'static str = {
    fn broken() -> &'static str {
        let local = DropString { inner: format!("Some local string") };
        return &local.inner;
    }
    broken
};

fn main() {
    // And yes, it all actually works
    let s = format!("some string");
    let s_moved = (MOVE)(&s);
    println!("s_moved: {}", s_moved);

    let v = vec![format!("immutable"), format!("vector")];
    (MUTATE)(&v);
    println!("mutated: {:?}", v);

    let local_ref = (LOCAL_REF)();
    println!("local_ref: {}", local_ref);
}

Activity

steveklabnik

steveklabnik commented on Feb 15, 2015

@steveklabnik
Member

Nominating, this seems incredibly serious.

lilyball

lilyball commented on Feb 15, 2015

@lilyball
ContributorAuthor

According to @eddyb it seems that the borrowck Visitor isn't bothering to walk statics/consts (see borrowck/mod.rs). Presumably this code was never updated when it became possible to use blocks as the initializer expression.

nikomatsakis

nikomatsakis commented on Feb 16, 2015

@nikomatsakis
Contributor

Um, yeah, not good. I'll investigate soonish, presuming @eddyb doesn't get there first.

self-assigned this
on Feb 19, 2015
pnkfelix

pnkfelix commented on Feb 19, 2015

@pnkfelix
Member

P-back-compatlang, 1.0 beta

added this to the 1.0 beta milestone on Feb 19, 2015
added a commit that references this issue on Feb 23, 2015
d443f98
added a commit that references this issue on Feb 24, 2015
2408698
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

    Development

    Participants

    @lilyball@steveklabnik@nikomatsakis@pnkfelix

    Issue actions

      Functions in const declarations ignore lifetimes, mutability, violate memory safety · Issue #22382 · rust-lang/rust