pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

PyO3 does not respect struct memory alignment

Open onsmith opened this issue 2 years ago • 0 comments

Bug Description

PyO3 does not respect memory alignment rules when defining Python classes using the #[pyclass] and #[new] annotations.

PyO3 Python classes with Rust-defined memory alignment requirements (for example, defined with #[repr(align())]) cause runtime panics or segfaults.

Steps to Reproduce

I created a complete minimal example to reproduce the issue. Key snippet:

#[derive(Clone)]
#[repr(align(64))]
struct Aligned64<T>(T);

#[pyclass]
pub(crate) struct StructWithAlignedFields {
    aligned_field: Aligned64<u64>,
}

#[pymethods]
impl StructWithAlignedFields {
    #[new]
    pub(crate) fn new() -> PyResult<Self> {
        Ok(StructWithAlignedFields {
            aligned_field: Aligned64(0),
        })
    }
}

#[pymodule]
fn foopy(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
    m.add_class::<StructWithAlignedFields>()?;
    Ok(())
}

This code panics when foopy.StructWithAlignedFields() is executed in Python 3:

misaligned pointer dereference: address must be a multiple of 0x40 but is 0x7f8a02ef9f30

Backtrace

No response

Your operating system and version

Amazon Linux 2

Your Python version (python --version)

Python 3.9.18

Your Rust version (rustc --version)

rustc 1.73.0 (cc66ad468 2023-10-03)

Your PyO3 version

0.20.0

How did you install python? Did you use a virtualenv?

make install from a source tarball from python.org

Additional Info

My guess is that the macro which copies the field attributes is not correctly grabbing the alignment or is unable to.

onsmith avatar Nov 29 '23 23:11 onsmith