Clippy cleanup

And this time, start running Clippy in CI
This commit is contained in:
Alan Somers 2021-09-18 21:07:00 -06:00
parent f0d6d0406d
commit a09b1c8ac6
41 changed files with 154 additions and 189 deletions

View File

@ -18,6 +18,7 @@ build: &BUILD
- . $HOME/.cargo/env || true
- $TOOL +$TOOLCHAIN $BUILD $ZFLAGS --target $TARGET --all-targets
- $TOOL +$TOOLCHAIN doc $ZFLAGS --no-deps --target $TARGET
- $TOOL +$TOOLCHAIN clippy $ZFLAGS --target $TARGET -- -D warnings
# Tests that do require executing the binaries
test: &TEST
@ -39,7 +40,9 @@ task:
setup_script:
- fetch https://sh.rustup.rs -o rustup.sh
- sh rustup.sh -y --profile=minimal --default-toolchain $TOOLCHAIN
- $HOME/.cargo/bin/rustup target add i686-unknown-freebsd
- . $HOME/.cargo/env
- rustup target add i686-unknown-freebsd
- rustup component add --toolchain $TOOLCHAIN clippy
<< : *TEST
i386_test_script:
- . $HOME/.cargo/env
@ -60,6 +63,7 @@ task:
- curl --proto '=https' --tlsv1.2 -sSf -o rustup.sh https://sh.rustup.rs
- sh rustup.sh -y --profile=minimal --default-toolchain $TOOLCHAIN
- . $HOME/.cargo/env
- rustup component add --toolchain $TOOLCHAIN clippy
<< : *TEST
before_cache_script: rm -rf $CARGO_HOME/registry/index
@ -142,6 +146,7 @@ task:
TARGET: x86_64-unknown-linux-musl
setup_script:
- rustup target add $TARGET
- rustup component add clippy
<< : *TEST
before_cache_script: rm -rf $CARGO_HOME/registry/index
@ -224,6 +229,7 @@ task:
setup_script:
- rustup target add $TARGET
- rustup toolchain install $TOOLCHAIN --profile minimal --target $TARGET
- rustup component add --toolchain $TOOLCHAIN clippy
<< : *BUILD
before_cache_script: rm -rf $CARGO_HOME/registry/index

View File

@ -84,7 +84,7 @@ impl AsRawFd for Dir {
impl Drop for Dir {
fn drop(&mut self) {
let e = Errno::result(unsafe { libc::closedir(self.0.as_ptr()) });
if !std::thread::panicking() && e == Err(Error::from(Errno::EBADF)) {
if !std::thread::panicking() && e == Err(Errno::EBADF) {
panic!("Closing an invalid file descriptor!");
};
}
@ -211,6 +211,7 @@ impl Entry {
target_os = "linux",
target_os = "macos",
target_os = "solaris")))]
#[allow(clippy::useless_conversion)] // Not useless on all OSes
pub fn ino(&self) -> u64 {
u64::from(self.0.d_fileno)
}

View File

@ -72,8 +72,9 @@ impl Errno {
since = "0.22.0",
note = "It's a no-op now; just delete it."
)]
#[allow(clippy::wrong_self_convention)] // False positive
pub fn from_errno(errno: Errno) -> Error {
Error::from(errno)
errno
}
/// Create a new invalid argument error (`EINVAL`)

View File

@ -325,7 +325,7 @@ fn inner_readlink<P: ?Sized + NixPath>(dirfd: Option<RawFd>, path: &P) -> Result
Some(next_size) => try_size = next_size,
// It's absurd that this would happen, but handle it sanely
// anyway.
None => break Err(super::Error::from(Errno::ENAMETOOLONG)),
None => break Err(Errno::ENAMETOOLONG),
}
}
}
@ -646,7 +646,6 @@ pub fn fallocate(
))]
mod posix_fadvise {
use crate::errno::Errno;
use libc;
use std::os::unix::io::RawFd;
use crate::Result;
@ -687,6 +686,6 @@ pub fn posix_fallocate(fd: RawFd, offset: libc::off_t, len: libc::off_t) -> Resu
match Errno::result(res) {
Err(err) => Err(err),
Ok(0) => Ok(()),
Ok(errno) => Err(crate::Error::from(Errno::from_i32(errno))),
Ok(errno) => Err(Errno::from_i32(errno)),
}
}

View File

@ -2,7 +2,6 @@
//!
//! For more details see
use libc;
use std::ffi::CStr;
use std::os::unix::io::AsRawFd;

View File

@ -160,7 +160,7 @@ impl NixPath for CStr {
where F: FnOnce(&CStr) -> T {
// Equivalence with the [u8] impl.
if self.len() >= PATH_MAX as usize {
return Err(Error::from(Errno::ENAMETOOLONG))
return Err(Errno::ENAMETOOLONG)
}
Ok(f(self))
@ -181,11 +181,11 @@ impl NixPath for [u8] {
let mut buf = [0u8; PATH_MAX as usize];
if self.len() >= PATH_MAX as usize {
return Err(Error::from(Errno::ENAMETOOLONG))
return Err(Errno::ENAMETOOLONG)
}
match self.iter().position(|b| *b == 0) {
Some(_) => Err(Error::from(Errno::EINVAL)),
Some(_) => Err(Errno::EINVAL),
None => {
unsafe {
// TODO: Replace with bytes::copy_memory. rust-lang/rust#24028

View File

@ -383,7 +383,7 @@ impl<'a> Nmount<'a> {
Some(CStr::from_bytes_with_nul(sl).unwrap())
}
};
Err(NmountError::new(error.into(), errmsg))
Err(NmountError::new(error, errmsg))
}
}
}

View File

@ -1,3 +1,4 @@
#![allow(missing_docs)]
use libc::{self, c_ulong, c_int};
use crate::{Result, NixPath};
use crate::errno::Errno;

View File

@ -1,10 +1,8 @@
//! Mount file systems
#[cfg(any(target_os = "android", target_os = "linux"))]
#[allow(missing_docs)]
mod linux;
#[cfg(any(target_os = "android", target_os = "linux"))]
#[allow(missing_docs)]
pub use self::linux::*;
#[cfg(any(target_os = "dragonfly",

View File

@ -155,6 +155,7 @@ pub fn mq_setattr(mqd: mqd_t, newattr: &MqAttr) -> Result<MqAttr> {
/// Convenience function.
/// Sets the `O_NONBLOCK` attribute for a given message queue descriptor
/// Returns the old attributes
#[allow(clippy::useless_conversion)] // Not useless on all OSes
pub fn mq_set_nonblock(mqd: mqd_t) -> Result<MqAttr> {
let oldattr = mq_getattr(mqd)?;
let newattr = MqAttr::new(mq_attr_member_t::from(MQ_OFlag::O_NONBLOCK.bits()),

View File

@ -10,7 +10,7 @@ use std::os::unix::prelude::*;
use crate::sys::termios::Termios;
use crate::unistd::{self, ForkResult, Pid};
use crate::{Result, Error, fcntl};
use crate::{Result, fcntl};
use crate::errno::Errno;
/// Representation of a master/slave pty pair
@ -99,7 +99,7 @@ impl io::Write for PtyMaster {
#[inline]
pub fn grantpt(fd: &PtyMaster) -> Result<()> {
if unsafe { libc::grantpt(fd.as_raw_fd()) } < 0 {
return Err(Error::from(Errno::last()));
return Err(Errno::last());
}
Ok(())
@ -145,7 +145,7 @@ pub fn posix_openpt(flags: fcntl::OFlag) -> Result<PtyMaster> {
};
if fd < 0 {
return Err(Error::from(Errno::last()));
return Err(Errno::last());
}
Ok(PtyMaster(fd))
@ -171,7 +171,7 @@ pub fn posix_openpt(flags: fcntl::OFlag) -> Result<PtyMaster> {
pub unsafe fn ptsname(fd: &PtyMaster) -> Result<String> {
let name_ptr = libc::ptsname(fd.as_raw_fd());
if name_ptr.is_null() {
return Err(Error::from(Errno::last()));
return Err(Errno::last());
}
let name = CStr::from_ptr(name_ptr);
@ -195,7 +195,7 @@ pub fn ptsname_r(fd: &PtyMaster) -> Result<String> {
let cname = unsafe {
let cap = name_buf.capacity();
if libc::ptsname_r(fd.as_raw_fd(), name_buf_ptr, cap) != 0 {
return Err(Error::last());
return Err(crate::Error::last());
}
CStr::from_ptr(name_buf.as_ptr())
};
@ -213,7 +213,7 @@ pub fn ptsname_r(fd: &PtyMaster) -> Result<String> {
#[inline]
pub fn unlockpt(fd: &PtyMaster) -> Result<()> {
if unsafe { libc::unlockpt(fd.as_raw_fd()) } < 0 {
return Err(Error::from(Errno::last()));
return Err(Errno::last());
}
Ok(())

View File

@ -15,7 +15,7 @@ mod sched_linux_like {
use std::option::Option;
use std::os::unix::io::RawFd;
use crate::unistd::Pid;
use crate::{Error, Result};
use crate::Result;
// For some functions taking with a parameter of type CloneFlags,
// only a subset of these flags have an effect.
@ -109,7 +109,7 @@ mod sched_linux_like {
/// `field` is the CPU id to test
pub fn is_set(&self, field: usize) -> Result<bool> {
if field >= CpuSet::count() {
Err(Error::from(Errno::EINVAL))
Err(Errno::EINVAL)
} else {
Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) })
}
@ -119,7 +119,7 @@ mod sched_linux_like {
/// `field` is the CPU id to add
pub fn set(&mut self, field: usize) -> Result<()> {
if field >= CpuSet::count() {
Err(Error::from(Errno::EINVAL))
Err(Errno::EINVAL)
} else {
unsafe { libc::CPU_SET(field, &mut self.cpu_set); }
Ok(())
@ -130,7 +130,7 @@ mod sched_linux_like {
/// `field` is the CPU id to remove
pub fn unset(&mut self, field: usize) -> Result<()> {
if field >= CpuSet::count() {
Err(Error::from(Errno::EINVAL))
Err(Errno::EINVAL)
} else {
unsafe { libc::CPU_CLR(field, &mut self.cpu_set);}
Ok(())

View File

@ -21,7 +21,7 @@
//! [`aio_cancel_all`](fn.aio_cancel_all.html), though the operating system may
//! not support this for all filesystems and devices.
use crate::{Error, Result};
use crate::Result;
use crate::errno::Errno;
use std::os::unix::io::RawFd;
use libc::{c_void, off_t, size_t};
@ -148,15 +148,13 @@ impl<'a> AioCb<'a> {
/// # use std::{thread, time};
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// let f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_fd( f.as_raw_fd(), 0, SigevNone);
/// aiocb.fsync(AioFsyncMode::O_SYNC).expect("aio_fsync failed early");
/// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
/// while (aiocb.error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// aiocb.aio_return().expect("aio_fsync failed late");
/// # }
/// ```
pub fn from_fd(fd: RawFd, prio: libc::c_int,
sigev_notify: SigevNotify) -> Pin<Box<AioCb<'a>>> {
@ -229,7 +227,6 @@ impl<'a> AioCb<'a> {
/// # use std::io::Write;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// const INITIAL: &[u8] = b"abcdef123456";
/// const LEN: usize = 4;
/// let mut rbuf = vec![0; LEN];
@ -243,13 +240,12 @@ impl<'a> AioCb<'a> {
/// SigevNotify::SigevNone,
/// LioOpcode::LIO_NOP);
/// aiocb.read().unwrap();
/// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
/// while (aiocb.error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// assert_eq!(aiocb.aio_return().unwrap() as usize, LEN);
/// }
/// assert_eq!(rbuf, b"cdef");
/// # }
/// ```
pub fn from_mut_slice(fd: RawFd, offs: off_t, buf: &'a mut [u8],
prio: libc::c_int, sigev_notify: SigevNotify,
@ -404,7 +400,6 @@ impl<'a> AioCb<'a> {
/// # use std::{thread, time};
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
@ -414,11 +409,10 @@ impl<'a> AioCb<'a> {
/// SigevNotify::SigevNone,
/// LioOpcode::LIO_NOP);
/// aiocb.write().unwrap();
/// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
/// while (aiocb.error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len());
/// # }
/// ```
// Note: another solution to the problem of writing const buffers would be
// to genericize AioCb for both &mut [u8] and &[u8] buffers. AioCb::read
@ -480,7 +474,6 @@ impl<'a> AioCb<'a> {
/// # use std::io::Write;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// let wbuf = b"CDEF";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
@ -492,13 +485,12 @@ impl<'a> AioCb<'a> {
/// aiocb.write().unwrap();
/// let cs = aiocb.cancel().unwrap();
/// if cs == AioCancelStat::AioNotCanceled {
/// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
/// while (aiocb.error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// }
/// // Must call `aio_return`, but ignore the result
/// let _ = aiocb.aio_return();
/// # }
/// ```
///
/// # References
@ -513,7 +505,7 @@ impl<'a> AioCb<'a> {
libc::AIO_CANCELED => Ok(AioCancelStat::AioCanceled),
libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled),
libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone),
-1 => Err(Error::from(Errno::last())),
-1 => Err(Errno::last()),
_ => panic!("unknown aio_cancel return value")
}
}
@ -524,8 +516,8 @@ impl<'a> AioCb<'a> {
};
match r {
0 => Ok(()),
num if num > 0 => Err(Error::from(Errno::from_i32(num))),
-1 => Err(Error::from(Errno::last())),
num if num > 0 => Err(Errno::from_i32(num)),
-1 => Err(Errno::last()),
num => panic!("unknown aio_error return value {:?}", num)
}
}
@ -548,7 +540,6 @@ impl<'a> AioCb<'a> {
/// # use std::{thread, time};
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
@ -558,11 +549,10 @@ impl<'a> AioCb<'a> {
/// SigevNotify::SigevNone,
/// LioOpcode::LIO_NOP);
/// aiocb.write().unwrap();
/// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
/// while (aiocb.error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len());
/// # }
/// ```
///
/// # References
@ -711,7 +701,6 @@ impl<'a> AioCb<'a> {
/// # use std::io::Write;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// let wbuf = b"CDEF";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
@ -723,13 +712,12 @@ impl<'a> AioCb<'a> {
/// aiocb.write().unwrap();
/// let cs = aio_cancel_all(f.as_raw_fd()).unwrap();
/// if cs == AioCancelStat::AioNotCanceled {
/// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
/// while (aiocb.error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// }
/// // Must call `aio_return`, but ignore the result
/// let _ = aiocb.aio_return();
/// # }
/// ```
///
/// # References
@ -740,7 +728,7 @@ pub fn aio_cancel_all(fd: RawFd) -> Result<AioCancelStat> {
libc::AIO_CANCELED => Ok(AioCancelStat::AioCanceled),
libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled),
libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone),
-1 => Err(Error::from(Errno::last())),
-1 => Err(Errno::last()),
_ => panic!("unknown aio_cancel return value")
}
}
@ -759,7 +747,6 @@ pub fn aio_cancel_all(fd: RawFd) -> Result<AioCancelStat> {
/// # use nix::sys::signal::SigevNotify;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
@ -771,7 +758,6 @@ pub fn aio_cancel_all(fd: RawFd) -> Result<AioCancelStat> {
/// aiocb.write().unwrap();
/// aio_suspend(&[aiocb.as_ref()], None).expect("aio_suspend failed");
/// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len());
/// # }
/// ```
/// # References
///
@ -876,7 +862,6 @@ impl<'a> LioCb<'a> {
/// # use nix::sys::signal::SigevNotify;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut liocb = LioCbBuilder::with_capacity(1)
@ -891,7 +876,6 @@ impl<'a> LioCb<'a> {
/// liocb.listio(LioMode::LIO_WAIT,
/// SigevNotify::SigevNone).unwrap();
/// assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len());
/// # }
/// ```
///
/// # References
@ -936,7 +920,6 @@ impl<'a> LioCb<'a> {
/// # use std::os::unix::io::AsRawFd;
/// # use std::{thread, time};
/// # use tempfile::tempfile;
/// # fn main() {
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut liocb = LioCbBuilder::with_capacity(1)
@ -949,13 +932,12 @@ impl<'a> LioCb<'a> {
/// LioOpcode::LIO_WRITE
/// ).finish();
/// let mut err = liocb.listio(LioMode::LIO_WAIT, SigevNotify::SigevNone);
/// while err == Err(Error::from(Errno::EIO)) ||
/// err == Err(Error::from(Errno::EAGAIN)) {
/// while err == Err(Errno::EIO) ||
/// err == Err(Errno::EAGAIN) {
/// thread::sleep(time::Duration::from_millis(10));
/// err = liocb.listio_resubmit(LioMode::LIO_WAIT, SigevNotify::SigevNone);
/// }
/// assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len());
/// # }
/// ```
///
/// # References

View File

@ -1,4 +1,4 @@
use crate::{Error, Result};
use crate::Result;
use crate::errno::Errno;
use libc::{self, c_int};
use std::os::unix::io::RawFd;
@ -86,7 +86,7 @@ pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result
{
let mut event: Option<&mut EpollEvent> = event.into();
if event.is_none() && op != EpollOp::EpollCtlDel {
Err(Error::from(Errno::EINVAL))
Err(Errno::EINVAL)
} else {
let res = unsafe {
if let Some(ref mut event) = event {

View File

@ -1,4 +1,3 @@
use libc;
use std::os::unix::io::RawFd;
use crate::Result;
use crate::errno::Errno;

View File

@ -1,4 +1,3 @@
use libc;
use std::os::unix::io::RawFd;
use crate::Result;
use crate::errno::Errno;

View File

@ -1,4 +1,4 @@
use crate::{Error, Result};
use crate::Result;
#[cfg(not(target_os = "android"))]
use crate::NixPath;
use crate::errno::Errno;
@ -333,7 +333,7 @@ pub unsafe fn mmap(addr: *mut c_void, length: size_t, prot: ProtFlags, flags: Ma
let ret = libc::mmap(addr, length, prot.bits(), flags.bits(), fd, offset);
if ret == libc::MAP_FAILED {
Err(Error::from(Errno::last()))
Err(Errno::last())
} else {
Ok(ret)
}
@ -366,7 +366,7 @@ pub unsafe fn mremap(
);
if ret == libc::MAP_FAILED {
Err(Error::from(Errno::last()))
Err(Errno::last())
} else {
Ok(ret)
}

View File

@ -39,7 +39,7 @@ pub fn get() -> Result<Persona> {
libc::personality(0xFFFFFFFF)
};
Errno::result(res).map(|r| Persona::from_bits_truncate(r))
Errno::result(res).map(Persona::from_bits_truncate)
}
/// Set the current process personality.
@ -66,5 +66,5 @@ pub fn set(persona: Persona) -> Result<Persona> {
libc::personality(persona.bits() as c_ulong)
};
Errno::result(res).map(|r| Persona::from_bits_truncate(r))
Errno::result(res).map(Persona::from_bits_truncate)
}

View File

@ -415,16 +415,15 @@ pub fn kill(pid: Pid) -> Result<()> {
/// use nix::unistd::Pid;
/// use nix::sys::signal::Signal;
/// use nix::sys::wait::*;
/// fn main() {
/// // If a process changes state to the stopped state because of a SIGUSR1
/// // signal, this will step the process forward and forward the user
/// // signal to the stopped process
/// match waitpid(Pid::from_raw(-1), None) {
/// Ok(WaitStatus::Stopped(pid, Signal::SIGUSR1)) => {
/// let _ = step(pid, Signal::SIGUSR1);
/// }
/// _ => {},
///
/// // If a process changes state to the stopped state because of a SIGUSR1
/// // signal, this will step the process forward and forward the user
/// // signal to the stopped process
/// match waitpid(Pid::from_raw(-1), None) {
/// Ok(WaitStatus::Stopped(pid, Signal::SIGUSR1)) => {
/// let _ = step(pid, Signal::SIGUSR1);
/// }
/// _ => {},
/// }
/// ```
pub fn step<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> {

View File

@ -1,8 +1,7 @@
//! Reboot/shutdown or enable/disable Ctrl-Alt-Delete.
use crate::{Error, Result};
use crate::Result;
use crate::errno::Errno;
use libc;
use std::convert::Infallible;
use std::mem::drop;
@ -27,7 +26,7 @@ pub fn reboot(how: RebootMode) -> Result<Infallible> {
unsafe {
libc::reboot(how as libc::c_int)
};
Err(Error::from(Errno::last()))
Err(Errno::last())
}
/// Enable or disable the reboot keystroke (Ctrl-Alt-Delete).

View File

@ -111,7 +111,7 @@ impl<'a> Iterator for Fds<'a> {
type Item = RawFd;
fn next(&mut self) -> Option<RawFd> {
while let Some(i) = self.range.next() {
for i in &mut self.range {
if self.set.contains(i as RawFd) {
return Some(i as RawFd);
}

View File

@ -156,7 +156,7 @@ impl FromStr for Signal {
target_os = "fuchsia", target_os = "linux",
target_os = "redox")))]
"SIGINFO" => Signal::SIGINFO,
_ => return Err(Error::from(Errno::EINVAL)),
_ => return Err(Errno::EINVAL),
})
}
}
@ -779,7 +779,7 @@ pub unsafe fn signal(signal: Signal, handler: SigHandler) -> Result<SigHandler>
SigHandler::SigIgn => libc::signal(signal, libc::SIG_IGN),
SigHandler::Handler(handler) => libc::signal(signal, handler as libc::sighandler_t),
#[cfg(not(target_os = "redox"))]
SigHandler::SigAction(_) => return Err(Error::from(Errno::ENOTSUP)),
SigHandler::SigAction(_) => return Err(Errno::ENOTSUP),
};
Errno::result(res).map(|oldhandler| {
match oldhandler {
@ -1091,7 +1091,7 @@ mod tests {
#[test]
fn test_from_str_invalid_value() {
let errval = Err(Error::from(Errno::EINVAL));
let errval = Err(Errno::EINVAL);
assert_eq!("NOSIGNAL".parse::<Signal>(), errval);
assert_eq!("kill".parse::<Signal>(), errval);
assert_eq!("9".parse::<Signal>(), errval);

View File

@ -15,9 +15,8 @@
//!
//! Please note that signal discarding is not specific to `signalfd`, but also happens with regular
//! signal handlers.
use libc;
use crate::unistd;
use crate::{Error, Result};
use crate::Result;
use crate::errno::Errno;
pub use crate::sys::signal::{self, SigSet};
pub use libc::signalfd_siginfo as siginfo;
@ -117,7 +116,7 @@ impl SignalFd {
impl Drop for SignalFd {
fn drop(&mut self) {
let e = unistd::close(self.0);
if !std::thread::panicking() && e == Err(Error::from(Errno::EBADF)) {
if !std::thread::panicking() && e == Err(Errno::EBADF) {
panic!("Closing an invalid file descriptor!");
};
}

View File

@ -1,5 +1,5 @@
use super::sa_family_t;
use crate::{Error, Result, NixPath};
use crate::{Result, NixPath};
use crate::errno::Errno;
use memoffset::offset_of;
use std::{fmt, mem, net, ptr, slice};
@ -270,6 +270,7 @@ pub enum InetAddr {
}
impl InetAddr {
#[allow(clippy::needless_update)] // It isn't needless on all OSes
pub fn from_std(std: &net::SocketAddr) -> InetAddr {
match *std {
net::SocketAddr::V4(ref addr) => {
@ -293,6 +294,7 @@ impl InetAddr {
}
}
#[allow(clippy::needless_update)] // It isn't needless on all OSes
pub fn new(ip: IpAddr, port: u16) -> InetAddr {
match ip {
IpAddr::V4(ref ip) => {
@ -565,7 +567,7 @@ impl UnixAddr {
let bytes = cstr.to_bytes();
if bytes.len() >= ret.sun_path.len() {
return Err(Error::from(Errno::ENAMETOOLONG));
return Err(Errno::ENAMETOOLONG);
}
ptr::copy_nonoverlapping(bytes.as_ptr(),
@ -592,7 +594,7 @@ impl UnixAddr {
};
if path.len() >= ret.sun_path.len() {
return Err(Error::from(Errno::ENAMETOOLONG));
return Err(Errno::ENAMETOOLONG);
}
// Abstract addresses are represented by sun_path[0] ==
@ -751,7 +753,7 @@ impl SockAddr {
#[cfg(any(target_os = "ios", target_os = "macos"))]
pub fn new_sys_control(sockfd: RawFd, name: &str, unit: u32) -> Result<SockAddr> {
SysControlAddr::from_name(sockfd, name, unit).map(|a| SockAddr::SysControl(a))
SysControlAddr::from_name(sockfd, name, unit).map(SockAddr::SysControl)
}
#[cfg(any(target_os = "android", target_os = "linux"))]
@ -1064,7 +1066,7 @@ pub mod sys_control {
use libc::{self, c_uchar};
use std::{fmt, mem};
use std::os::unix::io::RawFd;
use crate::{Errno, Error, Result};
use crate::{Errno, Result};
// FIXME: Move type into `libc`
#[repr(C)]
@ -1075,7 +1077,7 @@ pub mod sys_control {
pub ctl_name: [c_uchar; MAX_KCTL_NAME],
}
const CTL_IOC_MAGIC: u8 = 'N' as u8;
const CTL_IOC_MAGIC: u8 = b'N';
const CTL_IOC_INFO: u8 = 3;
const MAX_KCTL_NAME: usize = 96;
@ -1101,7 +1103,7 @@ pub mod sys_control {
pub fn from_name(sockfd: RawFd, name: &str, unit: u32) -> Result<SysControlAddr> {
if name.len() > MAX_KCTL_NAME {
return Err(Error::from(Errno::ENAMETOOLONG));
return Err(Errno::ENAMETOOLONG);
}
let mut ctl_name = [0; MAX_KCTL_NAME];

View File

@ -2,7 +2,7 @@
//!
//! [Further reading](https://man7.org/linux/man-pages/man7/socket.7.html)
use cfg_if::cfg_if;
use crate::{Error, Result, errno::Errno};
use crate::{Result, errno::Errno};
use libc::{self, c_void, c_int, iovec, socklen_t, size_t,
CMSG_FIRSTHDR, CMSG_NXTHDR, CMSG_DATA, CMSG_LEN};
use memoffset::offset_of;
@ -311,9 +311,9 @@ cfg_if! {
}
}
impl Into<libc::ucred> for UnixCredentials {
fn into(self) -> libc::ucred {
self.0
impl From<UnixCredentials> for libc::ucred {
fn from(uc: UnixCredentials) -> Self {
uc.0
}
}
} else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] {
@ -1300,6 +1300,7 @@ pub struct RecvMmsgData<'a, I>
target_os = "freebsd",
target_os = "netbsd",
))]
#[allow(clippy::needless_collect)] // Complicated false positive
pub fn recvmmsg<'a, I>(
fd: RawFd,
data: impl std::iter::IntoIterator<Item=&'a mut RecvMmsgData<'a, I>,
@ -1813,7 +1814,7 @@ pub fn sockaddr_storage_to_addr(
assert!(len <= mem::size_of::<sockaddr_storage>());
if len < mem::size_of_val(&addr.ss_family) {
return Err(Error::from(Errno::ENOTCONN));
return Err(Errno::ENOTCONN);
}
match c_int::from(addr.ss_family) {

View File

@ -150,7 +150,7 @@ mod test {
#[test]
fn statvfs_call() {
statvfs("/".as_bytes()).unwrap();
statvfs(&b"/"[..]).unwrap();
}
#[test]

View File

@ -257,14 +257,9 @@ impl TimerFd {
///
/// Note: If the alarm is unset, then you will wait forever.
pub fn wait(&self) -> Result<()> {
loop {
if let Err(e) = read(self.fd, &mut [0u8; 8]) {
match e {
Errno::EINTR => continue,
_ => return Err(e),
}
} else {
break;
while let Err(e) = read(self.fd, &mut [0u8; 8]) {
if e != Errno::EINTR {
return Err(e)
}
}

View File

@ -6,7 +6,7 @@ use crate::sys::time::TimeSpec;
target_os = "android",
target_os = "emscripten",
))]
use crate::{unistd::Pid, Error};
use crate::unistd::Pid;
use crate::{Errno, Result};
use libc::{self, clockid_t};
use std::mem::MaybeUninit;
@ -255,6 +255,6 @@ pub fn clock_getcpuclockid(pid: Pid) -> Result<ClockId> {
let res = unsafe { clk_id.assume_init() };
Ok(ClockId::from(res))
} else {
Err(Error::from(Errno::from_i32(ret)))
Err(Errno::from_i32(ret))
}
}

View File

@ -1,4 +1,3 @@
use libc;
#[cfg(not(target_env = "musl"))]
use crate::Result;
#[cfg(not(target_env = "musl"))]

View File

@ -180,10 +180,7 @@ impl ForkResult {
/// Return `true` if this is the child process of the `fork()`
#[inline]
pub fn is_child(self) -> bool {
match self {
ForkResult::Child => true,
_ => false
}
matches!(self, ForkResult::Child)
}
/// Returns `true` if this is the parent process of the `fork()`
@ -398,7 +395,7 @@ pub fn dup3(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
#[inline]
fn dup3_polyfill(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result<RawFd> {
if oldfd == newfd {
return Err(Error::from(Errno::EINVAL));
return Err(Errno::EINVAL);
}
let fd = dup2(oldfd, newfd)?;
@ -572,7 +569,7 @@ fn reserve_double_buffer_size<T>(buf: &mut Vec<T>, limit: usize) -> Result<()> {
use std::cmp::min;
if buf.capacity() >= limit {
return Err(Error::from(Errno::ERANGE))
return Err(Errno::ERANGE)
}
let capacity = min(buf.capacity() * 2, limit);
@ -615,9 +612,9 @@ pub fn getcwd() -> Result<PathBuf> {
let error = Errno::last();
// ERANGE means buffer was too small to store directory name
if error != Errno::ERANGE {
return Err(Error::from(error));
return Err(error);
}
}
}
// Trigger the internal buffer resizing logic.
reserve_double_buffer_size(&mut buf, PATH_MAX as usize)?;
@ -739,7 +736,7 @@ pub fn execv<S: AsRef<CStr>>(path: &CStr, argv: &[S]) -> Result<Infallible> {
libc::execv(path.as_ptr(), args_p.as_ptr())
};
Err(Error::from(Errno::last()))
Err(Errno::last())
}
@ -764,7 +761,7 @@ pub fn execve<SA: AsRef<CStr>, SE: AsRef<CStr>>(path: &CStr, args: &[SA], env: &
libc::execve(path.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
};
Err(Error::from(Errno::last()))
Err(Errno::last())
}
/// Replace the current process image with a new one and replicate shell `PATH`
@ -784,7 +781,7 @@ pub fn execvp<S: AsRef<CStr>>(filename: &CStr, args: &[S]) -> Result<Infallible>
libc::execvp(filename.as_ptr(), args_p.as_ptr())
};
Err(Error::from(Errno::last()))
Err(Errno::last())
}
/// Replace the current process image with a new one and replicate shell `PATH`
@ -805,7 +802,7 @@ pub fn execvpe<SA: AsRef<CStr>, SE: AsRef<CStr>>(filename: &CStr, args: &[SA], e
libc::execvpe(filename.as_ptr(), args_p.as_ptr(), env_p.as_ptr())
};
Err(Error::from(Errno::last()))
Err(Errno::last())
}
/// Replace the current process image with a new one (see
@ -833,7 +830,7 @@ pub fn fexecve<SA: AsRef<CStr> ,SE: AsRef<CStr>>(fd: RawFd, args: &[SA], env: &[
libc::fexecve(fd, args_p.as_ptr(), env_p.as_ptr())
};
Err(Error::from(Errno::last()))
Err(Errno::last())
}
/// Execute program relative to a directory file descriptor (see
@ -858,7 +855,7 @@ pub fn execveat<SA: AsRef<CStr>,SE: AsRef<CStr>>(dirfd: RawFd, pathname: &CStr,
args_p.as_ptr(), env_p.as_ptr(), flags);
};
Err(Error::from(Errno::last()))
Err(Errno::last())
}
/// Daemonize this process by detaching from the controlling terminal (see
@ -1138,9 +1135,9 @@ pub fn isatty(fd: RawFd) -> Result<bool> {
} else {
match Errno::last() {
Errno::ENOTTY => Ok(false),
err => Err(Error::from(err)),
err => Err(err),
}
}
}
}
}
@ -1449,7 +1446,7 @@ pub fn getgroups() -> Result<Vec<Gid>> {
// EINVAL indicates that the buffer size was too
// small, resize it up to ngroups_max as limit.
reserve_double_buffer_size(&mut groups, ngroups_max)
.or(Err(Error::from(Errno::EINVAL)))?;
.or(Err(Errno::EINVAL))?;
},
Err(e) => return Err(e)
}
@ -1571,7 +1568,7 @@ pub fn getgrouplist(user: &CStr, group: Gid) -> Result<Vec<Gid>> {
// groups as possible, but Linux manpages do not mention this
// behavior.
reserve_double_buffer_size(&mut groups, ngroups_max as usize)
.map_err(|_| Error::from(Errno::EINVAL))?;
.map_err(|_| Errno::EINVAL)?;
}
}
}
@ -1930,7 +1927,7 @@ pub fn fpathconf(fd: RawFd, var: PathconfVar) -> Result<Option<c_long>> {
if errno::errno() == 0 {
Ok(None)
} else {
Err(Error::from(Errno::last()))
Err(Errno::last())
}
} else {
Ok(Some(raw))
@ -1969,7 +1966,7 @@ pub fn pathconf<P: ?Sized + NixPath>(path: &P, var: PathconfVar) -> Result<Optio
if errno::errno() == 0 {
Ok(None)
} else {
Err(Error::from(Errno::last()))
Err(Errno::last())
}
} else {
Ok(Some(raw))
@ -2469,7 +2466,7 @@ pub fn sysconf(var: SysconfVar) -> Result<Option<c_long>> {
if errno::errno() == 0 {
Ok(None)
} else {
Err(Error::from(Errno::last()))
Err(Errno::last())
}
} else {
Ok(Some(raw))
@ -2788,7 +2785,7 @@ impl User {
// Trigger the internal buffer resizing logic.
reserve_double_buffer_size(&mut cbuf, buflimit)?;
} else {
return Err(Error::from(Errno::last()));
return Err(Errno::last());
}
}
}
@ -2909,7 +2906,7 @@ impl Group {
// Trigger the internal buffer resizing logic.
reserve_double_buffer_size(&mut cbuf, buflimit)?;
} else {
return Err(Error::from(Errno::last()));
return Err(Errno::last());
}
}
}
@ -2968,7 +2965,7 @@ pub fn ttyname(fd: RawFd) -> Result<PathBuf> {
let ret = unsafe { libc::ttyname_r(fd, c_buf, buf.len()) };
if ret != 0 {
return Err(Error::from(Errno::from_i32(ret)));
return Err(Errno::from_i32(ret));
}
let nul = buf.iter().position(|c| *c == b'\0').unwrap();

View File

@ -1,5 +1,5 @@
use libc::{c_int, c_void};
use nix::{Error, Result};
use nix::Result;
use nix::errno::*;
use nix::sys::aio::*;
use nix::sys::signal::{SaFlags, SigAction, sigaction, SigevNotify, SigHandler, Signal, SigSet};
@ -16,7 +16,7 @@ use tempfile::tempfile;
fn poll_aio(aiocb: &mut Pin<Box<AioCb>>) -> Result<()> {
loop {
let err = aiocb.error();
if err != Err(Error::from(Errno::EINPROGRESS)) { return err; };
if err != Err(Errno::EINPROGRESS) { return err; };
thread::sleep(time::Duration::from_millis(10));
}
}
@ -26,7 +26,7 @@ fn poll_aio(aiocb: &mut Pin<Box<AioCb>>) -> Result<()> {
fn poll_lio(liocb: &mut LioCb, i: usize) -> Result<()> {
loop {
let err = liocb.error(i);
if err != Err(Error::from(Errno::EINPROGRESS)) { return err; };
if err != Err(Errno::EINPROGRESS) { return err; };
thread::sleep(time::Duration::from_millis(10));
}
}
@ -70,7 +70,7 @@ fn test_cancel() {
LioOpcode::LIO_NOP);
aiocb.write().unwrap();
let err = aiocb.error();
assert!(err == Ok(()) || err == Err(Error::from(Errno::EINPROGRESS)));
assert!(err == Ok(()) || err == Err(Errno::EINPROGRESS));
let cancelstat = aiocb.cancel();
assert!(cancelstat.is_ok());
@ -95,7 +95,7 @@ fn test_aio_cancel_all() {
LioOpcode::LIO_NOP);
aiocb.write().unwrap();
let err = aiocb.error();
assert!(err == Ok(()) || err == Err(Error::from(Errno::EINPROGRESS)));
assert!(err == Ok(()) || err == Err(Errno::EINPROGRESS));
let cancelstat = aio_cancel_all(f.as_raw_fd());
assert!(cancelstat.is_ok());
@ -182,8 +182,8 @@ fn test_aio_suspend() {
Ok(_) => ()
};
}
if rcb.error() != Err(Error::from(Errno::EINPROGRESS)) &&
wcb.error() != Err(Error::from(Errno::EINPROGRESS)) {
if rcb.error() != Err(Errno::EINPROGRESS) &&
wcb.error() != Err(Errno::EINPROGRESS) {
break
}
}

View File

@ -1,6 +1,5 @@
use nix::sys::epoll::{EpollCreateFlags, EpollFlags, EpollOp, EpollEvent};
use nix::sys::epoll::{epoll_create1, epoll_ctl};
use nix::Error;
use nix::errno::Errno;
#[test]
@ -8,11 +7,11 @@ pub fn test_epoll_errno() {
let efd = epoll_create1(EpollCreateFlags::empty()).unwrap();
let result = epoll_ctl(efd, EpollOp::EpollCtlDel, 1, None);
assert!(result.is_err());
assert_eq!(result.unwrap_err(), Error::from(Errno::ENOENT));
assert_eq!(result.unwrap_err(), Errno::ENOENT);
let result = epoll_ctl(efd, EpollOp::EpollCtlAdd, 1, None);
assert!(result.is_err());
assert_eq!(result.unwrap_err(), Error::from(Errno::EINVAL));
assert_eq!(result.unwrap_err(), Errno::EINVAL);
}
#[test]

View File

@ -1,7 +1,5 @@
use nix::sys::inotify::{AddWatchFlags,InitFlags,Inotify};
use nix::Error;
use nix::errno::Errno;
use tempfile;
use std::ffi::OsString;
use std::fs::{rename, File};
@ -14,7 +12,7 @@ pub fn test_inotify() {
instance.add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS).unwrap();
let events = instance.read_events();
assert_eq!(events.unwrap_err(), Error::from(Errno::EAGAIN));
assert_eq!(events.unwrap_err(), Errno::EAGAIN);
File::create(tempdir.path().join("test")).unwrap();
@ -31,7 +29,7 @@ pub fn test_inotify_multi_events() {
instance.add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS).unwrap();
let events = instance.read_events();
assert_eq!(events.unwrap_err(), Error::from(Errno::EAGAIN));
assert_eq!(events.unwrap_err(), Errno::EAGAIN);
File::create(tempdir.path().join("test")).unwrap();
rename(tempdir.path().join("test"), tempdir.path().join("test2")).unwrap();

View File

@ -152,7 +152,7 @@ pub fn test_abstract_sun_path_too_long() {
pub fn test_addr_equality_abstract() {
let name = String::from("nix\0abstract\0test");
let addr1 = UnixAddr::new_abstract(name.as_bytes()).unwrap();
let mut addr2 = addr1.clone();
let mut addr2 = addr1;
assert_eq!(addr1, addr2);
assert_eq!(calculate_hash(&addr1), calculate_hash(&addr2));
@ -367,7 +367,6 @@ mod recvfrom {
target_os = "freebsd",
target_os = "netbsd",
))]
#[allow(clippy::vec_init_then_push)]
#[test]
pub fn udp_sendmmsg() {
use nix::sys::uio::IoVec;
@ -394,14 +393,14 @@ mod recvfrom {
let from = sendrecv(rsock, ssock, move |s, m, flags| {
let iov = [IoVec::from_slice(m)];
let mut msgs = Vec::new();
msgs.push(
let mut msgs = vec![
SendMmsgData {
iov: &iov,
cmsgs: &[],
addr: Some(sock_addr),
_lt: Default::default(),
});
}
];
let batch_size = 15;
@ -640,7 +639,6 @@ pub fn test_scm_rights() {
#[cfg_attr(qemu, ignore)]
#[test]
pub fn test_af_alg_cipher() {
use libc;
use nix::sys::uio::IoVec;
use nix::unistd::read;
use nix::sys::socket::{socket, sendmsg, bind, accept, setsockopt,
@ -837,7 +835,7 @@ pub fn test_sendmsg_ipv4packetinfo() {
if let InetAddr::V4(sin) = inet_addr {
cfg_if! {
if #[cfg(target_os = "netbsd")] {
drop(sin);
let _dontcare = sin;
let pi = libc::in_pktinfo {
ipi_ifindex: 0, /* Unspecified interface */
ipi_addr: libc::in_addr { s_addr: 0 },
@ -925,7 +923,6 @@ fn test_scm_rights_single_cmsg_multiple_fds() {
use nix::sys::socket::{ControlMessage, ControlMessageOwned, MsgFlags,
sendmsg, recvmsg};
use nix::sys::uio::IoVec;
use libc;
let (send, receive) = UnixDatagram::pair().unwrap();
let thread = thread::spawn(move || {
@ -1068,8 +1065,6 @@ fn test_scm_credentials() {
#[cfg_attr(qemu, ignore)]
#[test]
fn test_scm_credentials_and_rights() {
use libc;
let space = cmsg_space!(libc::ucred, RawFd);
test_impl_scm_credentials_and_rights(space);
}
@ -1278,7 +1273,6 @@ fn loopback_address(family: AddressFamily) -> Option<nix::ifaddrs::InterfaceAddr
), ignore)]
#[test]
pub fn test_recv_ipv4pktinfo() {
use libc;
use nix::sys::socket::sockopt::Ipv4PacketInfo;
use nix::sys::socket::{bind, SockFlag, SockType};
use nix::sys::socket::{getsockname, setsockopt, socket};
@ -1331,18 +1325,15 @@ pub fn test_recv_ipv4pktinfo() {
);
let mut cmsgs = msg.cmsgs();
match cmsgs.next() {
Some(ControlMessageOwned::Ipv4PacketInfo(pktinfo)) => {
let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex");
assert_eq!(
pktinfo.ipi_ifindex as libc::c_uint,
i,
"unexpected ifindex (expected {}, got {})",
i,
pktinfo.ipi_ifindex
);
}
_ => (),
if let Some(ControlMessageOwned::Ipv4PacketInfo(pktinfo)) = cmsgs.next() {
let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex");
assert_eq!(
pktinfo.ipi_ifindex as libc::c_uint,
i,
"unexpected ifindex (expected {}, got {})",
i,
pktinfo.ipi_ifindex
);
}
assert!(cmsgs.next().is_none(), "unexpected additional control msg");
assert_eq!(msg.bytes, 8);
@ -1371,7 +1362,6 @@ pub fn test_recv_ipv4pktinfo() {
), ignore)]
#[test]
pub fn test_recvif() {
use libc;
use nix::net::if_::*;
use nix::sys::socket::sockopt::{Ipv4RecvIf, Ipv4RecvDstAddr};
use nix::sys::socket::{bind, SockFlag, SockType};
@ -1485,7 +1475,6 @@ pub fn test_recvif() {
), ignore)]
#[test]
pub fn test_recv_ipv6pktinfo() {
use libc;
use nix::net::if_::*;
use nix::sys::socket::sockopt::Ipv6RecvPacketInfo;
use nix::sys::socket::{bind, SockFlag, SockType};
@ -1562,7 +1551,6 @@ pub fn test_recv_ipv6pktinfo() {
#[cfg_attr(graviton, ignore = "Not supported by the CI environment")]
#[test]
pub fn test_vsock() {
use libc;
use nix::errno::Errno;
use nix::sys::socket::{AddressFamily, socket, bind, connect, listen,
SockAddr, SockType, SockFlag};
@ -1838,7 +1826,7 @@ mod linux_errqueue {
} else {
panic!("Expected some error origin");
}
return *ext_err
*ext_err
} else {
panic!("Unexpected control message {:?}", cmsg);
}
@ -1884,7 +1872,7 @@ mod linux_errqueue {
} else {
panic!("Expected some error origin");
}
return *ext_err
*ext_err
} else {
panic!("Unexpected control message {:?}", cmsg);
}

View File

@ -17,6 +17,7 @@ fn flags() -> OFlag {
}
#[test]
#[allow(clippy::unnecessary_sort_by)] // False positive
fn read() {
let tmp = tempdir().unwrap();
File::create(&tmp.path().join("foo")).unwrap();

View File

@ -127,14 +127,14 @@ fn test_renameat2_exchange() {
let old_path = old_dir.path().join("old");
{
let mut old_f = File::create(&old_path).unwrap();
old_f.write(b"old").unwrap();
old_f.write_all(b"old").unwrap();
}
let new_dir = tempfile::tempdir().unwrap();
let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap();
let new_path = new_dir.path().join("new");
{
let mut new_f = File::create(&new_path).unwrap();
new_f.write(b"new").unwrap();
new_f.write_all(b"new").unwrap();
}
renameat2(
Some(old_dirfd),
@ -319,9 +319,10 @@ mod linux_android {
let buf1 = b"abcdef";
let buf2 = b"defghi";
let mut iovecs = Vec::with_capacity(2);
iovecs.push(IoVec::from_slice(&buf1[0..3]));
iovecs.push(IoVec::from_slice(&buf2[0..3]));
let iovecs = vec![
IoVec::from_slice(&buf1[0..3]),
IoVec::from_slice(&buf2[0..3])
];
let res = vmsplice(wr, &iovecs[..], SpliceFFlags::empty()).unwrap();

View File

@ -34,7 +34,6 @@ fn compile_kernel_module() -> (PathBuf, String, TempDir) {
use nix::errno::Errno;
use nix::kmod::{delete_module, DeleteModuleFlags};
use nix::kmod::{finit_module, init_module, ModuleInitFlags};
use nix::Error;
use std::ffi::CString;
use std::fs::File;
use std::io::Read;
@ -90,7 +89,7 @@ fn test_init_and_delete_module() {
let mut contents: Vec<u8> = Vec::new();
f.read_to_end(&mut contents)
.expect("unable to read kernel module content to buffer");
init_module(&mut contents, &CString::new("").unwrap()).expect("unable to load kernel module");
init_module(&contents, &CString::new("").unwrap()).expect("unable to load kernel module");
delete_module(
&CString::new(kmod_name).unwrap(),
@ -110,7 +109,7 @@ fn test_init_and_delete_module_with_params() {
let mut contents: Vec<u8> = Vec::new();
f.read_to_end(&mut contents)
.expect("unable to read kernel module content to buffer");
init_module(&mut contents, &CString::new("who=Nix number=2015").unwrap())
init_module(&contents, &CString::new("who=Nix number=2015").unwrap())
.expect("unable to load kernel module");
delete_module(
@ -130,7 +129,7 @@ fn test_finit_module_invalid() {
let f = File::open(kmod_path).expect("unable to open kernel module");
let result = finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty());
assert_eq!(result.unwrap_err(), Error::from(Errno::EINVAL));
assert_eq!(result.unwrap_err(), Errno::EINVAL);
}
#[test]
@ -147,7 +146,7 @@ fn test_finit_module_twice_and_delete_module() {
let result = finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty());
assert_eq!(result.unwrap_err(), Error::from(Errno::EEXIST));
assert_eq!(result.unwrap_err(), Errno::EEXIST);
delete_module(
&CString::new(kmod_name).unwrap(),
@ -163,5 +162,5 @@ fn test_delete_module_not_loaded() {
let result = delete_module(&CString::new("hello").unwrap(), DeleteModuleFlags::empty());
assert_eq!(result.unwrap_err(), Error::from(Errno::ENOENT));
assert_eq!(result.unwrap_err(), Errno::ENOENT);
}

View File

@ -21,14 +21,13 @@ mod test_mount {
use nix::sys::stat::{self, Mode};
use nix::unistd::getuid;
use tempfile;
static SCRIPT_CONTENTS: &'static [u8] = b"#!/bin/sh
static SCRIPT_CONTENTS: &[u8] = b"#!/bin/sh
exit 23";
const EXPECTED_STATUS: i32 = 23;
const NONE: Option<&'static [u8]> = None;
#[allow(clippy::bind_instead_of_map)] // False positive
pub fn test_mount_tmpfs_without_flags_allows_rwx() {
let tempdir = tempfile::tempdir().unwrap();

View File

@ -114,6 +114,8 @@ fn open_ptty_pair() -> (PtyMaster, File) {
let slave_fd = open(Path::new(&slave_name), OFlag::O_RDWR, stat::Mode::empty()).unwrap();
#[cfg(target_os = "illumos")]
// TODO: rewrite using ioctl!
#[allow(clippy::comparison_chain)]
{
use libc::{ioctl, I_FIND, I_PUSH};

View File

@ -59,6 +59,7 @@ fn assert_stat_results(stat_result: Result<FileStat>) {
#[cfg(not(any(target_os = "netbsd", target_os = "redox")))]
// (Android's st_blocks is ulonglong which is always non-negative.)
#[cfg_attr(target_os = "android", allow(unused_comparisons))]
#[allow(clippy::absurd_extreme_comparisons)] // Not absurd on all OSes
fn assert_lstat_results(stat_result: Result<FileStat>) {
let stats = stat_result.expect("stat call failed");
assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent

View File

@ -10,7 +10,7 @@ use nix::sys::stat::{self, Mode, SFlag};
#[cfg(not(any(target_os = "redox", target_os = "fuchsia")))]
use nix::pty::{posix_openpt, grantpt, unlockpt, ptsname};
use nix::errno::Errno;
use std::{env, iter};
use std::env;
#[cfg(not(any(target_os = "fuchsia", target_os = "redox")))]
use std::ffi::CString;
#[cfg(not(target_os = "redox"))]
@ -443,7 +443,7 @@ fn test_getcwd() {
// 4096 on linux, 1024 on macos)
let mut inner_tmp_dir = tmpdir_path;
for _ in 0..5 {
let newdir = iter::repeat("a").take(100).collect::<String>();
let newdir = "a".repeat(100);
inner_tmp_dir.push(newdir);
assert!(mkdir(inner_tmp_dir.as_path(), Mode::S_IRWXU).is_ok());
}
@ -1051,7 +1051,7 @@ fn test_setfsuid() {
dbg!(&temp_path);
let temp_path_2 = (&temp_path).to_path_buf();
let mut permissions = fs::metadata(&temp_path).unwrap().permissions();
permissions.set_mode(640);
permissions.set_mode(0o640);
// spawn a new thread where to test setfsuid
thread::spawn(move || {