Skip to content
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

Simplify CffiBuf code to avoid dangling pointer magic #10152

Merged
merged 1 commit into from
Jan 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/rust/src/buf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// 2.0, and the BSD License. See the LICENSE file in the root of this repository
// for complete details.

use std::{ptr, slice};
use std::slice;

use crate::types;

Expand All @@ -28,15 +28,9 @@ impl<'a> pyo3::conversion::FromPyObject<'a> for CffiBuf<'a> {
.extract()?;

let len = bufobj.len()?;
let ptr = if len == 0 {
ptr::NonNull::dangling().as_ptr()
let buf = if len == 0 {
&[]
} else {
ptrval as *const u8
};

Ok(CffiBuf {
_pyobj: pyobj,
_bufobj: bufobj,
// SAFETY: _extract_buffer_length ensures that we have a valid ptr
// and length (and we ensure we meet slice's requirements for
// 0-length slices above), we're keeping pyobj alive which ensures
Expand All @@ -45,7 +39,13 @@ impl<'a> pyo3::conversion::FromPyObject<'a> for CffiBuf<'a> {
// https://alexgaynor.net/2022/oct/23/buffers-on-the-edge/
// for details. This is the same as our cffi status quo ante, so
// we're doing an unsound thing and living with it.
buf: unsafe { slice::from_raw_parts(ptr, len) },
unsafe { slice::from_raw_parts(ptrval as *const u8, len) }
};

Ok(CffiBuf {
_pyobj: pyobj,
_bufobj: bufobj,
buf,
})
}
}
Loading