Skip to content

Method resolution can be influenced in unexpected ways by external crates. #90907

Open
@steffahn

Description

@steffahn

I tried this code:

use std::cell::RefCell;

fn foo(x: &RefCell<Box<[u8]>>) {
    let y = x.borrow();
    let z = y.as_ref();

    println!("{:?}", z);
}

fn main() {
    foo(&RefCell::new(Box::new([1, 2, 3_u8])));
}

I expected to see this happen: Either the code should fail to compile or it should print [1, 2, 3] (the latter is what currently happens when the above is executed in the playground).

Instead, this happened: The code prints [21, 42, 63]

Context

What I didn’t tell you, my crate also contains this code

fn _unrelated_function() {
    some_dependency::useful_api()
}

other than that, there are no other traits in scope, etc; no potential for any surprises, really there’s nothing else; you’ve seen the whole source code of a crate that prints [21, 42, 63].

More context

Now, the dependency in question offers only a single public thing, a function

pub fn useful_api() {}

Of course it also has some

// private module!
mod dont_look_at_this {
    [DETAILS OMITTED]
}

but that clearly isn’t used in the useful_api implementation, so it’s probably some tests or whatever, entirely unrelated, and I don’t have to worry about, correct? Well apparently not correct.

Here’s the whole source code of some_dependency (click to expand).
pub fn useful_api() {}

// private module!
mod dont_look_at_this {
    mod really_nobody_should_care_about_this {
        pub struct Pwned;
        use std::{cell, fmt};
        impl fmt::Debug for Pwned {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("[21, 42, 63]")
            }
        }
        impl AsRef<Pwned> for cell::Ref<'_, Box<[u8]>> {
            fn as_ref(&self) -> &Pwned {
                &Pwned
            }
        }
    }
}

Full reproduction guide:

git clone https://github.com/steffahn/iffy_methods.git
cd iffy_methods
cargo run

Is this a known issue? Is this something that needs to be fixed? @rustbot label T-lang, T-compiler, A-traits, A-security

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-securityArea: Security (example: address space layout randomization).A-trait-systemArea: Trait systemC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions