Skip to content

dyn Allocator together with Allocator + Clone requirements is unsound, leading to UB with Arc #156920

Description

@maxdexh

View all comments

Part 2! This time featuring Clone instead of PartialEq. This one is way worse because Arc relies on it.

#![feature(allocator_api)]

use std::{
    alloc::{Allocator, Global, System},
    sync::Arc,
};

pub trait NewTrait: Allocator {}
impl<A: Allocator> NewTrait for A {}

impl Clone for Box<dyn NewTrait> { // valid because Box is special and NewTrait is a local type
    fn clone(&self) -> Self {
        // safe clone impl that violates the safety
        // requirements of Allocator because now,
        // Self: Allocator + Clone but the clone is different
        Box::new(System)
    }
}

use jemallocator::Jemalloc;

#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;

fn main() {
    let evil_arc = Arc::new_in(69420, Box::new(Global) as Box<dyn NewTrait>);
    let wat = evil_arc.clone(); // clone() returns the wrong allocator
    drop(evil_arc);
    drop(wat); // free(): invalid pointer
}

cc #156882

Edit: also forgot to mention #156906

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-allocatorsArea: Custom and system allocatorsA-boxArea: Our favorite opsem complicationA-coherenceArea: CoherenceA-dyn-compatibilityArea: Dyn compatibility (formerly: object safety)A-dyn-traitArea: trait objects, vtable layoutC-bugCategory: This is a bug.I-lang-radarItems that are on lang's radar and will need eventual work or consideration.I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.requires-nightlyThis issue requires a nightly compiler in some way. When possible, use a F-* label instead.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions