Skip to content

Commit

Permalink
feat: Add Ioctl helper for integer arg
Browse files Browse the repository at this point in the history
Fixing low-hanging-fruit issue #1051.

Signed-off-by: John Nunley <[email protected]>
  • Loading branch information
notgull committed Sep 27, 2024
1 parent 75cb9d1 commit 9124c04
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/ioctl/patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,51 @@ unsafe impl<'a, Opcode: CompileTimeOpcode, T> Ioctl for Updater<'a, Opcode, T> {
}
}

/// Implements an `ioctl` that passes an integer into the `ioctl`.
pub struct IntegerSetter<Opcode> {
/// The value to pass in.
value: usize,

/// The opcode.
_opcode: PhantomData<Opcode>,
}

impl<Opcode: CompileTimeOpcode> IntegerSetter<Opcode> {
/// Create a new integer `Ioctl` helper.
///
/// # Safety
///
/// - `Opcode` must provide a valid opcode.
/// - For this opcode, it must expect an integer.
/// - The integer is in the valid range for this opcode.
#[inline]
pub unsafe fn new(value: usize) -> Self {
Self {
value,
_opcode: PhantomData,
}
}
}

unsafe impl<Opcode: CompileTimeOpcode> Ioctl for IntegerSetter<Opcode> {
type Output = ();

const IS_MUTATING: bool = false;
const OPCODE: self::Opcode = Opcode::OPCODE;

fn as_ptr(&mut self) -> *mut c::c_void {
// TODO: strict provenance
self.value as *mut c::c_void
}

unsafe fn output_from_ptr(
_out: IoctlOutput,
_extract_output: *mut c::c_void,
) -> Result<Self::Output> {
Ok(())
}
}

/// Trait for something that provides an `ioctl` opcode at compile time.
pub trait CompileTimeOpcode {
/// The opcode.
Expand Down
18 changes: 18 additions & 0 deletions tests/io/ioctl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,21 @@ fn test_ioctls() {
file.metadata().unwrap().len()
);
}

#[cfg(all(target_os = "linux", feature = "fs"))]
#[test]
fn test_int_setter() {
use rustix::fs::{open, Mode, OFlags};
use rustix::io::Errno;
use rustix::ioctl::{ioctl, BadOpcode, IntegerSetter, RawOpcode};

const TUNSETOFFLOAD: RawOpcode = 0x400454D0;

let tun = open("/dev/net/tun", OFlags::RDWR, Mode::empty()).unwrap();

// SAFETY: TUNSETOFFLOAD is defined for TUN.
unsafe {
let code = IntegerSetter::<BadOpcode<{ TUNSETOFFLOAD }>>::new(0);
assert_eq!(ioctl(&tun, code), Err(Errno::BADFD));
}
}

0 comments on commit 9124c04

Please sign in to comment.