Skip to content

Potential null pointer dereference with Deref implementation on Buf #1211

@shinmao

Description

@shinmao

We consider that there should be a null check before dereference on Buf.

git2-rs/src/buf.rs

Lines 23 to 49 in 03ec581

impl Buf {
/// Creates a new empty buffer.
pub fn new() -> Buf {
crate::init();
unsafe {
Binding::from_raw(&mut raw::git_buf {
ptr: ptr::null_mut(),
size: 0,
reserved: 0,
} as *mut _)
}
}
/// Attempt to view this buffer as a string slice.
///
/// Returns `None` if the buffer is not valid utf-8.
pub fn as_str(&self) -> Option<&str> {
str::from_utf8(&**self).ok()
}
}
impl Deref for Buf {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.raw.ptr as *const u8, self.raw.size as usize) }
}
}

In this code, if we dereference the buffer right after calling new(), it pass null pointer to the unsafe function slice::from_raw_parts. Based on the documentation of function,

data must be non-null and aligned even for zero-length slices or slices of ZSTs.

Even though it is zero-length slice, we should ensure that the pointer is not null.

How do you think about it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions