Skip to content

Potential Unsoundness in replace_header #110

Open
@lwz23

Description

The function ’replace_header‘

pub fn remove_from_payload_head(&mut self, size: usize) -> Result<()> {

pub fn replace_header(&mut self, hdr: &T) {
        unsafe {
            ptr::copy_nonoverlapping(hdr, self.header(), 1);
        }
    }

may cause undefined behavior (UB) even if self.header() always returns a valid pointer. This stems from the fact that the safety of this function depends on the user-provided hdr parameter. Here are the primary ways in which hdr could lead to UB:

  1. Invalid Pointer in hdr
    If hdr is constructed from an invalid pointer (e.g., a null pointer, dangling pointer, or a pointer to uninitialized memory), the function will attempt to copy data from an invalid source using std::ptr::copy_nonoverlapping. This would result in UB due to dereferencing an invalid memory location.
let ptr: *const T = std::ptr::null();
let hdr = unsafe { &*ptr }; // Invalid reference
self.replace_header(hdr);   // Causes UB
  1. Special T Behavior
    If T is a type with custom drop behavior, contains raw pointers, or requires specific memory management guarantees, blindly copying its bytes using std::ptr::copy_nonoverlapping can break invariants. This could lead to issues such as double frees, memory leaks, or corrupted state.
struct UnsafeDrop {
    ptr: *mut u8,
}

impl Drop for UnsafeDrop {
    fn drop(&mut self) {
        unsafe { std::ptr::drop_in_place(self.ptr); }
    }
}

// Passing `hdr` and `self.header()` pointing to the same memory
// can cause double free or corrupted state.

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