Skip to content

{Rc,Arc}::eq has suspicious specialization for DSTs due to vtable merging and opsem mess. #164817

Description

@theemathas

Since #155579 (which I thought was a good idea, oops), Rc::eq and Arc::eq use specialization so that: If two DSTs have equal data pointers and equal metadata, then the eq() function returns true. This is suspect for trait objects, whose metadata are vtable pointers.

It seems to me that comparing vtable pointers should behave similarly to comparing function pointers. And as per #162140, we can conclude almost nothing from function pointer comparisons, then we also shouldn't be able to conclude useful stuff from vtable pointer comparisons.

I'm not sure if there's a real issue here, but this situation seems very suspect.

cc @rust-lang/opsem

cc @Gaming32 (author of #155579), @Mark-Simulacrum (reviewer of #155579)

Activity

  1. added
    A-DSTs
    C-bug
    T-libs
    T-opsem
    A-dyn-trait
    on Oct 23, 2026
  2. added
    needs-triage
    on Oct 23, 2026
  3. maxdexh commented on Oct 23, 2026

    @maxdexh
    Member

    We don't have Arc subobjects. If two Arcs have the same pointer and vtable pointer, they are always the exact same Arc, i.e. they were created by the same invocation of Arc::new/Arc::from_raw. So I think this is correct?

  4. theemathas commented on Oct 23, 2026

    @theemathas
    ContributorAuthor

    The issue is: Two vtable pointers comparing equal according to == might not imply that the two pointers are identical.

    Yes, I think that vtable pointers have provenance.

  5. maxdexh commented on Oct 23, 2026

    @maxdexh
    Member

    Oops, I had a brainfart. What I meant to say was there is no way for two Arcs (of the same type) with the same pointer to have different vtables. So I think it would even be correct if we ignored the vtable pointer entirely

  6. theemathas commented on Oct 23, 2026

    @theemathas
    ContributorAuthor

    I don't think that's true. See #154998. (Although I'm too tired right now to understand my past self lol)

  7. maxdexh commented on Oct 23, 2026

    @maxdexh
    Member

    Ah wait this is not true, we can into_raw a clone, cast through repr(transparent), then from_raw, then unsize the two versions to the same trait object type, then have the vtables of the different types be merged somehow?

  8. maxdexh commented on Oct 23, 2026

    @maxdexh
    Member

    FWIW the docs claim the same thing I did, despite this not being the implemented behavior: https://doc.rust-lang.org/std/sync/struct.Arc.html#method.eq

    If T also implements Eq (implying reflexivity of equality), two Arcs that point to the same allocation are always equal.

    It is at moments like this where I wish the lolsob emoji was in unicode

  9. added
    A-docs
    and removed
    needs-triage
    on Oct 23, 2026
  10. theemathas commented on Oct 24, 2026

    @theemathas
    ContributorAuthor

    See also #163372

  11. CAD97 commented on Oct 24, 2026

    @CAD97
    Contributor

    Let's assume that comparing vtable pointers gives a random result. I believe that, while observable, this specialization can be considered allowable under the same justification as the specialization for sized types. The cases:

    • true negative vtable equality: calls T::eq; correct.
    • false negative vtable equality: calls T::eq; correct.
    • true positive vtable equality: correct result for reflexive Eq1.
    • false positive vtable equality: further split into:
      • addresses are nonequal: calls T::eq; correct.
      • addresses are equal: extremely exotic situation, and the interesting one.

    With an arbitrary false positive, we can easily construct a surprising case:

    trait Trait { fn type_id(&self) -> TypeId; }
    
    #[repr(C)] struct A;
    impl Trait for A { fn type_id(&self) -> TypeId { TypeId::of::<A>() } }
    
    #[repr(C)] struct B;
    impl Trait for B { fn type_id(&self) -> TypeId { TypeId::of::<B>() } }
    
    impl Eq for dyn Trait + '_ {}
    impl PartialEq for dyn Trait + '_ {
        fn eq(&self, other: &Self) -> bool { self.type_id() == other.type_id() }
    }
    
    fn main() {
        let a: Arc<A> = Arc::new(A);
        let b: Arc<B> = unsafe { Arc::from_raw(Arc::into_raw(a.clone()).cast()) };
        let a: Arc<dyn Trait> = a;
        let b: Arc<dyn Trait> = b;
        dbg!(Arc::eq(&a, &b));
    }

    Constructing a case that could generate be a false positive for vtable equality and return false from T::eq is much more challenging, potentially even impossible. However, proving it impossible is not necessary to argue soundness: the result of false positive equality results in a spurious true with the exact same consequence as spurious true comparison of sized non-reflexive Eq implementations.

    Footnotes

    1. If the Eq implementation is not reflexive, this will spuriously return true when the elided eq call would return false, the same as a non-reflexive implementation for a sized type. ↩

  12. niluxv commented on Oct 24, 2026

    @niluxv
    Contributor

    Constructing a case that could generate be a false positive for vtable equality and return false from T::eq is much more challenging, potentially even impossible.

    An actual "miscompile" is probably challenging, but the code you posted can technically print true; you just need a heck of a smart compiler: the optimiser could notice that as soon as it folds the vtable pointer comparison to true, <dyn Trait>::eq is unused, and then <A as Trait>::type_id and <B as Trait>::type_id are unused as well. Then it can merge the unused <A as Trait>::type_id and <B as Trait>::type_id, so the vtables become equal, and they can be merged as well. That (retroactively) justifies the fold that we started with.

    exact same consequence as spurious true comparison of sized non-reflexive Eq implementations.

    Yes, technically you can read the currently documented exception

    If T also implements Eq (implying reflexivity of equality), two Arcs that point to the same allocation are always equal.

    as implying that you never need to (actually: should not) compare pointer metadata. But clearly this was not meant. The PR that introduced the change even added a test

    let a: Arc<[()]> = Arc::new([(); 3]);
    let ptr: *const () = Arc::into_raw(a.clone()).cast();
    let b: Arc<[()]> = unsafe { Arc::from_raw(core::ptr::slice_from_raw_parts(ptr, 42)) };
    assert!(a != b);

    That contradicts the documentation: we have two Arc<[()]>s that point to the same address/allocation. Since [()] implements Eq, according to the documentation they must compare equal. The test checks that the compare unequal. I think everyone would agree that the test is correct and the documentation is wrong. Arcs of ZST-slices of different length should never compare equal, just like references to such slices would never compare equal.

    The main difference with the sized setting is that there, to get "wrong" behaviour from Arc::<T>::eq you need an implementation of T: PartialEq + Eq that does not adhere to the invariants documented on those traits. Since those traits are safe to implement, Arc explicitly documents that it does rely on a correct implementation to produce the correct answers for equality comparisons. But in the dyn Trait setting, the programmer did nothing wrong (at least according to current documentation), and still got the "wrong" answer.

    Btw, I don't think we should guarantee that

    If T also implements Eq (implying reflexivity of equality), two Arcs that point to the same allocation are always equal.

    because that guarantees that we always do the pointer comparison check. I think it would be better to phrase it as a "we might spuriously return true". That way we don't lock ourselves into always having to perform the pointer equality check (if it turns out to be a pessimization rather than optimization in some cases).

  13. RalfJung commented on Oct 24, 2026

    @RalfJung
    Member

    See past discussion in #46139, #69757.
    So yes, comparing vtables is indeed pretty meaningless.

    the optimiser could notice that as soon as it folds the vtable pointer comparison to true, <dyn Trait>::eq is unused, and then <A as Trait>::type_id and <B as Trait>::type_id are unused as well. Then it can merge the unused <A as Trait>::type_id and <B as Trait>::type_id, so the vtables become equal, and they can be merged as well. That (retroactively) justifies the fold that we started with.

    Wouldn't it be enough to inline everything, which makes the type_id functions unused, so their bodies can be erased, and then everything can be merged? That would not require a "loop" in the reasoning.

  14. RalfJung commented on Nov 18, 2026

    @RalfJung
    Member

    I think we should take back the specialization for types with dyn Trait tail: #166143.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-DSTsA-docsA-dyn-traitC-bugT-libsT-opsem

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions