Skip to content

getsockopt of every sockopt_impl! option writes through a pointer Stacked Borrows has invalidated #2878

Open

Description

@marius-momeu

getsockopt_impl! passes getter.ffi_ptr() and getter.ffi_len() as two arguments of the same libc::getsockopt call. Both methods take &mut self, so the second call's reborrow of getter invalidates the pointer the first returned, under Stacked Borrows, before the kernel writes the option value through it. Every GetSockOpt the macro generates is affected, sockopt::SocketError included. Tree Borrows accepts the same program, so this is an aliasing-model violation only.

#![forbid(unsafe_code)]
use nix::sys::socket::{getsockopt, socket, sockopt::SocketError, AddressFamily, SockFlag, SockType};

fn main() {
    let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap();
    println!("SO_ERROR = {}", getsockopt(&fd, SocketError).unwrap());
}

MIRIFLAGS=-Zmiri-disable-isolation cargo +nightly miri run:

error: Undefined Behavior: attempting a write access using <685> at alloc352[0x4], but that tag does not exist in the borrow stack for this location
   --> src/sys/socket/sockopt.rs:117:21
help: <685> was later invalidated at offsets [0x0..0x8] by a Unique function-entry retag inside this call

Versions: nix 0.31.3 (a46707b, also the master tip), libc 0.2.191, rustc/Miri nightly 2026-11-12 (8eb778d04), x86_64 Linux.

A possible fix, which we tested (the program above then runs clean under Miri and the crate's test suite passes): add fn ffi_ptrs(&mut self) -> (*mut c_void, *mut socklen_t) to Get, returning (self.val.as_mut_ptr().cast(), &mut self.len), and call it once in the macro.

Found by Crustify, an experimental UB/soundness auditing agent developed at UC Berkeley and running on Claude Opus 5.5, then manually reviewed and independently reproduced.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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