From 444c960cdfb46cda789d115ab5d56d01a133b128 Mon Sep 17 00:00:00 2001 From: Daniel Canencia Garcia Date: Sun, 13 Sep 2026 15:21:41 +0200 Subject: [PATCH] linux: Improve panic message for out-of-range fds in FD_* functions Passing a file descriptor that is negative or >= FD_SETSIZE to FD_SET, FD_CLR or FD_ISSET is undefined behavior per POSIX, and the previous "index out of bounds" panic gave no hint of the required range. Panic with a message that states the valid 0..FD_SETSIZE range instead. Source: https://github.com/bminor/glibc/blob/d2097651cc57834dbfcaa102ddfacae0d86cfb66/misc/sys/select.h Part of rust-lang/libc#1401 Signed-off-by: Daniel Canencia Garcia --- src/unix/linux_like/mod.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/unix/linux_like/mod.rs b/src/unix/linux_like/mod.rs index fe2975a8745b..583e81b2b880 100644 --- a/src/unix/linux_like/mod.rs +++ b/src/unix/linux_like/mod.rs @@ -1847,21 +1847,26 @@ f! { pub unsafe fn FD_CLR(fd: c_int, set: *mut fd_set) -> () { let fd = fd as usize; let size = size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] &= !(1 << (fd % size)); - return; + *(*set).fds_bits.get_mut(fd / size).unwrap_or_else(|| { + core::panic!("fd {fd} out of range: valid fds are 0..FD_SETSIZE (0..{FD_SETSIZE})") + }) &= !(1 << (fd % size)); } pub unsafe fn FD_ISSET(fd: c_int, set: *const fd_set) -> bool { let fd = fd as usize; let size = size_of_val(&(*set).fds_bits[0]) * 8; - return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0; + (*set).fds_bits.get(fd / size).unwrap_or_else(|| { + core::panic!("fd {fd} out of range: valid fds are 0..FD_SETSIZE (0..{FD_SETSIZE})") + }) & (1 << (fd % size)) + != 0 } pub unsafe fn FD_SET(fd: c_int, set: *mut fd_set) -> () { let fd = fd as usize; let size = size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] |= 1 << (fd % size); - return; + *(*set).fds_bits.get_mut(fd / size).unwrap_or_else(|| { + core::panic!("fd {fd} out of range: valid fds are 0..FD_SETSIZE (0..{FD_SETSIZE})") + }) |= 1 << (fd % size); } pub unsafe fn FD_ZERO(set: *mut fd_set) -> () {