Skip to content

AsPyPointer should be unsafe trait #3325

@alex

Description

@alex

Bug Description

Various code in pyo3 relies on AsPyPointer::as_ptr to return a valid pointer. But because it's not an unsafe trait, it has no invariants.

Steps to Reproduce

struct Malice;

impl pyo3::AsPyPointer for Malice {
    fn as_ptr(&self) -> *mut pyo3::ffi::PyObject {
        0xDEAFBEEF as *mut pyo3::ffi::PyObject
    }
}

fn main() {
    pyo3::prepare_freethreaded_python();
    pyo3::Python::with_gil(|py| {
        let obj = Malice;
        pyo3::types::PyIterator::from_object(py, &obj).expect("Failed to create iterator");
    });
}

Backtrace

/t/t ❯❯❯ cargo run
   Compiling t v0.1.0 (/private/tmp/t)
    Finished dev [unoptimized + debuginfo] target(s) in 0.11s
     Running `target/debug/t`
fish: Job 1, 'cargo run' terminated by signal SIGSEGV (Address boundary error)
/t/t ❯❯❯ gdb^C
/t/t ❯❯❯ lldb ./target/debug/t
(lldb) target create "./target/debug/t"
Current executable set to '/tmp/t/target/debug/t' (arm64).
(lldb) run
Process 46947 launched: '/tmp/t/target/debug/t' (arm64)
Process 46947 stopped
* thread #1, name = 'main', queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0xdeafbef7)
    frame #0: 0x000000010062f120 Python`PyObject_GetIter + 16
Python`PyObject_GetIter:
->  0x10062f120 <+16>: ldr    x8, [x0, #0x8]
    0x10062f124 <+20>: ldr    x9, [x8, #0xd8]
    0x10062f128 <+24>: cbz    x9, 0x10062f160           ; <+80>
    0x10062f12c <+28>: blr    x9
Target 0: (t) stopped.


### Your operating system and version

Impacts all

### Your Python version (`python --version`)

Impacts all

### Your Rust version (`rustc --version`)

Impacts all

### Your PyO3 version

0.19

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

Impacts all

### Additional Info

_No response_

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions