Skip to content

PyRawObject API unsafe #664

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
programmerjake opened this issue Nov 12, 2019 · 5 comments
Closed

PyRawObject API unsafe #664

programmerjake opened this issue Nov 12, 2019 · 5 comments
Labels

Comments

@programmerjake
Copy link
Contributor

PyRawObject doesn't track initialization:

#[pyclass]
struct MyType {
    value: String,
}

#[pymethods]
impl MyType {
    #[new]
    fn new(obj: &PyRawObject) -> PyResult<()> {
        obj.init(get_my_type_or_fail()?); // can fail to initialize, dropping uninitialized String
        obj.init(MyType { value: "abc".into() }); // can initialize twice, leaking memory
        Ok(())
    }
}
fn get_my_type_or_fail() -> PyResult<MyType> {
    unimplemented!()
}

PyRawObject doesn't check types:

#[pyclass]
struct MyType {
    value: String,
}
#[pyclass]
struct OtherType {
    value: f32,
}

#[pymethods]
impl MyType {
    #[new]
    fn new(obj: &PyRawObject) {
        obj.init(OtherType {value:1.0}); // initialize with incorrect type
        let value: &OtherType = obj.as_ref(); // get reference with incorrect type
        println!("{}", value.value); // access using incorrect type
    }
}
@programmerjake
Copy link
Contributor Author

I think it would be pretty common to forget to call init when handling errors, such as by using the ? operator. The rest of these problems are mostly theoretical.

@kngwyu kngwyu added the Unsound label Nov 12, 2019
@kngwyu
Copy link
Member

kngwyu commented Nov 12, 2019

Thank you for reporting.
But since I'm planning a huge API modification in this area, I don't want to fix this immediately.

@programmerjake
Copy link
Contributor Author

Thank you for reporting.
But since I'm planning a huge API modification in this area, I don't want to fix this immediately.

Would you be open to a pull request that just fixes initialization tracking so it panics, doesn't drop uninitialized memory, and/or doesn't double-initialize memory?

That should be pretty easy to do without a user-facing API change, would catch the most common mistake (forgetting to initialize), and can be replaced with your rewritten code when you're ready.

@kngwyu
Copy link
Member

kngwyu commented Nov 12, 2019

OK.
I’ll add simple assertions for that.

@Alexander-N
Copy link
Member

Fixed by #683

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants