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

Arg<T> Implementation Allows Undefined Behavior Due to Unsafe Pointer Operations #74

Open
lwz23 opened this issue Dec 3, 2024 · 1 comment

Comments

@lwz23
Copy link

lwz23 commented Dec 3, 2024

Hello, I found a soundness issue in this crate.

pub struct Arg<T>(*mut T);

impl<T> Arg<T> {
    pub fn get(&self) -> T {
        unsafe { std::ptr::read_unaligned(self.0) }
    }

    pub fn set(&self, val: T) {
        unsafe { std::ptr::write_unaligned(self.0, val) }
    }
}

This implementation assumes that the pointer self.0 is valid, aligned, and points to initialized memory, but these assumptions are not enforced, leading to potential UB.
Description
The current implementation of the Arg struct contains unsafe methods (get and set) that allow undefined behavior (UB) when the underlying pointer (*mut T) is invalid, null, or points to uninitialized memory. This can result in memory safety violations in safe code, making the implementation unsound.

Proof of Unsoundness

fn main() {
    // Create a null pointer
    let dangling_ptr: *mut i32 = std::ptr::null_mut();

    // Construct Arg<T> with a null pointer
    let arg = Arg(dangling_ptr);

    // Call `get`, attempting to read from the null pointer
    let value = arg.get(); // UB: Reading from a null pointer
    println!("Value: {}", value); // Unpredictable behavior
}

Output
PS E:\Github\lwz> cargo run

   Compiling lwz v0.1.0 (E:\Github\lwz)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.32s
     Running `target\debug\lwz.exe`
thread 'main' panicked at core\src\panicking.rs:223:5:
unsafe precondition(s) violated: ptr::copy_nonoverlapping requires that both pointer arguments are aligned and non-null and the specified memory ranges do not overlap
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread caused non-unwinding panic. aborting.
error: process didn't exit successfully: `target\debug\lwz.exe` (exit code: 0xc0000409, STATUS_STACK_BUFFER_OVERRUN)

@lwz23
Copy link
Author

lwz23 commented Dec 3, 2024

Please take a look at it and also #72 :)

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