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

Add Ioctl helper for integer arg #1172

Merged
merged 1 commit into from
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
17 changes: 17 additions & 0 deletions tests/io/ioctl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,20 @@ 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::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!(ioctl(&tun, code).is_err());
}
}