Skip to content

Static references to Python objects are allowed, but unsafe #653

@Askannz

Description

@Askannz

🐛 Bug Reports

There is no compile-time check preventing functions wrapped in PyO3 to take static references to Python objects. This allows those references to be stored and cause unsafe behavior.

Suggestion: forbid static references at compile-time (if possible), or add some documentation explaining why they shouldn't be used.

🌍 Environment

  • Your operating system and version: Archlinux
  • Your python version: 3.7.4
  • How did you install python (e.g. apt or pyenv)? Did you use a virtualenv?: Repo package + virtualenv
  • Your rust version (rustc --version): rustc 1.39.0-nightly (ca3766e2e 2019-09-14)
  • Are you using the latest pyo3 version? Have you tried using latest master (replace version = "0.x.y" with git = "https://github.com/PyO3/pyo3")? Yes

💥 Reproducing

Rust:

use pyo3::prelude::*;
use pyo3::types::PyList;

#[pymodule]
fn my_module(_py: Python, m: &PyModule) -> PyResult<()> {

    #[pyclass]
    struct MyClass { list: &'static PyList}

    #[pymethods]
    impl MyClass {

        #[new]
        fn new(obj: &PyRawObject, list: &'static PyList) {
            obj.init({ MyClass { list } });
        }

        fn print(&self) {
            println!("{}", self.list.len()); // KABOOM
        }
    }

    m.add_class::<MyClass>()?;

    Ok(())
}

Python :

>>> from my_module import MyClass
>>> obj = MyClass([1, 2, 3])
>>> obj.print()
Segmentation fault (core dumped)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions