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

Potential Unsoundness in replace_header #110

Open
lwz23 opened this issue Nov 25, 2024 · 1 comment
Open

Potential Unsoundness in replace_header #110

lwz23 opened this issue Nov 25, 2024 · 1 comment

Comments

@lwz23
Copy link

lwz23 commented Nov 25, 2024

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.

@lwz23
Copy link
Author

lwz23 commented Dec 3, 2024

maybe same problem for

pub fn allocate(src: T) -> CacheAligned<T> {
?
the ptr::write usage

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

No branches or pull requests

1 participant