Wrong method is called by vtable of trait object. Compiler bug?
⚓ Rust 📅 2025-09-13 👤 surdeus 👁️ 8Dear, All.
I need help of seasoned rustaceans because it seems that I stumbled upon a compiler bug or some very obscure problem that I can't debug myself.
I have a very weird issue when working with the trait objects - wrong methods are called by vtable and the program crash with memory corruption. The biggest problem is that I can't isolate the bug - it only happens inside rather complex code base of molar crate and it's impossible to provide a small self-consistent example.
In essence, I have the traits like this:
pub trait TopologyWrite: RandomAtomProvider + RandomBondProvider {}
pub trait StateWrite: RandomPosProvider + BoxProvider + TimeProvider {}
pub trait TopologyStateWrite: TopologyWrite + StateWrite {...}
Then I have a method that takes TopologyStateWrite trait object like this:
fn write_state(&mut self, data: &dyn StateWrite) -> Result<(), super::FileFormatError> {
...
let b = data.get_box();
...
}
This should call a method get_box() from the BoxProvider trait, which is a bound of StateWrite. However, when I step over it in debugger a completely different method num_bonds() is called instead, which is from RandomBondProvider trait (a bound of TopologyWrite)!
After some experimentation I found that whatever I do the compiler is calling the N-th method of TopologyWrite (in the order of declaration) when I'm asking to call the N-th method of StateWrite! So it literally uses the wrong vtable or wrong offset in a vtable, or whatever.
This looks like a compiler bug because I don't see anything so much cursed in the code (although it uses some unsafe things under the hood).
Can someone familiar with vtables magic help me with this to trace it either to compiler bug or to my own mistake?
In order to reproduce:
git clone -b dyn https://github.com/yesint/molar.gitcargo test --package molar --lib -- core::selection::tests::test_write_to_file --exact --show-output --nocapture- See the error "signal: 11, SIGSEGV: invalid memory reference" because wrong method is used and the memory is screwed up.
Any help will be deeply appreciated!
9 posts - 4 participants
🏷️ Rust_feed