diff --git a/src/errno.rs b/src/errno.rs index 0a38ab69f4..d3de6b6076 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -1,7 +1,7 @@ #[cfg(not(target_os = "dragonfly"))] use libc; use libc::c_int; -use std::{fmt, io, error}; +use std::{error, fmt, io}; use {Error, Result}; pub use self::consts::*; @@ -52,9 +52,7 @@ unsafe fn clear() -> () { /// Returns the platform-specific value of errno pub fn errno() -> i32 { - unsafe { - (*errno_location()) as i32 - } + unsafe { (*errno_location()) as i32 } } impl Errno { @@ -92,19 +90,27 @@ pub trait ErrnoSentinel: Sized { } impl ErrnoSentinel for isize { - fn sentinel() -> Self { -1 } + fn sentinel() -> Self { + -1 + } } impl ErrnoSentinel for i32 { - fn sentinel() -> Self { -1 } + fn sentinel() -> Self { + -1 + } } impl ErrnoSentinel for i64 { - fn sentinel() -> Self { -1 } + fn sentinel() -> Self { + -1 + } } impl ErrnoSentinel for *mut libc::c_void { - fn sentinel() -> Self { (-1 as isize) as *mut libc::c_void } + fn sentinel() -> Self { + (-1 as isize) as *mut libc::c_void + } } impl error::Error for Errno { @@ -132,400 +138,584 @@ fn last() -> Errno { fn desc(errno: Errno) -> &'static str { use self::Errno::*; match errno { - UnknownErrno => "Unknown errno", - EPERM => "Operation not permitted", - ENOENT => "No such file or directory", - ESRCH => "No such process", - EINTR => "Interrupted system call", - EIO => "I/O error", - ENXIO => "No such device or address", - E2BIG => "Argument list too long", - ENOEXEC => "Exec format error", - EBADF => "Bad file number", - ECHILD => "No child processes", - EAGAIN => "Try again", - ENOMEM => "Out of memory", - EACCES => "Permission denied", - EFAULT => "Bad address", - ENOTBLK => "Block device required", - EBUSY => "Device or resource busy", - EEXIST => "File exists", - EXDEV => "Cross-device link", - ENODEV => "No such device", - ENOTDIR => "Not a directory", - EISDIR => "Is a directory", - EINVAL => "Invalid argument", - ENFILE => "File table overflow", - EMFILE => "Too many open files", - ENOTTY => "Not a typewriter", - ETXTBSY => "Text file busy", - EFBIG => "File too large", - ENOSPC => "No space left on device", - ESPIPE => "Illegal seek", - EROFS => "Read-only file system", - EMLINK => "Too many links", - EPIPE => "Broken pipe", - EDOM => "Math argument out of domain of func", - ERANGE => "Math result not representable", - EDEADLK => "Resource deadlock would occur", - ENAMETOOLONG => "File name too long", - ENOLCK => "No record locks available", - ENOSYS => "Function not implemented", - ENOTEMPTY => "Directory not empty", - ELOOP => "Too many symbolic links encountered", - ENOMSG => "No message of desired type", - EIDRM => "Identifier removed", - EINPROGRESS => "Operation now in progress", - EALREADY => "Operation already in progress", - ENOTSOCK => "Socket operation on non-socket", - EDESTADDRREQ => "Destination address required", - EMSGSIZE => "Message too long", - EPROTOTYPE => "Protocol wrong type for socket", - ENOPROTOOPT => "Protocol not available", + UnknownErrno => "Unknown errno", + EPERM => "Operation not permitted", + ENOENT => "No such file or directory", + ESRCH => "No such process", + EINTR => "Interrupted system call", + EIO => "I/O error", + ENXIO => "No such device or address", + E2BIG => "Argument list too long", + ENOEXEC => "Exec format error", + EBADF => "Bad file number", + ECHILD => "No child processes", + EAGAIN => "Try again", + ENOMEM => "Out of memory", + EACCES => "Permission denied", + EFAULT => "Bad address", + ENOTBLK => "Block device required", + EBUSY => "Device or resource busy", + EEXIST => "File exists", + EXDEV => "Cross-device link", + ENODEV => "No such device", + ENOTDIR => "Not a directory", + EISDIR => "Is a directory", + EINVAL => "Invalid argument", + ENFILE => "File table overflow", + EMFILE => "Too many open files", + ENOTTY => "Not a typewriter", + ETXTBSY => "Text file busy", + EFBIG => "File too large", + ENOSPC => "No space left on device", + ESPIPE => "Illegal seek", + EROFS => "Read-only file system", + EMLINK => "Too many links", + EPIPE => "Broken pipe", + EDOM => "Math argument out of domain of func", + ERANGE => "Math result not representable", + EDEADLK => "Resource deadlock would occur", + ENAMETOOLONG => "File name too long", + ENOLCK => "No record locks available", + ENOSYS => "Function not implemented", + ENOTEMPTY => "Directory not empty", + ELOOP => "Too many symbolic links encountered", + ENOMSG => "No message of desired type", + EIDRM => "Identifier removed", + EINPROGRESS => "Operation now in progress", + EALREADY => "Operation already in progress", + ENOTSOCK => "Socket operation on non-socket", + EDESTADDRREQ => "Destination address required", + EMSGSIZE => "Message too long", + EPROTOTYPE => "Protocol wrong type for socket", + ENOPROTOOPT => "Protocol not available", EPROTONOSUPPORT => "Protocol not supported", ESOCKTNOSUPPORT => "Socket type not supported", - EPFNOSUPPORT => "Protocol family not supported", - EAFNOSUPPORT => "Address family not supported by protocol", - EADDRINUSE => "Address already in use", - EADDRNOTAVAIL => "Cannot assign requested address", - ENETDOWN => "Network is down", - ENETUNREACH => "Network is unreachable", - ENETRESET => "Network dropped connection because of reset", - ECONNABORTED => "Software caused connection abort", - ECONNRESET => "Connection reset by peer", - ENOBUFS => "No buffer space available", - EISCONN => "Transport endpoint is already connected", - ENOTCONN => "Transport endpoint is not connected", - ESHUTDOWN => "Cannot send after transport endpoint shutdown", - ETOOMANYREFS => "Too many references: cannot splice", - ETIMEDOUT => "Connection timed out", - ECONNREFUSED => "Connection refused", - EHOSTDOWN => "Host is down", - EHOSTUNREACH => "No route to host", + EPFNOSUPPORT => "Protocol family not supported", + EAFNOSUPPORT => "Address family not supported by protocol", + EADDRINUSE => "Address already in use", + EADDRNOTAVAIL => "Cannot assign requested address", + ENETDOWN => "Network is down", + ENETUNREACH => "Network is unreachable", + ENETRESET => "Network dropped connection because of reset", + ECONNABORTED => "Software caused connection abort", + ECONNRESET => "Connection reset by peer", + ENOBUFS => "No buffer space available", + EISCONN => "Transport endpoint is already connected", + ENOTCONN => "Transport endpoint is not connected", + ESHUTDOWN => "Cannot send after transport endpoint shutdown", + ETOOMANYREFS => "Too many references: cannot splice", + ETIMEDOUT => "Connection timed out", + ECONNREFUSED => "Connection refused", + EHOSTDOWN => "Host is down", + EHOSTUNREACH => "No route to host", #[cfg(any(target_os = "linux", target_os = "android"))] - ECHRNG => "Channel number out of range", + ECHRNG => "Channel number out of range", #[cfg(any(target_os = "linux", target_os = "android"))] - EL2NSYNC => "Level 2 not synchronized", + EL2NSYNC => "Level 2 not synchronized", #[cfg(any(target_os = "linux", target_os = "android"))] - EL3HLT => "Level 3 halted", + EL3HLT => "Level 3 halted", #[cfg(any(target_os = "linux", target_os = "android"))] - EL3RST => "Level 3 reset", + EL3RST => "Level 3 reset", #[cfg(any(target_os = "linux", target_os = "android"))] - ELNRNG => "Link number out of range", + ELNRNG => "Link number out of range", #[cfg(any(target_os = "linux", target_os = "android"))] - EUNATCH => "Protocol driver not attached", + EUNATCH => "Protocol driver not attached", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOCSI => "No CSI structure available", + ENOCSI => "No CSI structure available", #[cfg(any(target_os = "linux", target_os = "android"))] - EL2HLT => "Level 2 halted", + EL2HLT => "Level 2 halted", #[cfg(any(target_os = "linux", target_os = "android"))] - EBADE => "Invalid exchange", + EBADE => "Invalid exchange", #[cfg(any(target_os = "linux", target_os = "android"))] - EBADR => "Invalid request descriptor", + EBADR => "Invalid request descriptor", #[cfg(any(target_os = "linux", target_os = "android"))] - EXFULL => "Exchange full", + EXFULL => "Exchange full", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOANO => "No anode", + ENOANO => "No anode", #[cfg(any(target_os = "linux", target_os = "android"))] - EBADRQC => "Invalid request code", + EBADRQC => "Invalid request code", #[cfg(any(target_os = "linux", target_os = "android"))] - EBADSLT => "Invalid slot", + EBADSLT => "Invalid slot", #[cfg(any(target_os = "linux", target_os = "android"))] - EBFONT => "Bad font file format", + EBFONT => "Bad font file format", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOSTR => "Device not a stream", + ENOSTR => "Device not a stream", #[cfg(any(target_os = "linux", target_os = "android"))] - ENODATA => "No data available", + ENODATA => "No data available", #[cfg(any(target_os = "linux", target_os = "android"))] - ETIME => "Timer expired", + ETIME => "Timer expired", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOSR => "Out of streams resources", + ENOSR => "Out of streams resources", #[cfg(any(target_os = "linux", target_os = "android"))] - ENONET => "Machine is not on the network", + ENONET => "Machine is not on the network", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOPKG => "Package not installed", + ENOPKG => "Package not installed", #[cfg(any(target_os = "linux", target_os = "android"))] - EREMOTE => "Object is remote", + EREMOTE => "Object is remote", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOLINK => "Link has been severed", + ENOLINK => "Link has been severed", #[cfg(any(target_os = "linux", target_os = "android"))] - EADV => "Advertise error", + EADV => "Advertise error", #[cfg(any(target_os = "linux", target_os = "android"))] - ESRMNT => "Srmount error", + ESRMNT => "Srmount error", #[cfg(any(target_os = "linux", target_os = "android"))] - ECOMM => "Communication error on send", + ECOMM => "Communication error on send", #[cfg(any(target_os = "linux", target_os = "android"))] - EPROTO => "Protocol error", + EPROTO => "Protocol error", #[cfg(any(target_os = "linux", target_os = "android"))] - EMULTIHOP => "Multihop attempted", + EMULTIHOP => "Multihop attempted", #[cfg(any(target_os = "linux", target_os = "android"))] - EDOTDOT => "RFS specific error", + EDOTDOT => "RFS specific error", #[cfg(any(target_os = "linux", target_os = "android"))] - EBADMSG => "Not a data message", + EBADMSG => "Not a data message", #[cfg(any(target_os = "linux", target_os = "android"))] - EOVERFLOW => "Value too large for defined data type", + EOVERFLOW => "Value too large for defined data type", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOTUNIQ => "Name not unique on network", + ENOTUNIQ => "Name not unique on network", #[cfg(any(target_os = "linux", target_os = "android"))] - EBADFD => "File descriptor in bad state", + EBADFD => "File descriptor in bad state", #[cfg(any(target_os = "linux", target_os = "android"))] - EREMCHG => "Remote address changed", + EREMCHG => "Remote address changed", #[cfg(any(target_os = "linux", target_os = "android"))] - ELIBACC => "Can not access a needed shared library", + ELIBACC => "Can not access a needed shared library", #[cfg(any(target_os = "linux", target_os = "android"))] - ELIBBAD => "Accessing a corrupted shared library", + ELIBBAD => "Accessing a corrupted shared library", #[cfg(any(target_os = "linux", target_os = "android"))] - ELIBSCN => ".lib section in a.out corrupted", + ELIBSCN => ".lib section in a.out corrupted", #[cfg(any(target_os = "linux", target_os = "android"))] - ELIBMAX => "Attempting to link in too many shared libraries", + ELIBMAX => "Attempting to link in too many shared libraries", #[cfg(any(target_os = "linux", target_os = "android"))] - ELIBEXEC => "Cannot exec a shared library directly", + ELIBEXEC => "Cannot exec a shared library directly", #[cfg(any(target_os = "linux", target_os = "android", target_os = "openbsd"))] - EILSEQ => "Illegal byte sequence", + EILSEQ => "Illegal byte sequence", #[cfg(any(target_os = "linux", target_os = "android"))] - ERESTART => "Interrupted system call should be restarted", + ERESTART => "Interrupted system call should be restarted", #[cfg(any(target_os = "linux", target_os = "android"))] - ESTRPIPE => "Streams pipe error", + ESTRPIPE => "Streams pipe error", #[cfg(any(target_os = "linux", target_os = "android"))] - EUSERS => "Too many users", + EUSERS => "Too many users", #[cfg(any(target_os = "linux", target_os = "android", target_os = "netbsd"))] - EOPNOTSUPP => "Operation not supported on transport endpoint", + EOPNOTSUPP => "Operation not supported on transport endpoint", #[cfg(any(target_os = "linux", target_os = "android"))] - ESTALE => "Stale file handle", + ESTALE => "Stale file handle", #[cfg(any(target_os = "linux", target_os = "android"))] - EUCLEAN => "Structure needs cleaning", + EUCLEAN => "Structure needs cleaning", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOTNAM => "Not a XENIX named type file", + ENOTNAM => "Not a XENIX named type file", #[cfg(any(target_os = "linux", target_os = "android"))] - ENAVAIL => "No XENIX semaphores available", + ENAVAIL => "No XENIX semaphores available", #[cfg(any(target_os = "linux", target_os = "android"))] - EISNAM => "Is a named type file", + EISNAM => "Is a named type file", #[cfg(any(target_os = "linux", target_os = "android"))] - EREMOTEIO => "Remote I/O error", + EREMOTEIO => "Remote I/O error", #[cfg(any(target_os = "linux", target_os = "android"))] - EDQUOT => "Quota exceeded", - - #[cfg(any(target_os = "linux", target_os = "android", target_os = "openbsd", target_os = "dragonfly"))] - ENOMEDIUM => "No medium found", + EDQUOT => "Quota exceeded", + + #[cfg( + any( + target_os = "linux", + target_os = "android", + target_os = "openbsd", + target_os = "dragonfly" + ) + )] + ENOMEDIUM => "No medium found", #[cfg(any(target_os = "linux", target_os = "android", target_os = "openbsd"))] - EMEDIUMTYPE => "Wrong medium type", + EMEDIUMTYPE => "Wrong medium type", #[cfg(any(target_os = "linux", target_os = "android"))] - ECANCELED => "Operation canceled", + ECANCELED => "Operation canceled", #[cfg(any(target_os = "linux", target_os = "android"))] - ENOKEY => "Required key not available", + ENOKEY => "Required key not available", #[cfg(any(target_os = "linux", target_os = "android"))] - EKEYEXPIRED => "Key has expired", + EKEYEXPIRED => "Key has expired", #[cfg(any(target_os = "linux", target_os = "android"))] - EKEYREVOKED => "Key has been revoked", + EKEYREVOKED => "Key has been revoked", #[cfg(any(target_os = "linux", target_os = "android"))] - EKEYREJECTED => "Key was rejected by service", + EKEYREJECTED => "Key was rejected by service", #[cfg(any(target_os = "linux", target_os = "android"))] - EOWNERDEAD => "Owner died", + EOWNERDEAD => "Owner died", #[cfg(any(target_os = "linux", target_os = "android"))] ENOTRECOVERABLE => "State not recoverable", - #[cfg(all(target_os = "linux", not(target_arch="mips")))] - ERFKILL => "Operation not possible due to RF-kill", + #[cfg(all(target_os = "linux", not(target_arch = "mips")))] + ERFKILL => "Operation not possible due to RF-kill", - #[cfg(all(target_os = "linux", not(target_arch="mips")))] - EHWPOISON => "Memory page has hardware error", + #[cfg(all(target_os = "linux", not(target_arch = "mips")))] + EHWPOISON => "Memory page has hardware error", #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - EDOOFUS => "Programming error", + EDOOFUS => "Programming error", #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - EMULTIHOP => "Multihop attempted", + EMULTIHOP => "Multihop attempted", #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - ENOLINK => "Link has been severed", + ENOLINK => "Link has been severed", #[cfg(target_os = "freebsd")] - ENOTCAPABLE => "Capabilities insufficient", + ENOTCAPABLE => "Capabilities insufficient", #[cfg(target_os = "freebsd")] - ECAPMODE => "Not permitted in capability mode", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - ENEEDAUTH => "Need authenticator", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EOVERFLOW => "Value too large to be stored in data type", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "netbsd"))] - EILSEQ => "Illegal byte sequence", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - ENOATTR => "Attribute not found", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "netbsd"))] - EBADMSG => "Bad message", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "netbsd"))] - EPROTO => "Protocol error", + ECAPMODE => "Not permitted in capability mode", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + ENEEDAUTH => "Need authenticator", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EOVERFLOW => "Value too large to be stored in data type", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "netbsd" + ) + )] + EILSEQ => "Illegal byte sequence", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + ENOATTR => "Attribute not found", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "netbsd" + ) + )] + EBADMSG => "Bad message", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "netbsd" + ) + )] + EPROTO => "Protocol error", #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "ios"))] ENOTRECOVERABLE => "State not recoverable", #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "ios"))] - EOWNERDEAD => "Previous owner died", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - ENOTSUP => "Operation not supported", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EPROCLIM => "Too many processes", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EUSERS => "Too many users", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EDQUOT => "Disc quota exceeded", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - ESTALE => "Stale NFS file handle", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EREMOTE => "Too many levels of remote in path", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EBADRPC => "RPC struct is bad", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - ERPCMISMATCH => "RPC version wrong", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EPROGUNAVAIL => "RPC prog. not avail", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EPROGMISMATCH => "Program version wrong", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EPROCUNAVAIL => "Bad procedure for program", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EFTYPE => "Inappropriate file type or format", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - EAUTH => "Authentication error", - - #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] - ECANCELED => "Operation canceled", + EOWNERDEAD => "Previous owner died", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + ENOTSUP => "Operation not supported", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EPROCLIM => "Too many processes", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EUSERS => "Too many users", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EDQUOT => "Disc quota exceeded", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + ESTALE => "Stale NFS file handle", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EREMOTE => "Too many levels of remote in path", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EBADRPC => "RPC struct is bad", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + ERPCMISMATCH => "RPC version wrong", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EPROGUNAVAIL => "RPC prog. not avail", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EPROGMISMATCH => "Program version wrong", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EPROCUNAVAIL => "Bad procedure for program", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EFTYPE => "Inappropriate file type or format", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + EAUTH => "Authentication error", + + #[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) + )] + ECANCELED => "Operation canceled", #[cfg(any(target_os = "macos", target_os = "ios"))] - EPWROFF => "Device power is off", + EPWROFF => "Device power is off", #[cfg(any(target_os = "macos", target_os = "ios"))] - EDEVERR => "Device error, e.g. paper out", + EDEVERR => "Device error, e.g. paper out", #[cfg(any(target_os = "macos", target_os = "ios"))] - EBADEXEC => "Bad executable", + EBADEXEC => "Bad executable", #[cfg(any(target_os = "macos", target_os = "ios"))] - EBADARCH => "Bad CPU type in executable", + EBADARCH => "Bad CPU type in executable", #[cfg(any(target_os = "macos", target_os = "ios"))] - ESHLIBVERS => "Shared library version mismatch", + ESHLIBVERS => "Shared library version mismatch", #[cfg(any(target_os = "macos", target_os = "ios"))] - EBADMACHO => "Malformed Macho file", + EBADMACHO => "Malformed Macho file", #[cfg(any(target_os = "macos", target_os = "ios", target_os = "netbsd"))] - EMULTIHOP => "Reserved", + EMULTIHOP => "Reserved", #[cfg(any(target_os = "macos", target_os = "ios", target_os = "netbsd"))] - ENODATA => "No message available on STREAM", + ENODATA => "No message available on STREAM", #[cfg(any(target_os = "macos", target_os = "ios", target_os = "netbsd"))] - ENOLINK => "Reserved", + ENOLINK => "Reserved", #[cfg(any(target_os = "macos", target_os = "ios", target_os = "netbsd"))] - ENOSR => "No STREAM resources", + ENOSR => "No STREAM resources", #[cfg(any(target_os = "macos", target_os = "ios", target_os = "netbsd"))] - ENOSTR => "Not a STREAM", + ENOSTR => "Not a STREAM", #[cfg(any(target_os = "macos", target_os = "ios", target_os = "netbsd"))] - ETIME => "STREAM ioctl timeout", + ETIME => "STREAM ioctl timeout", #[cfg(any(target_os = "macos", target_os = "ios"))] - EOPNOTSUPP => "Operation not supported on socket", + EOPNOTSUPP => "Operation not supported on socket", #[cfg(any(target_os = "macos", target_os = "ios"))] - ENOPOLICY => "No such policy registered", + ENOPOLICY => "No such policy registered", #[cfg(any(target_os = "macos", target_os = "ios"))] - EQFULL => "Interface output queue is full", + EQFULL => "Interface output queue is full", #[cfg(target_os = "openbsd")] - EOPNOTSUPP => "Operation not supported", + EOPNOTSUPP => "Operation not supported", #[cfg(target_os = "openbsd")] - EIPSEC => "IPsec processing failure", + EIPSEC => "IPsec processing failure", #[cfg(target_os = "dragonfly")] EUNUSED94 | EUNUSED95 | EUNUSED96 | EUNUSED97 | EUNUSED98 => "Unused", #[cfg(target_os = "dragonfly")] - EASYNC => "Async", + EASYNC => "Async", } } @@ -536,144 +726,144 @@ mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EAGAIN = libc::EAGAIN, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EDEADLK = libc::EDEADLK, - ENAMETOOLONG = libc::ENAMETOOLONG, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - ENOTEMPTY = libc::ENOTEMPTY, - ELOOP = libc::ELOOP, - ENOMSG = libc::ENOMSG, - EIDRM = libc::EIDRM, - ECHRNG = libc::ECHRNG, - EL2NSYNC = libc::EL2NSYNC, - EL3HLT = libc::EL3HLT, - EL3RST = libc::EL3RST, - ELNRNG = libc::ELNRNG, - EUNATCH = libc::EUNATCH, - ENOCSI = libc::ENOCSI, - EL2HLT = libc::EL2HLT, - EBADE = libc::EBADE, - EBADR = libc::EBADR, - EXFULL = libc::EXFULL, - ENOANO = libc::ENOANO, - EBADRQC = libc::EBADRQC, - EBADSLT = libc::EBADSLT, - EBFONT = libc::EBFONT, - ENOSTR = libc::ENOSTR, - ENODATA = libc::ENODATA, - ETIME = libc::ETIME, - ENOSR = libc::ENOSR, - ENONET = libc::ENONET, - ENOPKG = libc::ENOPKG, - EREMOTE = libc::EREMOTE, - ENOLINK = libc::ENOLINK, - EADV = libc::EADV, - ESRMNT = libc::ESRMNT, - ECOMM = libc::ECOMM, - EPROTO = libc::EPROTO, - EMULTIHOP = libc::EMULTIHOP, - EDOTDOT = libc::EDOTDOT, - EBADMSG = libc::EBADMSG, - EOVERFLOW = libc::EOVERFLOW, - ENOTUNIQ = libc::ENOTUNIQ, - EBADFD = libc::EBADFD, - EREMCHG = libc::EREMCHG, - ELIBACC = libc::ELIBACC, - ELIBBAD = libc::ELIBBAD, - ELIBSCN = libc::ELIBSCN, - ELIBMAX = libc::ELIBMAX, - ELIBEXEC = libc::ELIBEXEC, - EILSEQ = libc::EILSEQ, - ERESTART = libc::ERESTART, - ESTRPIPE = libc::ESTRPIPE, - EUSERS = libc::EUSERS, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EAGAIN = libc::EAGAIN, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EDEADLK = libc::EDEADLK, + ENAMETOOLONG = libc::ENAMETOOLONG, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + ENOTEMPTY = libc::ENOTEMPTY, + ELOOP = libc::ELOOP, + ENOMSG = libc::ENOMSG, + EIDRM = libc::EIDRM, + ECHRNG = libc::ECHRNG, + EL2NSYNC = libc::EL2NSYNC, + EL3HLT = libc::EL3HLT, + EL3RST = libc::EL3RST, + ELNRNG = libc::ELNRNG, + EUNATCH = libc::EUNATCH, + ENOCSI = libc::ENOCSI, + EL2HLT = libc::EL2HLT, + EBADE = libc::EBADE, + EBADR = libc::EBADR, + EXFULL = libc::EXFULL, + ENOANO = libc::ENOANO, + EBADRQC = libc::EBADRQC, + EBADSLT = libc::EBADSLT, + EBFONT = libc::EBFONT, + ENOSTR = libc::ENOSTR, + ENODATA = libc::ENODATA, + ETIME = libc::ETIME, + ENOSR = libc::ENOSR, + ENONET = libc::ENONET, + ENOPKG = libc::ENOPKG, + EREMOTE = libc::EREMOTE, + ENOLINK = libc::ENOLINK, + EADV = libc::EADV, + ESRMNT = libc::ESRMNT, + ECOMM = libc::ECOMM, + EPROTO = libc::EPROTO, + EMULTIHOP = libc::EMULTIHOP, + EDOTDOT = libc::EDOTDOT, + EBADMSG = libc::EBADMSG, + EOVERFLOW = libc::EOVERFLOW, + ENOTUNIQ = libc::ENOTUNIQ, + EBADFD = libc::EBADFD, + EREMCHG = libc::EREMCHG, + ELIBACC = libc::ELIBACC, + ELIBBAD = libc::ELIBBAD, + ELIBSCN = libc::ELIBSCN, + ELIBMAX = libc::ELIBMAX, + ELIBEXEC = libc::ELIBEXEC, + EILSEQ = libc::EILSEQ, + ERESTART = libc::ERESTART, + ESTRPIPE = libc::ESTRPIPE, + EUSERS = libc::EUSERS, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - EOPNOTSUPP = libc::EOPNOTSUPP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - EALREADY = libc::EALREADY, - EINPROGRESS = libc::EINPROGRESS, - ESTALE = libc::ESTALE, - EUCLEAN = libc::EUCLEAN, - ENOTNAM = libc::ENOTNAM, - ENAVAIL = libc::ENAVAIL, - EISNAM = libc::EISNAM, - EREMOTEIO = libc::EREMOTEIO, - EDQUOT = libc::EDQUOT, - ENOMEDIUM = libc::ENOMEDIUM, - EMEDIUMTYPE = libc::EMEDIUMTYPE, - ECANCELED = libc::ECANCELED, - ENOKEY = libc::ENOKEY, - EKEYEXPIRED = libc::EKEYEXPIRED, - EKEYREVOKED = libc::EKEYREVOKED, - EKEYREJECTED = libc::EKEYREJECTED, - EOWNERDEAD = libc::EOWNERDEAD, + EOPNOTSUPP = libc::EOPNOTSUPP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + EALREADY = libc::EALREADY, + EINPROGRESS = libc::EINPROGRESS, + ESTALE = libc::ESTALE, + EUCLEAN = libc::EUCLEAN, + ENOTNAM = libc::ENOTNAM, + ENAVAIL = libc::ENAVAIL, + EISNAM = libc::EISNAM, + EREMOTEIO = libc::EREMOTEIO, + EDQUOT = libc::EDQUOT, + ENOMEDIUM = libc::ENOMEDIUM, + EMEDIUMTYPE = libc::EMEDIUMTYPE, + ECANCELED = libc::ECANCELED, + ENOKEY = libc::ENOKEY, + EKEYEXPIRED = libc::EKEYEXPIRED, + EKEYREVOKED = libc::EKEYREVOKED, + EKEYREJECTED = libc::EKEYREJECTED, + EOWNERDEAD = libc::EOWNERDEAD, ENOTRECOVERABLE = libc::ENOTRECOVERABLE, - #[cfg(not(any(target_os = "android", target_arch="mips")))] - ERFKILL = libc::ERFKILL, - #[cfg(not(any(target_os = "android", target_arch="mips")))] - EHWPOISON = libc::EHWPOISON, + #[cfg(not(any(target_os = "android", target_arch = "mips")))] + ERFKILL = libc::ERFKILL, + #[cfg(not(any(target_os = "android", target_arch = "mips")))] + EHWPOISON = libc::EHWPOISON, } pub const EWOULDBLOCK: Errno = Errno::EAGAIN; - pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EDEADLOCK: Errno = Errno::EDEADLK; pub fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -808,11 +998,11 @@ mod consts { libc::EKEYREJECTED => EKEYREJECTED, libc::EOWNERDEAD => EOWNERDEAD, libc::ENOTRECOVERABLE => ENOTRECOVERABLE, - #[cfg(not(any(target_os = "android", target_arch="mips")))] + #[cfg(not(any(target_os = "android", target_arch = "mips")))] libc::ERFKILL => ERFKILL, - #[cfg(not(any(target_os = "android", target_arch="mips")))] + #[cfg(not(any(target_os = "android", target_arch = "mips")))] libc::EHWPOISON => EHWPOISON, - _ => UnknownErrno, + _ => UnknownErrno, } } } @@ -824,118 +1014,118 @@ mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - ENOTSUP = libc::ENOTSUP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EPWROFF = libc::EPWROFF, - EDEVERR = libc::EDEVERR, - EOVERFLOW = libc::EOVERFLOW, - EBADEXEC = libc::EBADEXEC, - EBADARCH = libc::EBADARCH, - ESHLIBVERS = libc::ESHLIBVERS, - EBADMACHO = libc::EBADMACHO, - ECANCELED = libc::ECANCELED, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - EILSEQ = libc::EILSEQ, - ENOATTR = libc::ENOATTR, - EBADMSG = libc::EBADMSG, - EMULTIHOP = libc::EMULTIHOP, - ENODATA = libc::ENODATA, - ENOLINK = libc::ENOLINK, - ENOSR = libc::ENOSR, - ENOSTR = libc::ENOSTR, - EPROTO = libc::EPROTO, - ETIME = libc::ETIME, - EOPNOTSUPP = libc::EOPNOTSUPP, - ENOPOLICY = libc::ENOPOLICY, + ENOTSUP = libc::ENOTSUP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EPWROFF = libc::EPWROFF, + EDEVERR = libc::EDEVERR, + EOVERFLOW = libc::EOVERFLOW, + EBADEXEC = libc::EBADEXEC, + EBADARCH = libc::EBADARCH, + ESHLIBVERS = libc::ESHLIBVERS, + EBADMACHO = libc::EBADMACHO, + ECANCELED = libc::ECANCELED, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EILSEQ = libc::EILSEQ, + ENOATTR = libc::ENOATTR, + EBADMSG = libc::EBADMSG, + EMULTIHOP = libc::EMULTIHOP, + ENODATA = libc::ENODATA, + ENOLINK = libc::ENOLINK, + ENOSR = libc::ENOSR, + ENOSTR = libc::ENOSTR, + EPROTO = libc::EPROTO, + ETIME = libc::ETIME, + EOPNOTSUPP = libc::EOPNOTSUPP, + ENOPOLICY = libc::ENOPOLICY, ENOTRECOVERABLE = libc::ENOTRECOVERABLE, - EOWNERDEAD = libc::EOWNERDEAD, - EQFULL = libc::EQFULL, + EOWNERDEAD = libc::EOWNERDEAD, + EQFULL = libc::EQFULL, } - pub const ELAST: Errno = Errno::EQFULL; + pub const ELAST: Errno = Errno::EQFULL; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; - pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EDEADLOCK: Errno = Errno::EDEADLK; pub const EL2NSYNC: Errno = Errno::UnknownErrno; @@ -1049,7 +1239,7 @@ mod consts { libc::ENOTRECOVERABLE => ENOTRECOVERABLE, libc::EOWNERDEAD => EOWNERDEAD, libc::EQFULL => EQFULL, - _ => UnknownErrno, + _ => UnknownErrno, } } } @@ -1061,108 +1251,108 @@ mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - ENOTSUP = libc::ENOTSUP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - EOVERFLOW = libc::EOVERFLOW, - ECANCELED = libc::ECANCELED, - EILSEQ = libc::EILSEQ, - ENOATTR = libc::ENOATTR, - EDOOFUS = libc::EDOOFUS, - EBADMSG = libc::EBADMSG, - EMULTIHOP = libc::EMULTIHOP, - ENOLINK = libc::ENOLINK, - EPROTO = libc::EPROTO, - ENOTCAPABLE = libc::ENOTCAPABLE, - ECAPMODE = libc::ECAPMODE, + ENOTSUP = libc::ENOTSUP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EOVERFLOW = libc::EOVERFLOW, + ECANCELED = libc::ECANCELED, + EILSEQ = libc::EILSEQ, + ENOATTR = libc::ENOATTR, + EDOOFUS = libc::EDOOFUS, + EBADMSG = libc::EBADMSG, + EMULTIHOP = libc::EMULTIHOP, + ENOLINK = libc::ENOLINK, + EPROTO = libc::EPROTO, + ENOTCAPABLE = libc::ENOTCAPABLE, + ECAPMODE = libc::ECAPMODE, ENOTRECOVERABLE = libc::ENOTRECOVERABLE, - EOWNERDEAD = libc::EOWNERDEAD, + EOWNERDEAD = libc::EOWNERDEAD, } - pub const ELAST: Errno = Errno::EOWNERDEAD; + pub const ELAST: Errno = Errno::EOWNERDEAD; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; - pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EDEADLOCK: Errno = Errno::EDEADLK; pub const EL2NSYNC: Errno = Errno::UnknownErrno; @@ -1266,12 +1456,11 @@ mod consts { libc::ECAPMODE => ECAPMODE, libc::ENOTRECOVERABLE => ENOTRECOVERABLE, libc::EOWNERDEAD => EOWNERDEAD, - _ => UnknownErrno, + _ => UnknownErrno, } } } - #[cfg(target_os = "dragonfly")] mod consts { use libc; @@ -1279,112 +1468,112 @@ mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - ENOTSUP = libc::ENOTSUP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - EOVERFLOW = libc::EOVERFLOW, - ECANCELED = libc::ECANCELED, - EILSEQ = libc::EILSEQ, - ENOATTR = libc::ENOATTR, - EDOOFUS = libc::EDOOFUS, - EBADMSG = libc::EBADMSG, - EMULTIHOP = libc::EMULTIHOP, - ENOLINK = libc::ENOLINK, - EPROTO = libc::EPROTO, - ENOMEDIUM = libc::ENOMEDIUM, - EUNUSED94 = libc::EUNUSED94, - EUNUSED95 = libc::EUNUSED95, - EUNUSED96 = libc::EUNUSED96, - EUNUSED97 = libc::EUNUSED97, - EUNUSED98 = libc::EUNUSED98, - EASYNC = libc::EASYNC, + ENOTSUP = libc::ENOTSUP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EOVERFLOW = libc::EOVERFLOW, + ECANCELED = libc::ECANCELED, + EILSEQ = libc::EILSEQ, + ENOATTR = libc::ENOATTR, + EDOOFUS = libc::EDOOFUS, + EBADMSG = libc::EBADMSG, + EMULTIHOP = libc::EMULTIHOP, + ENOLINK = libc::ENOLINK, + EPROTO = libc::EPROTO, + ENOMEDIUM = libc::ENOMEDIUM, + EUNUSED94 = libc::EUNUSED94, + EUNUSED95 = libc::EUNUSED95, + EUNUSED96 = libc::EUNUSED96, + EUNUSED97 = libc::EUNUSED97, + EUNUSED98 = libc::EUNUSED98, + EASYNC = libc::EASYNC, } - pub const ELAST: Errno = Errno::EASYNC; + pub const ELAST: Errno = Errno::EASYNC; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; - pub const EDEADLOCK: Errno = Errno::EDEADLK; - pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; + pub const EDEADLOCK: Errno = Errno::EDEADLK; + pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; pub const EL2NSYNC: Errno = Errno::UnknownErrno; @@ -1412,7 +1601,7 @@ mod consts { libc::EXDEV => EXDEV, libc::ENODEV => ENODEV, libc::ENOTDIR => ENOTDIR, - libc::EISDIR=> EISDIR, + libc::EISDIR => EISDIR, libc::EINVAL => EINVAL, libc::ENFILE => ENFILE, libc::EMFILE => EMFILE, @@ -1491,12 +1680,11 @@ mod consts { libc::EUNUSED97 => EUNUSED97, libc::EUNUSED98 => EUNUSED98, libc::EASYNC => EASYNC, - _ => UnknownErrno, + _ => UnknownErrno, } } } - #[cfg(target_os = "openbsd")] mod consts { use libc; @@ -1504,101 +1692,101 @@ mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - EOPNOTSUPP = libc::EOPNOTSUPP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EIPSEC = libc::EIPSEC, - ENOATTR = libc::ENOATTR, - EILSEQ = libc::EILSEQ, - ENOMEDIUM = libc::ENOMEDIUM, - EMEDIUMTYPE = libc::EMEDIUMTYPE, - EOVERFLOW = libc::EOVERFLOW, - ECANCELED = libc::ECANCELED, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - ENOTSUP = libc::ENOTSUP, + EOPNOTSUPP = libc::EOPNOTSUPP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EIPSEC = libc::EIPSEC, + ENOATTR = libc::ENOATTR, + EILSEQ = libc::EILSEQ, + ENOMEDIUM = libc::ENOMEDIUM, + EMEDIUMTYPE = libc::EMEDIUMTYPE, + EOVERFLOW = libc::EOVERFLOW, + ECANCELED = libc::ECANCELED, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + ENOTSUP = libc::ENOTSUP, } - pub const ELAST: Errno = Errno::ENOTSUP; + pub const ELAST: Errno = Errno::ENOTSUP; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; pub const EL2NSYNC: Errno = Errno::UnknownErrno; @@ -1698,7 +1886,7 @@ mod consts { libc::EIDRM => EIDRM, libc::ENOMSG => ENOMSG, libc::ENOTSUP => ENOTSUP, - _ => UnknownErrno, + _ => UnknownErrno, } } } @@ -1710,106 +1898,106 @@ mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] pub enum Errno { - UnknownErrno = 0, - EPERM = libc::EPERM, - ENOENT = libc::ENOENT, - ESRCH = libc::ESRCH, - EINTR = libc::EINTR, - EIO = libc::EIO, - ENXIO = libc::ENXIO, - E2BIG = libc::E2BIG, - ENOEXEC = libc::ENOEXEC, - EBADF = libc::EBADF, - ECHILD = libc::ECHILD, - EDEADLK = libc::EDEADLK, - ENOMEM = libc::ENOMEM, - EACCES = libc::EACCES, - EFAULT = libc::EFAULT, - ENOTBLK = libc::ENOTBLK, - EBUSY = libc::EBUSY, - EEXIST = libc::EEXIST, - EXDEV = libc::EXDEV, - ENODEV = libc::ENODEV, - ENOTDIR = libc::ENOTDIR, - EISDIR = libc::EISDIR, - EINVAL = libc::EINVAL, - ENFILE = libc::ENFILE, - EMFILE = libc::EMFILE, - ENOTTY = libc::ENOTTY, - ETXTBSY = libc::ETXTBSY, - EFBIG = libc::EFBIG, - ENOSPC = libc::ENOSPC, - ESPIPE = libc::ESPIPE, - EROFS = libc::EROFS, - EMLINK = libc::EMLINK, - EPIPE = libc::EPIPE, - EDOM = libc::EDOM, - ERANGE = libc::ERANGE, - EAGAIN = libc::EAGAIN, - EINPROGRESS = libc::EINPROGRESS, - EALREADY = libc::EALREADY, - ENOTSOCK = libc::ENOTSOCK, - EDESTADDRREQ = libc::EDESTADDRREQ, - EMSGSIZE = libc::EMSGSIZE, - EPROTOTYPE = libc::EPROTOTYPE, - ENOPROTOOPT = libc::ENOPROTOOPT, + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + ENFILE = libc::ENFILE, + EMFILE = libc::EMFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EDESTADDRREQ = libc::EDESTADDRREQ, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, EPROTONOSUPPORT = libc::EPROTONOSUPPORT, ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, - EOPNOTSUPP = libc::EOPNOTSUPP, - EPFNOSUPPORT = libc::EPFNOSUPPORT, - EAFNOSUPPORT = libc::EAFNOSUPPORT, - EADDRINUSE = libc::EADDRINUSE, - EADDRNOTAVAIL = libc::EADDRNOTAVAIL, - ENETDOWN = libc::ENETDOWN, - ENETUNREACH = libc::ENETUNREACH, - ENETRESET = libc::ENETRESET, - ECONNABORTED = libc::ECONNABORTED, - ECONNRESET = libc::ECONNRESET, - ENOBUFS = libc::ENOBUFS, - EISCONN = libc::EISCONN, - ENOTCONN = libc::ENOTCONN, - ESHUTDOWN = libc::ESHUTDOWN, - ETOOMANYREFS = libc::ETOOMANYREFS, - ETIMEDOUT = libc::ETIMEDOUT, - ECONNREFUSED = libc::ECONNREFUSED, - ELOOP = libc::ELOOP, - ENAMETOOLONG = libc::ENAMETOOLONG, - EHOSTDOWN = libc::EHOSTDOWN, - EHOSTUNREACH = libc::EHOSTUNREACH, - ENOTEMPTY = libc::ENOTEMPTY, - EPROCLIM = libc::EPROCLIM, - EUSERS = libc::EUSERS, - EDQUOT = libc::EDQUOT, - ESTALE = libc::ESTALE, - EREMOTE = libc::EREMOTE, - EBADRPC = libc::EBADRPC, - ERPCMISMATCH = libc::ERPCMISMATCH, - EPROGUNAVAIL = libc::EPROGUNAVAIL, - EPROGMISMATCH = libc::EPROGMISMATCH, - EPROCUNAVAIL = libc::EPROCUNAVAIL, - ENOLCK = libc::ENOLCK, - ENOSYS = libc::ENOSYS, - EFTYPE = libc::EFTYPE, - EAUTH = libc::EAUTH, - ENEEDAUTH = libc::ENEEDAUTH, - EIDRM = libc::EIDRM, - ENOMSG = libc::ENOMSG, - EOVERFLOW = libc::EOVERFLOW, - EILSEQ = libc::EILSEQ, - ENOTSUP = libc::ENOTSUP, - ECANCELED = libc::ECANCELED, - EBADMSG = libc::EBADMSG, - ENODATA = libc::ENODATA, - ENOSR = libc::ENOSR, - ENOSTR = libc::ENOSTR, - ETIME = libc::ETIME, - ENOATTR = libc::ENOATTR, - EMULTIHOP = libc::EMULTIHOP, - ENOLINK = libc::ENOLINK, - EPROTO = libc::EPROTO, + EOPNOTSUPP = libc::EOPNOTSUPP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + ENOSYS = libc::ENOSYS, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + EIDRM = libc::EIDRM, + ENOMSG = libc::ENOMSG, + EOVERFLOW = libc::EOVERFLOW, + EILSEQ = libc::EILSEQ, + ENOTSUP = libc::ENOTSUP, + ECANCELED = libc::ECANCELED, + EBADMSG = libc::EBADMSG, + ENODATA = libc::ENODATA, + ENOSR = libc::ENOSR, + ENOSTR = libc::ENOSTR, + ETIME = libc::ETIME, + ENOATTR = libc::ENOATTR, + EMULTIHOP = libc::EMULTIHOP, + ENOLINK = libc::ENOLINK, + EPROTO = libc::EPROTO, } - pub const ELAST: Errno = Errno::ENOTSUP; + pub const ELAST: Errno = Errno::ENOTSUP; pub const EWOULDBLOCK: Errno = Errno::EAGAIN; pub const EL2NSYNC: Errno = Errno::UnknownErrno; @@ -1914,7 +2102,7 @@ mod consts { libc::EMULTIHOP => EMULTIHOP, libc::ENOLINK => ENOLINK, libc::EPROTO => EPROTO, - _ => UnknownErrno, + _ => UnknownErrno, } } } diff --git a/src/fcntl.rs b/src/fcntl.rs index 58de3b3119..5dab2d90f2 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -1,13 +1,13 @@ -use {Error, Result, NixPath}; use errno::Errno; -use libc::{self, c_int, c_uint, c_char, size_t, ssize_t}; -use sys::stat::Mode; -use std::os::unix::io::RawFd; +use libc::{self, c_char, c_int, c_uint, size_t, ssize_t}; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; +use std::os::unix::io::RawFd; +use sys::stat::Mode; +use {Error, NixPath, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] -use sys::uio::IoVec; // For vmsplice +use sys::uio::IoVec; // For vmsplice libc_bitflags!{ pub struct AtFlags: c_int { @@ -138,21 +138,26 @@ libc_bitflags!( ); pub fn open(path: &P, oflag: OFlag, mode: Mode) -> Result { - let fd = try!(path.with_nix_path(|cstr| { - unsafe { libc::open(cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) } + let fd = try!(path.with_nix_path(|cstr| unsafe { + libc::open(cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) })); Errno::result(fd) } -pub fn openat(dirfd: RawFd, path: &P, oflag: OFlag, mode: Mode) -> Result { - let fd = try!(path.with_nix_path(|cstr| { - unsafe { libc::openat(dirfd, cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) } +pub fn openat( + dirfd: RawFd, + path: &P, + oflag: OFlag, + mode: Mode, +) -> Result { + let fd = try!(path.with_nix_path(|cstr| unsafe { + libc::openat(dirfd, cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) })); Errno::result(fd) } -fn wrap_readlink_result(buffer: &mut[u8], res: ssize_t) -> Result<&OsStr> { +fn wrap_readlink_result(buffer: &mut [u8], res: ssize_t) -> Result<&OsStr> { match Errno::result(res) { Err(err) => Err(err), Ok(len) => { @@ -166,17 +171,29 @@ fn wrap_readlink_result(buffer: &mut[u8], res: ssize_t) -> Result<&OsStr> { } pub fn readlink<'a, P: ?Sized + NixPath>(path: &P, buffer: &'a mut [u8]) -> Result<&'a OsStr> { - let res = try!(path.with_nix_path(|cstr| { - unsafe { libc::readlink(cstr.as_ptr(), buffer.as_mut_ptr() as *mut c_char, buffer.len() as size_t) } + let res = try!(path.with_nix_path(|cstr| unsafe { + libc::readlink( + cstr.as_ptr(), + buffer.as_mut_ptr() as *mut c_char, + buffer.len() as size_t, + ) })); wrap_readlink_result(buffer, res) } - -pub fn readlinkat<'a, P: ?Sized + NixPath>(dirfd: RawFd, path: &P, buffer: &'a mut [u8]) -> Result<&'a OsStr> { - let res = try!(path.with_nix_path(|cstr| { - unsafe { libc::readlinkat(dirfd, cstr.as_ptr(), buffer.as_mut_ptr() as *mut c_char, buffer.len() as size_t) } +pub fn readlinkat<'a, P: ?Sized + NixPath>( + dirfd: RawFd, + path: &P, + buffer: &'a mut [u8], +) -> Result<&'a OsStr> { + let res = try!(path.with_nix_path(|cstr| unsafe { + libc::readlinkat( + dirfd, + cstr.as_ptr(), + buffer.as_mut_ptr() as *mut c_char, + buffer.len() as size_t, + ) })); wrap_readlink_result(buffer, res) @@ -232,7 +249,6 @@ pub enum FcntlArg<'a> { F_GETPIPE_SZ, #[cfg(any(target_os = "linux", target_os = "android"))] F_SETPIPE_SZ(c_int), - // TODO: Rest of flags } pub use self::FcntlArg::*; @@ -261,7 +277,7 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { #[cfg(any(target_os = "linux", target_os = "android"))] F_SETPIPE_SZ(size) => libc::fcntl(fd, libc::F_SETPIPE_SZ, size), #[cfg(any(target_os = "linux", target_os = "android"))] - _ => unimplemented!() + _ => unimplemented!(), } }; @@ -318,12 +334,21 @@ libc_bitflags! { } #[cfg(any(target_os = "linux", target_os = "android"))] -pub fn splice(fd_in: RawFd, off_in: Option<&mut libc::loff_t>, - fd_out: RawFd, off_out: Option<&mut libc::loff_t>, - len: usize, flags: SpliceFFlags) -> Result { +pub fn splice( + fd_in: RawFd, + off_in: Option<&mut libc::loff_t>, + fd_out: RawFd, + off_out: Option<&mut libc::loff_t>, + len: usize, + flags: SpliceFFlags, +) -> Result { use std::ptr; - let off_in = off_in.map(|offset| offset as *mut _).unwrap_or(ptr::null_mut()); - let off_out = off_out.map(|offset| offset as *mut _).unwrap_or(ptr::null_mut()); + let off_in = off_in + .map(|offset| offset as *mut _) + .unwrap_or(ptr::null_mut()); + let off_out = off_out + .map(|offset| offset as *mut _) + .unwrap_or(ptr::null_mut()); let ret = unsafe { libc::splice(fd_in, off_in, fd_out, off_out, len, flags.bits()) }; Errno::result(ret).map(|r| r as usize) @@ -338,7 +363,12 @@ pub fn tee(fd_in: RawFd, fd_out: RawFd, len: usize, flags: SpliceFFlags) -> Resu #[cfg(any(target_os = "linux", target_os = "android"))] pub fn vmsplice(fd: RawFd, iov: &[IoVec<&[u8]>], flags: SpliceFFlags) -> Result { let ret = unsafe { - libc::vmsplice(fd, iov.as_ptr() as *const libc::iovec, iov.len(), flags.bits()) + libc::vmsplice( + fd, + iov.as_ptr() as *const libc::iovec, + iov.len(), + flags.bits(), + ) }; Errno::result(ret).map(|r| r as usize) } @@ -379,7 +409,12 @@ libc_bitflags!( /// Allows the caller to directly manipulate the allocated disk space for the /// file referred to by fd. #[cfg(any(target_os = "linux"))] -pub fn fallocate(fd: RawFd, mode: FallocateFlags, offset: libc::off_t, len: libc::off_t) -> Result { +pub fn fallocate( + fd: RawFd, + mode: FallocateFlags, + offset: libc::off_t, + len: libc::off_t, +) -> Result { let res = unsafe { libc::fallocate(fd, mode.bits(), offset, len) }; Errno::result(res) } diff --git a/src/features.rs b/src/features.rs index 7797aa4641..253f74df81 100644 --- a/src/features.rs +++ b/src/features.rs @@ -11,10 +11,10 @@ mod os { // * accept4: 2.6.28 static VERS_UNKNOWN: usize = 1; - static VERS_2_6_18: usize = 2; - static VERS_2_6_27: usize = 3; - static VERS_2_6_28: usize = 4; - static VERS_3: usize = 5; + static VERS_2_6_18: usize = 2; + static VERS_2_6_27: usize = 3; + static VERS_2_6_28: usize = 4; + static VERS_3: usize = 5; #[inline] fn digit(dst: &mut usize, b: u8) { @@ -25,7 +25,7 @@ mod os { fn parse_kernel_version() -> usize { let u = uname(); - let mut curr: usize = 0; + let mut curr: usize = 0; let mut major: usize = 0; let mut minor: usize = 0; let mut patch: usize = 0; @@ -39,13 +39,11 @@ mod os { b'.' | b'-' => { curr += 1; } - b'0'...b'9' => { - match curr { - 0 => digit(&mut major, b), - 1 => digit(&mut minor, b), - _ => digit(&mut patch, b), - } - } + b'0'...b'9' => match curr { + 0 => digit(&mut major, b), + 1 => digit(&mut minor, b), + _ => digit(&mut patch, b), + }, _ => break, } } @@ -94,7 +92,16 @@ mod os { } } -#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "openbsd", target_os = "netbsd"))] +#[cfg( + any( + target_os = "macos", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "openbsd", + target_os = "netbsd" + ) +)] mod os { /// Check if the OS supports atomic close-on-exec for sockets pub fn socket_atomic_cloexec() -> bool { diff --git a/src/ifaddrs.rs b/src/ifaddrs.rs index 61d36ff4cd..a0a674eec3 100644 --- a/src/ifaddrs.rs +++ b/src/ifaddrs.rs @@ -10,9 +10,9 @@ use std::option::Option; use libc; -use {Result, Errno}; -use sys::socket::SockAddr; use net::if_::*; +use sys::socket::SockAddr; +use {Errno, Result}; /// Describes a single address for an interface as returned by `getifaddrs`. #[derive(Clone, Eq, Hash, PartialEq, Debug)] @@ -126,11 +126,9 @@ impl Iterator for InterfaceAddressIterator { /// ``` pub fn getifaddrs() -> Result { let mut addrs: *mut libc::ifaddrs = unsafe { mem::uninitialized() }; - Errno::result(unsafe { libc::getifaddrs(&mut addrs) }).map(|_| { - InterfaceAddressIterator { - base: addrs, - next: addrs, - } + Errno::result(unsafe { libc::getifaddrs(&mut addrs) }).map(|_| InterfaceAddressIterator { + base: addrs, + next: addrs, }) } diff --git a/src/lib.rs b/src/lib.rs index 44838b6243..859eccfa2e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,33 +26,40 @@ extern crate void; pub extern crate libc; // Private internal modules -#[macro_use] mod macros; +#[macro_use] +mod macros; // Public crates pub mod errno; +pub mod fcntl; #[deny(missing_docs)] pub mod features; -pub mod fcntl; #[deny(missing_docs)] -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] pub mod ifaddrs; -#[cfg(any(target_os = "android", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux"))] pub mod kmod; -#[cfg(any(target_os = "android", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux"))] pub mod mount; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "fushsia", - target_os = "linux", - target_os = "netbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "fushsia", + target_os = "linux", + target_os = "netbsd" + ) +)] pub mod mqueue; #[deny(missing_docs)] pub mod net; @@ -60,14 +67,12 @@ pub mod net; pub mod poll; #[deny(missing_docs)] pub mod pty; -#[cfg(any(target_os = "android", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux"))] pub mod sched; pub mod sys; // This can be implemented for other platforms as soon as libc // provides bindings for them. -#[cfg(all(target_os = "linux", - any(target_arch = "x86", target_arch = "x86_64")))] +#[cfg(all(target_os = "linux", any(target_arch = "x86", target_arch = "x86_64")))] pub mod ucontext; pub mod unistd; @@ -79,10 +84,10 @@ pub mod unistd; use libc::{c_char, PATH_MAX}; -use std::{error, fmt, ptr, result}; use std::ffi::{CStr, OsStr}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; +use std::{error, fmt, ptr, result}; use errno::Errno; @@ -109,7 +114,6 @@ pub enum Error { } impl Error { - /// Create a nix Error from a given errno pub fn from_errno(errno: Errno) -> Error { Error::Sys(errno) @@ -124,15 +128,18 @@ impl Error { pub fn invalid_argument() -> Error { Error::Sys(Errno::EINVAL) } - } impl From for Error { - fn from(errno: Errno) -> Error { Error::from_errno(errno) } + fn from(errno: Errno) -> Error { + Error::from_errno(errno) + } } impl From for Error { - fn from(_: std::string::FromUtf8Error) -> Error { Error::InvalidUtf8 } + fn from(_: std::string::FromUtf8Error) -> Error { + Error::InvalidUtf8 + } } impl error::Error for Error { @@ -161,7 +168,8 @@ pub trait NixPath { fn len(&self) -> usize; fn with_nix_path(&self, f: F) -> Result - where F: FnOnce(&CStr) -> T; + where + F: FnOnce(&CStr) -> T; } impl NixPath for str { @@ -170,9 +178,11 @@ impl NixPath for str { } fn with_nix_path(&self, f: F) -> Result - where F: FnOnce(&CStr) -> T { - OsStr::new(self).with_nix_path(f) - } + where + F: FnOnce(&CStr) -> T, + { + OsStr::new(self).with_nix_path(f) + } } impl NixPath for OsStr { @@ -181,9 +191,11 @@ impl NixPath for OsStr { } fn with_nix_path(&self, f: F) -> Result - where F: FnOnce(&CStr) -> T { - self.as_bytes().with_nix_path(f) - } + where + F: FnOnce(&CStr) -> T, + { + self.as_bytes().with_nix_path(f) + } } impl NixPath for CStr { @@ -192,7 +204,9 @@ impl NixPath for CStr { } fn with_nix_path(&self, f: F) -> Result - where F: FnOnce(&CStr) -> T { + where + F: FnOnce(&CStr) -> T, + { // Equivalence with the [u8] impl. if self.len() >= PATH_MAX as usize { return Err(Error::InvalidPath); @@ -208,7 +222,9 @@ impl NixPath for [u8] { } fn with_nix_path(&self, f: F) -> Result - where F: FnOnce(&CStr) -> T { + where + F: FnOnce(&CStr) -> T, + { let mut buf = [0u8; PATH_MAX as usize]; if self.len() >= PATH_MAX as usize { @@ -223,7 +239,6 @@ impl NixPath for [u8] { ptr::copy_nonoverlapping(self.as_ptr(), buf.as_mut_ptr(), self.len()); Ok(f(CStr::from_ptr(buf.as_ptr() as *const c_char))) } - } } } @@ -234,7 +249,10 @@ impl NixPath for Path { NixPath::len(self.as_os_str()) } - fn with_nix_path(&self, f: F) -> Result where F: FnOnce(&CStr) -> T { + fn with_nix_path(&self, f: F) -> Result + where + F: FnOnce(&CStr) -> T, + { self.as_os_str().with_nix_path(f) } } @@ -244,18 +262,24 @@ impl NixPath for PathBuf { NixPath::len(self.as_os_str()) } - fn with_nix_path(&self, f: F) -> Result where F: FnOnce(&CStr) -> T { + fn with_nix_path(&self, f: F) -> Result + where + F: FnOnce(&CStr) -> T, + { self.as_os_str().with_nix_path(f) } } /// Treats `None` as an empty string. -impl<'a, NP: ?Sized + NixPath> NixPath for Option<&'a NP> { +impl<'a, NP: ?Sized + NixPath> NixPath for Option<&'a NP> { fn len(&self) -> usize { self.map_or(0, NixPath::len) } - fn with_nix_path(&self, f: F) -> Result where F: FnOnce(&CStr) -> T { + fn with_nix_path(&self, f: F) -> Result + where + F: FnOnce(&CStr) -> T, + { if let Some(nix_path) = *self { nix_path.with_nix_path(f) } else { diff --git a/src/macros.rs b/src/macros.rs index 3d1b0e4b76..dd625a7fc8 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -260,5 +260,5 @@ macro_rules! libc_enum { macro_rules! offset_of { ($ty:ty, $field:ident) => { &(*(0 as *const $ty)).$field as *const _ as usize - } + }; } diff --git a/src/mount.rs b/src/mount.rs index 8fe995135c..9b88bca500 100644 --- a/src/mount.rs +++ b/src/mount.rs @@ -1,7 +1,7 @@ -use libc::{c_ulong, c_int}; -use libc; -use {Result, NixPath}; use errno::Errno; +use libc; +use libc::{c_int, c_ulong}; +use {NixPath, Result}; libc_bitflags!( pub struct MsFlags: c_ulong { @@ -55,46 +55,48 @@ libc_bitflags!( } ); -pub fn mount( - source: Option<&P1>, - target: &P2, - fstype: Option<&P3>, - flags: MsFlags, - data: Option<&P4>) -> Result<()> { +pub fn mount< + P1: ?Sized + NixPath, + P2: ?Sized + NixPath, + P3: ?Sized + NixPath, + P4: ?Sized + NixPath, +>( + source: Option<&P1>, + target: &P2, + fstype: Option<&P3>, + flags: MsFlags, + data: Option<&P4>, +) -> Result<()> { use libc; - let res = try!(try!(try!(try!( - source.with_nix_path(|source| { - target.with_nix_path(|target| { - fstype.with_nix_path(|fstype| { - data.with_nix_path(|data| { - unsafe { - libc::mount(source.as_ptr(), - target.as_ptr(), - fstype.as_ptr(), - flags.bits, - data.as_ptr() as *const libc::c_void) - } - }) + let res = try!(try!(try!(try!(source.with_nix_path(|source| { + target.with_nix_path(|target| { + fstype.with_nix_path(|fstype| { + data.with_nix_path(|data| unsafe { + libc::mount( + source.as_ptr(), + target.as_ptr(), + fstype.as_ptr(), + flags.bits, + data.as_ptr() as *const libc::c_void, + ) }) }) - }))))); + }) + }))))); Errno::result(res).map(drop) } pub fn umount(target: &P) -> Result<()> { - let res = try!(target.with_nix_path(|cstr| { - unsafe { libc::umount(cstr.as_ptr()) } - })); + let res = try!(target.with_nix_path(|cstr| unsafe { libc::umount(cstr.as_ptr()) })); Errno::result(res).map(drop) } pub fn umount2(target: &P, flags: MntFlags) -> Result<()> { - let res = try!(target.with_nix_path(|cstr| { - unsafe { libc::umount2(cstr.as_ptr(), flags.bits) } - })); + let res = + try!(target.with_nix_path(|cstr| unsafe { libc::umount2(cstr.as_ptr(), flags.bits) })); Errno::result(res).map(drop) } diff --git a/src/mqueue.rs b/src/mqueue.rs index 0c6990f663..5859621c83 100644 --- a/src/mqueue.rs +++ b/src/mqueue.rs @@ -2,13 +2,13 @@ //! //! [Further reading and details on the C API](http://man7.org/linux/man-pages/man7/mq_overview.7.html) -use Result; use errno::Errno; +use Result; use libc::{self, c_char, c_long, mqd_t, size_t}; use std::ffi::CString; -use sys::stat::Mode; use std::mem; +use sys::stat::Mode; libc_bitflags!{ pub struct MQ_OFlag: libc::c_int { @@ -39,18 +39,20 @@ impl PartialEq for MqAttr { fn eq(&self, other: &MqAttr) -> bool { let self_attr = self.mq_attr; let other_attr = other.mq_attr; - self_attr.mq_flags == other_attr.mq_flags && self_attr.mq_maxmsg == other_attr.mq_maxmsg && - self_attr.mq_msgsize == other_attr.mq_msgsize && - self_attr.mq_curmsgs == other_attr.mq_curmsgs + self_attr.mq_flags == other_attr.mq_flags + && self_attr.mq_maxmsg == other_attr.mq_maxmsg + && self_attr.mq_msgsize == other_attr.mq_msgsize + && self_attr.mq_curmsgs == other_attr.mq_curmsgs } } impl MqAttr { - pub fn new(mq_flags: c_long, - mq_maxmsg: c_long, - mq_msgsize: c_long, - mq_curmsgs: c_long) - -> MqAttr { + pub fn new( + mq_flags: c_long, + mq_maxmsg: c_long, + mq_msgsize: c_long, + mq_curmsgs: c_long, + ) -> MqAttr { let mut attr = unsafe { mem::uninitialized::() }; attr.mq_flags = mq_flags; attr.mq_maxmsg = mq_maxmsg; @@ -64,21 +66,23 @@ impl MqAttr { } } - /// Open a message queue /// /// See also [`mq_open(2)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_open.html) -pub fn mq_open(name: &CString, - oflag: MQ_OFlag, - mode: Mode, - attr: Option<&MqAttr>) - -> Result { +pub fn mq_open( + name: &CString, + oflag: MQ_OFlag, + mode: Mode, + attr: Option<&MqAttr>, +) -> Result { let res = match attr { Some(mq_attr) => unsafe { - libc::mq_open(name.as_ptr(), - oflag.bits(), - mode.bits() as libc::c_int, - &mq_attr.mq_attr as *const libc::mq_attr) + libc::mq_open( + name.as_ptr(), + oflag.bits(), + mode.bits() as libc::c_int, + &mq_attr.mq_attr as *const libc::mq_attr, + ) }, None => unsafe { libc::mq_open(name.as_ptr(), oflag.bits()) }, }; @@ -107,10 +111,12 @@ pub fn mq_close(mqdes: mqd_t) -> Result<()> { pub fn mq_receive(mqdes: mqd_t, message: &mut [u8], msg_prio: &mut u32) -> Result { let len = message.len() as size_t; let res = unsafe { - libc::mq_receive(mqdes, - message.as_mut_ptr() as *mut c_char, - len, - msg_prio as *mut u32) + libc::mq_receive( + mqdes, + message.as_mut_ptr() as *mut c_char, + len, + msg_prio as *mut u32, + ) }; Errno::result(res).map(|r| r as usize) } @@ -120,10 +126,12 @@ pub fn mq_receive(mqdes: mqd_t, message: &mut [u8], msg_prio: &mut u32) -> Resul /// See also [`mq_send(2)`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html) pub fn mq_send(mqdes: mqd_t, message: &[u8], msq_prio: u32) -> Result<()> { let res = unsafe { - libc::mq_send(mqdes, - message.as_ptr() as *const c_char, - message.len(), - msq_prio) + libc::mq_send( + mqdes, + message.as_ptr() as *const c_char, + message.len(), + msq_prio, + ) }; Errno::result(res).map(drop) } @@ -153,10 +161,12 @@ pub fn mq_setattr(mqd: mqd_t, newattr: &MqAttr) -> Result { /// Returns the old attributes pub fn mq_set_nonblock(mqd: mqd_t) -> Result<(MqAttr)> { let oldattr = try!(mq_getattr(mqd)); - let newattr = MqAttr::new(MQ_OFlag::O_NONBLOCK.bits() as c_long, - oldattr.mq_attr.mq_maxmsg, - oldattr.mq_attr.mq_msgsize, - oldattr.mq_attr.mq_curmsgs); + let newattr = MqAttr::new( + MQ_OFlag::O_NONBLOCK.bits() as c_long, + oldattr.mq_attr.mq_maxmsg, + oldattr.mq_attr.mq_msgsize, + oldattr.mq_attr.mq_curmsgs, + ); mq_setattr(mqd, &newattr) } @@ -165,9 +175,11 @@ pub fn mq_set_nonblock(mqd: mqd_t) -> Result<(MqAttr)> { /// Returns the old attributes pub fn mq_remove_nonblock(mqd: mqd_t) -> Result<(MqAttr)> { let oldattr = try!(mq_getattr(mqd)); - let newattr = MqAttr::new(0, - oldattr.mq_attr.mq_maxmsg, - oldattr.mq_attr.mq_msgsize, - oldattr.mq_attr.mq_curmsgs); + let newattr = MqAttr::new( + 0, + oldattr.mq_attr.mq_maxmsg, + oldattr.mq_attr.mq_msgsize, + oldattr.mq_attr.mq_curmsgs, + ); mq_setattr(mqd, &newattr) } diff --git a/src/net/if_.rs b/src/net/if_.rs index 714eac7750..2455ba651f 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -5,7 +5,7 @@ use libc; use libc::c_uint; -use {Result, Error, NixPath}; +use {Error, NixPath, Result}; /// Resolve an interface into a interface number. pub fn if_nametoindex(name: &P) -> Result { diff --git a/src/poll.rs b/src/poll.rs index eb6b241784..b1839825b3 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -1,14 +1,18 @@ //! Wait for events to trigger on specific file descriptors -#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] -use sys::time::TimeSpec; -#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] -use sys::signal::SigSet; -use std::os::unix::io::RawFd; use std::fmt; +use std::os::unix::io::RawFd; +#[cfg( + any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux") +)] +use sys::signal::SigSet; +#[cfg( + any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux") +)] +use sys::time::TimeSpec; +use errno::Errno; use libc; use Result; -use errno::Errno; /// This is a wrapper around `libc::pollfd`. /// @@ -132,9 +136,11 @@ libc_bitflags! { /// ready. pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result { let res = unsafe { - libc::poll(fds.as_mut_ptr() as *mut libc::pollfd, - fds.len() as libc::nfds_t, - timeout) + libc::poll( + fds.as_mut_ptr() as *mut libc::pollfd, + fds.len() as libc::nfds_t, + timeout, + ) }; Errno::result(res) @@ -147,15 +153,17 @@ pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result { /// `ppoll` behaves like `poll`, but let you specify what signals may interrupt it /// with the `sigmask` argument. /// -#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] +#[cfg( + any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux") +)] pub fn ppoll(fds: &mut [PollFd], timeout: TimeSpec, sigmask: SigSet) -> Result { - - let res = unsafe { - libc::ppoll(fds.as_mut_ptr() as *mut libc::pollfd, - fds.len() as libc::nfds_t, - timeout.as_ref(), - sigmask.as_ref()) + libc::ppoll( + fds.as_mut_ptr() as *mut libc::pollfd, + fds.len() as libc::nfds_t, + timeout.as_ref(), + sigmask.as_ref(), + ) }; Errno::result(res) } diff --git a/src/pty.rs b/src/pty.rs index b71718850e..b5430a12ca 100644 --- a/src/pty.rs +++ b/src/pty.rs @@ -9,9 +9,9 @@ use std::ffi::CStr; use std::mem; use std::os::unix::prelude::*; -use sys::termios::Termios; -use {Result, Error, fcntl}; use errno::Errno; +use sys::termios::Termios; +use {fcntl, Error, Result}; /// Representation of a master/slave pty pair /// @@ -26,7 +26,6 @@ pub struct OpenptyResult { pub slave: RawFd, } - /// Representation of the Master device in a master/slave pty pair /// /// While this datatype is a thin wrapper around `RawFd`, it enforces that the available PTY @@ -114,9 +113,7 @@ pub fn grantpt(fd: &PtyMaster) -> Result<()> { /// ``` #[inline] pub fn posix_openpt(flags: fcntl::OFlag) -> Result { - let fd = unsafe { - libc::posix_openpt(flags.bits()) - }; + let fd = unsafe { libc::posix_openpt(flags.bits()) }; if fd < 0 { return Err(Error::last()); @@ -194,7 +191,6 @@ pub fn unlockpt(fd: &PtyMaster) -> Result<()> { Ok(()) } - /// Create a new pseudoterminal, returning the slave and master file descriptors /// in `OpenptyResult` /// (see [`openpty`](http://man7.org/linux/man-pages/man3/openpty.3.html)). @@ -203,7 +199,10 @@ pub fn unlockpt(fd: &PtyMaster) -> Result<()> { /// the values in `winsize`. If `termios` is not `None`, the pseudoterminal's /// terminal settings of the slave will be set to the values in `termios`. #[inline] -pub fn openpty<'a, 'b, T: Into>, U: Into>>(winsize: T, termios: U) -> Result { +pub fn openpty<'a, 'b, T: Into>, U: Into>>( + winsize: T, + termios: U, +) -> Result { use std::ptr; let mut slave: libc::c_int = unsafe { mem::uninitialized() }; @@ -222,17 +221,15 @@ pub fn openpty<'a, 'b, T: Into>, U: Into ) } } - (None, Some(winsize)) => { - unsafe { - libc::openpty( - &mut master, - &mut slave, - ptr::null_mut(), - ptr::null_mut(), - winsize as *const Winsize as *mut _, - ) - } - } + (None, Some(winsize)) => unsafe { + libc::openpty( + &mut master, + &mut slave, + ptr::null_mut(), + ptr::null_mut(), + winsize as *const Winsize as *mut _, + ) + }, (Some(termios), None) => { let inner_termios = termios.get_libc_termios(); unsafe { @@ -245,17 +242,15 @@ pub fn openpty<'a, 'b, T: Into>, U: Into ) } } - (None, None) => { - unsafe { - libc::openpty( - &mut master, - &mut slave, - ptr::null_mut(), - ptr::null_mut(), - ptr::null_mut(), - ) - } - } + (None, None) => unsafe { + libc::openpty( + &mut master, + &mut slave, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ) + }, } }; diff --git a/src/sched.rs b/src/sched.rs index f8f3a68aa1..6b787c238b 100644 --- a/src/sched.rs +++ b/src/sched.rs @@ -1,10 +1,10 @@ +use errno::Errno; +use libc::{self, c_int, c_void}; use std::mem; -use std::os::unix::io::RawFd; use std::option::Option; -use libc::{self, c_int, c_void}; +use std::os::unix::io::RawFd; +use unistd::Pid; use {Error, Result}; -use errno::Errno; -use ::unistd::Pid; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. @@ -47,7 +47,9 @@ pub struct CpuSet { impl CpuSet { pub fn new() -> CpuSet { - CpuSet { cpu_set: unsafe { mem::zeroed() } } + CpuSet { + cpu_set: unsafe { mem::zeroed() }, + } } pub fn is_set(&self, field: usize) -> Result { @@ -77,19 +79,22 @@ impl CpuSet { pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> { let res = unsafe { - libc::sched_setaffinity(pid.into(), - mem::size_of::() as libc::size_t, - &cpuset.cpu_set) + libc::sched_setaffinity( + pid.into(), + mem::size_of::() as libc::size_t, + &cpuset.cpu_set, + ) }; Errno::result(res).map(drop) } -pub fn clone(mut cb: CloneCb, - stack: &mut [u8], - flags: CloneFlags, - signal: Option) - -> Result { +pub fn clone( + mut cb: CloneCb, + stack: &mut [u8], + flags: CloneFlags, + signal: Option, +) -> Result { extern "C" fn callback(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int @@ -99,10 +104,14 @@ pub fn clone(mut cb: CloneCb, let combined = flags.bits() | signal.unwrap_or(0); let ptr = stack.as_mut_ptr().offset(stack.len() as isize); let ptr_aligned = ptr.offset((ptr as usize % 16) as isize * -1); - libc::clone(mem::transmute(callback as extern "C" fn(*mut Box<::std::ops::FnMut() -> isize>) -> i32), - ptr_aligned as *mut c_void, - combined, - &mut cb as *mut _ as *mut c_void) + libc::clone( + mem::transmute( + callback as extern "C" fn(*mut Box<::std::ops::FnMut() -> isize>) -> i32, + ), + ptr_aligned as *mut c_void, + combined, + &mut cb as *mut _ as *mut c_void, + ) }; Errno::result(res).map(Pid::from_raw) diff --git a/src/sys/aio.rs b/src/sys/aio.rs index 3d53982134..2b1e254fe9 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -21,20 +21,20 @@ //! [`aio_cancel_all`](fn.aio_cancel_all.html), though the operating system may //! not support this for all filesystems and devices. -use {Error, Result}; use errno::Errno; -use std::os::unix::io::RawFd; -use libc::{c_void, off_t, size_t}; use libc; +use libc::{c_void, off_t, size_t}; use std::borrow::{Borrow, BorrowMut}; use std::fmt; use std::fmt::Debug; use std::marker::PhantomData; use std::mem; +use std::os::unix::io::RawFd; use std::ptr::{null, null_mut}; -use sys::signal::*; use std::thread; +use sys::signal::*; use sys::time::TimeSpec; +use {Error, Result}; libc_enum! { /// Mode for `AioCb::fsync`. Controls whether only data or both data and @@ -116,14 +116,16 @@ impl<'a> Debug for Buffer<'a> { Buffer::None => write!(fmt, "None"), Buffer::Phantom(p) => p.fmt(fmt), Buffer::BoxedSlice(ref bs) => { - let borrowed : &Borrow<[u8]> = bs.borrow(); - write!(fmt, "BoxedSlice({:?})", - borrowed as *const Borrow<[u8]>) - }, + let borrowed: &Borrow<[u8]> = bs.borrow(); + write!(fmt, "BoxedSlice({:?})", borrowed as *const Borrow<[u8]>) + } Buffer::BoxedMutSlice(ref bms) => { - let borrowed : &BorrowMut<[u8]> = bms.borrow(); - write!(fmt, "BoxedMutSlice({:?})", - borrowed as *const BorrowMut<[u8]>) + let borrowed: &BorrowMut<[u8]> = bms.borrow(); + write!( + fmt, + "BoxedMutSlice({:?})", + borrowed as *const BorrowMut<[u8]> + ) } } } @@ -143,7 +145,7 @@ pub struct AioCb<'a> { /// /// Used to keep buffers from `Drop`'ing, and may be returned once the /// `AioCb` is completed by [`buffer`](#method.buffer). - buffer: Buffer<'a> + buffer: Buffer<'a>, } impl<'a> AioCb<'a> { @@ -245,8 +247,7 @@ impl<'a> AioCb<'a> { /// aiocb.aio_return().expect("aio_fsync failed late"); /// # } /// ``` - pub fn from_fd(fd: RawFd, prio: libc::c_int, - sigev_notify: SigevNotify) -> AioCb<'a> { + pub fn from_fd(fd: RawFd, prio: libc::c_int, sigev_notify: SigevNotify) -> AioCb<'a> { let mut a = AioCb::common_init(fd, prio, sigev_notify); a.aio_offset = 0; a.aio_nbytes = 0; @@ -256,7 +257,7 @@ impl<'a> AioCb<'a> { aiocb: a, mutable: false, in_progress: false, - buffer: Buffer::None + buffer: Buffer::None, } } @@ -319,9 +320,14 @@ impl<'a> AioCb<'a> { /// 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, - opcode: LioOpcode) -> AioCb<'a> { + pub fn from_mut_slice( + fd: RawFd, + offs: off_t, + buf: &'a mut [u8], + prio: libc::c_int, + sigev_notify: SigevNotify, + opcode: LioOpcode, + ) -> AioCb<'a> { let mut a = AioCb::common_init(fd, prio, sigev_notify); a.aio_offset = offs; a.aio_nbytes = buf.len() as size_t; @@ -448,13 +454,18 @@ impl<'a> AioCb<'a> { /// ``` /// /// [`from_slice`]: #method.from_slice - pub fn from_boxed_slice(fd: RawFd, offs: off_t, buf: Box>, - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> AioCb<'a> { + pub fn from_boxed_slice( + fd: RawFd, + offs: off_t, + buf: Box>, + prio: libc::c_int, + sigev_notify: SigevNotify, + opcode: LioOpcode, + ) -> AioCb<'a> { let mut a = AioCb::common_init(fd, prio, sigev_notify); { - let borrowed : &Borrow<[u8]> = buf.borrow(); - let slice : &[u8] = borrowed.borrow(); + let borrowed: &Borrow<[u8]> = buf.borrow(); + let slice: &[u8] = borrowed.borrow(); a.aio_nbytes = slice.len() as size_t; a.aio_buf = slice.as_ptr() as *mut c_void; } @@ -515,14 +526,18 @@ impl<'a> AioCb<'a> { /// /// [`from_boxed_slice`]: #method.from_boxed_slice /// [`from_mut_slice`]: #method.from_mut_slice - pub fn from_boxed_mut_slice(fd: RawFd, offs: off_t, - mut buf: Box>, - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> AioCb<'a> { + pub fn from_boxed_mut_slice( + fd: RawFd, + offs: off_t, + mut buf: Box>, + prio: libc::c_int, + sigev_notify: SigevNotify, + opcode: LioOpcode, + ) -> AioCb<'a> { let mut a = AioCb::common_init(fd, prio, sigev_notify); { - let borrowed : &mut BorrowMut<[u8]> = buf.borrow_mut(); - let slice : &mut [u8] = borrowed.borrow_mut(); + let borrowed: &mut BorrowMut<[u8]> = buf.borrow_mut(); + let slice: &mut [u8] = borrowed.borrow_mut(); a.aio_nbytes = slice.len() as size_t; a.aio_buf = slice.as_mut_ptr() as *mut c_void; } @@ -564,10 +579,15 @@ impl<'a> AioCb<'a> { /// /// The caller must ensure that the storage pointed to by `buf` outlives the /// `AioCb`. The lifetime checker can't help here. - pub unsafe fn from_mut_ptr(fd: RawFd, offs: off_t, - buf: *mut c_void, len: usize, - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> AioCb<'a> { + pub unsafe fn from_mut_ptr( + fd: RawFd, + offs: off_t, + buf: *mut c_void, + len: usize, + prio: libc::c_int, + sigev_notify: SigevNotify, + opcode: LioOpcode, + ) -> AioCb<'a> { let mut a = AioCb::common_init(fd, prio, sigev_notify); a.aio_offset = offs; a.aio_nbytes = len; @@ -578,7 +598,7 @@ impl<'a> AioCb<'a> { aiocb: a, mutable: true, in_progress: false, - buffer: Buffer::None + buffer: Buffer::None, } } @@ -609,10 +629,15 @@ impl<'a> AioCb<'a> { /// /// The caller must ensure that the storage pointed to by `buf` outlives the /// `AioCb`. The lifetime checker can't help here. - pub unsafe fn from_ptr(fd: RawFd, offs: off_t, - buf: *const c_void, len: usize, - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> AioCb<'a> { + pub unsafe fn from_ptr( + fd: RawFd, + offs: off_t, + buf: *const c_void, + len: usize, + prio: libc::c_int, + sigev_notify: SigevNotify, + opcode: LioOpcode, + ) -> AioCb<'a> { let mut a = AioCb::common_init(fd, prio, sigev_notify); a.aio_offset = offs; a.aio_nbytes = len; @@ -625,7 +650,7 @@ impl<'a> AioCb<'a> { aiocb: a, mutable: false, in_progress: false, - buffer: Buffer::None + buffer: Buffer::None, } } @@ -672,9 +697,14 @@ impl<'a> AioCb<'a> { // could take the former and AioCb::write could take the latter. However, // then lio_listio wouldn't work, because that function needs a slice of // AioCb, and they must all be of the same type. - pub fn from_slice(fd: RawFd, offs: off_t, buf: &'a [u8], - prio: libc::c_int, sigev_notify: SigevNotify, - opcode: LioOpcode) -> AioCb { + pub fn from_slice( + fd: RawFd, + offs: off_t, + buf: &'a [u8], + prio: libc::c_int, + sigev_notify: SigevNotify, + opcode: LioOpcode, + ) -> AioCb { let mut a = AioCb::common_init(fd, prio, sigev_notify); a.aio_offset = offs; a.aio_nbytes = buf.len() as size_t; @@ -682,7 +712,10 @@ impl<'a> AioCb<'a> { // but technically its only unsafe to dereference it, not to create // it. a.aio_buf = buf.as_ptr() as *mut c_void; - assert!(opcode != LioOpcode::LIO_READ, "Can't read into an immutable buffer"); + assert!( + opcode != LioOpcode::LIO_READ, + "Can't read into an immutable buffer" + ); a.aio_lio_opcode = opcode as libc::c_int; AioCb { @@ -693,13 +726,12 @@ impl<'a> AioCb<'a> { } } - fn common_init(fd: RawFd, prio: libc::c_int, - sigev_notify: SigevNotify) -> libc::aiocb { + fn common_init(fd: RawFd, prio: libc::c_int, sigev_notify: SigevNotify) -> libc::aiocb { // Use mem::zeroed instead of explicitly zeroing each field, because the // number and name of reserved fields is OS-dependent. On some OSes, // some reserved fields are used the kernel for state, and must be // explicitly zeroed when allocated. - let mut a = unsafe { mem::zeroed::()}; + let mut a = unsafe { mem::zeroed::() }; a.aio_fildes = fd; a.aio_reqprio = prio; a.aio_sigevent = SigEvent::new(sigev_notify).sigevent(); @@ -766,7 +798,7 @@ impl<'a> AioCb<'a> { libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled), libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone), -1 => Err(Error::last()), - _ => panic!("unknown aio_cancel return value") + _ => panic!("unknown aio_cancel return value"), } } @@ -815,7 +847,7 @@ impl<'a> AioCb<'a> { 0 => Ok(()), num if num > 0 => Err(Error::from_errno(Errno::from_i32(num))), -1 => Err(Error::last()), - num => panic!("unknown aio_error return value {:?}", num) + num => panic!("unknown aio_error return value {:?}", num), } } @@ -826,9 +858,7 @@ impl<'a> AioCb<'a> { /// [aio_fsync](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_fsync.html) pub fn fsync(&mut self, mode: AioFsyncMode) -> Result<()> { let p: *mut libc::aiocb = &mut self.aiocb; - Errno::result(unsafe { - libc::aio_fsync(mode as libc::c_int, p) - }).map(|_| { + Errno::result(unsafe { libc::aio_fsync(mode as libc::c_int, p) }).map(|_| { self.in_progress = true; }) } @@ -842,7 +872,7 @@ impl<'a> AioCb<'a> { libc::LIO_READ => Some(LioOpcode::LIO_READ), libc::LIO_WRITE => Some(LioOpcode::LIO_WRITE), libc::LIO_NOP => Some(LioOpcode::LIO_NOP), - _ => None + _ => None, } } @@ -873,9 +903,7 @@ impl<'a> AioCb<'a> { pub fn read(&mut self) -> Result<()> { assert!(self.mutable, "Can't read into an immutable buffer"); let p: *mut libc::aiocb = &mut self.aiocb; - Errno::result(unsafe { - libc::aio_read(p) - }).map(|_| { + Errno::result(unsafe { libc::aio_read(p) }).map(|_| { self.in_progress = true; }) } @@ -908,13 +936,10 @@ impl<'a> AioCb<'a> { /// [aio_write](http://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_write.html) pub fn write(&mut self) -> Result<()> { let p: *mut libc::aiocb = &mut self.aiocb; - Errno::result(unsafe { - libc::aio_write(p) - }).map(|_| { + Errno::result(unsafe { libc::aio_write(p) }).map(|_| { self.in_progress = true; }) } - } /// Cancels outstanding AIO requests for a given file descriptor. @@ -965,7 +990,7 @@ pub fn aio_cancel_all(fd: RawFd) -> Result { libc::AIO_NOTCANCELED => Ok(AioCancelStat::AioNotCanceled), libc::AIO_ALLDONE => Ok(AioCancelStat::AioAllDone), -1 => Err(Error::last()), - _ => panic!("unknown aio_cancel return value") + _ => panic!("unknown aio_cancel return value"), } } @@ -1010,12 +1035,10 @@ pub fn aio_suspend(list: &[&AioCb], timeout: Option) -> Result<()> { let plist = list as *const [&AioCb] as *const [*const libc::aiocb]; let p = plist as *const *const libc::aiocb; let timep = match timeout { - None => null::(), - Some(x) => x.as_ref() as *const libc::timespec + None => null::(), + Some(x) => x.as_ref() as *const libc::timespec, }; - Errno::result(unsafe { - libc::aio_suspend(p, list.len() as i32, timep) - }).map(drop) + Errno::result(unsafe { libc::aio_suspend(p, list.len() as i32, timep) }).map(drop) } impl<'a> Debug for AioCb<'a> { @@ -1038,8 +1061,10 @@ impl<'a> Drop for AioCb<'a> { /// If the `AioCb` has no remaining state in the kernel, just drop it. /// Otherwise, dropping constitutes a resource leak, which is an error fn drop(&mut self) { - assert!(thread::panicking() || !self.in_progress, - "Dropped an in-progress AioCb"); + assert!( + thread::panicking() || !self.in_progress, + "Dropped an in-progress AioCb" + ); } } @@ -1064,7 +1089,7 @@ pub struct LioCb<'a> { /// A partial set of results. This field will get populated by /// `listio_resubmit` when an `LioCb` is resubmitted after an error - results: Vec>> + results: Vec>>, } #[cfg(not(any(target_os = "ios", target_os = "macos")))] @@ -1074,7 +1099,7 @@ impl<'a> LioCb<'a> { LioCb { aiocbs: Vec::with_capacity(capacity), list: Vec::with_capacity(capacity), - results: Vec::with_capacity(capacity) + results: Vec::with_capacity(capacity), } } @@ -1125,20 +1150,17 @@ impl<'a> LioCb<'a> { /// /// [`aio_suspend`]: fn.aio_suspend.html /// [`AioCb::error`]: struct.AioCb.html#method.error - pub fn listio(&mut self, mode: LioMode, - sigev_notify: SigevNotify) -> Result<()> { + pub fn listio(&mut self, mode: LioMode, sigev_notify: SigevNotify) -> Result<()> { let sigev = SigEvent::new(sigev_notify); let sigevp = &mut sigev.sigevent() as *mut libc::sigevent; self.list.clear(); for a in &mut self.aiocbs { a.in_progress = true; - self.list.push(a as *mut AioCb<'a> - as *mut libc::aiocb); + self.list.push(a as *mut AioCb<'a> as *mut libc::aiocb); } let p = self.list.as_ptr(); - Errno::result(unsafe { - libc::lio_listio(mode as i32, p, self.list.len() as i32, sigevp) - }).map(|_| ()) + Errno::result(unsafe { libc::lio_listio(mode as i32, p, self.list.len() as i32, sigevp) }) + .map(|_| ()) } /// Resubmits any incomplete operations with [`lio_listio`]. @@ -1194,8 +1216,7 @@ impl<'a> LioCb<'a> { // being stable. // Note: aiocbs that are Ok(()) must be finalized by aio_return, or else the // sigev_notify will immediately refire. - pub fn listio_resubmit(&mut self, mode:LioMode, - sigev_notify: SigevNotify) -> Result<()> { + pub fn listio_resubmit(&mut self, mode: LioMode, sigev_notify: SigevNotify) -> Result<()> { let sigev = SigEvent::new(sigev_notify); let sigevp = &mut sigev.sigevent() as *mut libc::sigevent; self.list.clear(); @@ -1213,23 +1234,23 @@ impl<'a> LioCb<'a> { Ok(()) => { // aiocb is complete; collect its status and don't resubmit self.results[i] = Some(a.aio_return()); - }, + } Err(Error::Sys(Errno::EAGAIN)) => { self.list.push(a as *mut AioCb<'a> as *mut libc::aiocb); - }, + } Err(Error::Sys(Errno::EINPROGRESS)) => { // aiocb is was successfully queued; no need to do anything () - }, - Err(Error::Sys(Errno::EINVAL)) => panic!( - "AioCb was never submitted, or already finalized"), - _ => unreachable!() + } + Err(Error::Sys(Errno::EINVAL)) => { + panic!("AioCb was never submitted, or already finalized") + } + _ => unreachable!(), } } let p = self.list.as_ptr(); - Errno::result(unsafe { - libc::lio_listio(mode as i32, p, self.list.len() as i32, sigevp) - }).map(|_| ()) + Errno::result(unsafe { libc::lio_listio(mode as i32, p, self.list.len() as i32, sigevp) }) + .map(|_| ()) } /// Collect final status for an individual `AioCb` submitted as part of an diff --git a/src/sys/epoll.rs b/src/sys/epoll.rs index 3ed1dd7240..0ab6307d58 100644 --- a/src/sys/epoll.rs +++ b/src/sys/epoll.rs @@ -1,10 +1,10 @@ -use Result; use errno::Errno; use libc::{self, c_int}; +use std::mem; use std::os::unix::io::RawFd; use std::ptr; -use std::mem; -use ::Error; +use Error; +use Result; libc_bitflags!( pub struct EpollFlags: c_int { @@ -51,7 +51,12 @@ pub struct EpollEvent { impl EpollEvent { pub fn new(events: EpollFlags, data: u64) -> Self { - EpollEvent { event: libc::epoll_event { events: events.bits() as u32, u64: data } } + EpollEvent { + event: libc::epoll_event { + events: events.bits() as u32, + u64: data, + }, + } } pub fn empty() -> Self { @@ -83,7 +88,8 @@ pub fn epoll_create1(flags: EpollCreateFlags) -> Result { #[inline] pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result<()> - where T: Into> +where + T: Into>, { let mut event: Option<&mut EpollEvent> = event.into(); if event.is_none() && op != EpollOp::EpollCtlDel { @@ -103,7 +109,12 @@ pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result #[inline] pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result { let res = unsafe { - libc::epoll_wait(epfd, events.as_mut_ptr() as *mut libc::epoll_event, events.len() as c_int, timeout_ms as c_int) + libc::epoll_wait( + epfd, + events.as_mut_ptr() as *mut libc::epoll_event, + events.len() as c_int, + timeout_ms as c_int, + ) }; Errno::result(res).map(|r| r as usize) diff --git a/src/sys/event.rs b/src/sys/event.rs index e2a4eaa16e..7b0020919a 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -1,15 +1,15 @@ /* TOOD: Implement for other kqueue based systems */ -use {Errno, Result}; +use libc; #[cfg(not(target_os = "netbsd"))] -use libc::{timespec, time_t, c_int, c_long, intptr_t, uintptr_t}; +use libc::{c_int, c_long, intptr_t, time_t, timespec, uintptr_t}; #[cfg(target_os = "netbsd")] -use libc::{timespec, time_t, c_long, intptr_t, uintptr_t, size_t}; -use libc; +use libc::{c_long, intptr_t, size_t, time_t, timespec, uintptr_t}; +use std::mem; use std::os::unix::io::RawFd; use std::ptr; -use std::mem; +use {Errno, Result}; // Redefine kevent in terms of programmer-friendly enums and bitfields. #[derive(Clone, Copy)] @@ -19,12 +19,17 @@ pub struct KEvent { kevent: libc::kevent, } -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd" + ) +)] type type_of_udata = *mut libc::c_void; -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos"))] +#[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos"))] type type_of_data = intptr_t; #[cfg(any(target_os = "netbsd"))] type type_of_udata = intptr_t; @@ -79,9 +84,15 @@ libc_enum! { } } -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd" + ) +)] pub type type_of_event_flag = u16; #[cfg(any(target_os = "netbsd"))] pub type type_of_event_flag = u32; @@ -219,24 +230,30 @@ pub fn kqueue() -> Result { Errno::result(res) } - // KEvent can't derive Send because on some operating systems, udata is defined // as a void*. However, KEvent's public API always treats udata as an intptr_t, // which is safe to Send. -unsafe impl Send for KEvent { -} +unsafe impl Send for KEvent {} impl KEvent { - pub fn new(ident: uintptr_t, filter: EventFilter, flags: EventFlag, - fflags:FilterFlag, data: intptr_t, udata: intptr_t) -> KEvent { - KEvent { kevent: libc::kevent { - ident: ident, - filter: filter as type_of_event_filter, - flags: flags.bits(), - fflags: fflags.bits(), - data: data as type_of_data, - udata: udata as type_of_udata - } } + pub fn new( + ident: uintptr_t, + filter: EventFilter, + flags: EventFlag, + fflags: FilterFlag, + data: intptr_t, + udata: intptr_t, + ) -> KEvent { + KEvent { + kevent: libc::kevent { + ident: ident, + filter: filter as type_of_event_filter, + flags: flags.bits(), + fflags: fflags.bits(), + data: data as type_of_data, + udata: udata as type_of_udata, + }, + } } pub fn ident(&self) -> uintptr_t { @@ -264,34 +281,40 @@ impl KEvent { } } -pub fn kevent(kq: RawFd, - changelist: &[KEvent], - eventlist: &mut [KEvent], - timeout_ms: usize) -> Result { - +pub fn kevent( + kq: RawFd, + changelist: &[KEvent], + eventlist: &mut [KEvent], + timeout_ms: usize, +) -> Result { // Convert ms to timespec let timeout = timespec { tv_sec: (timeout_ms / 1000) as time_t, - tv_nsec: ((timeout_ms % 1000) * 1_000_000) as c_long + tv_nsec: ((timeout_ms % 1000) * 1_000_000) as c_long, }; kevent_ts(kq, changelist, eventlist, Some(timeout)) } -#[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "openbsd" + ) +)] type type_of_nchanges = c_int; #[cfg(target_os = "netbsd")] type type_of_nchanges = size_t; -pub fn kevent_ts(kq: RawFd, - changelist: &[KEvent], - eventlist: &mut [KEvent], - timeout_opt: Option) -> Result { - +pub fn kevent_ts( + kq: RawFd, + changelist: &[KEvent], + eventlist: &mut [KEvent], + timeout_opt: Option, +) -> Result { let res = unsafe { libc::kevent( kq, @@ -299,44 +322,54 @@ pub fn kevent_ts(kq: RawFd, changelist.len() as type_of_nchanges, eventlist.as_mut_ptr() as *mut libc::kevent, eventlist.len() as type_of_nchanges, - if let Some(ref timeout) = timeout_opt {timeout as *const timespec} else {ptr::null()}) + if let Some(ref timeout) = timeout_opt { + timeout as *const timespec + } else { + ptr::null() + }, + ) }; Errno::result(res).map(|r| r as usize) } #[inline] -pub fn ev_set(ev: &mut KEvent, - ident: usize, - filter: EventFilter, - flags: EventFlag, - fflags: FilterFlag, - udata: intptr_t) { - - ev.kevent.ident = ident as uintptr_t; +pub fn ev_set( + ev: &mut KEvent, + ident: usize, + filter: EventFilter, + flags: EventFlag, + fflags: FilterFlag, + udata: intptr_t, +) { + ev.kevent.ident = ident as uintptr_t; ev.kevent.filter = filter as type_of_event_filter; - ev.kevent.flags = flags.bits(); + ev.kevent.flags = flags.bits(); ev.kevent.fflags = fflags.bits(); - ev.kevent.data = 0; - ev.kevent.udata = udata as type_of_udata; + ev.kevent.data = 0; + ev.kevent.udata = udata as type_of_udata; } #[test] fn test_struct_kevent() { - let udata : intptr_t = 12345; + let udata: intptr_t = 12345; - let expected = libc::kevent{ident: 0xdead_beef, - filter: libc::EVFILT_READ, - flags: libc::EV_ONESHOT | libc::EV_ADD, - fflags: libc::NOTE_CHILD | libc::NOTE_EXIT, - data: 0x1337, - udata: udata as type_of_udata}; - let actual = KEvent::new(0xdead_beef, - EventFilter::EVFILT_READ, - EventFlag::EV_ONESHOT | EventFlag::EV_ADD, - FilterFlag::NOTE_CHILD | FilterFlag::NOTE_EXIT, - 0x1337, - udata); + let expected = libc::kevent { + ident: 0xdead_beef, + filter: libc::EVFILT_READ, + flags: libc::EV_ONESHOT | libc::EV_ADD, + fflags: libc::NOTE_CHILD | libc::NOTE_EXIT, + data: 0x1337, + udata: udata as type_of_udata, + }; + let actual = KEvent::new( + 0xdead_beef, + EventFilter::EVFILT_READ, + EventFlag::EV_ONESHOT | EventFlag::EV_ADD, + FilterFlag::NOTE_CHILD | FilterFlag::NOTE_EXIT, + 0x1337, + udata, + ); assert!(expected.ident == actual.ident()); assert!(expected.filter == actual.filter() as type_of_event_filter); assert!(expected.flags == actual.flags().bits()); diff --git a/src/sys/eventfd.rs b/src/sys/eventfd.rs index c5a54e46a1..c427ab9ce9 100644 --- a/src/sys/eventfd.rs +++ b/src/sys/eventfd.rs @@ -1,7 +1,7 @@ +use errno::Errno; use libc; use std::os::unix::io::RawFd; use Result; -use errno::Errno; libc_bitflags! { pub struct EfdFlags: libc::c_int { diff --git a/src/sys/ioctl/bsd.rs b/src/sys/ioctl/bsd.rs index 4c39fa6a05..02b6ee099e 100644 --- a/src/sys/ioctl/bsd.rs +++ b/src/sys/ioctl/bsd.rs @@ -6,7 +6,7 @@ pub type ioctl_num_type = ::libc::c_ulong; pub type ioctl_param_type = ::libc::c_int; mod consts { - use ::sys::ioctl::ioctl_num_type; + use sys::ioctl::ioctl_num_type; #[doc(hidden)] pub const VOID: ioctl_num_type = 0x2000_0000; #[doc(hidden)] @@ -14,7 +14,7 @@ mod consts { #[doc(hidden)] pub const IN: ioctl_num_type = 0x8000_0000; #[doc(hidden)] - pub const INOUT: ioctl_num_type = (IN|OUT); + pub const INOUT: ioctl_num_type = (IN | OUT); #[doc(hidden)] pub const IOCPARM_MASK: ioctl_num_type = 0x1fff; } @@ -24,9 +24,12 @@ pub use self::consts::*; #[macro_export] #[doc(hidden)] macro_rules! ioc { - ($inout:expr, $group:expr, $num:expr, $len:expr) => ( - $inout | (($len as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::IOCPARM_MASK) << 16) | (($group as $crate::sys::ioctl::ioctl_num_type) << 8) | ($num as $crate::sys::ioctl::ioctl_num_type) - ) + ($inout:expr, $group:expr, $num:expr, $len:expr) => { + $inout + | (($len as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::IOCPARM_MASK) + << 16) | (($group as $crate::sys::ioctl::ioctl_num_type) << 8) + | ($num as $crate::sys::ioctl::ioctl_num_type) + }; } /// Generate an ioctl request code for a command that passes no data. @@ -46,7 +49,9 @@ macro_rules! ioc { /// ``` #[macro_export] macro_rules! request_code_none { - ($g:expr, $n:expr) => (ioc!($crate::sys::ioctl::VOID, $g, $n, 0)) + ($g:expr, $n:expr) => { + ioc!($crate::sys::ioctl::VOID, $g, $n, 0) + }; } /// Generate an ioctl request code for a command that passes an integer @@ -57,7 +62,14 @@ macro_rules! request_code_none { /// with is "bad" and you cannot use `ioctl_write_int!()` directly. #[macro_export] macro_rules! request_code_write_int { - ($g:expr, $n:expr) => (ioc!($crate::sys::ioctl::VOID, $g, $n, ::std::mem::size_of::<$crate::libc::c_int>())) + ($g:expr, $n:expr) => { + ioc!( + $crate::sys::ioctl::VOID, + $g, + $n, + ::std::mem::size_of::<$crate::libc::c_int>() + ) + }; } /// Generate an ioctl request code for a command that reads. @@ -72,7 +84,9 @@ macro_rules! request_code_write_int { /// writing. #[macro_export] macro_rules! request_code_read { - ($g:expr, $n:expr, $len:expr) => (ioc!($crate::sys::ioctl::OUT, $g, $n, $len)) + ($g:expr, $n:expr, $len:expr) => { + ioc!($crate::sys::ioctl::OUT, $g, $n, $len) + }; } /// Generate an ioctl request code for a command that writes. @@ -87,7 +101,9 @@ macro_rules! request_code_read { /// reading. #[macro_export] macro_rules! request_code_write { - ($g:expr, $n:expr, $len:expr) => (ioc!($crate::sys::ioctl::IN, $g, $n, $len)) + ($g:expr, $n:expr, $len:expr) => { + ioc!($crate::sys::ioctl::IN, $g, $n, $len) + }; } /// Generate an ioctl request code for a command that reads and writes. @@ -98,5 +114,7 @@ macro_rules! request_code_write { /// with is "bad" and you cannot use `ioctl_readwrite!()` directly. #[macro_export] macro_rules! request_code_readwrite { - ($g:expr, $n:expr, $len:expr) => (ioc!($crate::sys::ioctl::INOUT, $g, $n, $len)) + ($g:expr, $n:expr, $len:expr) => { + ioc!($crate::sys::ioctl::INOUT, $g, $n, $len) + }; } diff --git a/src/sys/ioctl/linux.rs b/src/sys/ioctl/linux.rs index 17c8cff9d1..735f32a735 100644 --- a/src/sys/ioctl/linux.rs +++ b/src/sys/ioctl/linux.rs @@ -14,7 +14,14 @@ pub const NRBITS: ioctl_num_type = 8; #[doc(hidden)] pub const TYPEBITS: ioctl_num_type = 8; -#[cfg(any(target_arch = "mips", target_arch = "mips64", target_arch = "powerpc", target_arch = "powerpc64"))] +#[cfg( + any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + ) +)] mod consts { #[doc(hidden)] pub const NONE: u8 = 1; @@ -29,11 +36,15 @@ mod consts { } // "Generic" ioctl protocol -#[cfg(any(target_arch = "x86", - target_arch = "arm", - target_arch = "s390x", - target_arch = "x86_64", - target_arch = "aarch64"))] +#[cfg( + any( + target_arch = "x86", + target_arch = "arm", + target_arch = "s390x", + target_arch = "x86_64", + target_arch = "aarch64" + ) +)] mod consts { #[doc(hidden)] pub const NONE: u8 = 0; @@ -71,11 +82,16 @@ pub const DIRMASK: ioctl_num_type = (1 << DIRBITS) - 1; #[macro_export] #[doc(hidden)] macro_rules! ioc { - ($dir:expr, $ty:expr, $nr:expr, $sz:expr) => ( - (($dir as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::DIRMASK) << $crate::sys::ioctl::DIRSHIFT) | - (($ty as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::TYPEMASK) << $crate::sys::ioctl::TYPESHIFT) | - (($nr as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::NRMASK) << $crate::sys::ioctl::NRSHIFT) | - (($sz as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::SIZEMASK) << $crate::sys::ioctl::SIZESHIFT)) + ($dir:expr, $ty:expr, $nr:expr, $sz:expr) => { + (($dir as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::DIRMASK) + << $crate::sys::ioctl::DIRSHIFT) + | (($ty as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::TYPEMASK) + << $crate::sys::ioctl::TYPESHIFT) + | (($nr as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::NRMASK) + << $crate::sys::ioctl::NRSHIFT) + | (($sz as $crate::sys::ioctl::ioctl_num_type & $crate::sys::ioctl::SIZEMASK) + << $crate::sys::ioctl::SIZESHIFT) + }; } /// Generate an ioctl request code for a command that passes no data. @@ -95,7 +111,9 @@ macro_rules! ioc { /// ``` #[macro_export] macro_rules! request_code_none { - ($ty:expr, $nr:expr) => (ioc!($crate::sys::ioctl::NONE, $ty, $nr, 0)) + ($ty:expr, $nr:expr) => { + ioc!($crate::sys::ioctl::NONE, $ty, $nr, 0) + }; } /// Generate an ioctl request code for a command that reads. @@ -110,7 +128,9 @@ macro_rules! request_code_none { /// writing. #[macro_export] macro_rules! request_code_read { - ($ty:expr, $nr:expr, $sz:expr) => (ioc!($crate::sys::ioctl::READ, $ty, $nr, $sz)) + ($ty:expr, $nr:expr, $sz:expr) => { + ioc!($crate::sys::ioctl::READ, $ty, $nr, $sz) + }; } /// Generate an ioctl request code for a command that writes. @@ -125,7 +145,9 @@ macro_rules! request_code_read { /// reading. #[macro_export] macro_rules! request_code_write { - ($ty:expr, $nr:expr, $sz:expr) => (ioc!($crate::sys::ioctl::WRITE, $ty, $nr, $sz)) + ($ty:expr, $nr:expr, $sz:expr) => { + ioc!($crate::sys::ioctl::WRITE, $ty, $nr, $sz) + }; } /// Generate an ioctl request code for a command that reads and writes. @@ -136,5 +158,12 @@ macro_rules! request_code_write { /// with is "bad" and you cannot use `ioctl_readwrite!()` directly. #[macro_export] macro_rules! request_code_readwrite { - ($ty:expr, $nr:expr, $sz:expr) => (ioc!($crate::sys::ioctl::READ | $crate::sys::ioctl::WRITE, $ty, $nr, $sz)) + ($ty:expr, $nr:expr, $sz:expr) => { + ioc!( + $crate::sys::ioctl::READ | $crate::sys::ioctl::WRITE, + $ty, + $nr, + $sz + ) + }; } diff --git a/src/sys/ioctl/mod.rs b/src/sys/ioctl/mod.rs index e00e5934d3..cc344b285b 100644 --- a/src/sys/ioctl/mod.rs +++ b/src/sys/ioctl/mod.rs @@ -229,32 +229,38 @@ mod linux; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::linux::*; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] #[macro_use] mod bsd; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] pub use self::bsd::*; /// Convert raw ioctl return value to a Nix result #[macro_export] #[doc(hidden)] macro_rules! convert_ioctl_res { - ($w:expr) => ( - { - $crate::errno::Errno::result($w) - } - ); + ($w:expr) => {{ + $crate::errno::Errno::result($w) + }}; } /// Generates a wrapper function for an ioctl that passes no data to the kernel. diff --git a/src/sys/memfd.rs b/src/sys/memfd.rs index 9672429b31..6b2ff9c913 100644 --- a/src/sys/memfd.rs +++ b/src/sys/memfd.rs @@ -1,8 +1,8 @@ +use errno::Errno; use libc; +use std::ffi::CStr; use std::os::unix::io::RawFd; use Result; -use errno::Errno; -use std::ffi::CStr; libc_bitflags!( pub struct MemFdCreateFlag: libc::c_uint { @@ -12,9 +12,7 @@ libc_bitflags!( ); pub fn memfd_create(name: &CStr, flags: MemFdCreateFlag) -> Result { - let res = unsafe { - libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags.bits()) - }; + let res = unsafe { libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags.bits()) }; Errno::result(res).map(|r| r as RawFd) } diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 48b5767e95..1ad96c2b43 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -1,13 +1,13 @@ -use {Error, Result}; -#[cfg(not(target_os = "android"))] -use NixPath; use errno::Errno; #[cfg(not(target_os = "android"))] use fcntl::OFlag; -use libc::{self, c_int, c_void, size_t, off_t}; +use libc::{self, c_int, c_void, off_t, size_t}; +use std::os::unix::io::RawFd; #[cfg(not(target_os = "android"))] use sys::stat::Mode; -use std::os::unix::io::RawFd; +#[cfg(not(target_os = "android"))] +use NixPath; +use {Error, Result}; libc_bitflags!{ /// Desired memory protection of a memory mapping. @@ -240,7 +240,14 @@ pub fn munlockall() -> Result<()> { /// Calls to mmap are inherently unsafe, so they must be made in an unsafe block. Typically /// a higher-level abstraction will hide the unsafe interactions with the mmap'd region. -pub unsafe fn mmap(addr: *mut c_void, length: size_t, prot: ProtFlags, flags: MapFlags, fd: RawFd, offset: off_t) -> Result<*mut c_void> { +pub unsafe fn mmap( + addr: *mut c_void, + length: size_t, + prot: ProtFlags, + flags: MapFlags, + fd: RawFd, + offset: off_t, +) -> Result<*mut c_void> { let ret = libc::mmap(addr, length, prot.bits(), flags.bits(), fd, offset); if ret == libc::MAP_FAILED { @@ -280,9 +287,7 @@ pub fn shm_open(name: &P, flag: OFlag, mode: Mode) -> Resul #[cfg(not(target_os = "android"))] pub fn shm_unlink(name: &P) -> Result<()> { - let ret = try!(name.with_nix_path(|cstr| { - unsafe { libc::shm_unlink(cstr.as_ptr()) } - })); + let ret = try!(name.with_nix_path(|cstr| unsafe { libc::shm_unlink(cstr.as_ptr()) })); Errno::result(ret).map(drop) } diff --git a/src/sys/mod.rs b/src/sys/mod.rs index e6c7880c1e..d5b583181c 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -1,33 +1,45 @@ -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd" + ) +)] pub mod aio; #[cfg(any(target_os = "android", target_os = "linux"))] pub mod epoll; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] pub mod event; #[cfg(target_os = "linux")] pub mod eventfd; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] #[macro_use] pub mod ioctl; @@ -49,11 +61,15 @@ pub mod reboot; pub mod select; -#[cfg(any(target_os = "android", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos"))] +#[cfg( + any( + target_os = "android", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos" + ) +)] pub mod sendfile; pub mod signal; diff --git a/src/sys/ptrace.rs b/src/sys/ptrace.rs index 4bb7e06f60..3cdf24956d 100644 --- a/src/sys/ptrace.rs +++ b/src/sys/ptrace.rs @@ -1,12 +1,11 @@ //! For detailed description of the ptrace requests, consult `man ptrace`. -use std::{mem, ptr}; -use {Error, Result}; use errno::Errno; -use libc::{self, c_void, c_long, siginfo_t}; -use ::unistd::Pid; +use libc::{self, c_long, c_void, siginfo_t}; +use std::{mem, ptr}; use sys::signal::Signal; - +use unistd::Pid; +use {Error, Result}; cfg_if! { if #[cfg(any(all(target_os = "linux", arch = "s390x"), @@ -167,15 +166,24 @@ libc_bitflags! { /// Performs a ptrace request. If the request in question is provided by a specialised function /// this function will return an unsupported operation error. #[deprecated( - since="0.10.0", - note="usages of `ptrace()` should be replaced with the specialized helper functions instead" + since = "0.10.0", + note = "usages of `ptrace()` should be replaced with the specialized helper functions instead" )] -pub unsafe fn ptrace(request: Request, pid: Pid, addr: *mut c_void, data: *mut c_void) -> Result { +pub unsafe fn ptrace( + request: Request, + pid: Pid, + addr: *mut c_void, + data: *mut c_void, +) -> Result { use self::Request::*; match request { - PTRACE_PEEKTEXT | PTRACE_PEEKDATA | PTRACE_PEEKUSER => ptrace_peek(request, pid, addr, data), - PTRACE_GETSIGINFO | PTRACE_GETEVENTMSG | PTRACE_SETSIGINFO | PTRACE_SETOPTIONS => Err(Error::UnsupportedOperation), - _ => ptrace_other(request, pid, addr, data) + PTRACE_PEEKTEXT | PTRACE_PEEKDATA | PTRACE_PEEKUSER => { + ptrace_peek(request, pid, addr, data) + } + PTRACE_GETSIGINFO | PTRACE_GETEVENTMSG | PTRACE_SETSIGINFO | PTRACE_SETOPTIONS => { + Err(Error::UnsupportedOperation) + } + _ => ptrace_other(request, pid, addr, data), } } @@ -198,17 +206,29 @@ fn ptrace_get_data(request: Request, pid: Pid) -> Result { // Creates an uninitialized pointer to store result in let data: T = unsafe { mem::uninitialized() }; let res = unsafe { - libc::ptrace(request as RequestType, - libc::pid_t::from(pid), - ptr::null_mut::(), - &data as *const _ as *const c_void) + libc::ptrace( + request as RequestType, + libc::pid_t::from(pid), + ptr::null_mut::(), + &data as *const _ as *const c_void, + ) }; Errno::result(res)?; Ok(data) } -unsafe fn ptrace_other(request: Request, pid: Pid, addr: *mut c_void, data: *mut c_void) -> Result { - Errno::result(libc::ptrace(request as RequestType, libc::pid_t::from(pid), addr, data)).map(|_| 0) +unsafe fn ptrace_other( + request: Request, + pid: Pid, + addr: *mut c_void, + data: *mut c_void, +) -> Result { + Errno::result(libc::ptrace( + request as RequestType, + libc::pid_t::from(pid), + addr, + data, + )).map(|_| 0) } /// Set options, as with `ptrace(PTRACE_SETOPTIONS,...)`. @@ -216,10 +236,12 @@ pub fn setoptions(pid: Pid, options: Options) -> Result<()> { use std::ptr; let res = unsafe { - libc::ptrace(Request::PTRACE_SETOPTIONS as RequestType, - libc::pid_t::from(pid), - ptr::null_mut::(), - options.bits() as *mut c_void) + libc::ptrace( + Request::PTRACE_SETOPTIONS as RequestType, + libc::pid_t::from(pid), + ptr::null_mut::(), + options.bits() as *mut c_void, + ) }; Errno::result(res).map(|_| ()) } @@ -236,12 +258,14 @@ pub fn getsiginfo(pid: Pid) -> Result { /// Set siginfo as with `ptrace(PTRACE_SETSIGINFO,...)` pub fn setsiginfo(pid: Pid, sig: &siginfo_t) -> Result<()> { - let ret = unsafe{ + let ret = unsafe { Errno::clear(); - libc::ptrace(Request::PTRACE_SETSIGINFO as RequestType, - libc::pid_t::from(pid), - ptr::null_mut::(), - sig as *const _ as *const c_void) + libc::ptrace( + Request::PTRACE_SETSIGINFO as RequestType, + libc::pid_t::from(pid), + ptr::null_mut::(), + sig as *const _ as *const c_void, + ) }; match Errno::result(ret) { Ok(_) => Ok(()), @@ -301,7 +325,7 @@ pub fn detach(pid: Pid) -> Result<()> { Request::PTRACE_DETACH, pid, ptr::null_mut(), - ptr::null_mut() + ptr::null_mut(), ).map(|_| ()) } } @@ -320,7 +344,7 @@ pub fn cont>>(pid: Pid, sig: T) -> Result<()> { } } -/// Move the stopped tracee process forward by a single step as with +/// Move the stopped tracee process forward by a single step as with /// `ptrace(PTRACE_SINGLESTEP, ...)` /// /// Advances the execution of the process with PID `pid` by a single step optionally delivering a @@ -331,11 +355,11 @@ pub fn cont>>(pid: Pid, sig: T) -> Result<()> { /// extern crate nix; /// use nix::sys::ptrace::step; /// use nix::unistd::Pid; -/// use nix::sys::signal::Signal; +/// 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 +/// // 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)) => { @@ -350,7 +374,5 @@ pub fn step>>(pid: Pid, sig: T) -> Result<()> { Some(s) => s as i32 as *mut c_void, None => ptr::null_mut(), }; - unsafe { - ptrace_other(Request::PTRACE_SINGLESTEP, pid, ptr::null_mut(), data).map(|_| ()) - } + unsafe { ptrace_other(Request::PTRACE_SINGLESTEP, pid, ptr::null_mut(), data).map(|_| ()) } } diff --git a/src/sys/quota.rs b/src/sys/quota.rs index b4cac1dc9b..22e4ca8827 100644 --- a/src/sys/quota.rs +++ b/src/sys/quota.rs @@ -12,11 +12,11 @@ //! dqblk.set_blocks_soft_limit(8000); //! quotactl_set(QuotaType::USRQUOTA, "/dev/sda1", 50, &dqblk, QuotaValidFlags::QIF_BLIMITS); //! ``` +use errno::Errno; +use libc::{self, c_char, c_int}; use std::default::Default; use std::{mem, ptr}; -use libc::{self, c_int, c_char}; -use {Result, NixPath}; -use errno::Errno; +use {NixPath, Result}; struct QuotaCmd(QuotaSubCmd, QuotaType); @@ -228,49 +228,94 @@ impl Dqblk { } } -fn quotactl(cmd: QuotaCmd, special: Option<&P>, id: c_int, addr: *mut c_char) -> Result<()> { +fn quotactl( + cmd: QuotaCmd, + special: Option<&P>, + id: c_int, + addr: *mut c_char, +) -> Result<()> { unsafe { Errno::clear(); - let res = try!( - match special { - Some(dev) => dev.with_nix_path(|path| libc::quotactl(cmd.as_int(), path.as_ptr(), id, addr)), - None => Ok(libc::quotactl(cmd.as_int(), ptr::null(), id, addr)), + let res = try!(match special { + Some(dev) => { + dev.with_nix_path(|path| libc::quotactl(cmd.as_int(), path.as_ptr(), id, addr)) } - ); + None => Ok(libc::quotactl(cmd.as_int(), ptr::null(), id, addr)), + }); Errno::result(res).map(drop) } } /// Turn on disk quotas for a block device. -pub fn quotactl_on(which: QuotaType, special: &P, format: QuotaFmt, quota_file: &P) -> Result<()> { +pub fn quotactl_on( + which: QuotaType, + special: &P, + format: QuotaFmt, + quota_file: &P, +) -> Result<()> { try!(quota_file.with_nix_path(|path| { let mut path_copy = path.to_bytes_with_nul().to_owned(); let p: *mut c_char = path_copy.as_mut_ptr() as *mut c_char; - quotactl(QuotaCmd(QuotaSubCmd::Q_QUOTAON, which), Some(special), format as c_int, p) + quotactl( + QuotaCmd(QuotaSubCmd::Q_QUOTAON, which), + Some(special), + format as c_int, + p, + ) })) } /// Disable disk quotas for a block device. pub fn quotactl_off(which: QuotaType, special: &P) -> Result<()> { - quotactl(QuotaCmd(QuotaSubCmd::Q_QUOTAOFF, which), Some(special), 0, ptr::null_mut()) + quotactl( + QuotaCmd(QuotaSubCmd::Q_QUOTAOFF, which), + Some(special), + 0, + ptr::null_mut(), + ) } /// Update the on-disk copy of quota usages for a filesystem. pub fn quotactl_sync(which: QuotaType, special: Option<&P>) -> Result<()> { - quotactl(QuotaCmd(QuotaSubCmd::Q_SYNC, which), special, 0, ptr::null_mut()) + quotactl( + QuotaCmd(QuotaSubCmd::Q_SYNC, which), + special, + 0, + ptr::null_mut(), + ) } /// Get disk quota limits and current usage for the given user/group id. -pub fn quotactl_get(which: QuotaType, special: &P, id: c_int) -> Result { +pub fn quotactl_get( + which: QuotaType, + special: &P, + id: c_int, +) -> Result { let mut dqblk = unsafe { mem::uninitialized() }; - quotactl(QuotaCmd(QuotaSubCmd::Q_GETQUOTA, which), Some(special), id, &mut dqblk as *mut _ as *mut c_char)?; + quotactl( + QuotaCmd(QuotaSubCmd::Q_GETQUOTA, which), + Some(special), + id, + &mut dqblk as *mut _ as *mut c_char, + )?; dqblk } /// Configure quota values for the specified fields for a given user/group id. -pub fn quotactl_set(which: QuotaType, special: &P, id: c_int, dqblk: &Dqblk, fields: QuotaValidFlags) -> Result<()> { +pub fn quotactl_set( + which: QuotaType, + special: &P, + id: c_int, + dqblk: &Dqblk, + fields: QuotaValidFlags, +) -> Result<()> { let mut dqblk_copy = *dqblk; dqblk_copy.0.dqb_valid = fields.bits(); - quotactl(QuotaCmd(QuotaSubCmd::Q_SETQUOTA, which), Some(special), id, &mut dqblk_copy as *mut _ as *mut c_char) + quotactl( + QuotaCmd(QuotaSubCmd::Q_SETQUOTA, which), + Some(special), + id, + &mut dqblk_copy as *mut _ as *mut c_char, + ) } diff --git a/src/sys/reboot.rs b/src/sys/reboot.rs index bafa8fc119..07278651cd 100644 --- a/src/sys/reboot.rs +++ b/src/sys/reboot.rs @@ -1,10 +1,10 @@ //! Reboot/shutdown or enable/disable Ctrl-Alt-Delete. -use {Error, Result}; use errno::Errno; use libc; -use void::Void; use std::mem::drop; +use void::Void; +use {Error, Result}; libc_enum! { /// How exactly should the system be rebooted. @@ -23,9 +23,7 @@ libc_enum! { } pub fn reboot(how: RebootMode) -> Result { - unsafe { - libc::reboot(how as libc::c_int) - }; + unsafe { libc::reboot(how as libc::c_int) }; Err(Error::Sys(Errno::last())) } @@ -38,8 +36,6 @@ pub fn set_cad_enabled(enable: bool) -> Result<()> { } else { libc::RB_DISABLE_CAD }; - let res = unsafe { - libc::reboot(cmd) - }; + let res = unsafe { libc::reboot(cmd) }; Errno::result(res).map(drop) } diff --git a/src/sys/select.rs b/src/sys/select.rs index 95b6b148f6..2c1d991ba2 100644 --- a/src/sys/select.rs +++ b/src/sys/select.rs @@ -1,11 +1,11 @@ +use errno::Errno; +use libc::{self, c_int}; use std::mem; use std::os::unix::io::RawFd; use std::ptr::{null, null_mut}; -use libc::{self, c_int}; -use Result; -use errno::Errno; use sys::signal::SigSet; use sys::time::{TimeSpec, TimeVal}; +use Result; pub use libc::FD_SETSIZE; @@ -62,7 +62,7 @@ impl FdSet { for i in (0..FD_SETSIZE).rev() { let i = i as RawFd; if unsafe { libc::FD_ISSET(i, self as *mut _ as *mut libc::fd_set) } { - return Some(i) + return Some(i); } } @@ -93,11 +93,13 @@ impl FdSet { /// [select(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/select.html) /// /// [`FdSet::highest`]: struct.FdSet.html#method.highest -pub fn select<'a, N, R, W, E, T>(nfds: N, - readfds: R, - writefds: W, - errorfds: E, - timeout: T) -> Result +pub fn select<'a, N, R, W, E, T>( + nfds: N, + readfds: R, + writefds: W, + errorfds: E, + timeout: T, +) -> Result where N: Into>, R: Into>, @@ -111,7 +113,8 @@ where let timeout = timeout.into(); let nfds = nfds.into().unwrap_or_else(|| { - readfds.iter_mut() + readfds + .iter_mut() .chain(writefds.iter_mut()) .chain(errorfds.iter_mut()) .map(|set| set.highest().unwrap_or(-1)) @@ -119,15 +122,20 @@ where .unwrap_or(-1) + 1 }); - let readfds = readfds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let writefds = writefds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let errorfds = errorfds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let timeout = timeout.map(|tv| tv as *mut _ as *mut libc::timeval) - .unwrap_or(null_mut()); - - let res = unsafe { - libc::select(nfds, readfds, writefds, errorfds, timeout) - }; + let readfds = readfds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let writefds = writefds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let errorfds = errorfds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let timeout = timeout + .map(|tv| tv as *mut _ as *mut libc::timeval) + .unwrap_or(null_mut()); + + let res = unsafe { libc::select(nfds, readfds, writefds, errorfds, timeout) }; Errno::result(res) } @@ -161,12 +169,14 @@ where /// [The new pselect() system call](https://lwn.net/Articles/176911/) /// /// [`FdSet::highest`]: struct.FdSet.html#method.highest -pub fn pselect<'a, N, R, W, E, T, S>(nfds: N, - readfds: R, - writefds: W, - errorfds: E, - timeout: T, - sigmask: S) -> Result +pub fn pselect<'a, N, R, W, E, T, S>( + nfds: N, + readfds: R, + writefds: W, + errorfds: E, + timeout: T, + sigmask: S, +) -> Result where N: Into>, R: Into>, @@ -182,7 +192,8 @@ where let timeout = timeout.into(); let nfds = nfds.into().unwrap_or_else(|| { - readfds.iter_mut() + readfds + .iter_mut() .chain(writefds.iter_mut()) .chain(errorfds.iter_mut()) .map(|set| set.highest().unwrap_or(-1)) @@ -190,26 +201,33 @@ where .unwrap_or(-1) + 1 }); - let readfds = readfds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let writefds = writefds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let errorfds = errorfds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let timeout = timeout.map(|ts| ts.as_ref() as *const libc::timespec).unwrap_or(null()); - let sigmask = sigmask.map(|sm| sm.as_ref() as *const libc::sigset_t).unwrap_or(null()); - - let res = unsafe { - libc::pselect(nfds, readfds, writefds, errorfds, timeout, sigmask) - }; + let readfds = readfds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let writefds = writefds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let errorfds = errorfds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let timeout = timeout + .map(|ts| ts.as_ref() as *const libc::timespec) + .unwrap_or(null()); + let sigmask = sigmask + .map(|sm| sm.as_ref() as *const libc::sigset_t) + .unwrap_or(null()); + + let res = unsafe { libc::pselect(nfds, readfds, writefds, errorfds, timeout, sigmask) }; Errno::result(res) } - #[cfg(test)] mod tests { use super::*; use std::os::unix::io::RawFd; use sys::time::{TimeVal, TimeValLike}; - use unistd::{write, pipe}; + use unistd::{pipe, write}; #[test] fn fdset_insert() { @@ -284,11 +302,10 @@ mod tests { fd_set.insert(r2); let mut timeout = TimeVal::seconds(10); - assert_eq!(1, select(None, - &mut fd_set, - None, - None, - &mut timeout).unwrap()); + assert_eq!( + 1, + select(None, &mut fd_set, None, None, &mut timeout).unwrap() + ); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); } @@ -304,11 +321,16 @@ mod tests { fd_set.insert(r2); let mut timeout = TimeVal::seconds(10); - assert_eq!(1, select(Some(fd_set.highest().unwrap() + 1), - &mut fd_set, - None, - None, - &mut timeout).unwrap()); + assert_eq!( + 1, + select( + Some(fd_set.highest().unwrap() + 1), + &mut fd_set, + None, + None, + &mut timeout + ).unwrap() + ); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); } @@ -324,11 +346,16 @@ mod tests { fd_set.insert(r2); let mut timeout = TimeVal::seconds(10); - assert_eq!(1, select(::std::cmp::max(r1, r2) + 1, - &mut fd_set, - None, - None, - &mut timeout).unwrap()); + assert_eq!( + 1, + select( + ::std::cmp::max(r1, r2) + 1, + &mut fd_set, + None, + None, + &mut timeout + ).unwrap() + ); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); } diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index 1190518d8b..f5db22c59d 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -3,8 +3,8 @@ use std::ptr; use libc::{self, off_t}; -use Result; use errno::Errno; +use Result; /// Copy up to `count` bytes to `out_fd` from `in_fd` starting at `offset`. /// diff --git a/src/sys/signal.rs b/src/sys/signal.rs index 73c3a95800..242410c636 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -1,15 +1,14 @@ // Portions of this file are Copyright 2014 The Rust Project Developers. // See http://rust-lang.org/COPYRIGHT. +use errno::Errno; ///! Operating system signals. - use libc; -use {Error, Result}; -use errno::Errno; use std::mem; #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] use std::os::unix::io::RawFd; use std::ptr; +use {Error, Result}; #[cfg(not(target_os = "openbsd"))] pub use self::sigevent::*; @@ -64,104 +63,34 @@ libc_enum!{ pub use self::Signal::*; -#[cfg(all(any(target_os = "linux", target_os = "android", target_os = "emscripten"), not(any(target_arch = "mips", target_arch = "mips64"))))] +#[cfg( + all( + any(target_os = "linux", target_os = "android", target_os = "emscripten"), + not(any(target_arch = "mips", target_arch = "mips64")) + ) +)] const SIGNALS: [Signal; 31] = [ - SIGHUP, - SIGINT, - SIGQUIT, - SIGILL, - SIGTRAP, - SIGABRT, - SIGBUS, - SIGFPE, - SIGKILL, - SIGUSR1, - SIGSEGV, - SIGUSR2, - SIGPIPE, - SIGALRM, - SIGTERM, - SIGSTKFLT, - SIGCHLD, - SIGCONT, - SIGSTOP, - SIGTSTP, - SIGTTIN, - SIGTTOU, - SIGURG, - SIGXCPU, - SIGXFSZ, - SIGVTALRM, - SIGPROF, - SIGWINCH, - SIGIO, - SIGPWR, - SIGSYS]; -#[cfg(all(any(target_os = "linux", target_os = "android", target_os = "emscripten"), any(target_arch = "mips", target_arch = "mips64")))] + SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, SIGUSR1, SIGSEGV, + SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGSTKFLT, SIGCHLD, SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, + SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGPWR, SIGSYS, +]; +#[cfg( + all( + any(target_os = "linux", target_os = "android", target_os = "emscripten"), + any(target_arch = "mips", target_arch = "mips64") + ) +)] const SIGNALS: [Signal; 30] = [ - SIGHUP, - SIGINT, - SIGQUIT, - SIGILL, - SIGTRAP, - SIGABRT, - SIGBUS, - SIGFPE, - SIGKILL, - SIGUSR1, - SIGSEGV, - SIGUSR2, - SIGPIPE, - SIGALRM, - SIGTERM, - SIGCHLD, - SIGCONT, - SIGSTOP, - SIGTSTP, - SIGTTIN, - SIGTTOU, - SIGURG, - SIGXCPU, - SIGXFSZ, - SIGVTALRM, - SIGPROF, - SIGWINCH, - SIGIO, - SIGPWR, - SIGSYS]; + SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, SIGUSR1, SIGSEGV, + SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, + SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGPWR, SIGSYS, +]; #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "emscripten")))] const SIGNALS: [Signal; 31] = [ - SIGHUP, - SIGINT, - SIGQUIT, - SIGILL, - SIGTRAP, - SIGABRT, - SIGBUS, - SIGFPE, - SIGKILL, - SIGUSR1, - SIGSEGV, - SIGUSR2, - SIGPIPE, - SIGALRM, - SIGTERM, - SIGCHLD, - SIGCONT, - SIGSTOP, - SIGTSTP, - SIGTTIN, - SIGTTOU, - SIGURG, - SIGXCPU, - SIGXFSZ, - SIGVTALRM, - SIGPROF, - SIGWINCH, - SIGIO, - SIGSYS, - SIGEMT, - SIGINFO]; + SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGKILL, SIGUSR1, SIGSEGV, + SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGCONT, SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, + SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGSYS, SIGEMT, SIGINFO, +]; pub const NSIG: libc::c_int = 32; @@ -187,7 +116,7 @@ impl Iterator for SignalIterator { impl Signal { pub fn iterator() -> SignalIterator { - SignalIterator{next: 0} + SignalIterator { next: 0 } } // We do not implement the From trait, because it is supposed to be infallible. @@ -203,9 +132,9 @@ impl Signal { } } -pub const SIGIOT : Signal = SIGABRT; -pub const SIGPOLL : Signal = SIGIO; -pub const SIGUNUSED : Signal = SIGSYS; +pub const SIGIOT: Signal = SIGABRT; +pub const SIGPOLL: Signal = SIGIO; +pub const SIGUNUSED: Signal = SIGSYS; #[cfg(not(target_os = "android"))] libc_bitflags!{ @@ -261,10 +190,9 @@ libc_enum! { #[derive(Clone, Copy)] #[allow(missing_debug_implementations)] pub struct SigSet { - sigset: libc::sigset_t + sigset: libc::sigset_t, } - impl SigSet { pub fn all() -> SigSet { let mut sigset: libc::sigset_t = unsafe { mem::uninitialized() }; @@ -281,7 +209,12 @@ impl SigSet { } pub fn add(&mut self, signal: Signal) { - unsafe { libc::sigaddset(&mut self.sigset as *mut libc::sigset_t, signal as libc::c_int) }; + unsafe { + libc::sigaddset( + &mut self.sigset as *mut libc::sigset_t, + signal as libc::c_int, + ) + }; } pub fn clear(&mut self) { @@ -289,11 +222,18 @@ impl SigSet { } pub fn remove(&mut self, signal: Signal) { - unsafe { libc::sigdelset(&mut self.sigset as *mut libc::sigset_t, signal as libc::c_int) }; + unsafe { + libc::sigdelset( + &mut self.sigset as *mut libc::sigset_t, + signal as libc::c_int, + ) + }; } pub fn contains(&self, signal: Signal) -> bool { - let res = unsafe { libc::sigismember(&self.sigset as *const libc::sigset_t, signal as libc::c_int) }; + let res = unsafe { + libc::sigismember(&self.sigset as *const libc::sigset_t, signal as libc::c_int) + }; match res { 1 => true, @@ -313,7 +253,11 @@ impl SigSet { /// Gets the currently blocked (masked) set of signals for the calling thread. pub fn thread_get_mask() -> Result { let mut oldmask: SigSet = unsafe { mem::uninitialized() }; - try!(pthread_sigmask(SigmaskHow::SIG_SETMASK, None, Some(&mut oldmask))); + try!(pthread_sigmask( + SigmaskHow::SIG_SETMASK, + None, + Some(&mut oldmask) + )); Ok(oldmask) } @@ -364,17 +308,17 @@ pub enum SigHandler { /// Request that the signal be ignored. SigIgn, /// Use the given signal-catching function, which takes in the signal. - Handler(extern fn(libc::c_int)), + Handler(extern "C" fn(libc::c_int)), /// Use the given signal-catching function, which takes in the signal, information about how /// the signal was generated, and a pointer to the threads `ucontext_t`. - SigAction(extern fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void)) + SigAction(extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void)), } /// Action to take on receipt of a signal. Corresponds to `sigaction`. #[derive(Clone, Copy)] #[allow(missing_debug_implementations)] pub struct SigAction { - sigaction: libc::sigaction + sigaction: libc::sigaction, } impl SigAction { @@ -388,8 +332,11 @@ impl SigAction { s.sa_sigaction = match handler { SigHandler::SigDfl => libc::SIG_DFL, SigHandler::SigIgn => libc::SIG_IGN, - SigHandler::Handler(f) => f as *const extern fn(libc::c_int) as usize, - SigHandler::SigAction(f) => f as *const extern fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void) as usize, + SigHandler::Handler(f) => f as *const extern "C" fn(libc::c_int) as usize, + SigHandler::SigAction(f) => { + f as *const extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void) + as usize + } }; s.sa_flags = match handler { SigHandler::SigAction(_) => (flags | SaFlags::SA_SIGINFO).bits(), @@ -408,7 +355,9 @@ impl SigAction { /// Returns the set of signals that are blocked during execution of the action's /// signal-catching function. pub fn mask(&self) -> SigSet { - SigSet { sigset: self.sigaction.sa_mask } + SigSet { + sigset: self.sigaction.sa_mask, + } } /// Returns the action's handler. @@ -416,9 +365,10 @@ impl SigAction { match self.sigaction.sa_sigaction { libc::SIG_DFL => SigHandler::SigDfl, libc::SIG_IGN => SigHandler::SigIgn, - f if self.flags().contains(SaFlags::SA_SIGINFO) => - SigHandler::SigAction( unsafe { mem::transmute(f) } ), - f => SigHandler::Handler( unsafe { mem::transmute(f) } ), + f if self.flags().contains(SaFlags::SA_SIGINFO) => { + SigHandler::SigAction(unsafe { mem::transmute(f) }) + } + f => SigHandler::Handler(unsafe { mem::transmute(f) }), } } } @@ -436,8 +386,11 @@ impl SigAction { pub unsafe fn sigaction(signal: Signal, sigaction: &SigAction) -> Result { let mut oldact = mem::uninitialized::(); - let res = - libc::sigaction(signal as libc::c_int, &sigaction.sigaction as *const libc::sigaction, &mut oldact as *mut libc::sigaction); + let res = libc::sigaction( + signal as libc::c_int, + &sigaction.sigaction as *const libc::sigaction, + &mut oldact as *mut libc::sigaction, + ); Errno::result(res).map(|_| SigAction { sigaction: oldact }) } @@ -457,20 +410,26 @@ pub unsafe fn sigaction(signal: Signal, sigaction: &SigAction) -> Result, - oldset: Option<&mut SigSet>) -> Result<()> { +pub fn pthread_sigmask( + how: SigmaskHow, + set: Option<&SigSet>, + oldset: Option<&mut SigSet>, +) -> Result<()> { if set.is_none() && oldset.is_none() { - return Ok(()) + return Ok(()); } let res = unsafe { // if set or oldset is None, pass in null pointers instead - libc::pthread_sigmask(how as libc::c_int, - set.map_or_else(ptr::null::, - |s| &s.sigset as *const libc::sigset_t), - oldset.map_or_else(ptr::null_mut::, - |os| &mut os.sigset as *mut libc::sigset_t)) + libc::pthread_sigmask( + how as libc::c_int, + set.map_or_else(ptr::null::, |s| { + &s.sigset as *const libc::sigset_t + }), + oldset.map_or_else(ptr::null_mut::, |os| { + &mut os.sigset as *mut libc::sigset_t + }), + ) }; Errno::result(res).map(drop) @@ -480,29 +439,41 @@ pub fn pthread_sigmask(how: SigmaskHow, /// /// For more informations see the [`sigprocmask` man /// pages](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigprocmask.html). -pub fn sigprocmask(how: SigmaskHow, set: Option<&SigSet>, oldset: Option<&mut SigSet>) -> Result<()> { +pub fn sigprocmask( + how: SigmaskHow, + set: Option<&SigSet>, + oldset: Option<&mut SigSet>, +) -> Result<()> { if set.is_none() && oldset.is_none() { - return Ok(()) + return Ok(()); } let res = unsafe { // if set or oldset is None, pass in null pointers instead - libc::sigprocmask(how as libc::c_int, - set.map_or_else(ptr::null::, - |s| &s.sigset as *const libc::sigset_t), - oldset.map_or_else(ptr::null_mut::, - |os| &mut os.sigset as *mut libc::sigset_t)) + libc::sigprocmask( + how as libc::c_int, + set.map_or_else(ptr::null::, |s| { + &s.sigset as *const libc::sigset_t + }), + oldset.map_or_else(ptr::null_mut::, |os| { + &mut os.sigset as *mut libc::sigset_t + }), + ) }; Errno::result(res).map(drop) } pub fn kill>>(pid: ::unistd::Pid, signal: T) -> Result<()> { - let res = unsafe { libc::kill(pid.into(), - match signal.into() { - Some(s) => s as libc::c_int, - None => 0, - }) }; + let res = unsafe { + libc::kill( + pid.into(), + match signal.into() { + Some(s) => s as libc::c_int, + None => 0, + }, + ) + }; Errno::result(res).map(drop) } @@ -513,7 +484,6 @@ pub fn raise(signal: Signal) -> Result<()> { Errno::result(res).map(drop) } - #[cfg(target_os = "freebsd")] pub type type_of_thread_id = libc::lwpid_t; #[cfg(target_os = "linux")] @@ -531,7 +501,10 @@ pub enum SigevNotify { /// The signal given by `signal` will be delivered to the process. The /// value in `si_value` will be present in the `si_value` field of the /// `siginfo_t` structure of the queued signal. - SigevSignal { signal: Signal, si_value: libc::intptr_t }, + SigevSignal { + signal: Signal, + si_value: libc::intptr_t, + }, // Note: SIGEV_THREAD is not implemented because libc::sigevent does not // expose a way to set the union members needed by SIGEV_THREAD. /// A new `kevent` is posted to the kqueue `kq`. The `kevent`'s `udata` @@ -542,26 +515,29 @@ pub enum SigevNotify { /// `thread_id`. The value stored in `si_value` will be present in the /// `si_value` of the `siginfo_t` structure of the queued signal. #[cfg(any(target_os = "freebsd", target_os = "linux"))] - SigevThreadId { signal: Signal, thread_id: type_of_thread_id, - si_value: libc::intptr_t }, + SigevThreadId { + signal: Signal, + thread_id: type_of_thread_id, + si_value: libc::intptr_t, + }, } #[cfg(not(target_os = "openbsd"))] mod sigevent { + #[cfg(any(target_os = "freebsd", target_os = "linux"))] + use super::type_of_thread_id; + use super::SigevNotify; use libc; + use std::fmt::{self, Debug}; use std::mem; use std::ptr; - use std::fmt::{self, Debug}; - use super::SigevNotify; - #[cfg(any(target_os = "freebsd", target_os = "linux"))] - use super::type_of_thread_id; /// Used to request asynchronous notification of the completion of certain /// events, such as POSIX AIO and timers. #[repr(C)] #[derive(Clone, Copy)] pub struct SigEvent { - sigevent: libc::sigevent + sigevent: libc::sigevent, } impl SigEvent { @@ -579,50 +555,49 @@ mod sigevent { /// `SIGEV_SIGNAL`. That field is part of a union that shares space with the /// more genuinely useful `sigev_notify_thread_id` pub fn new(sigev_notify: SigevNotify) -> SigEvent { - let mut sev = unsafe { mem::zeroed::()}; + let mut sev = unsafe { mem::zeroed::() }; sev.sigev_notify = match sigev_notify { SigevNotify::SigevNone => libc::SIGEV_NONE, - SigevNotify::SigevSignal{..} => libc::SIGEV_SIGNAL, + SigevNotify::SigevSignal { .. } => libc::SIGEV_SIGNAL, #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - SigevNotify::SigevKevent{..} => libc::SIGEV_KEVENT, + SigevNotify::SigevKevent { .. } => libc::SIGEV_KEVENT, #[cfg(target_os = "freebsd")] - SigevNotify::SigevThreadId{..} => libc::SIGEV_THREAD_ID, + SigevNotify::SigevThreadId { .. } => libc::SIGEV_THREAD_ID, #[cfg(all(target_os = "linux", target_env = "gnu", not(target_arch = "mips")))] - SigevNotify::SigevThreadId{..} => libc::SIGEV_THREAD_ID, + SigevNotify::SigevThreadId { .. } => libc::SIGEV_THREAD_ID, #[cfg(any(all(target_os = "linux", target_env = "musl"), target_arch = "mips"))] - SigevNotify::SigevThreadId{..} => 4 // No SIGEV_THREAD_ID defined + SigevNotify::SigevThreadId { .. } => 4, // No SIGEV_THREAD_ID defined }; sev.sigev_signo = match sigev_notify { - SigevNotify::SigevSignal{ signal, .. } => signal as libc::c_int, + SigevNotify::SigevSignal { signal, .. } => signal as libc::c_int, #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - SigevNotify::SigevKevent{ kq, ..} => kq, + SigevNotify::SigevKevent { kq, .. } => kq, #[cfg(any(target_os = "linux", target_os = "freebsd"))] - SigevNotify::SigevThreadId{ signal, .. } => signal as libc::c_int, - _ => 0 + SigevNotify::SigevThreadId { signal, .. } => signal as libc::c_int, + _ => 0, }; sev.sigev_value.sival_ptr = match sigev_notify { SigevNotify::SigevNone => ptr::null_mut::(), - SigevNotify::SigevSignal{ si_value, .. } => si_value as *mut libc::c_void, + SigevNotify::SigevSignal { si_value, .. } => si_value as *mut libc::c_void, #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - SigevNotify::SigevKevent{ udata, .. } => udata as *mut libc::c_void, + SigevNotify::SigevKevent { udata, .. } => udata as *mut libc::c_void, #[cfg(any(target_os = "freebsd", target_os = "linux"))] - SigevNotify::SigevThreadId{ si_value, .. } => si_value as *mut libc::c_void, + SigevNotify::SigevThreadId { si_value, .. } => si_value as *mut libc::c_void, }; SigEvent::set_tid(&mut sev, &sigev_notify); - SigEvent{sigevent: sev} + SigEvent { sigevent: sev } } #[cfg(any(target_os = "freebsd", target_os = "linux"))] fn set_tid(sev: &mut libc::sigevent, sigev_notify: &SigevNotify) { sev.sigev_notify_thread_id = match *sigev_notify { SigevNotify::SigevThreadId { thread_id, .. } => thread_id, - _ => 0 as type_of_thread_id + _ => 0 as type_of_thread_id, }; } #[cfg(not(any(target_os = "freebsd", target_os = "linux")))] - fn set_tid(_sev: &mut libc::sigevent, _sigev_notify: &SigevNotify) { - } + fn set_tid(_sev: &mut libc::sigevent, _sigev_notify: &SigevNotify) {} pub fn sigevent(&self) -> libc::sigevent { self.sigevent @@ -636,8 +611,10 @@ mod sigevent { .field("sigev_notify", &self.sigevent.sigev_notify) .field("sigev_signo", &self.sigevent.sigev_signo) .field("sigev_value", &self.sigevent.sigev_value.sival_ptr) - .field("sigev_notify_thread_id", - &self.sigevent.sigev_notify_thread_id) + .field( + "sigev_notify_thread_id", + &self.sigevent.sigev_notify_thread_id, + ) .finish() } @@ -653,7 +630,9 @@ mod sigevent { impl<'a> From<&'a libc::sigevent> for SigEvent { fn from(sigevent: &libc::sigevent) -> Self { - SigEvent{ sigevent: *sigevent } + SigEvent { + sigevent: *sigevent, + } } } } @@ -716,7 +695,9 @@ mod tests { assert!(new_mask.contains(SIGUSR1)); assert!(!new_mask.contains(SIGUSR2)); - prev_mask.thread_set_mask().expect("Failed to revert signal mask!"); + prev_mask + .thread_set_mask() + .expect("Failed to revert signal mask!"); } #[test] @@ -762,9 +743,13 @@ mod tests { fn test_sigaction() { use libc; - extern fn test_sigaction_handler(_: libc::c_int) {} - extern fn test_sigaction_action(_: libc::c_int, - _: *mut libc::siginfo_t, _: *mut libc::c_void) {} + extern "C" fn test_sigaction_handler(_: libc::c_int) {} + extern "C" fn test_sigaction_action( + _: libc::c_int, + _: *mut libc::siginfo_t, + _: *mut libc::c_void, + ) { + } let handler_sig = SigHandler::Handler(test_sigaction_handler); @@ -775,7 +760,10 @@ mod tests { let action_sig = SigAction::new(handler_sig, flags, mask); - assert_eq!(action_sig.flags(), SaFlags::SA_ONSTACK | SaFlags::SA_RESTART); + assert_eq!( + action_sig.flags(), + SaFlags::SA_ONSTACK | SaFlags::SA_RESTART + ); assert_eq!(action_sig.handler(), handler_sig); mask = action_sig.mask(); diff --git a/src/sys/signalfd.rs b/src/sys/signalfd.rs index 52027d3611..bbb474531e 100644 --- a/src/sys/signalfd.rs +++ b/src/sys/signalfd.rs @@ -15,16 +15,15 @@ //! //! Please note that signal discarding is not specific to `signalfd`, but also happens with regular //! signal handlers. +use errno::Errno; use libc; +pub use libc::signalfd_siginfo as siginfo; +pub use sys::signal::{self, SigSet}; use unistd; use {Error, Result}; -use errno::Errno; -pub use sys::signal::{self, SigSet}; -pub use libc::signalfd_siginfo as siginfo; -use std::os::unix::io::{RawFd, AsRawFd}; use std::mem; - +use std::os::unix::io::{AsRawFd, RawFd}; libc_bitflags!{ pub struct SfdFlags: libc::c_int { @@ -49,7 +48,11 @@ pub const SIGNALFD_SIGINFO_SIZE: usize = 128; /// See [the signalfd man page for more information](http://man7.org/linux/man-pages/man2/signalfd.2.html) pub fn signalfd(fd: RawFd, mask: &SigSet, flags: SfdFlags) -> Result { unsafe { - Errno::result(libc::signalfd(fd as libc::c_int, mask.as_ref(), flags.bits())) + Errno::result(libc::signalfd( + fd as libc::c_int, + mask.as_ref(), + flags.bits(), + )) } } @@ -104,7 +107,7 @@ impl SignalFd { Ok(SIGNALFD_SIGINFO_SIZE) => Ok(Some(unsafe { mem::transmute(buffer) })), Ok(_) => unreachable!("partial read on signalfd"), Err(Error::Sys(Errno::EAGAIN)) => Ok(None), - Err(error) => Err(error) + Err(error) => Err(error), } } } @@ -132,17 +135,18 @@ impl Iterator for SignalFd { } } - #[cfg(test)] mod tests { use super::*; - use std::mem; use libc; - + use std::mem; #[test] fn check_siginfo_size() { - assert_eq!(mem::size_of::(), SIGNALFD_SIGINFO_SIZE); + assert_eq!( + mem::size_of::(), + SIGNALFD_SIGINFO_SIZE + ); } #[test] diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 93014f1cf0..f9434ea55f 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -1,26 +1,30 @@ +#[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] +pub use self::datalink::LinkAddr; use super::sa_family_t; -use {Error, Result, NixPath}; use errno::Errno; use libc; -use std::{fmt, hash, mem, net, ptr, slice}; use std::ffi::OsStr; -use std::path::Path; use std::os::unix::ffi::OsStrExt; -#[cfg(any(target_os = "android", target_os = "linux"))] -use ::sys::socket::addr::netlink::NetlinkAddr; #[cfg(any(target_os = "ios", target_os = "macos"))] use std::os::unix::io::RawFd; +use std::path::Path; +use std::{fmt, hash, mem, net, ptr, slice}; +#[cfg(any(target_os = "android", target_os = "linux"))] +use sys::socket::addr::netlink::NetlinkAddr; #[cfg(any(target_os = "ios", target_os = "macos"))] -use ::sys::socket::addr::sys_control::SysControlAddr; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] -pub use self::datalink::LinkAddr; +use sys::socket::addr::sys_control::SysControlAddr; +use {Error, NixPath, Result}; /// These constants specify the protocol family to be used /// in [`socket`](fn.socket.html) and [`socketpair`](fn.socketpair.html) @@ -113,101 +117,152 @@ pub enum AddressFamily { Nfc = libc::AF_NFC, #[cfg(target_os = "linux")] Vsock = libc::AF_VSOCK, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] ImpLink = libc::AF_IMPLINK, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Pup = libc::AF_PUP, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Chaos = libc::AF_CHAOS, - #[cfg(any(target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any(target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd") + )] Ns = libc::AF_NS, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Iso = libc::AF_ISO, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Datakit = libc::AF_DATAKIT, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Ccitt = libc::AF_CCITT, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Dli = libc::AF_DLI, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Lat = libc::AF_LAT, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Hylink = libc::AF_HYLINK, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Link = libc::AF_LINK, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Coip = libc::AF_COIP, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Cnt = libc::AF_CNT, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Natm = libc::AF_NATM, } @@ -228,14 +283,18 @@ impl AddressFamily { libc::AF_SYSTEM => Some(AddressFamily::System), #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_PACKET => Some(AddressFamily::Packet), - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] libc::AF_LINK => Some(AddressFamily::Link), - _ => None + _ => None, } } } @@ -252,19 +311,19 @@ impl InetAddr { net::SocketAddr::V4(ref addr) => { InetAddr::V4(libc::sockaddr_in { sin_family: AddressFamily::Inet as sa_family_t, - sin_port: addr.port().to_be(), // network byte order + sin_port: addr.port().to_be(), // network byte order sin_addr: Ipv4Addr::from_std(addr.ip()).0, - .. unsafe { mem::zeroed() } + ..unsafe { mem::zeroed() } }) } net::SocketAddr::V6(ref addr) => { InetAddr::V6(libc::sockaddr_in6 { sin6_family: AddressFamily::Inet6 as sa_family_t, - sin6_port: addr.port().to_be(), // network byte order + sin6_port: addr.port().to_be(), // network byte order sin6_addr: Ipv6Addr::from_std(addr.ip()).0, - sin6_flowinfo: addr.flowinfo(), // host byte order - sin6_scope_id: addr.scope_id(), // host byte order - .. unsafe { mem::zeroed() } + sin6_flowinfo: addr.flowinfo(), // host byte order + sin6_scope_id: addr.scope_id(), // host byte order + ..unsafe { mem::zeroed() } }) } } @@ -272,22 +331,18 @@ impl InetAddr { pub fn new(ip: IpAddr, port: u16) -> InetAddr { match ip { - IpAddr::V4(ref ip) => { - InetAddr::V4(libc::sockaddr_in { - sin_family: AddressFamily::Inet as sa_family_t, - sin_port: port.to_be(), - sin_addr: ip.0, - .. unsafe { mem::zeroed() } - }) - } - IpAddr::V6(ref ip) => { - InetAddr::V6(libc::sockaddr_in6 { - sin6_family: AddressFamily::Inet6 as sa_family_t, - sin6_port: port.to_be(), - sin6_addr: ip.0, - .. unsafe { mem::zeroed() } - }) - } + IpAddr::V4(ref ip) => InetAddr::V4(libc::sockaddr_in { + sin_family: AddressFamily::Inet as sa_family_t, + sin_port: port.to_be(), + sin_addr: ip.0, + ..unsafe { mem::zeroed() } + }), + IpAddr::V6(ref ip) => InetAddr::V6(libc::sockaddr_in6 { + sin6_family: AddressFamily::Inet6 as sa_family_t, + sin6_port: port.to_be(), + sin6_addr: ip.0, + ..unsafe { mem::zeroed() } + }), } } /// Gets the IP address associated with this socket address. @@ -308,16 +363,16 @@ impl InetAddr { pub fn to_std(&self) -> net::SocketAddr { match *self { - InetAddr::V4(ref sa) => net::SocketAddr::V4( - net::SocketAddrV4::new( - Ipv4Addr(sa.sin_addr).to_std(), - self.port())), - InetAddr::V6(ref sa) => net::SocketAddr::V6( - net::SocketAddrV6::new( - Ipv6Addr(sa.sin6_addr).to_std(), - self.port(), - sa.sin6_flowinfo, - sa.sin6_scope_id)), + InetAddr::V4(ref sa) => net::SocketAddr::V4(net::SocketAddrV4::new( + Ipv4Addr(sa.sin_addr).to_std(), + self.port(), + )), + InetAddr::V6(ref sa) => net::SocketAddr::V6(net::SocketAddrV6::new( + Ipv6Addr(sa.sin6_addr).to_std(), + self.port(), + sa.sin6_flowinfo, + sa.sin6_scope_id, + )), } } @@ -330,38 +385,32 @@ impl PartialEq for InetAddr { fn eq(&self, other: &InetAddr) -> bool { match (*self, *other) { (InetAddr::V4(ref a), InetAddr::V4(ref b)) => { - a.sin_port == b.sin_port && - a.sin_addr.s_addr == b.sin_addr.s_addr + a.sin_port == b.sin_port && a.sin_addr.s_addr == b.sin_addr.s_addr } (InetAddr::V6(ref a), InetAddr::V6(ref b)) => { - a.sin6_port == b.sin6_port && - a.sin6_addr.s6_addr == b.sin6_addr.s6_addr && - a.sin6_flowinfo == b.sin6_flowinfo && - a.sin6_scope_id == b.sin6_scope_id + a.sin6_port == b.sin6_port + && a.sin6_addr.s6_addr == b.sin6_addr.s6_addr + && a.sin6_flowinfo == b.sin6_flowinfo + && a.sin6_scope_id == b.sin6_scope_id } _ => false, } } } -impl Eq for InetAddr { -} +impl Eq for InetAddr {} impl hash::Hash for InetAddr { fn hash(&self, s: &mut H) { match *self { - InetAddr::V4(ref a) => { - ( a.sin_family, - a.sin_port, - a.sin_addr.s_addr ).hash(s) - } - InetAddr::V6(ref a) => { - ( a.sin6_family, - a.sin6_port, - &a.sin6_addr.s6_addr, - a.sin6_flowinfo, - a.sin6_scope_id ).hash(s) - } + InetAddr::V4(ref a) => (a.sin_family, a.sin_port, a.sin_addr.s_addr).hash(s), + InetAddr::V6(ref a) => ( + a.sin6_family, + a.sin6_port, + &a.sin6_addr.s6_addr, + a.sin6_flowinfo, + a.sin6_scope_id, + ).hash(s), } } } @@ -433,7 +482,7 @@ impl fmt::Display for IpAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { IpAddr::V4(ref v4) => v4.fmt(f), - IpAddr::V6(ref v6) => v6.fmt(f) + IpAddr::V6(ref v6) => v6.fmt(f), } } } @@ -455,10 +504,8 @@ pub struct Ipv4Addr(pub libc::in_addr); impl Ipv4Addr { pub fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr { - let ip = (((a as u32) << 24) | - ((b as u32) << 16) | - ((c as u32) << 8) | - ((d as u32) << 0)).to_be(); + let ip = (((a as u32) << 24) | ((b as u32) << 16) | ((c as u32) << 8) | ((d as u32) << 0)) + .to_be(); Ipv4Addr(libc::in_addr { s_addr: ip }) } @@ -469,12 +516,19 @@ impl Ipv4Addr { } pub fn any() -> Ipv4Addr { - Ipv4Addr(libc::in_addr { s_addr: libc::INADDR_ANY }) + Ipv4Addr(libc::in_addr { + s_addr: libc::INADDR_ANY, + }) } pub fn octets(&self) -> [u8; 4] { let bits = u32::from_be(self.0.s_addr); - [(bits >> 24) as u8, (bits >> 16) as u8, (bits >> 8) as u8, bits as u8] + [ + (bits >> 24) as u8, + (bits >> 16) as u8, + (bits >> 8) as u8, + bits as u8, + ] } pub fn to_std(&self) -> net::Ipv4Addr { @@ -489,8 +543,7 @@ impl PartialEq for Ipv4Addr { } } -impl Eq for Ipv4Addr { -} +impl Eq for Ipv4Addr {} impl hash::Hash for Ipv4Addr { fn hash(&self, s: &mut H) { @@ -507,7 +560,11 @@ impl Clone for Ipv4Addr { impl fmt::Display for Ipv4Addr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let octets = self.octets(); - write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]) + write!( + fmt, + "{}.{}.{}.{}", + octets[0], octets[1], octets[2], octets[3] + ) } } @@ -544,8 +601,8 @@ macro_rules! to_u16_array { impl Ipv6Addr { pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr { - let mut in6_addr_var: libc::in6_addr = unsafe{mem::uninitialized()}; - in6_addr_var.s6_addr = to_u8_array!(a,b,c,d,e,f,g,h); + let mut in6_addr_var: libc::in6_addr = unsafe { mem::uninitialized() }; + in6_addr_var.s6_addr = to_u8_array!(a, b, c, d, e, f, g, h); Ipv6Addr(in6_addr_var) } @@ -556,7 +613,7 @@ impl Ipv6Addr { /// Return the eight 16-bit segments that make up this address pub fn segments(&self) -> [u16; 8] { - to_u16_array!(self, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) + to_u16_array!(self, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) } pub fn to_std(&self) -> net::Ipv6Addr { @@ -597,25 +654,25 @@ pub struct UnixAddr(pub libc::sockaddr_un, pub usize); impl UnixAddr { /// Create a new sockaddr_un representing a filesystem path. pub fn new(path: &P) -> Result { - try!(path.with_nix_path(|cstr| { - unsafe { - let mut ret = libc::sockaddr_un { - sun_family: AddressFamily::Unix as sa_family_t, - .. mem::zeroed() - }; + try!(path.with_nix_path(|cstr| unsafe { + let mut ret = libc::sockaddr_un { + sun_family: AddressFamily::Unix as sa_family_t, + ..mem::zeroed() + }; - let bytes = cstr.to_bytes(); + let bytes = cstr.to_bytes(); - if bytes.len() > ret.sun_path.len() { - return Err(Error::Sys(Errno::ENAMETOOLONG)); - } + if bytes.len() > ret.sun_path.len() { + return Err(Error::Sys(Errno::ENAMETOOLONG)); + } - ptr::copy_nonoverlapping(bytes.as_ptr(), - ret.sun_path.as_mut_ptr() as *mut u8, - bytes.len()); + ptr::copy_nonoverlapping( + bytes.as_ptr(), + ret.sun_path.as_mut_ptr() as *mut u8, + bytes.len(), + ); - Ok(UnixAddr(ret, bytes.len())) - } + Ok(UnixAddr(ret, bytes.len())) })) } @@ -630,7 +687,7 @@ impl UnixAddr { unsafe { let mut ret = libc::sockaddr_un { sun_family: AddressFamily::Unix as sa_family_t, - .. mem::zeroed() + ..mem::zeroed() }; if path.len() + 1 > ret.sun_path.len() { @@ -639,9 +696,11 @@ impl UnixAddr { // Abstract addresses are represented by sun_path[0] == // b'\0', so copy starting one byte in. - ptr::copy_nonoverlapping(path.as_ptr(), - ret.sun_path.as_mut_ptr().offset(1) as *mut u8, - path.len()); + ptr::copy_nonoverlapping( + path.as_ptr(), + ret.sun_path.as_mut_ptr().offset(1) as *mut u8, + path.len(), + ); Ok(UnixAddr(ret, path.len() + 1)) } @@ -689,12 +748,11 @@ impl PartialEq for UnixAddr { } } -impl Eq for UnixAddr { -} +impl Eq for UnixAddr {} impl hash::Hash for UnixAddr { fn hash(&self, s: &mut H) { - ( self.0.sun_family, self.sun_path() ).hash(s) + (self.0.sun_family, self.sun_path()).hash(s) } } @@ -739,15 +797,19 @@ pub enum SockAddr { #[cfg(any(target_os = "ios", target_os = "macos"))] SysControl(SysControlAddr), /// Datalink address (MAC) - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] - Link(LinkAddr) + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] + Link(LinkAddr), } impl SockAddr { @@ -780,13 +842,17 @@ impl SockAddr { SockAddr::SysControl(..) => AddressFamily::System, #[cfg(any(target_os = "android", target_os = "linux"))] SockAddr::Link(..) => AddressFamily::Packet, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] - SockAddr::Link(..) => AddressFamily::Link + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] + SockAddr::Link(..) => AddressFamily::Link, } } @@ -804,25 +870,34 @@ impl SockAddr { } else { match AddressFamily::from_i32((*addr).sa_family as i32) { Some(AddressFamily::Unix) => None, - Some(AddressFamily::Inet) => Some(SockAddr::Inet( - InetAddr::V4(*(addr as *const libc::sockaddr_in)))), - Some(AddressFamily::Inet6) => Some(SockAddr::Inet( - InetAddr::V6(*(addr as *const libc::sockaddr_in6)))), + Some(AddressFamily::Inet) => Some(SockAddr::Inet(InetAddr::V4( + *(addr as *const libc::sockaddr_in), + ))), + Some(AddressFamily::Inet6) => Some(SockAddr::Inet(InetAddr::V6( + *(addr as *const libc::sockaddr_in6), + ))), #[cfg(any(target_os = "android", target_os = "linux"))] - Some(AddressFamily::Netlink) => Some(SockAddr::Netlink( - NetlinkAddr(*(addr as *const libc::sockaddr_nl)))), + Some(AddressFamily::Netlink) => Some(SockAddr::Netlink(NetlinkAddr( + *(addr as *const libc::sockaddr_nl), + ))), #[cfg(any(target_os = "ios", target_os = "macos"))] - Some(AddressFamily::System) => Some(SockAddr::SysControl( - SysControlAddr(*(addr as *const libc::sockaddr_ctl)))), + Some(AddressFamily::System) => Some(SockAddr::SysControl(SysControlAddr( + *(addr as *const libc::sockaddr_ctl), + ))), #[cfg(any(target_os = "android", target_os = "linux"))] - Some(AddressFamily::Packet) => Some(SockAddr::Link( - LinkAddr(*(addr as *const libc::sockaddr_ll)))), - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + Some(AddressFamily::Packet) => Some(SockAddr::Link(LinkAddr( + *(addr as *const libc::sockaddr_ll), + ))), + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] Some(AddressFamily::Link) => { let ether_addr = LinkAddr(*(addr as *const libc::sockaddr_dl)); if ether_addr.is_empty() { @@ -830,7 +905,7 @@ impl SockAddr { } else { Some(SockAddr::Link(ether_addr)) } - }, + } // Other address families are currently not supported and simply yield a None // entry instead of a proper conversion to a `SockAddr`. Some(_) | None => None, @@ -847,22 +922,47 @@ impl SockAddr { /// a sockaddr * need to take the size of the underlying type as well and then internally cast it back. pub unsafe fn as_ffi_pair(&self) -> (&libc::sockaddr, libc::socklen_t) { match *self { - SockAddr::Inet(InetAddr::V4(ref addr)) => (mem::transmute(addr), mem::size_of::() as libc::socklen_t), - SockAddr::Inet(InetAddr::V6(ref addr)) => (mem::transmute(addr), mem::size_of::() as libc::socklen_t), - SockAddr::Unix(UnixAddr(ref addr, len)) => (mem::transmute(addr), (len + offset_of!(libc::sockaddr_un, sun_path)) as libc::socklen_t), + SockAddr::Inet(InetAddr::V4(ref addr)) => ( + mem::transmute(addr), + mem::size_of::() as libc::socklen_t, + ), + SockAddr::Inet(InetAddr::V6(ref addr)) => ( + mem::transmute(addr), + mem::size_of::() as libc::socklen_t, + ), + SockAddr::Unix(UnixAddr(ref addr, len)) => ( + mem::transmute(addr), + (len + offset_of!(libc::sockaddr_un, sun_path)) as libc::socklen_t, + ), #[cfg(any(target_os = "android", target_os = "linux"))] - SockAddr::Netlink(NetlinkAddr(ref sa)) => (mem::transmute(sa), mem::size_of::() as libc::socklen_t), + SockAddr::Netlink(NetlinkAddr(ref sa)) => ( + mem::transmute(sa), + mem::size_of::() as libc::socklen_t, + ), #[cfg(any(target_os = "ios", target_os = "macos"))] - SockAddr::SysControl(SysControlAddr(ref sa)) => (mem::transmute(sa), mem::size_of::() as libc::socklen_t), + SockAddr::SysControl(SysControlAddr(ref sa)) => ( + mem::transmute(sa), + mem::size_of::() as libc::socklen_t, + ), #[cfg(any(target_os = "android", target_os = "linux"))] - SockAddr::Link(LinkAddr(ref ether_addr)) => (mem::transmute(ether_addr), mem::size_of::() as libc::socklen_t), - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] - SockAddr::Link(LinkAddr(ref ether_addr)) => (mem::transmute(ether_addr), mem::size_of::() as libc::socklen_t), + SockAddr::Link(LinkAddr(ref ether_addr)) => ( + mem::transmute(ether_addr), + mem::size_of::() as libc::socklen_t, + ), + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] + SockAddr::Link(LinkAddr(ref ether_addr)) => ( + mem::transmute(ether_addr), + mem::size_of::() as libc::socklen_t, + ), } } } @@ -870,34 +970,29 @@ impl SockAddr { impl PartialEq for SockAddr { fn eq(&self, other: &SockAddr) -> bool { match (*self, *other) { - (SockAddr::Inet(ref a), SockAddr::Inet(ref b)) => { - a == b - } - (SockAddr::Unix(ref a), SockAddr::Unix(ref b)) => { - a == b - } + (SockAddr::Inet(ref a), SockAddr::Inet(ref b)) => a == b, + (SockAddr::Unix(ref a), SockAddr::Unix(ref b)) => a == b, #[cfg(any(target_os = "android", target_os = "linux"))] - (SockAddr::Netlink(ref a), SockAddr::Netlink(ref b)) => { - a == b - } - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] - (SockAddr::Link(ref a), SockAddr::Link(ref b)) => { - a == b - } + (SockAddr::Netlink(ref a), SockAddr::Netlink(ref b)) => a == b, + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] + (SockAddr::Link(ref a), SockAddr::Link(ref b)) => a == b, _ => false, } } } -impl Eq for SockAddr { -} +impl Eq for SockAddr {} impl hash::Hash for SockAddr { fn hash(&self, s: &mut H) { @@ -908,15 +1003,19 @@ impl hash::Hash for SockAddr { SockAddr::Netlink(ref a) => a.hash(s), #[cfg(any(target_os = "ios", target_os = "macos"))] SockAddr::SysControl(ref a) => a.hash(s), - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] - SockAddr::Link(ref ether_addr) => ether_addr.hash(s) + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] + SockAddr::Link(ref ether_addr) => ether_addr.hash(s), } } } @@ -936,25 +1035,29 @@ impl fmt::Display for SockAddr { SockAddr::Netlink(ref nl) => nl.fmt(f), #[cfg(any(target_os = "ios", target_os = "macos"))] SockAddr::SysControl(ref sc) => sc.fmt(f), - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] - SockAddr::Link(ref ether_addr) => ether_addr.fmt(f) + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] + SockAddr::Link(ref ether_addr) => ether_addr.fmt(f), } } } #[cfg(any(target_os = "android", target_os = "linux"))] pub mod netlink { - use ::sys::socket::addr::AddressFamily; use libc::{sa_family_t, sockaddr_nl}; - use std::{fmt, mem}; use std::hash::{Hash, Hasher}; + use std::{fmt, mem}; + use sys::socket::addr::AddressFamily; #[derive(Copy, Clone)] pub struct NetlinkAddr(pub sockaddr_nl); @@ -963,8 +1066,8 @@ pub mod netlink { impl PartialEq for NetlinkAddr { fn eq(&self, other: &Self) -> bool { let (inner, other) = (self.0, other.0); - (inner.nl_family, inner.nl_pid, inner.nl_groups) == - (other.nl_family, other.nl_pid, other.nl_groups) + (inner.nl_family, inner.nl_pid, inner.nl_groups) + == (other.nl_family, other.nl_pid, other.nl_groups) } } @@ -977,7 +1080,6 @@ pub mod netlink { } } - impl NetlinkAddr { pub fn new(pid: u32, groups: u32) -> NetlinkAddr { let mut addr: sockaddr_nl = unsafe { mem::zeroed() }; @@ -1012,11 +1114,11 @@ pub mod netlink { #[cfg(any(target_os = "ios", target_os = "macos"))] pub mod sys_control { - use ::sys::socket::addr::AddressFamily; use libc::{self, c_uchar, uint16_t, uint32_t}; - use std::{fmt, mem}; use std::hash::{Hash, Hasher}; use std::os::unix::io::RawFd; + use std::{fmt, mem}; + use sys::socket::addr::AddressFamily; use {Errno, Error, Result}; #[repr(C)] @@ -1038,8 +1140,7 @@ pub mod sys_control { impl PartialEq for SysControlAddr { fn eq(&self, other: &Self) -> bool { let (inner, other) = (self.0, other.0); - (inner.sc_id, inner.sc_unit) == - (other.sc_id, other.sc_unit) + (inner.sc_id, inner.sc_unit) == (other.sc_id, other.sc_unit) } } @@ -1052,7 +1153,6 @@ pub mod sys_control { } } - impl SysControlAddr { pub fn new(id: u32, unit: u32) -> SysControlAddr { let addr = libc::sockaddr_ctl { @@ -1061,7 +1161,7 @@ pub mod sys_control { ss_sysaddr: libc::AF_SYS_CONTROL as uint16_t, sc_id: id, sc_unit: unit, - sc_reserved: [0; 5] + sc_reserved: [0; 5], }; SysControlAddr(addr) @@ -1074,9 +1174,14 @@ pub mod sys_control { let mut ctl_name = [0; MAX_KCTL_NAME]; ctl_name[..name.len()].clone_from_slice(name.as_bytes()); - let mut info = ctl_ioc_info { ctl_id: 0, ctl_name: ctl_name }; + let mut info = ctl_ioc_info { + ctl_id: 0, + ctl_name: ctl_name, + }; - unsafe { try!(ctl_info(sockfd, &mut info)); } + unsafe { + try!(ctl_info(sockfd, &mut info)); + } Ok(SysControlAddr::new(info.ctl_id, unit)) } @@ -1109,10 +1214,9 @@ pub mod sys_control { } } - #[cfg(any(target_os = "android", target_os = "linux"))] mod datalink { - use super::{libc, hash, fmt, AddressFamily}; + use super::{fmt, hash, libc, AddressFamily}; /// Hardware Address #[derive(Clone, Copy)] @@ -1168,31 +1272,50 @@ mod datalink { impl PartialEq for LinkAddr { fn eq(&self, other: &Self) -> bool { let (a, b) = (self.0, other.0); - (a.sll_family, a.sll_protocol, a.sll_ifindex, a.sll_hatype, - a.sll_pkttype, a.sll_halen, a.sll_addr) == - (b.sll_family, b.sll_protocol, b.sll_ifindex, b.sll_hatype, - b.sll_pkttype, b.sll_halen, b.sll_addr) + ( + a.sll_family, + a.sll_protocol, + a.sll_ifindex, + a.sll_hatype, + a.sll_pkttype, + a.sll_halen, + a.sll_addr, + ) + == ( + b.sll_family, + b.sll_protocol, + b.sll_ifindex, + b.sll_hatype, + b.sll_pkttype, + b.sll_halen, + b.sll_addr, + ) } } impl hash::Hash for LinkAddr { fn hash(&self, s: &mut H) { let a = self.0; - (a.sll_family, a.sll_protocol, a.sll_ifindex, a.sll_hatype, - a.sll_pkttype, a.sll_halen, a.sll_addr).hash(s); + ( + a.sll_family, + a.sll_protocol, + a.sll_ifindex, + a.sll_hatype, + a.sll_pkttype, + a.sll_halen, + a.sll_addr, + ).hash(s); } } impl fmt::Display for LinkAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let addr = self.addr(); - write!(f, "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", - addr[0], - addr[1], - addr[2], - addr[3], - addr[4], - addr[5]) + write!( + f, + "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", + addr[0], addr[1], addr[2], addr[3], addr[4], addr[5] + ) } } @@ -1203,14 +1326,18 @@ mod datalink { } } -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] mod datalink { - use super::{libc, hash, fmt, AddressFamily}; + use super::{fmt, hash, libc, AddressFamily}; /// Hardware Address #[derive(Clone, Copy)] @@ -1288,59 +1415,119 @@ mod datalink { impl Eq for LinkAddr {} impl PartialEq for LinkAddr { - #[cfg(any(target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] fn eq(&self, other: &Self) -> bool { let (a, b) = (self.0, other.0); - (a.sdl_len, a.sdl_family, a.sdl_index, a.sdl_type, - a.sdl_nlen, a.sdl_alen, a.sdl_slen, &a.sdl_data[..]) == - (b.sdl_len, b.sdl_family, b.sdl_index, b.sdl_type, - b.sdl_nlen, b.sdl_alen, b.sdl_slen, &b.sdl_data[..]) + ( + a.sdl_len, + a.sdl_family, + a.sdl_index, + a.sdl_type, + a.sdl_nlen, + a.sdl_alen, + a.sdl_slen, + &a.sdl_data[..], + ) + == ( + b.sdl_len, + b.sdl_family, + b.sdl_index, + b.sdl_type, + b.sdl_nlen, + b.sdl_alen, + b.sdl_slen, + &b.sdl_data[..], + ) } #[cfg(target_os = "dragonfly")] fn eq(&self, other: &Self) -> bool { let (a, b) = (self.0, other.0); - (a.sdl_len, a.sdl_family, a.sdl_index, a.sdl_type, a.sdl_nlen, - a.sdl_alen, a.sdl_slen, a.sdl_data, a.sdl_rcf, a.sdl_route) == - (b.sdl_len, b.sdl_family, b.sdl_index, b.sdl_type, b.sdl_nlen, - b.sdl_alen, b.sdl_slen, b.sdl_data, b.sdl_rcf, b.sdl_route) + ( + a.sdl_len, + a.sdl_family, + a.sdl_index, + a.sdl_type, + a.sdl_nlen, + a.sdl_alen, + a.sdl_slen, + a.sdl_data, + a.sdl_rcf, + a.sdl_route, + ) + == ( + b.sdl_len, + b.sdl_family, + b.sdl_index, + b.sdl_type, + b.sdl_nlen, + b.sdl_alen, + b.sdl_slen, + b.sdl_data, + b.sdl_rcf, + b.sdl_route, + ) } } impl hash::Hash for LinkAddr { - #[cfg(any(target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] fn hash(&self, s: &mut H) { let a = self.0; - (a.sdl_len, a.sdl_family, a.sdl_index, a.sdl_type, - a.sdl_nlen, a.sdl_alen, a.sdl_slen, &a.sdl_data[..]).hash(s); + ( + a.sdl_len, + a.sdl_family, + a.sdl_index, + a.sdl_type, + a.sdl_nlen, + a.sdl_alen, + a.sdl_slen, + &a.sdl_data[..], + ).hash(s); } #[cfg(target_os = "dragonfly")] fn hash(&self, s: &mut H) { let a = self.0; - (a.sdl_len, a.sdl_family, a.sdl_index, a.sdl_type, a.sdl_nlen, - a.sdl_alen, a.sdl_slen, a.sdl_data, a.sdl_rcf, a.sdl_route).hash(s); + ( + a.sdl_len, + a.sdl_family, + a.sdl_index, + a.sdl_type, + a.sdl_nlen, + a.sdl_alen, + a.sdl_slen, + a.sdl_data, + a.sdl_rcf, + a.sdl_route, + ).hash(s); } } impl fmt::Display for LinkAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let addr = self.addr(); - write!(f, "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", - addr[0], - addr[1], - addr[2], - addr[3], - addr[4], - addr[5]) + write!( + f, + "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", + addr[0], addr[1], addr[2], addr[3], addr[4], addr[5] + ) } } @@ -1353,20 +1540,28 @@ mod datalink { #[cfg(test)] mod tests { - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] use super::*; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] #[test] fn test_macos_loopback_datalink_addr() { let bytes = [20i8, 18, 1, 0, 24, 3, 0, 0, 108, 111, 48, 0, 0, 0, 0, 0]; @@ -1375,15 +1570,21 @@ mod tests { assert!(_sock_addr.is_none()); } - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] #[test] fn test_macos_tap_datalink_addr() { - let bytes = [20i8, 18, 7, 0, 6, 3, 6, 0, 101, 110, 48, 24, 101, -112, -35, 76, -80]; + let bytes = [ + 20i8, 18, 7, 0, 6, 3, 6, 0, 101, 110, 48, 24, 101, -112, -35, 76, -80, + ]; let ptr = bytes.as_ptr(); let sa = ptr as *const libc::sockaddr; let _sock_addr = unsafe { SockAddr::from_libc_sockaddr(sa) }; @@ -1397,8 +1598,8 @@ mod tests { match sock_addr { SockAddr::Link(ether_addr) => { assert_eq!(ether_addr.addr(), [24u8, 101, 144, 221, 76, 176]); - }, - _ => { unreachable!() } + } + _ => unreachable!(), }; } } diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index ecef05d8d6..bbb3b95fdc 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1,13 +1,13 @@ //! Socket interface functions //! //! [Further reading](http://man7.org/linux/man-pages/man7/socket.7.html) -use {Error, Result}; use errno::Errno; -use libc::{self, c_void, c_int, socklen_t, size_t}; -use std::{fmt, mem, ptr, slice}; +use libc::{self, c_int, c_void, size_t, socklen_t}; use std::os::unix::io::RawFd; +use std::{fmt, mem, ptr, slice}; use sys::time::TimeVal; use sys::uio::IoVec; +use {Error, Result}; mod addr; pub mod sockopt; @@ -19,26 +19,13 @@ pub mod sockopt; */ pub use self::addr::{ - AddressFamily, - SockAddr, - InetAddr, - UnixAddr, - IpAddr, - Ipv4Addr, - Ipv6Addr, - LinkAddr, + AddressFamily, InetAddr, IpAddr, Ipv4Addr, Ipv6Addr, LinkAddr, SockAddr, UnixAddr, }; #[cfg(any(target_os = "linux", target_os = "android"))] -pub use ::sys::socket::addr::netlink::NetlinkAddr; +pub use sys::socket::addr::netlink::NetlinkAddr; pub use libc::{ - cmsghdr, - msghdr, - sa_family_t, - sockaddr, - sockaddr_in, - sockaddr_in6, - sockaddr_storage, + cmsghdr, msghdr, sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_storage, sockaddr_un, }; @@ -272,8 +259,8 @@ impl Ipv6MembershipRequest { impl PartialEq for Ipv6MembershipRequest { fn eq(&self, other: &Self) -> bool { - self.0.ipv6mr_multiaddr.s6_addr == other.0.ipv6mr_multiaddr.s6_addr && - self.0.ipv6mr_interface == other.0.ipv6mr_interface + self.0.ipv6mr_multiaddr.s6_addr == other.0.ipv6mr_multiaddr.s6_addr + && self.0.ipv6mr_interface == other.0.ipv6mr_interface } } impl Eq for Ipv6MembershipRequest {} @@ -303,7 +290,7 @@ unsafe fn copy_bytes<'a, T: ?Sized>(src: &T, dst: &'a mut [u8]) -> &'a mut [u8] ptr::copy_nonoverlapping( src as *const T as *const u8, dst[..srclen].as_mut_ptr(), - srclen + srclen, ); &mut dst[srclen..] @@ -374,7 +361,7 @@ impl<'a> RecvMsg<'a> { pub fn cmsgs(&self) -> CmsgIterator { CmsgIterator { buf: self.cmsg_buffer, - next: 0 + next: 0, } } } @@ -424,21 +411,22 @@ impl<'a> Iterator for CmsgIterator<'a> { match (cmsg.cmsg_level, cmsg.cmsg_type) { (libc::SOL_SOCKET, libc::SCM_RIGHTS) => unsafe { - Some(ControlMessage::ScmRights( - slice::from_raw_parts(cmsg_data.as_ptr() as *const _, - cmsg_data.len() / mem::size_of::()))) + Some(ControlMessage::ScmRights(slice::from_raw_parts( + cmsg_data.as_ptr() as *const _, + cmsg_data.len() / mem::size_of::(), + ))) }, (libc::SOL_SOCKET, libc::SCM_TIMESTAMP) => unsafe { Some(ControlMessage::ScmTimestamp( - &*(cmsg_data.as_ptr() as *const _))) + &*(cmsg_data.as_ptr() as *const _), + )) }, (_, _) => unsafe { Some(ControlMessage::Unknown(UnknownCmsg( cmsg, - slice::from_raw_parts( - cmsg_data.as_ptr() as *const _, - len)))) - } + slice::from_raw_parts(cmsg_data.as_ptr() as *const _, len), + ))) + }, } } } @@ -555,15 +543,9 @@ impl<'a> ControlMessage<'a> { /// The value of CMSG_LEN on this message. fn len(&self) -> usize { cmsg_align(mem::size_of::()) + match *self { - ControlMessage::ScmRights(fds) => { - mem::size_of_val(fds) - }, - ControlMessage::ScmTimestamp(t) => { - mem::size_of_val(t) - }, - ControlMessage::Unknown(UnknownCmsg(_, bytes)) => { - mem::size_of_val(bytes) - } + ControlMessage::ScmRights(fds) => mem::size_of_val(fds), + ControlMessage::ScmTimestamp(t) => mem::size_of_val(t), + ControlMessage::Unknown(UnknownCmsg(_, bytes)) => mem::size_of_val(bytes), } } @@ -580,15 +562,14 @@ impl<'a> ControlMessage<'a> { }; let buf = copy_bytes(&cmsg, buf); - let padlen = cmsg_align(mem::size_of_val(&cmsg)) - - mem::size_of_val(&cmsg); + let padlen = cmsg_align(mem::size_of_val(&cmsg)) - mem::size_of_val(&cmsg); let buf = pad_bytes(padlen, buf); let buf = copy_bytes(fds, buf); let padlen = self.space() - self.len(); pad_bytes(padlen, buf); - }, + } ControlMessage::ScmTimestamp(t) => { let cmsg = cmsghdr { cmsg_len: self.len() as _, @@ -598,20 +579,19 @@ impl<'a> ControlMessage<'a> { }; let buf = copy_bytes(&cmsg, buf); - let padlen = cmsg_align(mem::size_of_val(&cmsg)) - - mem::size_of_val(&cmsg); + let padlen = cmsg_align(mem::size_of_val(&cmsg)) - mem::size_of_val(&cmsg); let buf = pad_bytes(padlen, buf); let buf = copy_bytes(t, buf); let padlen = self.space() - self.len(); pad_bytes(padlen, buf); - }, + } ControlMessage::Unknown(UnknownCmsg(orig_cmsg, bytes)) => { let buf = copy_bytes(orig_cmsg, buf); - let padlen = cmsg_align(mem::size_of_val(&orig_cmsg)) - - mem::size_of_val(&orig_cmsg); + let padlen = + cmsg_align(mem::size_of_val(&orig_cmsg)) - mem::size_of_val(&orig_cmsg); let buf = pad_bytes(padlen, buf); let buf = copy_bytes(bytes, buf); @@ -623,13 +603,18 @@ impl<'a> ControlMessage<'a> { } } - /// Send data in scatter-gather vectors to a socket, possibly accompanied /// by ancillary data. Optionally direct the message at the given address, /// as with sendto. /// /// Allocates if cmsgs is nonempty. -pub fn sendmsg<'a>(fd: RawFd, iov: &[IoVec<&'a [u8]>], cmsgs: &[ControlMessage<'a>], flags: MsgFlags, addr: Option<&'a SockAddr>) -> Result { +pub fn sendmsg<'a>( + fd: RawFd, + iov: &[IoVec<&'a [u8]>], + cmsgs: &[ControlMessage<'a>], + flags: MsgFlags, + addr: Option<&'a SockAddr>, +) -> Result { let mut capacity = 0; for cmsg in cmsgs { capacity += cmsg.space(); @@ -653,7 +638,10 @@ pub fn sendmsg<'a>(fd: RawFd, iov: &[IoVec<&'a [u8]>], cmsgs: &[ControlMessage<' } let (name, namelen) = match addr { - Some(addr) => { let (x, y) = unsafe { addr.as_ffi_pair() }; (x as *const _, y) } + Some(addr) => { + let (x, y) = unsafe { addr.as_ffi_pair() }; + (x as *const _, y) + } None => (ptr::null(), 0), }; @@ -665,13 +653,13 @@ pub fn sendmsg<'a>(fd: RawFd, iov: &[IoVec<&'a [u8]>], cmsgs: &[ControlMessage<' let mhdr = unsafe { let mut mhdr: msghdr = mem::uninitialized(); - mhdr.msg_name = name as *mut _; - mhdr.msg_namelen = namelen; - mhdr.msg_iov = iov.as_ptr() as *mut _; - mhdr.msg_iovlen = iov.len() as _; - mhdr.msg_control = cmsg_ptr as *mut _; - mhdr.msg_controllen = capacity as _; - mhdr.msg_flags = 0; + mhdr.msg_name = name as *mut _; + mhdr.msg_namelen = namelen; + mhdr.msg_iov = iov.as_ptr() as *mut _; + mhdr.msg_iovlen = iov.len() as _; + mhdr.msg_control = cmsg_ptr as *mut _; + mhdr.msg_controllen = capacity as _; + mhdr.msg_flags = 0; mhdr }; let ret = unsafe { libc::sendmsg(fd, &mhdr, flags.bits()) }; @@ -682,7 +670,12 @@ pub fn sendmsg<'a>(fd: RawFd, iov: &[IoVec<&'a [u8]>], cmsgs: &[ControlMessage<' /// Receive message in scatter-gather vectors from a socket, and /// optionally receive ancillary data into the provided buffer. /// If no ancillary data is desired, use () as the type parameter. -pub fn recvmsg<'a, T>(fd: RawFd, iov: &[IoVec<&mut [u8]>], cmsg_buffer: Option<&'a mut CmsgSpace>, flags: MsgFlags) -> Result> { +pub fn recvmsg<'a, T>( + fd: RawFd, + iov: &[IoVec<&mut [u8]>], + cmsg_buffer: Option<&'a mut CmsgSpace>, + flags: MsgFlags, +) -> Result> { let mut address: sockaddr_storage = unsafe { mem::uninitialized() }; let (msg_control, msg_controllen) = match cmsg_buffer { Some(cmsg_buffer) => (cmsg_buffer as *mut _, mem::size_of_val(cmsg_buffer)), @@ -690,13 +683,13 @@ pub fn recvmsg<'a, T>(fd: RawFd, iov: &[IoVec<&mut [u8]>], cmsg_buffer: Option<& }; let mut mhdr = unsafe { let mut mhdr: msghdr = mem::uninitialized(); - mhdr.msg_name = &mut address as *mut _ as *mut _; - mhdr.msg_namelen = mem::size_of::() as socklen_t; - mhdr.msg_iov = iov.as_ptr() as *mut _; - mhdr.msg_iovlen = iov.len() as _; - mhdr.msg_control = msg_control as *mut _; - mhdr.msg_controllen = msg_controllen as _; - mhdr.msg_flags = 0; + mhdr.msg_name = &mut address as *mut _ as *mut _; + mhdr.msg_namelen = mem::size_of::() as socklen_t; + mhdr.msg_iov = iov.as_ptr() as *mut _; + mhdr.msg_iovlen = iov.len() as _; + mhdr.msg_control = msg_control as *mut _; + mhdr.msg_controllen = msg_controllen as _; + mhdr.msg_flags = 0; mhdr }; let ret = unsafe { libc::recvmsg(fd, &mut mhdr, flags.bits()) }; @@ -707,24 +700,23 @@ pub fn recvmsg<'a, T>(fd: RawFd, iov: &[IoVec<&mut [u8]>], cmsg_buffer: Option<& unsafe { // Safe: The pointer is not null and the length is correct as part of `recvmsg`s // contract. - slice::from_raw_parts(mhdr.msg_control as *const u8, - mhdr.msg_controllen as usize) + slice::from_raw_parts(mhdr.msg_control as *const u8, mhdr.msg_controllen as usize) } } else { // No control message, create an empty buffer to avoid creating a slice from a null pointer &[] }; - Ok(unsafe { RecvMsg { - bytes: try!(Errno::result(ret)) as usize, - cmsg_buffer, - address: sockaddr_storage_to_addr(&address, - mhdr.msg_namelen as usize).ok(), - flags: MsgFlags::from_bits_truncate(mhdr.msg_flags), - } }) + Ok(unsafe { + RecvMsg { + bytes: try!(Errno::result(ret)) as usize, + cmsg_buffer, + address: sockaddr_storage_to_addr(&address, mhdr.msg_namelen as usize).ok(), + flags: MsgFlags::from_bits_truncate(mhdr.msg_flags), + } + }) } - /// Create an endpoint for communication /// /// The `protocol` specifies a particular protocol to be used with the @@ -735,7 +727,12 @@ pub fn recvmsg<'a, T>(fd: RawFd, iov: &[IoVec<&mut [u8]>], cmsg_buffer: Option<& /// specified in this manner. /// /// [Further reading](http://pubs.opengroup.org/onlinepubs/9699919799/functions/socket.html) -pub fn socket>>(domain: AddressFamily, ty: SockType, flags: SockFlag, protocol: T) -> Result { +pub fn socket>>( + domain: AddressFamily, + ty: SockType, + flags: SockFlag, + protocol: T, +) -> Result { let protocol = match protocol.into() { None => 0, Some(p) => p as c_int, @@ -755,8 +752,12 @@ pub fn socket>>(domain: AddressFamily, ty: SockType /// Create a pair of connected sockets /// /// [Further reading](http://pubs.opengroup.org/onlinepubs/9699919799/functions/socketpair.html) -pub fn socketpair>>(domain: AddressFamily, ty: SockType, protocol: T, - flags: SockFlag) -> Result<(RawFd, RawFd)> { +pub fn socketpair>>( + domain: AddressFamily, + ty: SockType, + protocol: T, + flags: SockFlag, +) -> Result<(RawFd, RawFd)> { let protocol = match protocol.into() { None => 0, Some(p) => p as c_int, @@ -809,10 +810,9 @@ pub fn accept(sockfd: RawFd) -> Result { /// Accept a connection on a socket /// /// [Further reading](http://man7.org/linux/man-pages/man2/accept.2.html) -#[cfg(any(target_os = "android", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg( + any(target_os = "android", target_os = "freebsd", target_os = "linux", target_os = "openbsd") +)] pub fn accept4(sockfd: RawFd, flags: SockFlag) -> Result { let res = unsafe { libc::accept4(sockfd, ptr::null_mut(), ptr::null_mut(), flags.bits()) }; @@ -841,7 +841,8 @@ pub fn recv(sockfd: RawFd, buf: &mut [u8], flags: MsgFlags) -> Result { sockfd, buf.as_ptr() as *mut c_void, buf.len() as size_t, - flags.bits()); + flags.bits(), + ); Errno::result(ret).map(|r| r as usize) } @@ -862,10 +863,10 @@ pub fn recvfrom(sockfd: RawFd, buf: &mut [u8]) -> Result<(usize, SockAddr)> { buf.len() as size_t, 0, mem::transmute(&addr), - &mut len as *mut socklen_t))); + &mut len as *mut socklen_t + ))); - sockaddr_storage_to_addr(&addr, len as usize) - .map(|addr| (ret as usize, addr)) + sockaddr_storage_to_addr(&addr, len as usize).map(|addr| (ret as usize, addr)) } } @@ -875,7 +876,14 @@ pub fn recvfrom(sockfd: RawFd, buf: &mut [u8]) -> Result<(usize, SockAddr)> { pub fn sendto(fd: RawFd, buf: &[u8], addr: &SockAddr, flags: MsgFlags) -> Result { let ret = unsafe { let (ptr, len) = addr.as_ffi_pair(); - libc::sendto(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, flags.bits(), ptr, len) + libc::sendto( + fd, + buf.as_ptr() as *const c_void, + buf.len() as size_t, + flags.bits(), + ptr, + len, + ) }; Errno::result(ret).map(|r| r as usize) @@ -886,7 +894,12 @@ pub fn sendto(fd: RawFd, buf: &[u8], addr: &SockAddr, flags: MsgFlags) -> Result /// [Further reading](http://pubs.opengroup.org/onlinepubs/9699919799/functions/send.html) pub fn send(fd: RawFd, buf: &[u8], flags: MsgFlags) -> Result { let ret = unsafe { - libc::send(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, flags.bits()) + libc::send( + fd, + buf.as_ptr() as *const c_void, + buf.len() as size_t, + flags.bits(), + ) }; Errno::result(ret).map(|r| r as usize) @@ -916,7 +929,7 @@ pub enum SockLevel { /// Represents a socket option that can be accessed or set. Used as an argument /// to `getsockopt` -pub trait GetSockOpt : Copy { +pub trait GetSockOpt: Copy { type Val; #[doc(hidden)] @@ -925,7 +938,7 @@ pub trait GetSockOpt : Copy { /// Represents a socket option that can be accessed or set. Used as an argument /// to `setsockopt` -pub trait SetSockOpt : Copy { +pub trait SetSockOpt: Copy { type Val; #[doc(hidden)] @@ -984,10 +997,7 @@ pub fn getsockname(fd: RawFd) -> Result { /// allocated and valid. It must be at least as large as all the useful parts /// of the structure. Note that in the case of a `sockaddr_un`, `len` need not /// include the terminating null. -pub unsafe fn sockaddr_storage_to_addr( - addr: &sockaddr_storage, - len: usize) -> Result { - +pub unsafe fn sockaddr_storage_to_addr(addr: &sockaddr_storage, len: usize) -> Result { if len < mem::size_of_val(&addr.ss_family) { return Err(Error::Sys(Errno::ENOTCONN)); } @@ -1000,7 +1010,9 @@ pub unsafe fn sockaddr_storage_to_addr( } libc::AF_INET6 => { assert!(len as usize == mem::size_of::()); - Ok(SockAddr::Inet(InetAddr::V6(*(addr as *const _ as *const sockaddr_in6)))) + Ok(SockAddr::Inet(InetAddr::V6( + *(addr as *const _ as *const sockaddr_in6), + ))) } libc::AF_UNIX => { let sun = *(addr as *const _ as *const sockaddr_un); @@ -1010,13 +1022,14 @@ pub unsafe fn sockaddr_storage_to_addr( #[cfg(any(target_os = "linux", target_os = "android"))] libc::AF_NETLINK => { use libc::sockaddr_nl; - Ok(SockAddr::Netlink(NetlinkAddr(*(addr as *const _ as *const sockaddr_nl)))) + Ok(SockAddr::Netlink(NetlinkAddr( + *(addr as *const _ as *const sockaddr_nl), + ))) } af => panic!("unexpected address family {}", af), } } - #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Shutdown { /// Further receptions will be disallowed. @@ -1035,9 +1048,9 @@ pub fn shutdown(df: RawFd, how: Shutdown) -> Result<()> { use libc::shutdown; let how = match how { - Shutdown::Read => libc::SHUT_RD, + Shutdown::Read => libc::SHUT_RD, Shutdown::Write => libc::SHUT_WR, - Shutdown::Both => libc::SHUT_RDWR, + Shutdown::Both => libc::SHUT_RDWR, }; Errno::result(shutdown(df, how)).map(drop) diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 56f3a1ee10..c3e17046dd 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -1,10 +1,10 @@ use super::{GetSockOpt, SetSockOpt}; -use Result; use errno::Errno; -use sys::time::TimeVal; -use libc::{self, c_int, uint8_t, c_void, socklen_t}; +use libc::{self, c_int, c_void, socklen_t, uint8_t}; use std::mem; use std::os::unix::io::RawFd; +use sys::time::TimeVal; +use Result; /// Helper for implementing `SetSockOpt` for a given socket option. See /// [`::sys::socket::SetSockOpt`](sys/socket/trait.SetSockOpt.html). @@ -37,14 +37,13 @@ macro_rules! setsockopt_impl { unsafe { let setter: $setter = Set::new(val); - let res = libc::setsockopt(fd, $level, $flag, - setter.ffi_ptr(), - setter.ffi_len()); + let res = + libc::setsockopt(fd, $level, $flag, setter.ffi_ptr(), setter.ffi_len()); Errno::result(res).map(drop) } } } - } + }; } /// Helper for implementing `GetSockOpt` for a given socket option. See @@ -78,16 +77,15 @@ macro_rules! getsockopt_impl { unsafe { let mut getter: $getter = Get::blank(); - let res = libc::getsockopt(fd, $level, $flag, - getter.ffi_ptr(), - getter.ffi_len()); + let res = + libc::getsockopt(fd, $level, $flag, getter.ffi_ptr(), getter.ffi_len()); try!(Errno::result(res)); Ok(getter.unwrap()) } } } - } + }; } /// Helper to generate the sockopt accessors. See @@ -116,39 +114,39 @@ macro_rules! getsockopt_impl { /// * `$getter:ty`: `Get` implementation; optional; only for `GetOnly` and `Both`. /// * `$setter:ty`: `Set` implementation; optional; only for `SetOnly` and `Both`. macro_rules! sockopt_impl { - (GetOnly, $name:ident, $level:path, $flag:path, bool) => { + (GetOnly, $name:ident, $level:path, $flag:path,bool) => { sockopt_impl!(GetOnly, $name, $level, $flag, bool, GetBool); }; - (GetOnly, $name:ident, $level:path, $flag:path, u8) => { + (GetOnly, $name:ident, $level:path, $flag:path,u8) => { sockopt_impl!(GetOnly, $name, $level, $flag, u8, GetU8); }; - (GetOnly, $name:ident, $level:path, $flag:path, usize) => { + (GetOnly, $name:ident, $level:path, $flag:path,usize) => { sockopt_impl!(GetOnly, $name, $level, $flag, usize, GetUsize); }; - (SetOnly, $name:ident, $level:path, $flag:path, bool) => { + (SetOnly, $name:ident, $level:path, $flag:path,bool) => { sockopt_impl!(SetOnly, $name, $level, $flag, bool, SetBool); }; - (SetOnly, $name:ident, $level:path, $flag:path, u8) => { + (SetOnly, $name:ident, $level:path, $flag:path,u8) => { sockopt_impl!(SetOnly, $name, $level, $flag, u8, SetU8); }; - (SetOnly, $name:ident, $level:path, $flag:path, usize) => { + (SetOnly, $name:ident, $level:path, $flag:path,usize) => { sockopt_impl!(SetOnly, $name, $level, $flag, usize, SetUsize); }; - (Both, $name:ident, $level:path, $flag:path, bool) => { + (Both, $name:ident, $level:path, $flag:path,bool) => { sockopt_impl!(Both, $name, $level, $flag, bool, GetBool, SetBool); }; - (Both, $name:ident, $level:path, $flag:path, u8) => { + (Both, $name:ident, $level:path, $flag:path,u8) => { sockopt_impl!(Both, $name, $level, $flag, u8, GetU8, SetU8); }; - (Both, $name:ident, $level:path, $flag:path, usize) => { + (Both, $name:ident, $level:path, $flag:path,usize) => { sockopt_impl!(Both, $name, $level, $flag, usize, GetUsize, SetUsize); }; @@ -187,7 +185,15 @@ macro_rules! sockopt_impl { }; (Both, $name:ident, $level:path, $flag:path, $ty:ty) => { - sockopt_impl!(Both, $name, $level, $flag, $ty, GetStruct<$ty>, SetStruct<$ty>); + sockopt_impl!( + Both, + $name, + $level, + $flag, + $ty, + GetStruct<$ty>, + SetStruct<$ty> + ); }; } @@ -200,9 +206,27 @@ macro_rules! sockopt_impl { sockopt_impl!(Both, ReuseAddr, libc::SOL_SOCKET, libc::SO_REUSEADDR, bool); sockopt_impl!(Both, ReusePort, libc::SOL_SOCKET, libc::SO_REUSEPORT, bool); sockopt_impl!(Both, TcpNoDelay, libc::IPPROTO_TCP, libc::TCP_NODELAY, bool); -sockopt_impl!(Both, Linger, libc::SOL_SOCKET, libc::SO_LINGER, libc::linger); -sockopt_impl!(SetOnly, IpAddMembership, libc::IPPROTO_IP, libc::IP_ADD_MEMBERSHIP, super::IpMembershipRequest); -sockopt_impl!(SetOnly, IpDropMembership, libc::IPPROTO_IP, libc::IP_DROP_MEMBERSHIP, super::IpMembershipRequest); +sockopt_impl!( + Both, + Linger, + libc::SOL_SOCKET, + libc::SO_LINGER, + libc::linger +); +sockopt_impl!( + SetOnly, + IpAddMembership, + libc::IPPROTO_IP, + libc::IP_ADD_MEMBERSHIP, + super::IpMembershipRequest +); +sockopt_impl!( + SetOnly, + IpDropMembership, + libc::IPPROTO_IP, + libc::IP_DROP_MEMBERSHIP, + super::IpMembershipRequest +); cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { sockopt_impl!(SetOnly, Ipv6AddMembership, libc::IPPROTO_IPV6, libc::IPV6_ADD_MEMBERSHIP, super::Ipv6MembershipRequest); @@ -217,38 +241,125 @@ cfg_if! { sockopt_impl!(SetOnly, Ipv6DropMembership, libc::IPPROTO_IPV6, libc::IPV6_LEAVE_GROUP, super::Ipv6MembershipRequest); } } -sockopt_impl!(Both, IpMulticastTtl, libc::IPPROTO_IP, libc::IP_MULTICAST_TTL, u8); -sockopt_impl!(Both, IpMulticastLoop, libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP, bool); -sockopt_impl!(Both, ReceiveTimeout, libc::SOL_SOCKET, libc::SO_RCVTIMEO, TimeVal); -sockopt_impl!(Both, SendTimeout, libc::SOL_SOCKET, libc::SO_SNDTIMEO, TimeVal); +sockopt_impl!( + Both, + IpMulticastTtl, + libc::IPPROTO_IP, + libc::IP_MULTICAST_TTL, + u8 +); +sockopt_impl!( + Both, + IpMulticastLoop, + libc::IPPROTO_IP, + libc::IP_MULTICAST_LOOP, + bool +); +sockopt_impl!( + Both, + ReceiveTimeout, + libc::SOL_SOCKET, + libc::SO_RCVTIMEO, + TimeVal +); +sockopt_impl!( + Both, + SendTimeout, + libc::SOL_SOCKET, + libc::SO_SNDTIMEO, + TimeVal +); sockopt_impl!(Both, Broadcast, libc::SOL_SOCKET, libc::SO_BROADCAST, bool); sockopt_impl!(Both, OobInline, libc::SOL_SOCKET, libc::SO_OOBINLINE, bool); sockopt_impl!(GetOnly, SocketError, libc::SOL_SOCKET, libc::SO_ERROR, i32); sockopt_impl!(Both, KeepAlive, libc::SOL_SOCKET, libc::SO_KEEPALIVE, bool); #[cfg(any(target_os = "android", target_os = "linux"))] -sockopt_impl!(GetOnly, PeerCredentials, libc::SOL_SOCKET, libc::SO_PEERCRED, super::UnixCredentials); -#[cfg(any(target_os = "ios", - target_os = "macos"))] -sockopt_impl!(Both, TcpKeepAlive, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE, u32); -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "nacl"))] -sockopt_impl!(Both, TcpKeepIdle, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE, u32); +sockopt_impl!( + GetOnly, + PeerCredentials, + libc::SOL_SOCKET, + libc::SO_PEERCRED, + super::UnixCredentials +); +#[cfg(any(target_os = "ios", target_os = "macos"))] +sockopt_impl!( + Both, + TcpKeepAlive, + libc::IPPROTO_TCP, + libc::TCP_KEEPALIVE, + u32 +); +#[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "nacl" + ) +)] +sockopt_impl!( + Both, + TcpKeepIdle, + libc::IPPROTO_TCP, + libc::TCP_KEEPIDLE, + u32 +); sockopt_impl!(Both, RcvBuf, libc::SOL_SOCKET, libc::SO_RCVBUF, usize); sockopt_impl!(Both, SndBuf, libc::SOL_SOCKET, libc::SO_SNDBUF, usize); #[cfg(any(target_os = "android", target_os = "linux"))] -sockopt_impl!(SetOnly, RcvBufForce, libc::SOL_SOCKET, libc::SO_RCVBUFFORCE, usize); +sockopt_impl!( + SetOnly, + RcvBufForce, + libc::SOL_SOCKET, + libc::SO_RCVBUFFORCE, + usize +); #[cfg(any(target_os = "android", target_os = "linux"))] -sockopt_impl!(SetOnly, SndBufForce, libc::SOL_SOCKET, libc::SO_SNDBUFFORCE, usize); -sockopt_impl!(GetOnly, SockType, libc::SOL_SOCKET, libc::SO_TYPE, super::SockType); -sockopt_impl!(GetOnly, AcceptConn, libc::SOL_SOCKET, libc::SO_ACCEPTCONN, bool); +sockopt_impl!( + SetOnly, + SndBufForce, + libc::SOL_SOCKET, + libc::SO_SNDBUFFORCE, + usize +); +sockopt_impl!( + GetOnly, + SockType, + libc::SOL_SOCKET, + libc::SO_TYPE, + super::SockType +); +sockopt_impl!( + GetOnly, + AcceptConn, + libc::SOL_SOCKET, + libc::SO_ACCEPTCONN, + bool +); #[cfg(any(target_os = "android", target_os = "linux"))] -sockopt_impl!(GetOnly, OriginalDst, libc::SOL_IP, libc::SO_ORIGINAL_DST, libc::sockaddr_in); -sockopt_impl!(Both, ReceiveTimestamp, libc::SOL_SOCKET, libc::SO_TIMESTAMP, bool); +sockopt_impl!( + GetOnly, + OriginalDst, + libc::SOL_IP, + libc::SO_ORIGINAL_DST, + libc::sockaddr_in +); +sockopt_impl!( + Both, + ReceiveTimestamp, + libc::SOL_SOCKET, + libc::SO_TIMESTAMP, + bool +); #[cfg(any(target_os = "android", target_os = "linux"))] -sockopt_impl!(Both, IpTransparent, libc::SOL_IP, libc::IP_TRANSPARENT, bool); +sockopt_impl!( + Both, + IpTransparent, + libc::SOL_IP, + libc::IP_TRANSPARENT, + bool +); #[cfg(target_os = "openbsd")] sockopt_impl!(Both, BindAny, libc::SOL_SOCKET, libc::SO_BINDANY, bool); #[cfg(target_os = "freebsd")] @@ -311,7 +422,10 @@ unsafe impl Get for GetStruct { } unsafe fn unwrap(self) -> T { - assert!(self.len as usize == mem::size_of::(), "invalid getsockopt implementation"); + assert!( + self.len as usize == mem::size_of::(), + "invalid getsockopt implementation" + ); self.val } } @@ -358,7 +472,10 @@ unsafe impl Get for GetBool { } unsafe fn unwrap(self) -> bool { - assert!(self.len as usize == mem::size_of::(), "invalid getsockopt implementation"); + assert!( + self.len as usize == mem::size_of::(), + "invalid getsockopt implementation" + ); self.val != 0 } } @@ -370,7 +487,9 @@ struct SetBool { unsafe impl<'a> Set<'a, bool> for SetBool { fn new(val: &'a bool) -> SetBool { - SetBool { val: if *val { 1 } else { 0 } } + SetBool { + val: if *val { 1 } else { 0 }, + } } fn ffi_ptr(&self) -> *const c_void { @@ -405,7 +524,10 @@ unsafe impl Get for GetU8 { } unsafe fn unwrap(self) -> u8 { - assert!(self.len as usize == mem::size_of::(), "invalid getsockopt implementation"); + assert!( + self.len as usize == mem::size_of::(), + "invalid getsockopt implementation" + ); self.val as u8 } } @@ -417,7 +539,9 @@ struct SetU8 { unsafe impl<'a> Set<'a, u8> for SetU8 { fn new(val: &'a u8) -> SetU8 { - SetU8 { val: *val as uint8_t } + SetU8 { + val: *val as uint8_t, + } } fn ffi_ptr(&self) -> *const c_void { @@ -452,7 +576,10 @@ unsafe impl Get for GetUsize { } unsafe fn unwrap(self) -> usize { - assert!(self.len as usize == mem::size_of::(), "invalid getsockopt implementation"); + assert!( + self.len as usize == mem::size_of::(), + "invalid getsockopt implementation" + ); self.val as usize } } @@ -483,7 +610,12 @@ mod test { fn can_get_peercred_on_unix_socket() { use super::super::*; - let (a, b) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()).unwrap(); + let (a, b) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ).unwrap(); let a_cred = getsockopt(a, super::PeerCredentials).unwrap(); let b_cred = getsockopt(b, super::PeerCredentials).unwrap(); assert_eq!(a_cred, b_cred); @@ -493,9 +625,14 @@ mod test { #[test] fn is_socket_type_unix() { use super::super::*; - use ::unistd::close; - - let (a, b) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()).unwrap(); + use unistd::close; + + let (a, b) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ).unwrap(); let a_type = getsockopt(a, super::SockType).unwrap(); assert!(a_type == SockType::Stream); close(a).unwrap(); @@ -505,23 +642,31 @@ mod test { #[test] fn is_socket_type_dgram() { use super::super::*; - use ::unistd::close; - - let s = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None).unwrap(); + use unistd::close; + + let s = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ).unwrap(); let s_type = getsockopt(s, super::SockType).unwrap(); assert!(s_type == SockType::Datagram); close(s).unwrap(); } - #[cfg(any(target_os = "freebsd", - target_os = "linux", - target_os = "nacl"))] + #[cfg(any(target_os = "freebsd", target_os = "linux", target_os = "nacl"))] #[test] fn can_get_listen_on_tcp_socket() { use super::super::*; - use ::unistd::close; - - let s = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + use unistd::close; + + let s = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ).unwrap(); let s_listening = getsockopt(s, super::AcceptConn).unwrap(); assert!(!s_listening); listen(s, 10).unwrap(); @@ -534,8 +679,8 @@ mod test { #[test] fn is_so_mark_functional() { use super::super::*; - use ::unistd::Uid; - use ::std::io::{self, Write}; + use std::io::{self, Write}; + use unistd::Uid; if !Uid::current().is_root() { let stderr = io::stderr(); @@ -544,7 +689,12 @@ mod test { return; } - let s = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + let s = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ).unwrap(); setsockopt(s, super::Mark, &1337).unwrap(); let mark = getsockopt(s, super::Mark).unwrap(); assert_eq!(mark, 1337); diff --git a/src/sys/stat.rs b/src/sys/stat.rs index 7bcf1fce3b..72c4d35ee7 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -1,12 +1,12 @@ pub use libc::dev_t; pub use libc::stat as FileStat; -use {Result, NixPath}; use errno::Errno; use fcntl::AtFlags; use libc::{self, mode_t}; use std::mem; use std::os::unix::io::RawFd; +use {NixPath, Result}; libc_bitflags!( pub struct SFlag: mode_t { @@ -42,10 +42,8 @@ libc_bitflags! { } pub fn mknod(path: &P, kind: SFlag, perm: Mode, dev: dev_t) -> Result<()> { - let res = try!(path.with_nix_path(|cstr| { - unsafe { - libc::mknod(cstr.as_ptr(), kind.bits | perm.bits() as mode_t, dev) - } + let res = try!(path.with_nix_path(|cstr| unsafe { + libc::mknod(cstr.as_ptr(), kind.bits | perm.bits() as mode_t, dev) })); Errno::result(res).map(drop) @@ -53,22 +51,20 @@ pub fn mknod(path: &P, kind: SFlag, perm: Mode, dev: dev_t) #[cfg(target_os = "linux")] pub fn major(dev: dev_t) -> u64 { - ((dev >> 32) & 0xffff_f000) | - ((dev >> 8) & 0x0000_0fff) + ((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0x0000_0fff) } #[cfg(target_os = "linux")] pub fn minor(dev: dev_t) -> u64 { - ((dev >> 12) & 0xffff_ff00) | - ((dev ) & 0x0000_00ff) + ((dev >> 12) & 0xffff_ff00) | ((dev) & 0x0000_00ff) } #[cfg(target_os = "linux")] pub fn makedev(major: u64, minor: u64) -> dev_t { - ((major & 0xffff_f000) << 32) | - ((major & 0x0000_0fff) << 8) | - ((minor & 0xffff_ff00) << 12) | - (minor & 0x0000_00ff) + ((major & 0xffff_f000) << 32) + | ((major & 0x0000_0fff) << 8) + | ((minor & 0xffff_ff00) << 12) + | (minor & 0x0000_00ff) } pub fn umask(mode: Mode) -> Mode { @@ -78,11 +74,9 @@ pub fn umask(mode: Mode) -> Mode { pub fn stat(path: &P) -> Result { let mut dst = unsafe { mem::uninitialized() }; - let res = try!(path.with_nix_path(|cstr| { - unsafe { - libc::stat(cstr.as_ptr(), &mut dst as *mut FileStat) - } - })); + let res = try!( + path.with_nix_path(|cstr| unsafe { libc::stat(cstr.as_ptr(), &mut dst as *mut FileStat) }) + ); try!(Errno::result(res)); @@ -91,11 +85,9 @@ pub fn stat(path: &P) -> Result { pub fn lstat(path: &P) -> Result { let mut dst = unsafe { mem::uninitialized() }; - let res = try!(path.with_nix_path(|cstr| { - unsafe { - libc::lstat(cstr.as_ptr(), &mut dst as *mut FileStat) - } - })); + let res = try!( + path.with_nix_path(|cstr| unsafe { libc::lstat(cstr.as_ptr(), &mut dst as *mut FileStat) }) + ); try!(Errno::result(res)); @@ -113,8 +105,13 @@ pub fn fstat(fd: RawFd) -> Result { pub fn fstatat(dirfd: RawFd, pathname: &P, f: AtFlags) -> Result { let mut dst = unsafe { mem::uninitialized() }; - let res = try!(pathname.with_nix_path(|cstr| { - unsafe { libc::fstatat(dirfd, cstr.as_ptr(), &mut dst as *mut FileStat, f.bits() as libc::c_int) } + let res = try!(pathname.with_nix_path(|cstr| unsafe { + libc::fstatat( + dirfd, + cstr.as_ptr(), + &mut dst as *mut FileStat, + f.bits() as libc::c_int, + ) })); try!(Errno::result(res)); @@ -162,16 +159,14 @@ pub fn fchmodat( mode: Mode, flag: FchmodatFlags, ) -> Result<()> { - let actual_dirfd = - match dirfd { - None => libc::AT_FDCWD, - Some(fd) => fd, - }; - let atflag = - match flag { - FchmodatFlags::FollowSymlink => AtFlags::empty(), - FchmodatFlags::NoFollowSymlink => AtFlags::AT_SYMLINK_NOFOLLOW, - }; + let actual_dirfd = match dirfd { + None => libc::AT_FDCWD, + Some(fd) => fd, + }; + let atflag = match flag { + FchmodatFlags::FollowSymlink => AtFlags::empty(), + FchmodatFlags::NoFollowSymlink => AtFlags::AT_SYMLINK_NOFOLLOW, + }; let res = path.with_nix_path(|cstr| unsafe { libc::fchmodat( actual_dirfd, diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index 6d4fafe968..673a3a30e8 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -1,14 +1,12 @@ -use {Result, NixPath}; use errno::Errno; -use std::os::unix::io::AsRawFd; use libc; +use std::os::unix::io::AsRawFd; +use {NixPath, Result}; pub fn statfs(path: &P, stat: &mut libc::statfs) -> Result<()> { unsafe { Errno::clear(); - let res = try!( - path.with_nix_path(|path| libc::statfs(path.as_ptr(), stat)) - ); + let res = try!(path.with_nix_path(|path| libc::statfs(path.as_ptr(), stat))); Errno::result(res).map(drop) } diff --git a/src/sys/statvfs.rs b/src/sys/statvfs.rs index 845ae0dbd5..ddc3b438f3 100644 --- a/src/sys/statvfs.rs +++ b/src/sys/statvfs.rs @@ -7,8 +7,8 @@ use std::os::unix::io::AsRawFd; use libc::{self, c_ulong}; -use {Result, NixPath}; use errno::Errno; +use {NixPath, Result}; libc_bitflags!( /// File system mount Flags @@ -118,7 +118,6 @@ impl Statvfs { pub fn name_max(&self) -> c_ulong { self.0.f_namemax } - } /// Return a `Statvfs` object with information about the `path` @@ -126,9 +125,7 @@ pub fn statvfs(path: &P) -> Result { unsafe { Errno::clear(); let mut stat: Statvfs = mem::uninitialized(); - let res = try!( - path.with_nix_path(|path| libc::statvfs(path.as_ptr(), &mut stat.0)) - ); + let res = try!(path.with_nix_path(|path| libc::statvfs(path.as_ptr(), &mut stat.0))); Errno::result(res).map(|_| stat) } diff --git a/src/sys/sysinfo.rs b/src/sys/sysinfo.rs index 98ef7bd517..0c65c6f649 100644 --- a/src/sys/sysinfo.rs +++ b/src/sys/sysinfo.rs @@ -1,9 +1,9 @@ use libc::{self, SI_LOAD_SHIFT}; -use std::{cmp, mem}; use std::time::Duration; +use std::{cmp, mem}; -use Result; use errno::Errno; +use Result; /// System info structure returned by `sysinfo`. #[derive(Copy, Clone)] diff --git a/src/sys/termios.rs b/src/sys/termios.rs index 11cacd7c57..a211fbff12 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -87,10 +87,9 @@ //! //! On non-BSDs, `cfgetispeed()` and `cfgetospeed()` both return a `BaudRate`: //! -// FIXME: Replace `ignore` with `compile_fail` once 1.22 is the minimum support Rust version #![cfg_attr(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd"), - doc = " ```rust,ignore")] + doc = " ```rust,compile_fail")] #![cfg_attr(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd")), doc = " ```rust")] @@ -105,14 +104,13 @@ //! ``` //! //! But on the BSDs, `cfgetispeed()` and `cfgetospeed()` both return `u32`s: -//! -// FIXME: Replace `ignore` with `compile_fail` once 1.22 is the minimum support Rust version +//!sion #![cfg_attr(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd"), doc = " ```rust")] #![cfg_attr(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd")), - doc = " ```rust,ignore")] + doc = " ```rust,compile_fail")] //! # extern crate nix; //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfgetospeed, cfsetspeed, Termios}; //! # fn main() { @@ -125,13 +123,12 @@ //! //! It's trivial to convert from a `BaudRate` to a `u32` on BSDs: //! -// FIXME: Replace `ignore` with `compile_fail` once 1.22 is the minimum support Rust version #![cfg_attr(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd"), doc = " ```rust")] #![cfg_attr(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd")), - doc = " ```rust,ignore")] + doc = " ```rust,compile_fail")] //! # extern crate nix; //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfsetspeed, Termios}; //! # fn main() { @@ -145,13 +142,12 @@ //! And on BSDs you can specify arbitrary baud rates (**note** this depends on hardware support) //! by specifying baud rates directly using `u32`s: //! -// FIXME: Replace `ignore` with `compile_fail` once 1.22 is the minimum support Rust version #![cfg_attr(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd"), doc = " ```rust")] #![cfg_attr(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd")), - doc = " ```rust,ignore")] + doc = " ```rust,compile_fail")] //! # extern crate nix; //! # use nix::sys::termios::{cfsetispeed, cfsetospeed, cfsetspeed, Termios}; //! # fn main() { @@ -161,15 +157,15 @@ //! cfsetspeed(&mut t, 9600u32); //! # } //! ``` -use Result; use errno::Errno; use libc::{self, c_int, tcflag_t}; use std::cell::{Ref, RefCell}; use std::convert::From; use std::mem; use std::os::unix::io::RawFd; +use Result; -use ::unistd::Pid; +use unistd::Pid; /// Stores settings for the termios API /// @@ -379,22 +375,33 @@ libc_enum!{ impl From for BaudRate { fn from(s: libc::speed_t) -> BaudRate { - - use libc::{B0, B50, B75, B110, B134, B150, B200, B300, B600, B1200, B1800, B2400, B4800, - B9600, B19200, B38400, B57600, B115200, B230400}; + use libc::{ + B0, B110, B115200, B1200, B134, B150, B1800, B19200, B200, B230400, B2400, B300, + B38400, B4800, B50, B57600, B600, B75, B9600, + }; #[cfg(any(target_os = "android", target_os = "linux"))] - use libc::{B500000, B576000, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, - B3500000, B4000000}; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] - use libc::{B7200, B14400, B28800, B76800}; - #[cfg(any(target_os = "android", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd"))] + use libc::{ + B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000, + B500000, B576000, + }; + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] + use libc::{B14400, B28800, B7200, B76800}; + #[cfg( + any( + target_os = "android", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd" + ) + )] use libc::{B460800, B921600}; match s { @@ -411,49 +418,73 @@ impl From for BaudRate { B1800 => BaudRate::B1800, B2400 => BaudRate::B2400, B4800 => BaudRate::B4800, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] B7200 => BaudRate::B7200, B9600 => BaudRate::B9600, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] B14400 => BaudRate::B14400, B19200 => BaudRate::B19200, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] B28800 => BaudRate::B28800, B38400 => BaudRate::B38400, B57600 => BaudRate::B57600, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] B76800 => BaudRate::B76800, B115200 => BaudRate::B115200, B230400 => BaudRate::B230400, - #[cfg(any(target_os = "android", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd" + ) + )] B460800 => BaudRate::B460800, #[cfg(any(target_os = "android", target_os = "linux"))] B500000 => BaudRate::B500000, #[cfg(any(target_os = "android", target_os = "linux"))] B576000 => BaudRate::B576000, - #[cfg(any(target_os = "android", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd" + ) + )] B921600 => BaudRate::B921600, #[cfg(any(target_os = "android", target_os = "linux"))] B1000000 => BaudRate::B1000000, @@ -477,12 +508,16 @@ impl From for BaudRate { } // TODO: Include `TryFrom for BaudRate` once that API stabilizes -#[cfg(any(target_os = "freebsd", - target_os = "dragonfly", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] impl From for u32 { fn from(b: BaudRate) -> u32 { b as u32 @@ -582,12 +617,16 @@ libc_enum! { } pub use libc::NCCS; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] pub use libc::_POSIX_VDISABLE; libc_bitflags! { diff --git a/src/sys/time.rs b/src/sys/time.rs index 51286a06b4..40a6b03635 100644 --- a/src/sys/time.rs +++ b/src/sys/time.rs @@ -1,5 +1,5 @@ +use libc::{c_long, suseconds_t, time_t, timespec, timeval}; use std::{cmp, fmt, ops}; -use libc::{c_long, time_t, suseconds_t, timespec, timeval}; pub trait TimeValLike: Sized { #[inline] @@ -9,14 +9,16 @@ pub trait TimeValLike: Sized { #[inline] fn hours(hours: i64) -> Self { - let secs = hours.checked_mul(SECS_PER_HOUR) + let secs = hours + .checked_mul(SECS_PER_HOUR) .expect("TimeValLike::hours ouf of bounds"); Self::seconds(secs) } #[inline] fn minutes(minutes: i64) -> Self { - let secs = minutes.checked_mul(SECS_PER_MINUTE) + let secs = minutes + .checked_mul(SECS_PER_MINUTE) .expect("TimeValLike::minutes out of bounds"); Self::seconds(secs) } @@ -58,7 +60,6 @@ const TS_MAX_SECONDS: i64 = ::std::isize::MAX as i64; const TS_MIN_SECONDS: i64 = -TS_MAX_SECONDS; - impl AsRef for TimeSpec { fn as_ref(&self) -> ×pec { &self.0 @@ -105,14 +106,21 @@ impl PartialOrd for TimeSpec { impl TimeValLike for TimeSpec { #[inline] fn seconds(seconds: i64) -> TimeSpec { - assert!(seconds >= TS_MIN_SECONDS && seconds <= TS_MAX_SECONDS, - "TimeSpec out of bounds; seconds={}", seconds); - TimeSpec(timespec {tv_sec: seconds as time_t, tv_nsec: 0 }) + assert!( + seconds >= TS_MIN_SECONDS && seconds <= TS_MAX_SECONDS, + "TimeSpec out of bounds; seconds={}", + seconds + ); + TimeSpec(timespec { + tv_sec: seconds as time_t, + tv_nsec: 0, + }) } #[inline] fn milliseconds(milliseconds: i64) -> TimeSpec { - let nanoseconds = milliseconds.checked_mul(1_000_000) + let nanoseconds = milliseconds + .checked_mul(1_000_000) .expect("TimeSpec::milliseconds out of bounds"); TimeSpec::nanoseconds(nanoseconds) @@ -121,7 +129,8 @@ impl TimeValLike for TimeSpec { /// Makes a new `TimeSpec` with given number of microseconds. #[inline] fn microseconds(microseconds: i64) -> TimeSpec { - let nanoseconds = microseconds.checked_mul(1_000) + let nanoseconds = microseconds + .checked_mul(1_000) .expect("TimeSpec::milliseconds out of bounds"); TimeSpec::nanoseconds(nanoseconds) @@ -131,10 +140,14 @@ impl TimeValLike for TimeSpec { #[inline] fn nanoseconds(nanoseconds: i64) -> TimeSpec { let (secs, nanos) = div_mod_floor_64(nanoseconds, NANOS_PER_SEC); - assert!(secs >= TS_MIN_SECONDS && secs <= TS_MAX_SECONDS, - "TimeSpec out of bounds"); - TimeSpec(timespec {tv_sec: secs as time_t, - tv_nsec: nanos as c_long }) + assert!( + secs >= TS_MIN_SECONDS && secs <= TS_MAX_SECONDS, + "TimeSpec out of bounds" + ); + TimeSpec(timespec { + tv_sec: secs as time_t, + tv_nsec: nanos as c_long, + }) } fn num_seconds(&self) -> i64 { @@ -190,8 +203,7 @@ impl ops::Add for TimeSpec { type Output = TimeSpec; fn add(self, rhs: TimeSpec) -> TimeSpec { - TimeSpec::nanoseconds( - self.num_nanoseconds() + rhs.num_nanoseconds()) + TimeSpec::nanoseconds(self.num_nanoseconds() + rhs.num_nanoseconds()) } } @@ -199,8 +211,7 @@ impl ops::Sub for TimeSpec { type Output = TimeSpec; fn sub(self, rhs: TimeSpec) -> TimeSpec { - TimeSpec::nanoseconds( - self.num_nanoseconds() - rhs.num_nanoseconds()) + TimeSpec::nanoseconds(self.num_nanoseconds() - rhs.num_nanoseconds()) } } @@ -208,7 +219,9 @@ impl ops::Mul for TimeSpec { type Output = TimeSpec; fn mul(self, rhs: i32) -> TimeSpec { - let usec = self.num_nanoseconds().checked_mul(rhs as i64) + let usec = self + .num_nanoseconds() + .checked_mul(rhs as i64) .expect("TimeSpec multiply out of bounds"); TimeSpec::nanoseconds(usec) @@ -243,7 +256,12 @@ impl fmt::Display for TimeSpec { try!(write!(f, "{} seconds", sec)); } } else if abs.tv_nsec() % 1_000_000 == 0 { - try!(write!(f, "{}.{:03} seconds", sec, abs.tv_nsec() / 1_000_000)); + try!(write!( + f, + "{}.{:03} seconds", + sec, + abs.tv_nsec() / 1_000_000 + )); } else if abs.tv_nsec() % 1_000 == 0 { try!(write!(f, "{}.{:06} seconds", sec, abs.tv_nsec() / 1_000)); } else { @@ -254,8 +272,6 @@ impl fmt::Display for TimeSpec { } } - - #[repr(C)] #[derive(Clone, Copy)] pub struct TimeVal(timeval); @@ -316,14 +332,21 @@ impl PartialOrd for TimeVal { impl TimeValLike for TimeVal { #[inline] fn seconds(seconds: i64) -> TimeVal { - assert!(seconds >= TV_MIN_SECONDS && seconds <= TV_MAX_SECONDS, - "TimeVal out of bounds; seconds={}", seconds); - TimeVal(timeval {tv_sec: seconds as time_t, tv_usec: 0 }) + assert!( + seconds >= TV_MIN_SECONDS && seconds <= TV_MAX_SECONDS, + "TimeVal out of bounds; seconds={}", + seconds + ); + TimeVal(timeval { + tv_sec: seconds as time_t, + tv_usec: 0, + }) } #[inline] fn milliseconds(milliseconds: i64) -> TimeVal { - let microseconds = milliseconds.checked_mul(1_000) + let microseconds = milliseconds + .checked_mul(1_000) .expect("TimeVal::milliseconds out of bounds"); TimeVal::microseconds(microseconds) @@ -333,10 +356,14 @@ impl TimeValLike for TimeVal { #[inline] fn microseconds(microseconds: i64) -> TimeVal { let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC); - assert!(secs >= TV_MIN_SECONDS && secs <= TV_MAX_SECONDS, - "TimeVal out of bounds"); - TimeVal(timeval {tv_sec: secs as time_t, - tv_usec: micros as suseconds_t }) + assert!( + secs >= TV_MIN_SECONDS && secs <= TV_MAX_SECONDS, + "TimeVal out of bounds" + ); + TimeVal(timeval { + tv_sec: secs as time_t, + tv_usec: micros as suseconds_t, + }) } /// Makes a new `TimeVal` with given number of nanoseconds. Some precision @@ -345,10 +372,14 @@ impl TimeValLike for TimeVal { fn nanoseconds(nanoseconds: i64) -> TimeVal { let microseconds = nanoseconds / 1000; let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC); - assert!(secs >= TV_MIN_SECONDS && secs <= TV_MAX_SECONDS, - "TimeVal out of bounds"); - TimeVal(timeval {tv_sec: secs as time_t, - tv_usec: micros as suseconds_t }) + assert!( + secs >= TV_MIN_SECONDS && secs <= TV_MAX_SECONDS, + "TimeVal out of bounds" + ); + TimeVal(timeval { + tv_sec: secs as time_t, + tv_usec: micros as suseconds_t, + }) } fn num_seconds(&self) -> i64 { @@ -404,8 +435,7 @@ impl ops::Add for TimeVal { type Output = TimeVal; fn add(self, rhs: TimeVal) -> TimeVal { - TimeVal::microseconds( - self.num_microseconds() + rhs.num_microseconds()) + TimeVal::microseconds(self.num_microseconds() + rhs.num_microseconds()) } } @@ -413,8 +443,7 @@ impl ops::Sub for TimeVal { type Output = TimeVal; fn sub(self, rhs: TimeVal) -> TimeVal { - TimeVal::microseconds( - self.num_microseconds() - rhs.num_microseconds()) + TimeVal::microseconds(self.num_microseconds() - rhs.num_microseconds()) } } @@ -422,7 +451,9 @@ impl ops::Mul for TimeVal { type Output = TimeVal; fn mul(self, rhs: i32) -> TimeVal { - let usec = self.num_microseconds().checked_mul(rhs as i64) + let usec = self + .num_microseconds() + .checked_mul(rhs as i64) .expect("TimeVal multiply out of bounds"); TimeVal::microseconds(usec) @@ -474,18 +505,16 @@ fn div_mod_floor_64(this: i64, other: i64) -> (i64, i64) { #[inline] fn div_floor_64(this: i64, other: i64) -> i64 { match div_rem_64(this, other) { - (d, r) if (r > 0 && other < 0) - || (r < 0 && other > 0) => d - 1, - (d, _) => d, + (d, r) if (r > 0 && other < 0) || (r < 0 && other > 0) => d - 1, + (d, _) => d, } } #[inline] fn mod_floor_64(this: i64, other: i64) -> i64 { match this % other { - r if (r > 0 && other < 0) - || (r < 0 && other > 0) => r + other, - r => r, + r if (r > 0 && other < 0) || (r < 0 && other > 0) => r + other, + r => r, } } @@ -501,10 +530,14 @@ mod test { #[test] pub fn test_timespec() { assert!(TimeSpec::seconds(1) != TimeSpec::zero()); - assert_eq!(TimeSpec::seconds(1) + TimeSpec::seconds(2), - TimeSpec::seconds(3)); - assert_eq!(TimeSpec::minutes(3) + TimeSpec::seconds(2), - TimeSpec::seconds(182)); + assert_eq!( + TimeSpec::seconds(1) + TimeSpec::seconds(2), + TimeSpec::seconds(3) + ); + assert_eq!( + TimeSpec::minutes(3) + TimeSpec::seconds(2), + TimeSpec::seconds(182) + ); } #[test] @@ -537,10 +570,14 @@ mod test { #[test] pub fn test_timeval() { assert!(TimeVal::seconds(1) != TimeVal::zero()); - assert_eq!(TimeVal::seconds(1) + TimeVal::seconds(2), - TimeVal::seconds(3)); - assert_eq!(TimeVal::minutes(3) + TimeVal::seconds(2), - TimeVal::seconds(182)); + assert_eq!( + TimeVal::seconds(1) + TimeVal::seconds(2), + TimeVal::seconds(3) + ); + assert_eq!( + TimeVal::minutes(3) + TimeVal::seconds(2), + TimeVal::seconds(182) + ); } #[test] diff --git a/src/sys/uio.rs b/src/sys/uio.rs index 45860be5aa..2f11c63c8d 100644 --- a/src/sys/uio.rs +++ b/src/sys/uio.rs @@ -1,11 +1,11 @@ // Silence invalid warnings due to rust-lang/rust#16719 #![allow(improper_ctypes)] -use Result; use errno::Errno; -use libc::{self, c_int, c_void, size_t, off_t}; +use libc::{self, c_int, c_void, off_t, size_t}; use std::marker::PhantomData; use std::os::unix::io::RawFd; +use Result; pub fn writev(fd: RawFd, iov: &[IoVec<&[u8]>]) -> Result { let res = unsafe { libc::writev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) }; @@ -25,15 +25,23 @@ pub fn readv(fd: RawFd, iov: &mut [IoVec<&mut [u8]>]) -> Result { /// or an error occurs. The file offset is not changed. /// /// See also: [`writev`](fn.writev.html) and [`pwrite`](fn.pwrite.html) -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd"))] -pub fn pwritev(fd: RawFd, iov: &[IoVec<&[u8]>], - offset: off_t) -> Result { +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd" + ) +)] +pub fn pwritev(fd: RawFd, iov: &[IoVec<&[u8]>], offset: off_t) -> Result { let res = unsafe { - libc::pwritev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset) + libc::pwritev( + fd, + iov.as_ptr() as *const libc::iovec, + iov.len() as c_int, + offset, + ) }; Errno::result(res).map(|r| r as usize) @@ -46,15 +54,23 @@ pub fn pwritev(fd: RawFd, iov: &[IoVec<&[u8]>], /// changed. /// /// See also: [`readv`](fn.readv.html) and [`pread`](fn.pread.html) -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd"))] -pub fn preadv(fd: RawFd, iov: &[IoVec<&mut [u8]>], - offset: off_t) -> Result { +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd" + ) +)] +pub fn preadv(fd: RawFd, iov: &[IoVec<&mut [u8]>], offset: off_t) -> Result { let res = unsafe { - libc::preadv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset) + libc::preadv( + fd, + iov.as_ptr() as *const libc::iovec, + iov.len() as c_int, + offset, + ) }; Errno::result(res).map(|r| r as usize) @@ -62,17 +78,25 @@ pub fn preadv(fd: RawFd, iov: &[IoVec<&mut [u8]>], pub fn pwrite(fd: RawFd, buf: &[u8], offset: off_t) -> Result { let res = unsafe { - libc::pwrite(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, - offset) + libc::pwrite( + fd, + buf.as_ptr() as *const c_void, + buf.len() as size_t, + offset, + ) }; Errno::result(res).map(|r| r as usize) } -pub fn pread(fd: RawFd, buf: &mut [u8], offset: off_t) -> Result{ +pub fn pread(fd: RawFd, buf: &mut [u8], offset: off_t) -> Result { let res = unsafe { - libc::pread(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t, - offset) + libc::pread( + fd, + buf.as_mut_ptr() as *mut c_void, + buf.len() as size_t, + offset, + ) }; Errno::result(res).map(|r| r as usize) @@ -118,11 +142,20 @@ pub struct RemoteIoVec { /// [`IoVec`]: struct.IoVec.html /// [`RemoteIoVec`]: struct.RemoteIoVec.html #[cfg(target_os = "linux")] -pub fn process_vm_writev(pid: ::unistd::Pid, local_iov: &[IoVec<&[u8]>], remote_iov: &[RemoteIoVec]) -> Result { +pub fn process_vm_writev( + pid: ::unistd::Pid, + local_iov: &[IoVec<&[u8]>], + remote_iov: &[RemoteIoVec], +) -> Result { let res = unsafe { - libc::process_vm_writev(pid.into(), - local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong, - remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0) + libc::process_vm_writev( + pid.into(), + local_iov.as_ptr() as *const libc::iovec, + local_iov.len() as libc::c_ulong, + remote_iov.as_ptr() as *const libc::iovec, + remote_iov.len() as libc::c_ulong, + 0, + ) }; Errno::result(res).map(|r| r as usize) @@ -149,11 +182,20 @@ pub fn process_vm_writev(pid: ::unistd::Pid, local_iov: &[IoVec<&[u8]>], remote_ /// [`IoVec`]: struct.IoVec.html /// [`RemoteIoVec`]: struct.RemoteIoVec.html #[cfg(any(target_os = "linux"))] -pub fn process_vm_readv(pid: ::unistd::Pid, local_iov: &[IoVec<&mut [u8]>], remote_iov: &[RemoteIoVec]) -> Result { +pub fn process_vm_readv( + pid: ::unistd::Pid, + local_iov: &[IoVec<&mut [u8]>], + remote_iov: &[RemoteIoVec], +) -> Result { let res = unsafe { - libc::process_vm_readv(pid.into(), - local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong, - remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0) + libc::process_vm_readv( + pid.into(), + local_iov.as_ptr() as *const libc::iovec, + local_iov.len() as libc::c_ulong, + remote_iov.as_ptr() as *const libc::iovec, + remote_iov.len() as libc::c_ulong, + 0, + ) }; Errno::result(res).map(|r| r as usize) @@ -168,28 +210,30 @@ impl IoVec { pub fn as_slice(&self) -> &[u8] { use std::slice; - unsafe { - slice::from_raw_parts( - self.0.iov_base as *const u8, - self.0.iov_len as usize) - } + unsafe { slice::from_raw_parts(self.0.iov_base as *const u8, self.0.iov_len as usize) } } } impl<'a> IoVec<&'a [u8]> { pub fn from_slice(buf: &'a [u8]) -> IoVec<&'a [u8]> { - IoVec(libc::iovec { - iov_base: buf.as_ptr() as *mut c_void, - iov_len: buf.len() as size_t, - }, PhantomData) + IoVec( + libc::iovec { + iov_base: buf.as_ptr() as *mut c_void, + iov_len: buf.len() as size_t, + }, + PhantomData, + ) } } impl<'a> IoVec<&'a mut [u8]> { pub fn from_mut_slice(buf: &'a mut [u8]) -> IoVec<&'a mut [u8]> { - IoVec(libc::iovec { - iov_base: buf.as_ptr() as *mut c_void, - iov_len: buf.len() as size_t, - }, PhantomData) + IoVec( + libc::iovec { + iov_base: buf.as_ptr() as *mut c_void, + iov_len: buf.len() as size_t, + }, + PhantomData, + ) } } diff --git a/src/sys/utsname.rs b/src/sys/utsname.rs index e33d0739a0..e41a6b0fef 100644 --- a/src/sys/utsname.rs +++ b/src/sys/utsname.rs @@ -1,6 +1,6 @@ -use std::mem; use libc::{self, c_char}; use std::ffi::CStr; +use std::mem; use std::str::from_utf8_unchecked; #[repr(C)] @@ -10,23 +10,23 @@ pub struct UtsName(libc::utsname); impl UtsName { pub fn sysname(&self) -> &str { - to_str(&(&self.0.sysname as *const c_char ) as *const *const c_char) + to_str(&(&self.0.sysname as *const c_char) as *const *const c_char) } pub fn nodename(&self) -> &str { - to_str(&(&self.0.nodename as *const c_char ) as *const *const c_char) + to_str(&(&self.0.nodename as *const c_char) as *const *const c_char) } pub fn release(&self) -> &str { - to_str(&(&self.0.release as *const c_char ) as *const *const c_char) + to_str(&(&self.0.release as *const c_char) as *const *const c_char) } pub fn version(&self) -> &str { - to_str(&(&self.0.version as *const c_char ) as *const *const c_char) + to_str(&(&self.0.version as *const c_char) as *const *const c_char) } pub fn machine(&self) -> &str { - to_str(&(&self.0.machine as *const c_char ) as *const *const c_char) + to_str(&(&self.0.machine as *const c_char) as *const *const c_char) } } diff --git a/src/sys/wait.rs b/src/sys/wait.rs index 038354b107..906bd62459 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -1,7 +1,7 @@ -use libc::{self, c_int}; -use Result; use errno::Errno; +use libc::{self, c_int}; use unistd::Pid; +use Result; use sys::signal::Signal; @@ -104,8 +104,7 @@ impl WaitStatus { pub fn pid(&self) -> Option { use self::WaitStatus::*; match *self { - Exited(p, _) | Signaled(p, _, _) | - Stopped(p, _) | Continued(p) => Some(p), + Exited(p, _) | Signaled(p, _, _) | Stopped(p, _) | Continued(p) => Some(p), StillAlive => None, #[cfg(any(target_os = "android", target_os = "linux"))] PtraceEvent(p, _, _) | PtraceSyscall(p) => Some(p), diff --git a/src/ucontext.rs b/src/ucontext.rs index c94464d570..47f8ff093b 100644 --- a/src/ucontext.rs +++ b/src/ucontext.rs @@ -1,10 +1,10 @@ -use libc; -#[cfg(not(target_env = "musl"))] -use Result; #[cfg(not(target_env = "musl"))] use errno::Errno; +use libc; use std::mem; use sys::signal::SigSet; +#[cfg(not(target_env = "musl"))] +use Result; #[derive(Clone, Copy)] #[allow(missing_debug_implementations)] @@ -16,17 +16,13 @@ impl UContext { #[cfg(not(target_env = "musl"))] pub fn get() -> Result { let mut context: libc::ucontext_t = unsafe { mem::uninitialized() }; - let res = unsafe { - libc::getcontext(&mut context as *mut libc::ucontext_t) - }; + let res = unsafe { libc::getcontext(&mut context as *mut libc::ucontext_t) }; Errno::result(res).map(|_| UContext { context: context }) } #[cfg(not(target_env = "musl"))] pub fn set(&self) -> Result<()> { - let res = unsafe { - libc::setcontext(&self.context as *const libc::ucontext_t) - }; + let res = unsafe { libc::setcontext(&self.context as *const libc::ucontext_t) }; Errno::result(res).map(drop) } diff --git a/src/unistd.rs b/src/unistd.rs index c0b44d57e5..0c4f4a7dde 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -1,24 +1,26 @@ //! Safe wrappers around functions found in libc "unistd.h" header use errno::{self, Errno}; -use {Error, Result, NixPath}; -use fcntl::{fcntl, FdFlag, OFlag}; use fcntl::FcntlArg::F_SETFD; -use libc::{self, c_char, c_void, c_int, c_long, c_uint, size_t, pid_t, off_t, - uid_t, gid_t, mode_t}; -use std::{fmt, mem, ptr}; -use std::ffi::{CString, CStr, OsString, OsStr}; -use std::os::unix::ffi::{OsStringExt, OsStrExt}; +use fcntl::{fcntl, FdFlag, OFlag}; +use libc::{ + self, c_char, c_int, c_long, c_uint, c_void, gid_t, mode_t, off_t, pid_t, size_t, uid_t, +}; +use std::ffi::{CStr, CString, OsStr, OsString}; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::os::unix::io::RawFd; use std::path::PathBuf; -use void::Void; +use std::{fmt, mem, ptr}; use sys::stat::Mode; +use void::Void; +use {Error, NixPath, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::pivot_root::*; -#[cfg(any(target_os = "android", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] +#[cfg( + any(target_os = "android", target_os = "freebsd", target_os = "linux", target_os = "openbsd") +)] pub use self::setres::*; /// User identifier @@ -137,7 +139,6 @@ impl fmt::Display for Pid { } } - /// Represents the successful result of calling `fork` /// /// When `fork` is called, the process continues execution in the parent process @@ -150,13 +151,12 @@ pub enum ForkResult { } 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 + _ => false, } } @@ -275,7 +275,6 @@ pub fn getsid(pid: Option) -> Result { Errno::result(res).map(Pid) } - /// Get the terminal foreground process group (see /// [tcgetpgrp(3)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/tcgetpgrp.html)). /// @@ -297,7 +296,6 @@ pub fn tcsetpgrp(fd: c_int, pgrp: Pid) -> Result<()> { Errno::result(res).map(drop) } - /// Get the group id of the calling process (see ///[getpgrp(3)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getpgrp.html)). /// @@ -388,9 +386,7 @@ fn dup3_polyfill(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result { /// pages for additional details on possible failure cases. #[inline] pub fn chdir(path: &P) -> Result<()> { - let res = try!(path.with_nix_path(|cstr| { - unsafe { libc::chdir(cstr.as_ptr()) } - })); + let res = try!(path.with_nix_path(|cstr| unsafe { libc::chdir(cstr.as_ptr()) })); Errno::result(res).map(drop) } @@ -426,10 +422,10 @@ pub fn fchdir(dirfd: RawFd) -> Result<()> { /// /// use nix::unistd; /// use nix::sys::stat; -/// use tempfile::Builder; +/// use tempfile::tempdir; /// /// fn main() { -/// let tmp_dir1 = Builder::new().prefix("test_mkdir").tempdir().unwrap(); +/// let tmp_dir1 = tempdir().unwrap(); /// let tmp_dir2 = tmp_dir1.path().join("new_dir"); /// /// // create new directory and give read, write and execute rights to the owner @@ -441,9 +437,9 @@ pub fn fchdir(dirfd: RawFd) -> Result<()> { /// ``` #[inline] pub fn mkdir(path: &P, mode: Mode) -> Result<()> { - let res = try!(path.with_nix_path(|cstr| { - unsafe { libc::mkdir(cstr.as_ptr(), mode.bits() as mode_t) } - })); + let res = try!( + path.with_nix_path(|cstr| unsafe { libc::mkdir(cstr.as_ptr(), mode.bits() as mode_t) }) + ); Errno::result(res).map(drop) } @@ -469,10 +465,10 @@ pub fn mkdir(path: &P, mode: Mode) -> Result<()> { /// /// use nix::unistd; /// use nix::sys::stat; -/// use tempfile::Builder; +/// use tempfile::tempdir; /// /// fn main() { -/// let tmp_dir = Builder::new().prefix("test_fifo").tempdir().unwrap(); +/// let tmp_dir = tempdir().unwrap(); /// let fifo_path = tmp_dir.path().join("foo.pipe"); /// /// // create new fifo and give read, write and execute rights to the owner @@ -484,9 +480,9 @@ pub fn mkdir(path: &P, mode: Mode) -> Result<()> { /// ``` #[inline] pub fn mkfifo(path: &P, mode: Mode) -> Result<()> { - let res = try!(path.with_nix_path(|cstr| { - unsafe { libc::mkfifo(cstr.as_ptr(), mode.bits() as mode_t) } - })); + let res = try!( + path.with_nix_path(|cstr| unsafe { libc::mkfifo(cstr.as_ptr(), mode.bits() as mode_t) }) + ); Errno::result(res).map(drop) } @@ -521,7 +517,9 @@ pub fn getcwd() -> Result { // To safely handle this we start with a reasonable size (512 bytes) // and double the buffer size upon every error if !libc::getcwd(ptr, buf.capacity()).is_null() { - let len = CStr::from_ptr(buf.as_ptr() as *const c_char).to_bytes().len(); + let len = CStr::from_ptr(buf.as_ptr() as *const c_char) + .to_bytes() + .len(); buf.set_len(len); buf.shrink_to_fit(); return Ok(PathBuf::from(OsString::from_vec(buf))); @@ -555,9 +553,17 @@ pub fn chown(path: &P, owner: Option, group: Option Vec<*const c_char> { pub fn execv(path: &CString, argv: &[CString]) -> Result { let args_p = to_exec_array(argv); - unsafe { - libc::execv(path.as_ptr(), args_p.as_ptr()) - }; + unsafe { libc::execv(path.as_ptr(), args_p.as_ptr()) }; Err(Error::Sys(Errno::last())) } - /// Replace the current process image with a new one (see /// [execve(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html)). /// @@ -604,9 +607,7 @@ pub fn execve(path: &CString, args: &[CString], env: &[CString]) -> Result let args_p = to_exec_array(args); let env_p = to_exec_array(env); - unsafe { - libc::execve(path.as_ptr(), args_p.as_ptr(), env_p.as_ptr()) - }; + unsafe { libc::execve(path.as_ptr(), args_p.as_ptr(), env_p.as_ptr()) }; Err(Error::Sys(Errno::last())) } @@ -624,9 +625,7 @@ pub fn execve(path: &CString, args: &[CString], env: &[CString]) -> Result pub fn execvp(filename: &CString, args: &[CString]) -> Result { let args_p = to_exec_array(args); - unsafe { - libc::execvp(filename.as_ptr(), args_p.as_ptr()) - }; + unsafe { libc::execvp(filename.as_ptr(), args_p.as_ptr()) }; Err(Error::Sys(Errno::last())) } @@ -641,19 +640,21 @@ pub fn execvp(filename: &CString, args: &[CString]) -> Result { /// /// This function is similar to `execve`, except that the program to be executed /// is referenced as a file descriptor instead of a path. -#[cfg(any(target_os = "android", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "android", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd" + ) +)] #[inline] pub fn fexecve(fd: RawFd, args: &[CString], env: &[CString]) -> Result { let args_p = to_exec_array(args); let env_p = to_exec_array(env); - unsafe { - libc::fexecve(fd, args_p.as_ptr(), env_p.as_ptr()) - }; + unsafe { libc::fexecve(fd, args_p.as_ptr(), env_p.as_ptr()) }; Err(Error::Sys(Errno::last())) } @@ -670,14 +671,25 @@ pub fn fexecve(fd: RawFd, args: &[CString], env: &[CString]) -> Result { /// is referenced as a file descriptor to the base directory plus a path. #[cfg(any(target_os = "android", target_os = "linux"))] #[inline] -pub fn execveat(dirfd: RawFd, pathname: &CString, args: &[CString], - env: &[CString], flags: super::fcntl::AtFlags) -> Result { +pub fn execveat( + dirfd: RawFd, + pathname: &CString, + args: &[CString], + env: &[CString], + flags: super::fcntl::AtFlags, +) -> Result { let args_p = to_exec_array(args); let env_p = to_exec_array(env); unsafe { - libc::syscall(libc::SYS_execveat, dirfd, pathname.as_ptr(), - args_p.as_ptr(), env_p.as_ptr(), flags); + libc::syscall( + libc::SYS_execveat, + dirfd, + pathname.as_ptr(), + args_p.as_ptr(), + env_p.as_ptr(), + flags, + ); }; Err(Error::Sys(Errno::last())) @@ -844,21 +856,33 @@ pub enum Whence { /// Specify an offset relative to the next location in the file greater than or /// equal to offset that contains some data. If offset points to /// some data, then the file offset is set to offset. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - all(target_os = "linux", not(any(target_env = "musl", - target_arch = "mips", - target_arch = "mips64")))))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + all( + target_os = "linux", + not(any(target_env = "musl", target_arch = "mips", target_arch = "mips64")) + ) + ) + )] SeekData = libc::SEEK_DATA, /// Specify an offset relative to the next hole in the file greater than /// or equal to offset. If offset points into the middle of a hole, then /// the file offset should be set to offset. If there is no hole past offset, /// then the file offset should be adjusted to the end of the file (i.e., there /// is an implicit hole at the end of any file). - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - all(target_os = "linux", not(any(target_env = "musl", - target_arch = "mips", - target_arch = "mips64")))))] - SeekHole = libc::SEEK_HOLE + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + all( + target_os = "linux", + not(any(target_env = "musl", target_arch = "mips", target_arch = "mips64")) + ) + ) + )] + SeekHole = libc::SEEK_HOLE, } /// Move the read/write file offset. @@ -901,13 +925,17 @@ pub fn pipe() -> Result<(RawFd, RawFd)> { /// `O_NONBLOCK`: Set the non-blocking flag for the ends of the pipe. /// /// See also [pipe(2)](http://man7.org/linux/man-pages/man2/pipe.2.html) -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "emscripten", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "emscripten", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd" + ) +)] pub fn pipe2(flags: OFlag) -> Result<(RawFd, RawFd)> { let mut fds: [c_int; 2] = unsafe { mem::uninitialized() }; @@ -927,8 +955,8 @@ pub fn pipe2(flags: OFlag) -> Result<(RawFd, RawFd)> { /// `O_NONBLOCK`: Set the non-blocking flag for the ends of the pipe. #[cfg(any(target_os = "ios", target_os = "macos"))] #[deprecated( - since="0.10.0", - note="pipe2(2) is not actually atomic on these platforms. Use pipe(2) and fcntl(2) instead" + since = "0.10.0", + note = "pipe2(2) is not actually atomic on these platforms. Use pipe(2) and fcntl(2) instead" )] pub fn pipe2(flags: OFlag) -> Result<(RawFd, RawFd)> { let mut fds: [c_int; 2] = unsafe { mem::uninitialized() }; @@ -944,8 +972,8 @@ pub fn pipe2(flags: OFlag) -> Result<(RawFd, RawFd)> { #[cfg(any(target_os = "ios", target_os = "macos"))] fn pipe2_setflags(fd1: RawFd, fd2: RawFd, flags: OFlag) -> Result<()> { - use fcntl::FdFlag; use fcntl::FcntlArg::F_SETFL; + use fcntl::FdFlag; let mut res = Ok(0); @@ -1000,19 +1028,13 @@ pub fn isatty(fd: RawFd) -> Result { /// /// See also [unlink(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/unlink.html) pub fn unlink(path: &P) -> Result<()> { - let res = try!(path.with_nix_path(|cstr| { - unsafe { - libc::unlink(cstr.as_ptr()) - } - })); + let res = try!(path.with_nix_path(|cstr| unsafe { libc::unlink(cstr.as_ptr()) })); Errno::result(res).map(drop) } #[inline] pub fn chroot(path: &P) -> Result<()> { - let res = try!(path.with_nix_path(|cstr| { - unsafe { libc::chroot(cstr.as_ptr()) } - })); + let res = try!(path.with_nix_path(|cstr| unsafe { libc::chroot(cstr.as_ptr()) })); Errno::result(res).map(drop) } @@ -1033,9 +1055,7 @@ pub fn fsync(fd: RawFd) -> Result<()> { /// [fdatasync(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fdatasync.html) // `fdatasync(2) is in POSIX, but in libc it is only defined in `libc::notbsd`. // TODO: exclude only Apple systems after https://github.com/rust-lang/libc/pull/211 -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "emscripten"))] +#[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))] #[inline] pub fn fdatasync(fd: RawFd) -> Result<()> { let res = unsafe { libc::fdatasync(fd) }; @@ -1124,14 +1144,17 @@ pub fn getgroups() -> Result> { // the same representation in memory as a bare `gid_t`. This is not // necessarily the case on all Rust platforms, though. See RFC 1785. let ret = unsafe { - libc::getgroups(groups.capacity() as c_int, groups.as_mut_ptr() as *mut gid_t) + libc::getgroups( + groups.capacity() as c_int, + groups.as_mut_ptr() as *mut gid_t, + ) }; match Errno::result(ret) { Ok(s) => { unsafe { groups.set_len(s as usize) }; return Ok(groups); - }, + } Err(Error::Sys(Errno::EINVAL)) => { // EINVAL indicates that the buffer size was too small. Trigger // the internal buffer resizing logic of `Vec` by requiring @@ -1139,8 +1162,8 @@ pub fn getgroups() -> Result> { let cap = groups.capacity(); unsafe { groups.set_len(cap) }; groups.reserve(1); - }, - Err(e) => return Err(e) + } + Err(e) => return Err(e), } } } @@ -1196,7 +1219,10 @@ pub fn setgroups(groups: &[Gid]) -> Result<()> { // same representation in memory as a bare `gid_t`. This is not necessarily // the case on all Rust platforms, though. See RFC 1785. let res = unsafe { - libc::setgroups(groups.len() as setgroups_ngroups_t, groups.as_ptr() as *const gid_t) + libc::setgroups( + groups.len() as setgroups_ngroups_t, + groups.as_ptr() as *const gid_t, + ) }; Errno::result(res).map(|_| ()) @@ -1241,10 +1267,12 @@ pub fn getgrouplist(user: &CStr, group: Gid) -> Result> { let gid: gid_t = group.into(); loop { let ret = unsafe { - libc::getgrouplist(user.as_ptr(), - gid as getgrouplist_group_t, - groups.as_mut_ptr() as *mut getgrouplist_group_t, - &mut ngroups) + libc::getgrouplist( + user.as_ptr(), + gid as getgrouplist_group_t, + groups.as_mut_ptr() as *mut getgrouplist_group_t, + &mut ngroups, + ) }; // BSD systems only return 0 or -1, Linux returns ngroups on success. @@ -1396,7 +1424,10 @@ pub mod alarm { /// /// Returns the leftover time of a previously set alarm if there was one. pub fn set(secs: libc::c_uint) -> Option { - assert!(secs != 0, "passing 0 to `alarm::set` is not allowed, to cancel an alarm use `alarm::cancel`"); + assert!( + secs != 0, + "passing 0 to `alarm::set` is not allowed, to cancel an alarm use `alarm::cancel`" + ); alarm(secs) } @@ -1450,7 +1481,7 @@ pub fn sleep(seconds: c_uint) -> c_uint { /// ``` #[inline] pub fn mkstemp(template: &P) -> Result<(RawFd, PathBuf)> { - let mut path = try!(template.with_nix_path(|path| {path.to_bytes_with_nul().to_owned()})); + let mut path = try!(template.with_nix_path(|path| path.to_bytes_with_nul().to_owned())); let p = path.as_mut_ptr() as *mut _; let fd = unsafe { libc::mkstemp(p) }; let last = path.pop(); // drop the trailing nul @@ -1479,8 +1510,15 @@ pub fn mkstemp(template: &P) -> Result<(RawFd, PathBuf)> { #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[repr(i32)] pub enum PathconfVar { - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "linux", - target_os = "netbsd", target_os = "openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// Minimum number of bits needed to represent, as a signed integer value, /// the maximum size of a regular file allowed in the specified directory. FILESIZEBITS = libc::_PC_FILESIZEBITS, @@ -1503,34 +1541,84 @@ pub enum PathconfVar { /// Maximum number of bytes that is guaranteed to be atomic when writing to /// a pipe. PIPE_BUF = libc::_PC_PIPE_BUF, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "linux", - target_os = "netbsd", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// Symbolic links can be created. POSIX2_SYMLINKS = libc::_PC_2_SYMLINKS, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" + ) + )] /// Minimum number of bytes of storage actually allocated for any portion of /// a file. POSIX_ALLOC_SIZE_MIN = libc::_PC_ALLOC_SIZE_MIN, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" + ) + )] /// Recommended increment for file transfer sizes between the /// `POSIX_REC_MIN_XFER_SIZE` and `POSIX_REC_MAX_XFER_SIZE` values. POSIX_REC_INCR_XFER_SIZE = libc::_PC_REC_INCR_XFER_SIZE, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" + ) + )] /// Maximum recommended file transfer size. POSIX_REC_MAX_XFER_SIZE = libc::_PC_REC_MAX_XFER_SIZE, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" + ) + )] /// Minimum recommended file transfer size. POSIX_REC_MIN_XFER_SIZE = libc::_PC_REC_MIN_XFER_SIZE, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" + ) + )] /// Recommended file transfer buffer alignment. POSIX_REC_XFER_ALIGN = libc::_PC_REC_XFER_ALIGN, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// Maximum number of bytes in a symbolic link. SYMLINK_MAX = libc::_PC_SYMLINK_MAX, /// The use of `chown` and `fchown` is restricted to a process with @@ -1543,24 +1631,46 @@ pub enum PathconfVar { /// This symbol shall be defined to be the value of a character that shall /// disable terminal special character handling. _POSIX_VDISABLE = libc::_PC_VDISABLE, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" + ) + )] /// Asynchronous input or output operations may be performed for the /// associated file. _POSIX_ASYNC_IO = libc::_PC_ASYNC_IO, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" + ) + )] /// Prioritized input or output operations may be performed for the /// associated file. _POSIX_PRIO_IO = libc::_PC_PRIO_IO, - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// Synchronized input or output operations may be performed for the /// associated file. _POSIX_SYNC_IO = libc::_PC_SYNC_IO, #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] /// The resolution in nanoseconds for all file timestamps. - _POSIX_TIMESTAMP_RESOLUTION = libc::_PC_TIMESTAMP_RESOLUTION + _POSIX_TIMESTAMP_RESOLUTION = libc::_PC_TIMESTAMP_RESOLUTION, } /// Like `pathconf`, but works with file descriptors instead of paths (see @@ -1617,11 +1727,9 @@ pub fn fpathconf(fd: RawFd, var: PathconfVar) -> Result> { /// unsupported (for option variables) /// - `Err(x)`: an error occurred pub fn pathconf(path: &P, var: PathconfVar) -> Result> { - let raw = try!(path.with_nix_path(|cstr| { - unsafe { - Errno::clear(); - libc::pathconf(cstr.as_ptr(), var as c_int) - } + let raw = try!(path.with_nix_path(|cstr| unsafe { + Errno::clear(); + libc::pathconf(cstr.as_ptr(), var as c_int) })); if raw == -1 { if errno::errno() == 0 { @@ -1659,9 +1767,17 @@ pub enum SysconfVar { /// Maximum number of outstanding asynchronous I/O operations supported by /// the implementation. AIO_MAX = libc::_SC_AIO_MAX, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The maximum amount by which a process can decrease its asynchronous I/O /// priority level from its own scheduling priority. AIO_PRIO_DELTA_MAX = libc::_SC_AIO_PRIO_DELTA_MAX, @@ -1688,9 +1804,17 @@ pub enum SysconfVar { /// Maximum number of expressions that can be nested within parentheses by /// the expr utility. EXPR_NEST_MAX = libc::_SC_EXPR_NEST_MAX, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// Maximum length of a host name (not including the terminating null) as /// returned from the `gethostname` function HOST_NAME_MAX = libc::_SC_HOST_NAME_MAX, @@ -1717,31 +1841,71 @@ pub enum SysconfVar { /// A value one greater than the maximum value that the system may assign to /// a newly-created file descriptor. OPEN_MAX = libc::_SC_OPEN_MAX, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Advisory Information option. _POSIX_ADVISORY_INFO = libc::_SC_ADVISORY_INFO, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports barriers. _POSIX_BARRIERS = libc::_SC_BARRIERS, /// The implementation supports asynchronous input and output. _POSIX_ASYNCHRONOUS_IO = libc::_SC_ASYNCHRONOUS_IO, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports clock selection. _POSIX_CLOCK_SELECTION = libc::_SC_CLOCK_SELECTION, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Process CPU-Time Clocks option. _POSIX_CPUTIME = libc::_SC_CPUTIME, /// The implementation supports the File Synchronization option. _POSIX_FSYNC = libc::_SC_FSYNC, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the IPv6 option. _POSIX_IPV6 = libc::_SC_IPV6, /// The implementation supports job control. @@ -1758,30 +1922,70 @@ pub enum SysconfVar { _POSIX_MESSAGE_PASSING = libc::_SC_MESSAGE_PASSING, /// The implementation supports the Monotonic Clock option. _POSIX_MONOTONIC_CLOCK = libc::_SC_MONOTONIC_CLOCK, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Prioritized Input and Output option. _POSIX_PRIORITIZED_IO = libc::_SC_PRIORITIZED_IO, /// The implementation supports the Process Scheduling option. _POSIX_PRIORITY_SCHEDULING = libc::_SC_PRIORITY_SCHEDULING, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Raw Sockets option. _POSIX_RAW_SOCKETS = libc::_SC_RAW_SOCKETS, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports read-write locks. _POSIX_READER_WRITER_LOCKS = libc::_SC_READER_WRITER_LOCKS, - #[cfg(any(target_os = "android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports realtime signals. _POSIX_REALTIME_SIGNALS = libc::_SC_REALTIME_SIGNALS, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Regular Expression Handling option. _POSIX_REGEXP = libc::_SC_REGEXP, /// Each process has a saved set-user-ID and a saved set-group-ID. @@ -1790,27 +1994,58 @@ pub enum SysconfVar { _POSIX_SEMAPHORES = libc::_SC_SEMAPHORES, /// The implementation supports the Shared Memory Objects option. _POSIX_SHARED_MEMORY_OBJECTS = libc::_SC_SHARED_MEMORY_OBJECTS, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the POSIX shell. _POSIX_SHELL = libc::_SC_SHELL, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Spawn option. _POSIX_SPAWN = libc::_SC_SPAWN, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports spin locks. _POSIX_SPIN_LOCKS = libc::_SC_SPIN_LOCKS, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Process Sporadic Server option. _POSIX_SPORADIC_SERVER = libc::_SC_SPORADIC_SERVER, - #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg(any(target_os = "ios", target_os = "linux", target_os = "macos", target_os = "openbsd"))] _POSIX_SS_REPL_MAX = libc::_SC_SS_REPL_MAX, /// The implementation supports the Synchronized Input and Output option. _POSIX_SYNCHRONIZED_IO = libc::_SC_SYNCHRONIZED_IO, @@ -1818,8 +2053,15 @@ pub enum SysconfVar { _POSIX_THREAD_ATTR_STACKADDR = libc::_SC_THREAD_ATTR_STACKADDR, /// The implementation supports the Thread Stack Size Attribute option. _POSIX_THREAD_ATTR_STACKSIZE = libc::_SC_THREAD_ATTR_STACKSIZE, - #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos", - target_os="netbsd", target_os="openbsd"))] + #[cfg( + any( + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Thread CPU-Time Clocks option. _POSIX_THREAD_CPUTIME = libc::_SC_THREAD_CPUTIME, /// The implementation supports the Non-Robust Mutex Priority Inheritance @@ -1829,90 +2071,182 @@ pub enum SysconfVar { _POSIX_THREAD_PRIO_PROTECT = libc::_SC_THREAD_PRIO_PROTECT, /// The implementation supports the Thread Execution Scheduling option. _POSIX_THREAD_PRIORITY_SCHEDULING = libc::_SC_THREAD_PRIORITY_SCHEDULING, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Thread Process-Shared Synchronization /// option. _POSIX_THREAD_PROCESS_SHARED = libc::_SC_THREAD_PROCESS_SHARED, - #[cfg(any(target_os="dragonfly", target_os="linux", target_os="openbsd"))] + #[cfg(any(target_os = "dragonfly", target_os = "linux", target_os = "openbsd"))] /// The implementation supports the Robust Mutex Priority Inheritance option. _POSIX_THREAD_ROBUST_PRIO_INHERIT = libc::_SC_THREAD_ROBUST_PRIO_INHERIT, - #[cfg(any(target_os="dragonfly", target_os="linux", target_os="openbsd"))] + #[cfg(any(target_os = "dragonfly", target_os = "linux", target_os = "openbsd"))] /// The implementation supports the Robust Mutex Priority Protection option. _POSIX_THREAD_ROBUST_PRIO_PROTECT = libc::_SC_THREAD_ROBUST_PRIO_PROTECT, /// The implementation supports thread-safe functions. _POSIX_THREAD_SAFE_FUNCTIONS = libc::_SC_THREAD_SAFE_FUNCTIONS, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Thread Sporadic Server option. _POSIX_THREAD_SPORADIC_SERVER = libc::_SC_THREAD_SPORADIC_SERVER, /// The implementation supports threads. _POSIX_THREADS = libc::_SC_THREADS, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports timeouts. _POSIX_TIMEOUTS = libc::_SC_TIMEOUTS, /// The implementation supports timers. _POSIX_TIMERS = libc::_SC_TIMERS, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Trace option. _POSIX_TRACE = libc::_SC_TRACE, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Trace Event Filter option. _POSIX_TRACE_EVENT_FILTER = libc::_SC_TRACE_EVENT_FILTER, - #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg(any(target_os = "ios", target_os = "linux", target_os = "macos", target_os = "openbsd"))] _POSIX_TRACE_EVENT_NAME_MAX = libc::_SC_TRACE_EVENT_NAME_MAX, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Trace Inherit option. _POSIX_TRACE_INHERIT = libc::_SC_TRACE_INHERIT, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Trace Log option. _POSIX_TRACE_LOG = libc::_SC_TRACE_LOG, - #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg(any(target_os = "ios", target_os = "linux", target_os = "macos", target_os = "openbsd"))] _POSIX_TRACE_NAME_MAX = libc::_SC_TRACE_NAME_MAX, - #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg(any(target_os = "ios", target_os = "linux", target_os = "macos", target_os = "openbsd"))] _POSIX_TRACE_SYS_MAX = libc::_SC_TRACE_SYS_MAX, - #[cfg(any(target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg(any(target_os = "ios", target_os = "linux", target_os = "macos", target_os = "openbsd"))] _POSIX_TRACE_USER_EVENT_MAX = libc::_SC_TRACE_USER_EVENT_MAX, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Typed Memory Objects option. _POSIX_TYPED_MEMORY_OBJECTS = libc::_SC_TYPED_MEMORY_OBJECTS, /// Integer value indicating version of this standard (C-language binding) /// to which the implementation conforms. For implementations conforming to /// POSIX.1-2008, the value shall be 200809L. _POSIX_VERSION = libc::_SC_VERSION, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation provides a C-language compilation environment with /// 32-bit `int`, `long`, `pointer`, and `off_t` types. _POSIX_V6_ILP32_OFF32 = libc::_SC_V6_ILP32_OFF32, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation provides a C-language compilation environment with /// 32-bit `int`, `long`, and pointer types and an `off_t` type using at /// least 64 bits. _POSIX_V6_ILP32_OFFBIG = libc::_SC_V6_ILP32_OFFBIG, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation provides a C-language compilation environment with /// 32-bit `int` and 64-bit `long`, `pointer`, and `off_t` types. _POSIX_V6_LP64_OFF64 = libc::_SC_V6_LP64_OFF64, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation provides a C-language compilation environment with an /// `int` type using at least 32 bits and `long`, pointer, and `off_t` types /// using at least 64 bits. @@ -1930,35 +2264,83 @@ pub enum SysconfVar { /// The implementation supports the creation of locales by the localedef /// utility. _POSIX2_LOCALEDEF = libc::_SC_2_LOCALEDEF, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Batch Environment Services and Utilities /// option. _POSIX2_PBS = libc::_SC_2_PBS, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Batch Accounting option. _POSIX2_PBS_ACCOUNTING = libc::_SC_2_PBS_ACCOUNTING, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Batch Checkpoint/Restart option. _POSIX2_PBS_CHECKPOINT = libc::_SC_2_PBS_CHECKPOINT, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Locate Batch Job Request option. _POSIX2_PBS_LOCATE = libc::_SC_2_PBS_LOCATE, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Batch Job Message Request option. _POSIX2_PBS_MESSAGE = libc::_SC_2_PBS_MESSAGE, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] /// The implementation supports the Track Batch Job Request option. _POSIX2_PBS_TRACK = libc::_SC_2_PBS_TRACK, /// The implementation supports the Software Development Utilities option. @@ -1978,67 +2360,163 @@ pub enum SysconfVar { PTHREAD_STACK_MIN = libc::_SC_THREAD_STACK_MIN, PTHREAD_THREADS_MAX = libc::_SC_THREAD_THREADS_MAX, RE_DUP_MAX = libc::_SC_RE_DUP_MAX, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] RTSIG_MAX = libc::_SC_RTSIG_MAX, SEM_NSEMS_MAX = libc::_SC_SEM_NSEMS_MAX, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] SEM_VALUE_MAX = libc::_SC_SEM_VALUE_MAX, - #[cfg(any(target_os = "android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os = "openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] SIGQUEUE_MAX = libc::_SC_SIGQUEUE_MAX, STREAM_MAX = libc::_SC_STREAM_MAX, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="netbsd", - target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) + )] SYMLOOP_MAX = libc::_SC_SYMLOOP_MAX, TIMER_MAX = libc::_SC_TIMER_MAX, TTY_NAME_MAX = libc::_SC_TTY_NAME_MAX, TZNAME_MAX = libc::_SC_TZNAME_MAX, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the X/Open Encryption Option Group. _XOPEN_CRYPT = libc::_SC_XOPEN_CRYPT, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the Issue 4, Version 2 Enhanced /// Internationalization Option Group. _XOPEN_ENH_I18N = libc::_SC_XOPEN_ENH_I18N, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] _XOPEN_LEGACY = libc::_SC_XOPEN_LEGACY, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the X/Open Realtime Option Group. _XOPEN_REALTIME = libc::_SC_XOPEN_REALTIME, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the X/Open Realtime Threads Option Group. _XOPEN_REALTIME_THREADS = libc::_SC_XOPEN_REALTIME_THREADS, /// The implementation supports the Issue 4, Version 2 Shared Memory Option /// Group. _XOPEN_SHM = libc::_SC_XOPEN_SHM, - #[cfg(any(target_os="dragonfly", target_os="freebsd", target_os = "ios", - target_os="linux", target_os = "macos", target_os="openbsd"))] + #[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the XSI STREAMS Option Group. _XOPEN_STREAMS = libc::_SC_XOPEN_STREAMS, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// The implementation supports the XSI option _XOPEN_UNIX = libc::_SC_XOPEN_UNIX, - #[cfg(any(target_os="android", target_os="dragonfly", target_os="freebsd", - target_os = "ios", target_os="linux", target_os = "macos", - target_os="openbsd"))] + #[cfg( + any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "openbsd" + ) + )] /// Integer value indicating version of the X/Open Portability Guide to /// which the implementation conforms. _XOPEN_VERSION = libc::_SC_XOPEN_VERSION, @@ -2078,17 +2556,17 @@ pub fn sysconf(var: SysconfVar) -> Result> { #[cfg(any(target_os = "android", target_os = "linux"))] mod pivot_root { - use libc; - use {Result, NixPath}; use errno::Errno; + use libc; + use {NixPath, Result}; pub fn pivot_root( - new_root: &P1, put_old: &P2) -> Result<()> { + new_root: &P1, + put_old: &P2, + ) -> Result<()> { let res = try!(try!(new_root.with_nix_path(|new_root| { - put_old.with_nix_path(|put_old| { - unsafe { - libc::syscall(libc::SYS_pivot_root, new_root.as_ptr(), put_old.as_ptr()) - } + put_old.with_nix_path(|put_old| unsafe { + libc::syscall(libc::SYS_pivot_root, new_root.as_ptr(), put_old.as_ptr()) }) }))); @@ -2096,13 +2574,14 @@ mod pivot_root { } } -#[cfg(any(target_os = "android", target_os = "freebsd", - target_os = "linux", target_os = "openbsd"))] +#[cfg( + any(target_os = "android", target_os = "freebsd", target_os = "linux", target_os = "openbsd") +)] mod setres { + use super::{Gid, Uid}; + use errno::Errno; use libc; use Result; - use errno::Errno; - use super::{Uid, Gid}; /// Sets the real, effective, and saved uid. /// ([see setresuid(2)](http://man7.org/linux/man-pages/man2/setresuid.2.html)) diff --git a/test/sys/mod.rs b/test/sys/mod.rs index bdc079d84c..517861208d 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -5,27 +5,30 @@ mod test_signal; // works or not heavily depends on which pthread implementation is chosen // by the user at link time. For this reason we do not want to run aio test // cases on DragonFly. -#[cfg(any(target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd"))] +#[cfg( + any( + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd" + ) +)] mod test_aio; +mod test_ioctl; +mod test_select; #[cfg(target_os = "linux")] mod test_signalfd; mod test_socket; mod test_sockopt; -mod test_select; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_sysinfo; mod test_termios; -mod test_ioctl; -mod test_wait; mod test_uio; +mod test_wait; #[cfg(target_os = "linux")] mod test_epoll; mod test_pthread; -#[cfg(any(target_os = "android", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux"))] mod test_ptrace; diff --git a/test/sys/test_aio.rs b/test/sys/test_aio.rs index d4b09b0b81..5c29d3005a 100644 --- a/test/sys/test_aio.rs +++ b/test/sys/test_aio.rs @@ -1,11 +1,11 @@ use bytes::{Bytes, BytesMut}; use libc::{c_int, c_void}; -use nix::{Error, Result}; use nix::errno::*; use nix::sys::aio::*; -use nix::sys::signal::{SaFlags, SigAction, sigaction, SigevNotify, SigHandler, Signal, SigSet}; +use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, SigevNotify, Signal}; use nix::sys::time::{TimeSpec, TimeValLike}; -use std::io::{Write, Read, Seek, SeekFrom}; +use nix::{Error, Result}; +use std::io::{Read, Seek, SeekFrom, Write}; use std::ops::Deref; use std::os::unix::io::AsRawFd; use std::sync::atomic::{AtomicBool, Ordering}; @@ -16,7 +16,9 @@ use tempfile::tempfile; fn poll_aio(aiocb: &mut AioCb) -> Result<()> { loop { let err = aiocb.error(); - if err != Err(Error::from(Errno::EINPROGRESS)) { return err; }; + if err != Err(Error::from(Errno::EINPROGRESS)) { + return err; + }; thread::sleep(time::Duration::from_millis(10)); } } @@ -24,15 +26,17 @@ fn poll_aio(aiocb: &mut AioCb) -> Result<()> { #[test] fn test_accessors() { let mut rbuf = vec![0; 4]; - let aiocb = AioCb::from_mut_slice( 1001, - 2, //offset - &mut rbuf, - 42, //priority - SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, - si_value: 99 - }, - LioOpcode::LIO_NOP); + let aiocb = AioCb::from_mut_slice( + 1001, + 2, //offset + &mut rbuf, + 42, //priority + SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 99, + }, + LioOpcode::LIO_NOP, + ); assert_eq!(1001, aiocb.fd()); assert_eq!(Some(LioOpcode::LIO_NOP), aiocb.lio_opcode()); assert_eq!(4, aiocb.nbytes()); @@ -52,12 +56,14 @@ fn test_cancel() { let wbuf: &[u8] = b"CDEF"; let f = tempfile().unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 0, //offset - wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_slice( + f.as_raw_fd(), + 0, //offset + wbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.write().unwrap(); let err = aiocb.error(); assert!(err == Ok(()) || err == Err(Error::from(Errno::EINPROGRESS))); @@ -77,12 +83,14 @@ fn test_aio_cancel_all() { let wbuf: &[u8] = b"CDEF"; let f = tempfile().unwrap(); - let mut aiocb = AioCb::from_slice(f.as_raw_fd(), - 0, //offset - wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_slice( + f.as_raw_fd(), + 0, //offset + wbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.write().unwrap(); let err = aiocb.error(); assert!(err == Ok(()) || err == Err(Error::from(Errno::EINPROGRESS))); @@ -101,9 +109,11 @@ fn test_fsync() { const INITIAL: &[u8] = b"abcdef123456"; let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_fd( f.as_raw_fd(), - 0, //priority - SigevNotify::SigevNone); + let mut aiocb = AioCb::from_fd( + f.as_raw_fd(), + 0, //priority + SigevNotify::SigevNone, + ); let err = aiocb.fsync(AioFsyncMode::O_SYNC); assert!(err.is_ok()); poll_aio(&mut aiocb).unwrap(); @@ -124,9 +134,11 @@ fn test_fsync_error() { let mode = unsafe { mem::transmute(666) }; let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_fd( f.as_raw_fd(), - 0, //priority - SigevNotify::SigevNone); + let mut aiocb = AioCb::from_fd( + f.as_raw_fd(), + 0, //priority + SigevNotify::SigevNone, + ); let err = aiocb.fsync(mode); assert!(err.is_err()); } @@ -142,19 +154,23 @@ fn test_aio_suspend() { let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut wcb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE); - - let mut rcb = AioCb::from_mut_slice( f.as_raw_fd(), - 8, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ); + let mut wcb = AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_WRITE, + ); + + let mut rcb = AioCb::from_mut_slice( + f.as_raw_fd(), + 8, //offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_READ, + ); wcb.write().unwrap(); rcb.read().unwrap(); loop { @@ -162,9 +178,10 @@ fn test_aio_suspend() { let cbbuf = [&wcb, &rcb]; assert!(aio_suspend(&cbbuf[..], Some(timeout)).is_ok()); } - if rcb.error() != Err(Error::from(Errno::EINPROGRESS)) && - wcb.error() != Err(Error::from(Errno::EINPROGRESS)) { - break + if rcb.error() != Err(Error::from(Errno::EINPROGRESS)) + && wcb.error() != Err(Error::from(Errno::EINPROGRESS)) + { + break; } } @@ -183,12 +200,14 @@ fn test_read() { let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); { - let mut aiocb = AioCb::from_mut_slice( f.as_raw_fd(), - 2, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_mut_slice( + f.as_raw_fd(), + 2, //offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.read().unwrap(); let err = poll_aio(&mut aiocb); @@ -210,12 +229,14 @@ fn test_read_error() { let mut rbuf = vec![0; 4]; let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_mut_slice( f.as_raw_fd(), - -1, //an invalid offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_mut_slice( + f.as_raw_fd(), + -1, //an invalid offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); assert!(aiocb.read().is_err()); } @@ -229,12 +250,14 @@ fn test_read_into_mut_slice() { let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); { - let mut aiocb = AioCb::from_mut_slice( f.as_raw_fd(), - 2, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_mut_slice( + f.as_raw_fd(), + 2, //offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.read().unwrap(); let err = poll_aio(&mut aiocb); @@ -257,13 +280,15 @@ fn test_read_into_pointer() { { // Safety: ok because rbuf lives until after poll_aio let mut aiocb = unsafe { - AioCb::from_mut_ptr( f.as_raw_fd(), - 2, //offset - rbuf.as_mut_ptr() as *mut c_void, - rbuf.len(), - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP) + AioCb::from_mut_ptr( + f.as_raw_fd(), + 2, //offset + rbuf.as_mut_ptr() as *mut c_void, + rbuf.len(), + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ) }; aiocb.read().unwrap(); @@ -283,16 +308,17 @@ fn test_read_into_pointer() { fn test_read_immutable_buffer() { let rbuf: &[u8] = b"CDEF"; let f = tempfile().unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.read().unwrap(); } - // Test a simple aio operation with no completion notification. We must poll // for completion. Unlike test_aio_read, this test uses AioCb::from_slice #[test] @@ -305,12 +331,14 @@ fn test_write() { let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - &wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + &wbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.write().unwrap(); let err = poll_aio(&mut aiocb); @@ -335,12 +363,14 @@ fn test_write_bytes() { let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_boxed_slice( f.as_raw_fd(), - 2, //offset - wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_boxed_slice( + f.as_raw_fd(), + 2, //offset + wbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.write().unwrap(); let err = poll_aio(&mut aiocb); @@ -363,12 +393,14 @@ fn test_read_bytes_mut_small() { let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_boxed_mut_slice( f.as_raw_fd(), - 2, //offset - rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_boxed_mut_slice( + f.as_raw_fd(), + 2, //offset + rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.read().unwrap(); let err = poll_aio(&mut aiocb); @@ -391,13 +423,15 @@ fn test_write_from_pointer() { f.write_all(INITIAL).unwrap(); // Safety: ok because aiocb outlives poll_aio let mut aiocb = unsafe { - AioCb::from_ptr( f.as_raw_fd(), - 2, //offset - wbuf.as_ptr() as *const c_void, - wbuf.len(), - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP) + AioCb::from_ptr( + f.as_raw_fd(), + 2, //offset + wbuf.as_ptr() as *const c_void, + wbuf.len(), + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ) }; aiocb.write().unwrap(); @@ -419,12 +453,14 @@ fn test_write_from_pointer() { #[cfg(any(target_os = "freebsd", target_os = "macos"))] fn test_write_error() { let wbuf = "CDEF".to_string().into_bytes(); - let mut aiocb = AioCb::from_slice( 666, // An invalid file descriptor - 0, //offset - &wbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_slice( + 666, // An invalid file descriptor + 0, //offset + &wbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); assert!(aiocb.write().is_err()); } @@ -432,19 +468,30 @@ lazy_static! { pub static ref SIGNALED: AtomicBool = AtomicBool::new(false); } -extern fn sigfunc(_: c_int) { +extern "C" fn sigfunc(_: c_int) { SIGNALED.store(true, Ordering::Relaxed); } // Test an aio operation with completion delivered by a signal // FIXME: This test is ignored on mips because of failures in qemu in CI #[test] -#[cfg_attr(any(all(target_env = "musl", target_arch = "x86_64"), target_arch = "mips", target_arch = "mips64"), ignore)] +#[cfg_attr( + any( + all(target_env = "musl", target_arch = "x86_64"), + target_arch = "mips", + target_arch = "mips64" + ), + ignore +)] fn test_write_sigev_signal() { - let _m = ::SIGNAL_MTX.lock().expect("Mutex got poisoned by another test"); - let sa = SigAction::new(SigHandler::Handler(sigfunc), - SaFlags::SA_RESETHAND, - SigSet::empty()); + let _m = ::SIGNAL_MTX + .lock() + .expect("Mutex got poisoned by another test"); + let sa = SigAction::new( + SigHandler::Handler(sigfunc), + SaFlags::SA_RESETHAND, + SigSet::empty(), + ); SIGNALED.store(false, Ordering::Relaxed); unsafe { sigaction(Signal::SIGUSR2, &sa) }.unwrap(); @@ -455,15 +502,17 @@ fn test_write_sigev_signal() { let mut f = tempfile().unwrap(); f.write_all(INITIAL).unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, - si_value: 0 //TODO: validate in sigfunc - }, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 0, //TODO: validate in sigfunc + }, + LioOpcode::LIO_NOP, + ); aiocb.write().unwrap(); while !SIGNALED.load(Ordering::Relaxed) { thread::sleep(time::Duration::from_millis(10)); @@ -493,19 +542,23 @@ fn test_liocb_listio_wait() { f.write_all(INITIAL).unwrap(); { - let wcb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE); - - let rcb = AioCb::from_mut_slice( f.as_raw_fd(), - 8, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ); + let wcb = AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_WRITE, + ); + + let rcb = AioCb::from_mut_slice( + f.as_raw_fd(), + 8, //offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_READ, + ); let mut liocb = LioCb::with_capacity(2); liocb.aiocbs.push(wcb); liocb.aiocbs.push(rcb); @@ -540,19 +593,23 @@ fn test_liocb_listio_nowait() { f.write_all(INITIAL).unwrap(); { - let wcb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE); - - let rcb = AioCb::from_mut_slice( f.as_raw_fd(), - 8, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ); + let wcb = AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_WRITE, + ); + + let rcb = AioCb::from_mut_slice( + f.as_raw_fd(), + 8, //offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_READ, + ); let mut liocb = LioCb::with_capacity(2); liocb.aiocbs.push(wcb); liocb.aiocbs.push(rcb); @@ -579,7 +636,9 @@ fn test_liocb_listio_nowait() { #[cfg(not(any(target_os = "ios", target_os = "macos")))] #[cfg_attr(any(target_arch = "mips", target_arch = "mips64", target_env = "musl"), ignore)] fn test_liocb_listio_signal() { - let _m = ::SIGNAL_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::SIGNAL_MTX + .lock() + .expect("Mutex got poisoned by another test"); const INITIAL: &[u8] = b"abcdef123456"; const WBUF: &[u8] = b"CDEF"; let mut rbuf = vec![0; 4]; @@ -587,28 +646,36 @@ fn test_liocb_listio_signal() { let mut rbuf2 = Vec::new(); const EXPECT: &[u8] = b"abCDEF123456"; let mut f = tempfile().unwrap(); - let sa = SigAction::new(SigHandler::Handler(sigfunc), - SaFlags::SA_RESETHAND, - SigSet::empty()); - let sigev_notify = SigevNotify::SigevSignal { signal: Signal::SIGUSR2, - si_value: 0 }; + let sa = SigAction::new( + SigHandler::Handler(sigfunc), + SaFlags::SA_RESETHAND, + SigSet::empty(), + ); + let sigev_notify = SigevNotify::SigevSignal { + signal: Signal::SIGUSR2, + si_value: 0, + }; f.write_all(INITIAL).unwrap(); { - let wcb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE); - - let rcb = AioCb::from_mut_slice( f.as_raw_fd(), - 8, //offset - &mut rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ); + let wcb = AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_WRITE, + ); + + let rcb = AioCb::from_mut_slice( + f.as_raw_fd(), + 8, //offset + &mut rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_READ, + ); let mut liocb = LioCb::with_capacity(2); liocb.aiocbs.push(wcb); liocb.aiocbs.push(rcb); @@ -641,14 +708,13 @@ fn test_liocb_listio_read_immutable() { let rbuf: &[u8] = b"abcd"; let f = tempfile().unwrap(); - - let mut liocb = LioCb::from(vec![ - AioCb::from_slice( f.as_raw_fd(), - 2, //offset - rbuf, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_READ) - ]); + let mut liocb = LioCb::from(vec![AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + rbuf, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_READ, + )]); let _ = liocb.listio(LioMode::LIO_NOWAIT, SigevNotify::SigevNone); } diff --git a/test/sys/test_aio_drop.rs b/test/sys/test_aio_drop.rs index 1f4a3e7963..bdb5375f90 100644 --- a/test/sys/test_aio_drop.rs +++ b/test/sys/test_aio_drop.rs @@ -17,11 +17,13 @@ fn test_drop() { let f = tempfile().unwrap(); f.set_len(6).unwrap(); - let mut aiocb = AioCb::from_slice( f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_NOP); + let mut aiocb = AioCb::from_slice( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_NOP, + ); aiocb.write().unwrap(); } diff --git a/test/sys/test_epoll.rs b/test/sys/test_epoll.rs index e0dc5131de..7e99478d1f 100644 --- a/test/sys/test_epoll.rs +++ b/test/sys/test_epoll.rs @@ -1,7 +1,7 @@ -use nix::sys::epoll::{EpollCreateFlags, EpollFlags, EpollOp, EpollEvent}; +use nix::errno::Errno; use nix::sys::epoll::{epoll_create1, epoll_ctl}; +use nix::sys::epoll::{EpollCreateFlags, EpollEvent, EpollFlags, EpollOp}; use nix::Error; -use nix::errno::Errno; #[test] pub fn test_epoll_errno() { diff --git a/test/sys/test_ioctl.rs b/test/sys/test_ioctl.rs index 0a439b3346..e509c7d8d0 100644 --- a/test/sys/test_ioctl.rs +++ b/test/sys/test_ioctl.rs @@ -32,7 +32,12 @@ ioctl_readwrite_buf!(readwritebuf_test, 0, 0, u32); mod linux { #[test] fn test_op_none() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_none!(b'q', 10), 0x2000_710A); assert_eq!(request_code_none!(b'a', 255), 0x2000_61FF); } else { @@ -43,7 +48,12 @@ mod linux { #[test] fn test_op_write() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_write!(b'z', 10, 1), 0x8001_7A0A); assert_eq!(request_code_write!(b'z', 10, 512), 0x8200_7A0A); } else { @@ -55,17 +65,21 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_write_64() { - if cfg!(any(target_arch = "mips64", target_arch="powerpc64")){ + if cfg!(any(target_arch = "mips64", target_arch = "powerpc64")) { assert_eq!(request_code_write!(b'z', 10, (1 as u64) << 32), 0x8000_7A0A); } else { assert_eq!(request_code_write!(b'z', 10, (1 as u64) << 32), 0x4000_7A0A); } - } #[test] fn test_op_read() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_read!(b'z', 10, 1), 0x4001_7A0A); assert_eq!(request_code_read!(b'z', 10, 512), 0x4200_7A0A); } else { @@ -77,7 +91,7 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_64() { - if cfg!(any(target_arch = "mips64", target_arch="powerpc64")){ + if cfg!(any(target_arch = "mips64", target_arch = "powerpc64")) { assert_eq!(request_code_read!(b'z', 10, (1 as u64) << 32), 0x4000_7A0A); } else { assert_eq!(request_code_read!(b'z', 10, (1 as u64) << 32), 0x8000_7A0A); @@ -93,16 +107,23 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_write_64() { - assert_eq!(request_code_readwrite!(b'z', 10, (1 as u64) << 32), 0xC000_7A0A); + assert_eq!( + request_code_readwrite!(b'z', 10, (1 as u64) << 32), + 0xC000_7A0A + ); } } -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) +)] mod bsd { #[test] fn test_op_none() { @@ -150,7 +171,10 @@ mod bsd { #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_write_64() { - assert_eq!(request_code_readwrite!(b'z', 10, (1 as u64) << 32), 0xC000_7A0A); + assert_eq!( + request_code_readwrite!(b'z', 10, (1 as u64) << 32), + 0xC000_7A0A + ); } } @@ -159,11 +183,11 @@ mod linux_ioctls { use std::mem; use std::os::unix::io::AsRawFd; + use libc::{termios, TCGETS, TCSBRK, TCSETS, TIOCNXCL}; use tempfile::tempfile; - use libc::{TCGETS, TCSBRK, TCSETS, TIOCNXCL, termios}; + use nix::errno::Errno::{ENOSYS, ENOTTY}; use nix::Error::Sys; - use nix::errno::Errno::{ENOTTY, ENOSYS}; ioctl_none_bad!(tiocnxcl, TIOCNXCL); #[test] @@ -251,7 +275,7 @@ mod linux_ioctls { } // From linux/videodev2.h - ioctl_readwrite!(enum_audio, b'V', 65, v4l2_audio); + ioctl_readwrite!(enum_audio, b'V', 65, v4l2_audio); #[test] fn test_ioctl_readwrite() { let file = tempfile().unwrap(); @@ -277,7 +301,12 @@ mod linux_ioctls { } // From linux/spi/spidev.h - ioctl_write_buf!(spi_ioc_message, super::SPI_IOC_MAGIC, super::SPI_IOC_MESSAGE, spi_ioc_transfer); + ioctl_write_buf!( + spi_ioc_message, + super::SPI_IOC_MAGIC, + super::SPI_IOC_MESSAGE, + spi_ioc_transfer + ); #[test] fn test_ioctl_write_buf() { let file = tempfile().unwrap(); @@ -294,11 +323,11 @@ mod freebsd_ioctls { use std::mem; use std::os::unix::io::AsRawFd; - use tempfile::tempfile; use libc::termios; + use tempfile::tempfile; - use nix::Error::Sys; use nix::errno::Errno::ENOTTY; + use nix::Error::Sys; // From sys/sys/ttycom.h const TTY_IOC_MAGIC: u8 = b't'; diff --git a/test/sys/test_lio_listio_resubmit.rs b/test/sys/test_lio_listio_resubmit.rs index 19ee3facf8..02a549383c 100644 --- a/test/sys/test_lio_listio_resubmit.rs +++ b/test/sys/test_lio_listio_resubmit.rs @@ -8,12 +8,12 @@ extern crate nix; extern crate sysctl; extern crate tempfile; -use nix::Error; use nix::errno::*; use nix::libc::off_t; use nix::sys::aio::*; use nix::sys::signal::SigevNotify; -use nix::unistd::{SysconfVar, sysconf}; +use nix::unistd::{sysconf, SysconfVar}; +use nix::Error; use std::os::unix::io::AsRawFd; use std::{thread, time}; use sysctl::CtlValue; @@ -29,9 +29,10 @@ fn finish_liocb(liocb: &mut LioCb) { let e = liocb.error(j); match e { Ok(()) => break, - Err(Error::Sys(Errno::EINPROGRESS)) => - thread::sleep(time::Duration::from_millis(10)), - Err(x) => panic!("aio_error({:?})", x) + Err(Error::Sys(Errno::EINPROGRESS)) => { + thread::sleep(time::Duration::from_millis(10)) + } + Err(x) => panic!("aio_error({:?})", x), } } assert_eq!(liocb.aio_return(j).unwrap(), BYTES_PER_OP as isize); @@ -48,9 +49,9 @@ fn test_lio_listio_resubmit() { // Lookup system resource limits let alm = sysconf(SysconfVar::AIO_LISTIO_MAX) - .expect("sysconf").unwrap() as usize; - let maqpp = if let CtlValue::Int(x) = sysctl::value( - "vfs.aio.max_aio_queue_per_proc").unwrap(){ + .expect("sysconf") + .unwrap() as usize; + let maqpp = if let CtlValue::Int(x) = sysctl::value("vfs.aio.max_aio_queue_per_proc").unwrap() { x as usize } else { panic!("unknown sysctl"); @@ -61,42 +62,52 @@ fn test_lio_listio_resubmit() { let target_ops = maqpp + alm / 2; let num_listios = (target_ops + alm - 3) / (alm - 2); let ops_per_listio = (target_ops + num_listios - 1) / num_listios; - assert!((num_listios - 1) * ops_per_listio < maqpp, - "the last lio_listio won't make any progress; fix the algorithm"); - println!("Using {:?} LioCbs of {:?} operations apiece", num_listios, - ops_per_listio); + assert!( + (num_listios - 1) * ops_per_listio < maqpp, + "the last lio_listio won't make any progress; fix the algorithm" + ); + println!( + "Using {:?} LioCbs of {:?} operations apiece", + num_listios, ops_per_listio + ); let f = tempfile().unwrap(); - let buffer_set = (0..num_listios).map(|_| { - (0..ops_per_listio).map(|_| { - vec![0u8; BYTES_PER_OP] - }).collect::>() - }).collect::>(); + let buffer_set = (0..num_listios) + .map(|_| { + (0..ops_per_listio) + .map(|_| vec![0u8; BYTES_PER_OP]) + .collect::>() + }) + .collect::>(); - let mut liocbs = (0..num_listios).map(|i| { - let mut liocb = LioCb::with_capacity(ops_per_listio); - for j in 0..ops_per_listio { - let offset = (BYTES_PER_OP * (i * ops_per_listio + j)) as off_t; - let wcb = AioCb::from_slice( f.as_raw_fd(), - offset, - &buffer_set[i][j][..], - 0, //priority - SigevNotify::SigevNone, - LioOpcode::LIO_WRITE); - liocb.aiocbs.push(wcb); - } - let mut err = liocb.listio(LioMode::LIO_NOWAIT, SigevNotify::SigevNone); - while err == Err(Error::Sys(Errno::EIO)) || - err == Err(Error::Sys(Errno::EAGAIN)) || - err == Err(Error::Sys(Errno::EINTR)) { - // - thread::sleep(time::Duration::from_millis(10)); - resubmit_count += 1; - err = liocb.listio_resubmit(LioMode::LIO_NOWAIT, - SigevNotify::SigevNone); - } - liocb - }).collect::>(); + let mut liocbs = (0..num_listios) + .map(|i| { + let mut liocb = LioCb::with_capacity(ops_per_listio); + for j in 0..ops_per_listio { + let offset = (BYTES_PER_OP * (i * ops_per_listio + j)) as off_t; + let wcb = AioCb::from_slice( + f.as_raw_fd(), + offset, + &buffer_set[i][j][..], + 0, //priority + SigevNotify::SigevNone, + LioOpcode::LIO_WRITE, + ); + liocb.aiocbs.push(wcb); + } + let mut err = liocb.listio(LioMode::LIO_NOWAIT, SigevNotify::SigevNone); + while err == Err(Error::Sys(Errno::EIO)) + || err == Err(Error::Sys(Errno::EAGAIN)) + || err == Err(Error::Sys(Errno::EINTR)) + { + // + thread::sleep(time::Duration::from_millis(10)); + resubmit_count += 1; + err = liocb.listio_resubmit(LioMode::LIO_NOWAIT, SigevNotify::SigevNone); + } + liocb + }) + .collect::>(); // Ensure that every AioCb completed for liocb in liocbs.iter_mut() { diff --git a/test/sys/test_ptrace.rs b/test/sys/test_ptrace.rs index debc451755..ad8372f9e1 100644 --- a/test/sys/test_ptrace.rs +++ b/test/sys/test_ptrace.rs @@ -1,7 +1,7 @@ -use nix::Error; use nix::errno::Errno; -use nix::unistd::getpid; use nix::sys::ptrace::{self, Options}; +use nix::unistd::getpid; +use nix::Error; use std::mem; @@ -44,7 +44,6 @@ fn test_ptrace_setsiginfo() { } } - #[test] fn test_ptrace_cont() { use nix::sys::ptrace; @@ -72,17 +71,22 @@ fn test_ptrace_cont() { loop { raise(Signal::SIGTRAP).unwrap(); } - - }, + } Parent { child } => { - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGTRAP)) + ); ptrace::cont(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGTRAP)) + ); ptrace::cont(child, Signal::SIGKILL).unwrap(); match waitpid(child, None) { Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) if pid == child => {} _ => panic!("The process should have been killed"), } - }, + } } } diff --git a/test/sys/test_select.rs b/test/sys/test_select.rs index cf68700c5e..cf0795b7e5 100644 --- a/test/sys/test_select.rs +++ b/test/sys/test_select.rs @@ -1,7 +1,7 @@ use nix::sys::select::*; -use nix::unistd::{pipe, write}; use nix::sys::signal::SigSet; use nix::sys::time::{TimeSpec, TimeValLike}; +use nix::unistd::{pipe, write}; #[test] pub fn test_pselect() { diff --git a/test/sys/test_signal.rs b/test/sys/test_signal.rs index c8dd977680..3ae82405a6 100644 --- a/test/sys/test_signal.rs +++ b/test/sys/test_signal.rs @@ -1,5 +1,5 @@ -use nix::unistd::*; use nix::sys::signal::*; +use nix::unistd::*; #[test] fn test_kill_none() { @@ -22,13 +22,14 @@ fn test_old_sigaction_flags() { #[test] fn test_sigprocmask_noop() { - sigprocmask(SigmaskHow::SIG_BLOCK, None, None) - .expect("this should be an effective noop"); + sigprocmask(SigmaskHow::SIG_BLOCK, None, None).expect("this should be an effective noop"); } #[test] fn test_sigprocmask() { - let _m = ::SIGNAL_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::SIGNAL_MTX + .lock() + .expect("Mutex got poisoned by another test"); // This needs to be a signal that rust doesn't use in the test harness. const SIGNAL: Signal = Signal::SIGCHLD; @@ -39,9 +40,13 @@ fn test_sigprocmask() { // Make sure the old set doesn't contain the signal, otherwise the following // test don't make sense. - assert_eq!(old_signal_set.contains(SIGNAL), false, - "the {:?} signal is already blocked, please change to a \ - different one", SIGNAL); + assert_eq!( + old_signal_set.contains(SIGNAL), + false, + "the {:?} signal is already blocked, please change to a \ + different one", + SIGNAL + ); // Now block the signal. let mut signal_set = SigSet::empty(); @@ -53,8 +58,12 @@ fn test_sigprocmask() { old_signal_set.clear(); sigprocmask(SigmaskHow::SIG_BLOCK, None, Some(&mut old_signal_set)) .expect("expect to be able to retrieve old signals"); - assert_eq!(old_signal_set.contains(SIGNAL), true, - "expected the {:?} to be blocked", SIGNAL); + assert_eq!( + old_signal_set.contains(SIGNAL), + true, + "expected the {:?} to be blocked", + SIGNAL + ); // Reset the signal. sigprocmask(SigmaskHow::SIG_UNBLOCK, Some(&signal_set), None) diff --git a/test/sys/test_signalfd.rs b/test/sys/test_signalfd.rs index a3b6098841..66b7cc41e7 100644 --- a/test/sys/test_signalfd.rs +++ b/test/sys/test_signalfd.rs @@ -1,10 +1,12 @@ #[test] fn test_signalfd() { + use nix::sys::signal::{self, raise, SigSet, Signal}; use nix::sys::signalfd::SignalFd; - use nix::sys::signal::{self, raise, Signal, SigSet}; // Grab the mutex for altering signals so we don't interfere with other tests. - let _m = ::SIGNAL_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::SIGNAL_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Block the SIGUSR1 signal from automatic processing for this thread let mut mask = SigSet::empty(); diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index e8a953fb31..1537f2de43 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1,10 +1,10 @@ -use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; -use std::slice; +use libc::c_char; +use nix::sys::socket::{getsockname, InetAddr, UnixAddr}; use std::net::{self, Ipv6Addr, SocketAddr, SocketAddrV6}; +use std::os::unix::io::RawFd; use std::path::Path; +use std::slice; use std::str::FromStr; -use std::os::unix::io::RawFd; -use libc::c_char; #[test] pub fn test_inetv4_addr_to_sock_addr() { @@ -56,9 +56,8 @@ pub fn test_path_to_sock_addr() { let actual = Path::new(path); let addr = UnixAddr::new(actual).unwrap(); - let expect: &[c_char] = unsafe { - slice::from_raw_parts(path.as_bytes().as_ptr() as *const c_char, path.len()) - }; + let expect: &[c_char] = + unsafe { slice::from_raw_parts(path.as_bytes().as_ptr() as *const c_char, path.len()) }; assert_eq!(&addr.0.sun_path[..8], expect); assert_eq!(addr.path(), Some(actual)); @@ -78,9 +77,8 @@ pub fn test_abstract_uds_addr() { assert_eq!(addr.path(), None); // Internally, name is null-prefixed (abstract namespace) - let internal: &[u8] = unsafe { - slice::from_raw_parts(addr.0.sun_path.as_ptr() as *const u8, addr.1) - }; + let internal: &[u8] = + unsafe { slice::from_raw_parts(addr.0.sun_path.as_ptr() as *const u8, addr.1) }; let mut abstract_name = name.clone(); abstract_name.insert(0, '\0'); assert_eq!(internal, abstract_name.as_bytes()); @@ -88,29 +86,39 @@ pub fn test_abstract_uds_addr() { #[test] pub fn test_getsockname() { - use nix::sys::socket::{socket, AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, SockAddr}; - use tempfile::Builder; + use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType}; + use tempfile::tempdir; - let tempdir = Builder::new().prefix("test_getsockname").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let sockname = tempdir.path().join("sock"); - let sock = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(sock, &sockaddr).expect("bind failed"); - assert_eq!(sockaddr.to_str(), - getsockname(sock).expect("getsockname failed").to_str()); + assert_eq!( + sockaddr.to_str(), + getsockname(sock).expect("getsockname failed").to_str() + ); } #[test] pub fn test_socketpair() { + use nix::sys::socket::{socketpair, AddressFamily, SockFlag, SockType}; use nix::unistd::{read, write}; - use nix::sys::socket::{socketpair, AddressFamily, SockType, SockFlag}; - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ).unwrap(); write(fd1, b"hello").unwrap(); - let mut buf = [0;5]; + let mut buf = [0; 5]; read(fd2, &mut buf).unwrap(); assert_eq!(&buf[..], b"hello"); @@ -118,14 +126,19 @@ pub fn test_socketpair() { #[test] pub fn test_scm_rights() { + use nix::sys::socket::{ + recvmsg, sendmsg, socketpair, AddressFamily, CmsgSpace, ControlMessage, MsgFlags, SockFlag, + SockType, + }; use nix::sys::uio::IoVec; - use nix::unistd::{pipe, read, write, close}; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, - AddressFamily, SockType, SockFlag, - ControlMessage, CmsgSpace, MsgFlags}; - - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + use nix::unistd::{close, pipe, read, write}; + + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ).unwrap(); let (r, w) = pipe().unwrap(); let mut received_r: Option = None; @@ -133,7 +146,10 @@ pub fn test_scm_rights() { let iov = [IoVec::from_slice(b"hello")]; let fds = [r]; let cmsg = ControlMessage::ScmRights(&fds); - assert_eq!(sendmsg(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), + 5 + ); close(r).unwrap(); close(fd1).unwrap(); } @@ -153,7 +169,10 @@ pub fn test_scm_rights() { panic!("unexpected cmsg"); } } - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!( + !msg.flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) + ); close(fd2).unwrap(); } @@ -170,12 +189,12 @@ pub fn test_scm_rights() { /// Tests that passing multiple fds using a single `ControlMessage` works. #[test] fn test_scm_rights_single_cmsg_multiple_fds() { + use libc; + use nix::sys::socket::{recvmsg, sendmsg, CmsgSpace, ControlMessage, MsgFlags}; + use nix::sys::uio::IoVec; + use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::UnixDatagram; - use std::os::unix::io::{RawFd, AsRawFd}; use std::thread; - use nix::sys::socket::{CmsgSpace, ControlMessage, MsgFlags, sendmsg, recvmsg}; - use nix::sys::uio::IoVec; - use libc; let (send, receive) = UnixDatagram::pair().unwrap(); let thread = thread::spawn(move || { @@ -186,27 +205,36 @@ fn test_scm_rights_single_cmsg_multiple_fds() { receive.as_raw_fd(), &iovec, Some(&mut space), - MsgFlags::empty() + MsgFlags::empty(), ).unwrap(); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!( + !msg.flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) + ); let mut cmsgs = msg.cmsgs(); match cmsgs.next() { Some(ControlMessage::ScmRights(fds)) => { - assert_eq!(fds.len(), 2, - "unexpected fd count (expected 2 fds, got {})", - fds.len()); - }, + assert_eq!( + fds.len(), + 2, + "unexpected fd count (expected 2 fds, got {})", + fds.len() + ); + } _ => panic!(), } assert!(cmsgs.next().is_none(), "unexpected control msg"); - assert_eq!(iovec[0].as_slice(), [1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8]); + assert_eq!( + iovec[0].as_slice(), + [1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8] + ); }); let slice = [1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8]; let iov = [IoVec::from_slice(&slice)]; - let fds = [libc::STDIN_FILENO, libc::STDOUT_FILENO]; // pass stdin and stdout + let fds = [libc::STDIN_FILENO, libc::STDOUT_FILENO]; // pass stdin and stdout let cmsg = [ControlMessage::ScmRights(&fds)]; sendmsg(send.as_raw_fd(), &iov, &cmsg, MsgFlags::empty(), None).unwrap(); thread.join().unwrap(); @@ -218,14 +246,18 @@ fn test_scm_rights_single_cmsg_multiple_fds() { // raw `sendmsg`. #[test] pub fn test_sendmsg_empty_cmsgs() { + use nix::sys::socket::{ + recvmsg, sendmsg, socketpair, AddressFamily, CmsgSpace, MsgFlags, SockFlag, SockType, + }; use nix::sys::uio::IoVec; use nix::unistd::close; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, - AddressFamily, SockType, SockFlag, - CmsgSpace, MsgFlags}; - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ).unwrap(); { let iov = [IoVec::from_slice(b"hello")]; @@ -242,7 +274,10 @@ pub fn test_sendmsg_empty_cmsgs() { for _ in msg.cmsgs() { panic!("unexpected cmsg"); } - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!( + !msg.flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) + ); close(fd2).unwrap(); } } @@ -250,23 +285,31 @@ pub fn test_sendmsg_empty_cmsgs() { // Test creating and using named unix domain sockets #[test] pub fn test_unixdomain() { - use nix::sys::socket::{AddressFamily, SockType, SockFlag}; - use nix::sys::socket::{bind, socket, connect, listen, accept, SockAddr}; - use nix::unistd::{read, write, close}; + use nix::sys::socket::{accept, bind, connect, listen, socket, SockAddr}; + use nix::sys::socket::{AddressFamily, SockFlag, SockType}; + use nix::unistd::{close, read, write}; use std::thread; - use tempfile::Builder; + use tempfile::tempdir; - let tempdir = Builder::new().prefix("test_unixdomain").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let sockname = tempdir.path().join("sock"); - let s1 = socket(AddressFamily::Unix, SockType::Stream, - SockFlag::empty(), None).expect("socket failed"); + let s1 = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(s1, &sockaddr).expect("bind failed"); listen(s1, 10).expect("listen failed"); let thr = thread::spawn(move || { - let s2 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), None) - .expect("socket failed"); + let s2 = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ).expect("socket failed"); connect(s2, &sockaddr).expect("connect failed"); write(s2, b"hello").expect("write failed"); close(s2).unwrap(); @@ -274,7 +317,7 @@ pub fn test_unixdomain() { let s3 = accept(s1).expect("accept failed"); - let mut buf = [0;5]; + let mut buf = [0; 5]; read(s3, &mut buf).unwrap(); close(s3).unwrap(); close(s1).unwrap(); @@ -287,15 +330,22 @@ pub fn test_unixdomain() { #[cfg(any(target_os = "macos", target_os = "ios"))] #[test] pub fn test_syscontrol() { - use nix::Error; use nix::errno::Errno; - use nix::sys::socket::{AddressFamily, socket, SockAddr, SockType, SockFlag, SockProtocol}; + use nix::sys::socket::{socket, AddressFamily, SockAddr, SockFlag, SockProtocol, SockType}; + use nix::Error; - let fd = socket(AddressFamily::System, SockType::Datagram, - SockFlag::empty(), SockProtocol::KextControl) - .expect("socket failed"); - let _sockaddr = SockAddr::new_sys_control(fd, "com.apple.net.utun_control", 0).expect("resolving sys_control name failed"); - assert_eq!(SockAddr::new_sys_control(fd, "foo.bar.lol", 0).err(), Some(Error::Sys(Errno::ENOENT))); + let fd = socket( + AddressFamily::System, + SockType::Datagram, + SockFlag::empty(), + SockProtocol::KextControl, + ).expect("socket failed"); + let _sockaddr = SockAddr::new_sys_control(fd, "com.apple.net.utun_control", 0) + .expect("resolving sys_control name failed"); + assert_eq!( + SockAddr::new_sys_control(fd, "foo.bar.lol", 0).err(), + Some(Error::Sys(Errno::ENOENT)) + ); // requires root privileges // connect(fd, &sockaddr).expect("connect failed"); diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index a38657c1ea..7914bfe748 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -1,10 +1,16 @@ +use nix::sys::socket::{ + getsockopt, setsockopt, socket, sockopt, AddressFamily, SockFlag, SockProtocol, SockType, +}; use rand::{thread_rng, Rng}; -use nix::sys::socket::{socket, sockopt, getsockopt, setsockopt, AddressFamily, SockType, SockFlag, SockProtocol}; #[test] fn test_so_buf() { - let fd = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), SockProtocol::Udp) - .unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + SockProtocol::Udp, + ).unwrap(); let bufsize: usize = thread_rng().gen_range(4096, 131_072); setsockopt(fd, sockopt::SndBuf, &bufsize).unwrap(); let actual = getsockopt(fd, sockopt::SndBuf).unwrap(); diff --git a/test/sys/test_sysinfo.rs b/test/sys/test_sysinfo.rs index 73e6586f62..2897366eff 100644 --- a/test/sys/test_sysinfo.rs +++ b/test/sys/test_sysinfo.rs @@ -9,10 +9,12 @@ fn sysinfo_works() { assert!(l5 >= 0.0); assert!(l15 >= 0.0); - info.uptime(); // just test Duration construction + info.uptime(); // just test Duration construction - assert!(info.swap_free() <= info.swap_total(), - "more swap available than installed (free: {}, total: {})", - info.swap_free(), - info.swap_total()); + assert!( + info.swap_free() <= info.swap_total(), + "more swap available than installed (free: {}, total: {})", + info.swap_free(), + info.swap_total() + ); } diff --git a/test/sys/test_termios.rs b/test/sys/test_termios.rs index a14b8ce1a2..f3b2770e3c 100644 --- a/test/sys/test_termios.rs +++ b/test/sys/test_termios.rs @@ -1,11 +1,11 @@ use std::os::unix::prelude::*; use tempfile::tempfile; -use nix::{Error, fcntl}; use nix::errno::Errno; use nix::pty::openpty; -use nix::sys::termios::{self, LocalFlags, OutputFlags, Termios, tcgetattr}; -use nix::unistd::{read, write, close}; +use nix::sys::termios::{self, tcgetattr, LocalFlags, OutputFlags, Termios}; +use nix::unistd::{close, read, write}; +use nix::{fcntl, Error}; /// Helper function analogous to `std::io::Write::write_all`, but for `RawFd`s fn write_all(f: RawFd, buf: &[u8]) { @@ -19,7 +19,9 @@ fn write_all(f: RawFd, buf: &[u8]) { #[test] fn test_tcgetattr_pty() { // openpty uses ptname(3) internally - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); let pty = openpty(None, None).expect("openpty failed"); assert!(termios::tcgetattr(pty.master).is_ok()); @@ -31,22 +33,25 @@ fn test_tcgetattr_pty() { #[test] fn test_tcgetattr_enotty() { let file = tempfile().unwrap(); - assert_eq!(termios::tcgetattr(file.as_raw_fd()).err(), - Some(Error::Sys(Errno::ENOTTY))); + assert_eq!( + termios::tcgetattr(file.as_raw_fd()).err(), + Some(Error::Sys(Errno::ENOTTY)) + ); } // Test tcgetattr on an invalid file descriptor #[test] fn test_tcgetattr_ebadf() { - assert_eq!(termios::tcgetattr(-1).err(), - Some(Error::Sys(Errno::EBADF))); + assert_eq!(termios::tcgetattr(-1).err(), Some(Error::Sys(Errno::EBADF))); } // Test modifying output flags #[test] fn test_output_flags() { // openpty uses ptname(3) internally - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Open one pty to get attributes for the second one let mut termios = { @@ -60,11 +65,17 @@ fn test_output_flags() { }; // Make sure postprocessing '\r' isn't specified by default or this test is useless. - assert!(!termios.output_flags.contains(OutputFlags::OPOST | OutputFlags::OCRNL)); + assert!( + !termios + .output_flags + .contains(OutputFlags::OPOST | OutputFlags::OCRNL) + ); // Specify that '\r' characters should be transformed to '\n' // OPOST is specified to enable post-processing - termios.output_flags.insert(OutputFlags::OPOST | OutputFlags::OCRNL); + termios + .output_flags + .insert(OutputFlags::OPOST | OutputFlags::OCRNL); // Open a pty let pty = openpty(None, &termios).unwrap(); @@ -88,7 +99,9 @@ fn test_output_flags() { #[test] fn test_local_flags() { // openpty uses ptname(3) internally - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Open one pty to get attributes for the second one let mut termios = { diff --git a/test/sys/test_uio.rs b/test/sys/test_uio.rs index e95563cd49..4e86133f94 100644 --- a/test/sys/test_uio.rs +++ b/test/sys/test_uio.rs @@ -1,12 +1,11 @@ use nix::sys::uio::*; use nix::unistd::*; use rand::{thread_rng, Rng}; -use std::{cmp, iter}; -use std::fs::{OpenOptions}; +use std::fs::OpenOptions; use std::os::unix::io::AsRawFd; +use std::{cmp, iter}; -use tempfile::Builder; -use tempfile::tempfile; +use tempfile::{tempdir, tempfile}; #[test] fn test_writev() { @@ -21,8 +20,12 @@ fn test_writev() { let mut consumed = 0; while consumed < to_write.len() { let left = to_write.len() - consumed; - let slice_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; - let b = &to_write[consumed..consumed+slice_len]; + let slice_len = if left <= 64 { + left + } else { + thread_rng().gen_range(64, cmp::min(256, left)) + }; + let b = &to_write[consumed..consumed + slice_len]; iovecs.push(IoVec::from_slice(b)); consumed += slice_len; } @@ -54,13 +57,17 @@ fn test_writev() { #[test] fn test_readv() { - let s:String = thread_rng().gen_ascii_chars().take(128).collect(); + let s: String = thread_rng().gen_ascii_chars().take(128).collect(); let to_write = s.as_bytes().to_vec(); let mut storage = Vec::new(); let mut allocated = 0; while allocated < to_write.len() { let left = to_write.len() - allocated; - let vec_len = if left <= 64 { left } else { thread_rng().gen_range(64, cmp::min(256, left)) }; + let vec_len = if left <= 64 { + left + } else { + thread_rng().gen_range(64, cmp::min(256, left)) + }; let v: Vec = iter::repeat(0u8).take(vec_len).collect(); storage.push(v); allocated += vec_len; @@ -101,12 +108,12 @@ fn test_pwrite() { use std::io::Read; let mut file = tempfile().unwrap(); - let buf = [1u8;8]; + let buf = [1u8; 8]; assert_eq!(Ok(8), pwrite(file.as_raw_fd(), &buf, 8)); let mut file_content = Vec::new(); file.read_to_end(&mut file_content).unwrap(); - let mut expected = vec![0u8;8]; - expected.extend(vec![1;8]); + let mut expected = vec![0u8; 8]; + expected.extend(vec![1; 8]); assert_eq!(file_content, expected); } @@ -114,15 +121,20 @@ fn test_pwrite() { fn test_pread() { use std::io::Write; - let tempdir = Builder::new().prefix("nix-test_pread").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let path = tempdir.path().join("pread_test_file"); - let mut file = OpenOptions::new().write(true).read(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .write(true) + .read(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); let file_content: Vec = (0..64).collect(); file.write_all(&file_content).unwrap(); - let mut buf = [0u8;16]; + let mut buf = [0u8; 16]; assert_eq!(Ok(16), pread(file.as_raw_fd(), &mut buf, 16)); let expected: Vec<_> = (16..32).collect(); assert_eq!(&buf[..], &expected[..]); @@ -134,7 +146,7 @@ fn test_pwritev() { use std::io::Read; let to_write: Vec = (0..128).collect(); - let expected: Vec = [vec![0;100], to_write.clone()].concat(); + let expected: Vec = [vec![0; 100], to_write.clone()].concat(); let iovecs = [ IoVec::from_slice(&to_write[0..17]), @@ -142,12 +154,17 @@ fn test_pwritev() { IoVec::from_slice(&to_write[64..128]), ]; - let tempdir = Builder::new().prefix("nix-test_pwritev").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); // pwritev them into a temporary file let path = tempdir.path().join("pwritev_test_file"); - let mut file = OpenOptions::new().write(true).read(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .write(true) + .read(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); let written = pwritev(file.as_raw_fd(), &iovecs, 100).ok().unwrap(); assert_eq!(written, to_write.len()); @@ -166,24 +183,27 @@ fn test_preadv() { let to_write: Vec = (0..200).collect(); let expected: Vec = (100..200).collect(); - let tempdir = Builder::new().prefix("nix-test_preadv").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let path = tempdir.path().join("preadv_test_file"); - let mut file = OpenOptions::new().read(true).write(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); file.write_all(&to_write).unwrap(); - let mut buffers: Vec> = vec![ - vec![0; 24], - vec![0; 1], - vec![0; 75], - ]; + let mut buffers: Vec> = vec![vec![0; 24], vec![0; 1], vec![0; 75]]; { // Borrow the buffers into IoVecs and preadv into them - let iovecs: Vec<_> = buffers.iter_mut().map( - |buf| IoVec::from_mut_slice(&mut buf[..])).collect(); + let iovecs: Vec<_> = buffers + .iter_mut() + .map(|buf| IoVec::from_mut_slice(&mut buf[..])) + .collect(); assert_eq!(Ok(100), preadv(file.as_raw_fd(), &iovecs, 100)); } @@ -196,11 +216,13 @@ fn test_preadv() { // FIXME: qemu-user doesn't implement process_vm_readv/writev on most arches #[cfg_attr(not(any(target_arch = "x86", target_arch = "x86_64")), ignore)] fn test_process_vm_readv() { - use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; + use nix::unistd::ForkResult::*; - let _ = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); + let _ = ::FORK_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Pre-allocate memory in the child, since allocation isn't safe // post-fork (~= async-signal-safe) @@ -218,16 +240,14 @@ fn test_process_vm_readv() { let remote_iov = RemoteIoVec { base: ptr, len: 5 }; let mut buf = vec![0u8; 5]; - let ret = process_vm_readv(child, - &[IoVec::from_mut_slice(&mut buf)], - &[remote_iov]); + let ret = process_vm_readv(child, &[IoVec::from_mut_slice(&mut buf)], &[remote_iov]); kill(child, SIGTERM).unwrap(); waitpid(child, None).unwrap(); assert_eq!(Ok(5), ret); assert_eq!(20u8, buf.iter().sum()); - }, + } Child => { let _ = close(r); for i in &mut vector { @@ -235,7 +255,9 @@ fn test_process_vm_readv() { } let _ = write(w, b"\0"); let _ = close(w); - loop { let _ = pause(); } - }, + loop { + let _ = pause(); + } + } } } diff --git a/test/sys/test_wait.rs b/test/sys/test_wait.rs index d07d82f0d9..540bcd44d4 100644 --- a/test/sys/test_wait.rs +++ b/test/sys/test_wait.rs @@ -1,51 +1,71 @@ -use nix::Error; -use nix::unistd::*; -use nix::unistd::ForkResult::*; +use libc::_exit; use nix::sys::signal::*; use nix::sys::wait::*; -use libc::_exit; +use nix::unistd::ForkResult::*; +use nix::unistd::*; +use nix::Error; #[test] fn test_wait_signal() { - let _ = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); + let _ = ::FORK_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Safe: The child only calls `pause` and/or `_exit`, which are async-signal-safe. match fork().expect("Error: Fork Failed") { - Child => { - pause(); - unsafe { _exit(123) } - }, - Parent { child } => { - kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, SIGKILL, false))); - }, + Child => { + pause(); + unsafe { _exit(123) } + } + Parent { child } => { + kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Signaled(child, SIGKILL, false)) + ); + } } } #[test] fn test_wait_exit() { - let _m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::FORK_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Safe: Child only calls `_exit`, which is async-signal-safe. match fork().expect("Error: Fork Failed") { - Child => unsafe { _exit(12); }, - Parent { child } => { - assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12))); - }, + Child => unsafe { + _exit(12); + }, + Parent { child } => { + assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12))); + } } } #[test] fn test_waitstatus_from_raw() { let pid = Pid::from_raw(1); - assert_eq!(WaitStatus::from_raw(pid, 0x0002), Ok(WaitStatus::Signaled(pid, Signal::SIGINT, false))); - assert_eq!(WaitStatus::from_raw(pid, 0x0200), Ok(WaitStatus::Exited(pid, 2))); - assert_eq!(WaitStatus::from_raw(pid, 0x7f7f), Err(Error::invalid_argument())); + assert_eq!( + WaitStatus::from_raw(pid, 0x0002), + Ok(WaitStatus::Signaled(pid, Signal::SIGINT, false)) + ); + assert_eq!( + WaitStatus::from_raw(pid, 0x0200), + Ok(WaitStatus::Exited(pid, 2)) + ); + assert_eq!( + WaitStatus::from_raw(pid, 0x7f7f), + Err(Error::invalid_argument()) + ); } #[test] fn test_waitstatus_pid() { - let _m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::FORK_MTX + .lock() + .expect("Mutex got poisoned by another test"); match fork().unwrap() { Child => unsafe { _exit(0) }, @@ -60,12 +80,12 @@ fn test_waitstatus_pid() { // FIXME: qemu-user doesn't implement ptrace on most arches #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod ptrace { - use nix::sys::ptrace::{self, Options, Event}; + use libc::_exit; + use nix::sys::ptrace::{self, Event, Options}; use nix::sys::signal::*; use nix::sys::wait::*; - use nix::unistd::*; use nix::unistd::ForkResult::*; - use libc::_exit; + use nix::unistd::*; fn ptrace_child() -> ! { ptrace::traceme().unwrap(); @@ -77,16 +97,31 @@ mod ptrace { fn ptrace_parent(child: Pid) { // Wait for the raised SIGTRAP - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, SIGTRAP)) + ); // We want to test a syscall stop and a PTRACE_EVENT stop - assert!(ptrace::setoptions(child, Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT).is_ok()); + assert!( + ptrace::setoptions( + child, + Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT + ).is_ok() + ); // First, stop on the next system call, which will be exit() assert!(ptrace::syscall(child).is_ok()); assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); // Then get the ptrace event for the process exiting assert!(ptrace::cont(child, None).is_ok()); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceEvent(child, SIGTRAP, Event::PTRACE_EVENT_EXIT as i32))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceEvent( + child, + SIGTRAP, + Event::PTRACE_EVENT_EXIT as i32 + )) + ); // Finally get the normal wait() result, now that the process has exited assert!(ptrace::cont(child, None).is_ok()); assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 0))); @@ -94,7 +129,9 @@ mod ptrace { #[test] fn test_wait_ptrace() { - let _m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::FORK_MTX + .lock() + .expect("Mutex got poisoned by another test"); match fork().expect("Error: Fork Failed") { Child => ptrace_child(), diff --git a/test/test.rs b/test/test.rs index bfa60b4cbb..4242f35534 100644 --- a/test/test.rs +++ b/test/test.rs @@ -26,34 +26,41 @@ macro_rules! skip_if_not_root { mod sys; mod test_fcntl; -#[cfg(any(target_os = "android", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux"))] mod test_kmod; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "fushsia", - target_os = "linux", - target_os = "netbsd"))] +#[cfg( + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "fushsia", + target_os = "linux", + target_os = "netbsd" + ) +)] mod test_mq; mod test_net; mod test_nix_path; mod test_poll; mod test_pty; -#[cfg(any(target_os = "android", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos"))] +#[cfg( + any( + target_os = "android", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos" + ) +)] mod test_sendfile; mod test_stat; mod test_unistd; +use nix::unistd::read; use std::os::unix::io::RawFd; use std::sync::Mutex; -use nix::unistd::read; /// Helper function analogous to `std::io::Read::read_exact`, but for `RawFD`s -fn read_exact(f: RawFd, buf: &mut [u8]) { +fn read_exact(f: RawFd, buf: &mut [u8]) { let mut len = 0; while len < buf.len() { // get_mut would be better than split_at_mut, but it requires nightly diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index eb93837c92..a5cb8f4d00 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -1,10 +1,9 @@ -use nix::fcntl::{openat, open, OFlag, readlink, readlinkat}; +use nix::fcntl::{open, openat, readlink, readlinkat, OFlag}; use nix::sys::stat::Mode; use nix::unistd::{close, read}; -use tempfile::Builder; -use tempfile::NamedTempFile; use std::io::prelude::*; use std::os::unix::fs; +use tempfile::{tempdir, NamedTempFile}; #[test] fn test_openat() { @@ -12,13 +11,13 @@ fn test_openat() { let mut tmp = NamedTempFile::new().unwrap(); tmp.write_all(CONTENTS).unwrap(); - let dirfd = open(tmp.path().parent().unwrap(), - OFlag::empty(), - Mode::empty()).unwrap(); - let fd = openat(dirfd, - tmp.path().file_name().unwrap(), - OFlag::O_RDONLY, - Mode::empty()).unwrap(); + let dirfd = open(tmp.path().parent().unwrap(), OFlag::empty(), Mode::empty()).unwrap(); + let fd = openat( + dirfd, + tmp.path().file_name().unwrap(), + OFlag::O_RDONLY, + Mode::empty(), + ).unwrap(); let mut buf = [0u8; 1024]; assert_eq!(4, read(fd, &mut buf).unwrap()); @@ -30,21 +29,23 @@ fn test_openat() { #[test] fn test_readlink() { - let tempdir = Builder::new().prefix("nix-test_readdir").tempdir() - .unwrap_or_else(|e| panic!("tempdir failed: {}", e)); + let tempdir = tempdir().unwrap(); + let src = tempdir.path().join("a"); let dst = tempdir.path().join("b"); println!("a: {:?}, b: {:?}", &src, &dst); fs::symlink(&src.as_path(), &dst.as_path()).unwrap(); - let dirfd = open(tempdir.path(), - OFlag::empty(), - Mode::empty()).unwrap(); + let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); let mut buf = vec![0; src.to_str().unwrap().len() + 1]; - assert_eq!(readlink(&dst, &mut buf).unwrap().to_str().unwrap(), - src.to_str().unwrap()); - assert_eq!(readlinkat(dirfd, "b", &mut buf).unwrap().to_str().unwrap(), - src.to_str().unwrap()); + assert_eq!( + readlink(&dst, &mut buf).unwrap().to_str().unwrap(), + src.to_str().unwrap() + ); + assert_eq!( + readlinkat(dirfd, "b", &mut buf).unwrap().to_str().unwrap(), + src.to_str().unwrap() + ); } #[cfg(any(target_os = "linux", target_os = "android"))] @@ -54,7 +55,7 @@ mod linux_android { use libc::loff_t; - use nix::fcntl::{SpliceFFlags, FallocateFlags, fallocate, splice, tee, vmsplice}; + use nix::fcntl::{fallocate, splice, tee, vmsplice, FallocateFlags, SpliceFFlags}; use nix::sys::uio::IoVec; use nix::unistd::{close, pipe, read, write}; @@ -68,8 +69,14 @@ mod linux_android { let (rd, wr) = pipe().unwrap(); let mut offset: loff_t = 5; - let res = splice(tmp.as_raw_fd(), Some(&mut offset), - wr, None, 2, SpliceFFlags::empty()).unwrap(); + let res = splice( + tmp.as_raw_fd(), + Some(&mut offset), + wr, + None, + 2, + SpliceFFlags::empty(), + ).unwrap(); assert_eq!(2, res); diff --git a/test/test_kmod/mod.rs b/test/test_kmod/mod.rs index 6e5a37a67d..2e09200a91 100644 --- a/test/test_kmod/mod.rs +++ b/test/test_kmod/mod.rs @@ -3,17 +3,14 @@ extern crate tempfile; use std::fs::copy; use std::path::PathBuf; use std::process::Command; -use tempfile::{Builder, TempDir}; +use tempfile::{tempdir, TempDir}; fn compile_kernel_module() -> (PathBuf, String, TempDir) { let _m = ::FORK_MTX .lock() .expect("Mutex got poisoned by another test"); - let tmp_dir = Builder::new() - .prefix("kmod_test_module") - .tempdir() - .expect("unable to create temporary build directory"); + let tmp_dir = tempdir().expect("unable to create temporary build directory"); copy( "test/test_kmod/hello_mod/hello.c", diff --git a/test/test_mount.rs b/test/test_mount.rs index ed560cd830..9335432db2 100644 --- a/test/test_mount.rs +++ b/test/test_mount.rs @@ -23,7 +23,7 @@ mod test_mount { use nix::sys::stat::{self, Mode}; use nix::unistd::getuid; - use tempfile::Builder; + use tempfile::tempdir; static SCRIPT_CONTENTS: &'static [u8] = b"#!/bin/sh exit 23"; @@ -32,15 +32,15 @@ exit 23"; const NONE: Option<&'static [u8]> = None; pub fn test_mount_tmpfs_without_flags_allows_rwx() { - let tempdir = Builder::new().prefix("nix-test_mount").tempdir() - .unwrap_or_else(|e| panic!("tempdir failed: {}", e)); + let tempdir = tempdir().expect("tempdir failed"); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::empty(), - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::empty(), + NONE, + ).unwrap_or_else(|e| panic!("mount failed: {}", e)); let test_path = tempdir.path().join("test"); @@ -50,7 +50,7 @@ exit 23"; .write(true) .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) .open(&test_path) - .or_else(|e| + .or_else(|e| { if Errno::from_i32(e.raw_os_error().unwrap()) == Errno::EOVERFLOW { // Skip tests on certain Linux kernels which have a bug // regarding tmpfs in namespaces. @@ -60,13 +60,12 @@ exit 23"; // https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1659087 let stderr = io::stderr(); let mut handle = stderr.lock(); - writeln!(handle, "Buggy Linux kernel detected. Skipping test.") - .unwrap(); + writeln!(handle, "Buggy Linux kernel detected. Skipping test.").unwrap(); process::exit(0); - } else { - panic!("open failed: {}", e); - } - ) + } else { + panic!("open failed: {}", e); + } + }) .and_then(|mut f| f.write(SCRIPT_CONTENTS)) .unwrap_or_else(|e| panic!("write failed: {}", e)); @@ -78,44 +77,51 @@ exit 23"; assert_eq!(buf, SCRIPT_CONTENTS); // Verify execute. - assert_eq!(EXPECTED_STATUS, - Command::new(&test_path) - .status() - .unwrap_or_else(|e| panic!("exec failed: {}", e)) - .code() - .unwrap_or_else(|| panic!("child killed by signal"))); + assert_eq!( + EXPECTED_STATUS, + Command::new(&test_path) + .status() + .unwrap_or_else(|e| panic!("exec failed: {}", e)) + .code() + .unwrap_or_else(|| panic!("child killed by signal")) + ); umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_rdonly_disallows_write() { - let tempdir = Builder::new().prefix("nix-test_mount").tempdir() - .unwrap_or_else(|e| panic!("tempdir failed: {}", e)); + let tempdir = tempdir().expect("tempdir failed"); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::MS_RDONLY, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::MS_RDONLY, + NONE, + ).unwrap_or_else(|e| panic!("mount failed: {}", e)); // EROFS: Read-only file system - assert_eq!(EROFS as i32, - File::create(tempdir.path().join("test")).unwrap_err().raw_os_error().unwrap()); + assert_eq!( + EROFS as i32, + File::create(tempdir.path().join("test")) + .unwrap_err() + .raw_os_error() + .unwrap() + ); umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_noexec_disallows_exec() { - let tempdir = Builder::new().prefix("nix-test_mount").tempdir() - .unwrap_or_else(|e| panic!("tempdir failed: {}", e)); + let tempdir = tempdir().expect("tempdir failed"); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::MS_NOEXEC, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::MS_NOEXEC, + NONE, + ).unwrap_or_else(|e| panic!("mount failed: {}", e)); let test_path = tempdir.path().join("test"); @@ -128,38 +134,45 @@ exit 23"; .unwrap_or_else(|e| panic!("write failed: {}", e)); // Verify that we cannot execute despite a+x permissions being set. - let mode = stat::Mode::from_bits_truncate(fs::metadata(&test_path) - .map(|md| md.permissions().mode()) - .unwrap_or_else(|e| { - panic!("metadata failed: {}", e) - })); - - assert!(mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH), - "{:?} did not have execute permissions", - &test_path); + let mode = stat::Mode::from_bits_truncate( + fs::metadata(&test_path) + .map(|md| md.permissions().mode()) + .unwrap_or_else(|e| panic!("metadata failed: {}", e)), + ); + + assert!( + mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH), + "{:?} did not have execute permissions", + &test_path + ); // EACCES: Permission denied - assert_eq!(EACCES as i32, - Command::new(&test_path).status().unwrap_err().raw_os_error().unwrap()); + assert_eq!( + EACCES as i32, + Command::new(&test_path) + .status() + .unwrap_err() + .raw_os_error() + .unwrap() + ); umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_bind() { - let tempdir = Builder::new().prefix("nix-test_mount").tempdir() - .unwrap_or_else(|e| panic!("tempdir failed: {}", e)); + let binddir = tempdir().expect("tempdir failed"); let file_name = "test"; { - let mount_point = Builder::new().prefix("nix-test_mount").tempdir() - .unwrap_or_else(|e| panic!("tempdir failed: {}", e)); + let mount_point = tempdir().expect("tempdir failed"); - mount(Some(tempdir.path()), - mount_point.path(), - NONE, - MsFlags::MS_BIND, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + Some(binddir.path()), + mount_point.path(), + NONE, + MsFlags::MS_BIND, + NONE, + ).unwrap_or_else(|e| panic!("mount failed: {}", e)); fs::OpenOptions::new() .create(true) @@ -176,7 +189,7 @@ exit 23"; // after unmounting. let mut buf = Vec::new(); - File::open(tempdir.path().join(file_name)) + File::open(binddir.path().join(file_name)) .and_then(|mut f| f.read_to_end(&mut buf)) .unwrap_or_else(|e| panic!("read failed: {}", e)); assert_eq!(buf, SCRIPT_CONTENTS); @@ -189,9 +202,11 @@ exit 23"; unshare(CloneFlags::CLONE_NEWNS | CloneFlags::CLONE_NEWUSER).unwrap_or_else(|e| { let stderr = io::stderr(); let mut handle = stderr.lock(); - writeln!(handle, - "unshare failed: {}. Are unprivileged user namespaces available?", - e).unwrap(); + writeln!( + handle, + "unshare failed: {}. Are unprivileged user namespaces available?", + e + ).unwrap(); writeln!(handle, "mount is not being tested").unwrap(); // Exit with success because not all systems support unprivileged user namespaces, and // that's not what we're testing for. @@ -207,7 +222,6 @@ exit 23"; } } - // Test runner /// Mimic normal test output (hackishly). @@ -227,15 +241,18 @@ macro_rules! run_tests { #[cfg(target_os = "linux")] fn main() { - use test_mount::{setup_namespaces, test_mount_tmpfs_without_flags_allows_rwx, - test_mount_rdonly_disallows_write, test_mount_noexec_disallows_exec, - test_mount_bind}; + use test_mount::{ + setup_namespaces, test_mount_bind, test_mount_noexec_disallows_exec, + test_mount_rdonly_disallows_write, test_mount_tmpfs_without_flags_allows_rwx, + }; setup_namespaces(); - run_tests!(test_mount_tmpfs_without_flags_allows_rwx, - test_mount_rdonly_disallows_write, - test_mount_noexec_disallows_exec, - test_mount_bind); + run_tests!( + test_mount_tmpfs_without_flags_allows_rwx, + test_mount_rdonly_disallows_write, + test_mount_noexec_disallows_exec, + test_mount_bind + ); } #[cfg(not(target_os = "linux"))] diff --git a/test/test_mq.rs b/test/test_mq.rs index 26fd587f92..629b7a225b 100644 --- a/test/test_mq.rs +++ b/test/test_mq.rs @@ -4,16 +4,19 @@ use std::ffi::CString; use std::str; use nix::errno::Errno::*; -use nix::Error::Sys; -use nix::mqueue::{mq_open, mq_close, mq_send, mq_receive, mq_getattr, mq_setattr, mq_unlink, mq_set_nonblock, mq_remove_nonblock}; -use nix::mqueue::{MqAttr, MQ_OFlag}; +use nix::mqueue::{ + mq_close, mq_getattr, mq_open, mq_receive, mq_remove_nonblock, mq_send, mq_set_nonblock, + mq_setattr, mq_unlink, +}; +use nix::mqueue::{MQ_OFlag, MqAttr}; use nix::sys::stat::Mode; +use nix::Error::Sys; #[test] fn test_mq_send_and_receive() { - const MSG_SIZE: c_long = 32; - let attr = MqAttr::new(0, 10, MSG_SIZE, 0); - let mq_name= &CString::new(b"/a_nix_test_queue".as_ref()).unwrap(); + const MSG_SIZE: c_long = 32; + let attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let mq_name = &CString::new(b"/a_nix_test_queue".as_ref()).unwrap(); let oflag0 = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -38,11 +41,10 @@ fn test_mq_send_and_receive() { assert_eq!(msg_to_send, str::from_utf8(&buf[0..len]).unwrap()); } - #[test] fn test_mq_getattr() { - const MSG_SIZE: c_long = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + const MSG_SIZE: c_long = 32; + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -62,8 +64,8 @@ fn test_mq_getattr() { #[test] #[cfg_attr(any(target_arch = "mips", target_arch = "mips64"), ignore)] fn test_mq_setattr() { - const MSG_SIZE: c_long = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + const MSG_SIZE: c_long = 32; + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -74,7 +76,7 @@ fn test_mq_setattr() { }; let mqd = r.unwrap(); - let new_attr = MqAttr::new(0, 20, MSG_SIZE * 2, 100); + let new_attr = MqAttr::new(0, 20, MSG_SIZE * 2, 100); let old_attr = mq_setattr(mqd, &new_attr); assert!(old_attr.unwrap() == initial_attr); @@ -83,7 +85,7 @@ fn test_mq_setattr() { // O_NONBLOCK can be set (see tests below) assert!(new_attr_get.unwrap() != new_attr); - let new_attr_non_blocking = MqAttr::new(MQ_OFlag::O_NONBLOCK.bits() as c_long, 10, MSG_SIZE, 0); + let new_attr_non_blocking = MqAttr::new(MQ_OFlag::O_NONBLOCK.bits() as c_long, 10, MSG_SIZE, 0); mq_setattr(mqd, &new_attr_non_blocking).unwrap(); let new_attr_get = mq_getattr(mqd); @@ -97,8 +99,8 @@ fn test_mq_setattr() { #[test] #[cfg_attr(any(target_arch = "mips", target_arch = "mips64"), ignore)] fn test_mq_set_nonblocking() { - const MSG_SIZE: c_long = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + const MSG_SIZE: c_long = 32; + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -119,8 +121,8 @@ fn test_mq_set_nonblocking() { #[test] fn test_mq_unlink() { - const MSG_SIZE: c_long = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + const MSG_SIZE: c_long = 32; + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name_opened = &CString::new(b"/mq_unlink_test".as_ref()).unwrap(); let mq_name_not_opened = &CString::new(b"/mq_unlink_test".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; @@ -133,12 +135,12 @@ fn test_mq_unlink() { let mqd = r.unwrap(); let res_unlink = mq_unlink(mq_name_opened); - assert!(res_unlink == Ok(()) ); + assert!(res_unlink == Ok(())); let res_unlink_not_opened = mq_unlink(mq_name_not_opened); - assert!(res_unlink_not_opened == Err(Sys(ENOENT)) ); + assert!(res_unlink_not_opened == Err(Sys(ENOENT))); mq_close(mqd).unwrap(); let res_unlink_after_close = mq_unlink(mq_name_opened); - assert!(res_unlink_after_close == Err(Sys(ENOENT)) ); + assert!(res_unlink_after_close == Err(Sys(ENOENT))); } diff --git a/test/test_nix_path.rs b/test/test_nix_path.rs index e69de29bb2..8b13789179 100644 --- a/test/test_nix_path.rs +++ b/test/test_nix_path.rs @@ -0,0 +1 @@ + diff --git a/test/test_poll.rs b/test/test_poll.rs index a9831ed4ce..b258ce7a3f 100644 --- a/test/test_poll.rs +++ b/test/test_poll.rs @@ -1,7 +1,7 @@ -use nix::poll::{EventFlags, poll, PollFd}; +use nix::poll::{poll, EventFlags, PollFd}; use nix::sys::signal::SigSet; use nix::sys::time::{TimeSpec, TimeValLike}; -use nix::unistd::{write, pipe, close}; +use nix::unistd::{close, pipe, write}; #[test] fn test_poll() { @@ -23,10 +23,14 @@ fn test_poll() { #[test] fn test_poll_debug() { - assert_eq!(format!("{:?}", PollFd::new(0, EventFlags::empty())), - "PollFd { fd: 0, events: (empty), revents: (empty) }"); - assert_eq!(format!("{:?}", PollFd::new(1, EventFlags::POLLIN)), - "PollFd { fd: 1, events: POLLIN, revents: (empty) }"); + assert_eq!( + format!("{:?}", PollFd::new(0, EventFlags::empty())), + "PollFd { fd: 0, events: (empty), revents: (empty) }" + ); + assert_eq!( + format!("{:?}", PollFd::new(1, EventFlags::POLLIN)), + "PollFd { fd: 1, events: POLLIN, revents: (empty) }" + ); // Testing revents requires doing some I/O let (r, w) = pipe().unwrap(); @@ -34,18 +38,22 @@ fn test_poll_debug() { write(w, b" ").unwrap(); close(w).unwrap(); poll(&mut fds, -1).unwrap(); - assert_eq!(format!("{:?}", fds[0]), - format!("PollFd {{ fd: {}, events: POLLIN, revents: POLLIN | POLLHUP }}", r)); + assert_eq!( + format!("{:?}", fds[0]), + format!( + "PollFd {{ fd: {}, events: POLLIN, revents: POLLIN | POLLHUP }}", + r + ) + ); close(r).unwrap(); } // ppoll(2) is the same as poll except for how it handles timeouts and signals. // Repeating the test for poll(2) should be sufficient to check that our // bindings are correct. -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux"))] +#[cfg( + any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux") +)] #[test] fn test_ppoll() { use nix::poll::ppoll; diff --git a/test/test_pty.rs b/test/test_pty.rs index 4f428bed9a..4dcc0788b9 100644 --- a/test/test_pty.rs +++ b/test/test_pty.rs @@ -1,13 +1,13 @@ use std::io::Write; -use std::path::Path; use std::os::unix::prelude::*; +use std::path::Path; use tempfile::tempfile; -use nix::fcntl::{OFlag, open}; +use nix::fcntl::{open, OFlag}; use nix::pty::*; use nix::sys::stat; use nix::sys::termios::*; -use nix::unistd::{write, close}; +use nix::unistd::{close, write}; /// Regression test for Issue #659 /// This is the correct way to explicitly close a `PtyMaster` @@ -27,14 +27,16 @@ fn test_explicit_close() { #[test] #[cfg(any(target_os = "android", target_os = "linux"))] fn test_ptsname_equivalence() { - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Open a new PTTY master let master_fd = posix_openpt(OFlag::O_RDWR).unwrap(); assert!(master_fd.as_raw_fd() > 0); // Get the name of the slave - let slave_name = unsafe { ptsname(&master_fd) }.unwrap() ; + let slave_name = unsafe { ptsname(&master_fd) }.unwrap(); let slave_name_r = ptsname_r(&master_fd).unwrap(); assert_eq!(slave_name, slave_name_r); } @@ -44,7 +46,9 @@ fn test_ptsname_equivalence() { #[test] #[cfg(any(target_os = "android", target_os = "linux"))] fn test_ptsname_copy() { - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Open a new PTTY master let master_fd = posix_openpt(OFlag::O_RDWR).unwrap(); @@ -78,7 +82,9 @@ fn test_ptsname_r_copy() { #[test] #[cfg(any(target_os = "android", target_os = "linux"))] fn test_ptsname_unique() { - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Open a new PTTY master let master1_fd = posix_openpt(OFlag::O_RDWR).unwrap(); @@ -100,8 +106,10 @@ fn test_ptsname_unique() { /// this test we perform the basic act of getting a file handle for a connect master/slave PTTY /// pair. #[test] -fn test_open_ptty_pair() { - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); +fn test_open_ptty_pair() { + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Open a new PTTY master let master_fd = posix_openpt(OFlag::O_RDWR).expect("posix_openpt failed"); @@ -122,7 +130,9 @@ fn test_open_ptty_pair() { #[test] fn test_openpty() { // openpty uses ptname(3) internally - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); let pty = openpty(None, None).unwrap(); assert!(pty.master > 0); @@ -157,7 +167,9 @@ fn test_openpty() { #[test] fn test_openpty_with_termios() { // openpty uses ptname(3) internally - let _m = ::PTSNAME_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::PTSNAME_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Open one pty to get attributes for the second one let mut termios = { diff --git a/test/test_ptymaster_drop.rs b/test/test_ptymaster_drop.rs index 9b59d66435..466e4f1f40 100644 --- a/test/test_ptymaster_drop.rs +++ b/test/test_ptymaster_drop.rs @@ -17,5 +17,5 @@ use std::os::unix::io::AsRawFd; fn test_double_close() { let m = posix_openpt(OFlag::O_RDWR).unwrap(); close(m.as_raw_fd()).unwrap(); - drop(m); // should panic here + drop(m); // should panic here } diff --git a/test/test_stat.rs b/test/test_stat.rs index 77a6cbffcf..071b856ddc 100644 --- a/test/test_stat.rs +++ b/test/test_stat.rs @@ -2,14 +2,14 @@ use std::fs::File; use std::os::unix::fs::symlink; use std::os::unix::prelude::AsRawFd; -use libc::{S_IFMT, S_IFLNK}; +use libc::{S_IFLNK, S_IFMT}; use nix::fcntl; use nix::sys::stat::{self, fchmod, fchmodat, fstat, lstat, stat}; -use nix::sys::stat::{FileStat, Mode, FchmodatFlags}; +use nix::sys::stat::{FchmodatFlags, FileStat, Mode}; use nix::unistd::chdir; use nix::Result; -use tempfile::Builder; +use tempfile::tempdir; #[allow(unused_comparisons)] // uid and gid are signed on Windows, but not on other platforms. This function @@ -23,30 +23,30 @@ fn valid_uid_gid(stat: FileStat) -> bool { fn assert_stat_results(stat_result: Result) { let stats = stat_result.expect("stat call failed"); - assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent - assert!(stats.st_mode > 0); // must be positive integer - assert!(stats.st_nlink == 1); // there links created, must be 1 - assert!(valid_uid_gid(stats)); // must be positive integers - assert!(stats.st_size == 0); // size is 0 because we did not write anything to the file - assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_blocks <= 16); // Up to 16 blocks can be allocated for a blank file + assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent + assert!(stats.st_mode > 0); // must be positive integer + assert!(stats.st_nlink == 1); // there links created, must be 1 + assert!(valid_uid_gid(stats)); // must be positive integers + assert!(stats.st_size == 0); // size is 0 because we did not write anything to the file + assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_blocks <= 16); // Up to 16 blocks can be allocated for a blank file } fn assert_lstat_results(stat_result: Result) { let stats = stat_result.expect("stat call failed"); - assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent - assert!(stats.st_mode > 0); // must be positive integer + assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent + assert!(stats.st_mode > 0); // must be positive integer // st_mode is c_uint (u32 on Android) while S_IFMT is mode_t // (u16 on Android), and that will be a compile error. // On other platforms they are the same (either both are u16 or u32). assert!((stats.st_mode as usize) & (S_IFMT as usize) == S_IFLNK as usize); // should be a link - assert!(stats.st_nlink == 1); // there links created, must be 1 - assert!(valid_uid_gid(stats)); // must be positive integers - assert!(stats.st_size > 0); // size is > 0 because it points to another file - assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_nlink == 1); // there links created, must be 1 + assert!(valid_uid_gid(stats)); // must be positive integers + assert!(stats.st_size > 0); // size is > 0 because it points to another file + assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent // st_blocks depends on whether the machine's file system uses fast // or slow symlinks, so just make sure it's not negative @@ -56,7 +56,7 @@ fn assert_lstat_results(stat_result: Result) { #[test] fn test_stat_and_fstat() { - let tempdir = Builder::new().prefix("nix-test_stat_and_fstat").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let filename = tempdir.path().join("foo.txt"); let file = File::create(&filename).unwrap(); @@ -69,22 +69,18 @@ fn test_stat_and_fstat() { #[test] fn test_fstatat() { - let tempdir = Builder::new().prefix("nix-test_fstatat").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let filename = tempdir.path().join("foo.txt"); File::create(&filename).unwrap(); - let dirfd = fcntl::open(tempdir.path(), - fcntl::OFlag::empty(), - stat::Mode::empty()); + let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()); - let result = stat::fstatat(dirfd.unwrap(), - &filename, - fcntl::AtFlags::empty()); + let result = stat::fstatat(dirfd.unwrap(), &filename, fcntl::AtFlags::empty()); assert_stat_results(result); } #[test] fn test_stat_fstat_lstat() { - let tempdir = Builder::new().prefix("nix-test_stat_fstat_lstat").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let filename = tempdir.path().join("bar.txt"); let linkname = tempdir.path().join("barlink"); @@ -106,7 +102,7 @@ fn test_stat_fstat_lstat() { #[test] fn test_fchmod() { - let tempdir = Builder::new().prefix("nix-test_fchmod").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let filename = tempdir.path().join("foo.txt"); let file = File::create(&filename).unwrap(); @@ -128,7 +124,7 @@ fn test_fchmod() { #[test] fn test_fchmodat() { - let tempdir = Builder::new().prefix("nix-test_fchmodat").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let filename = "foo.txt"; let fullpath = tempdir.path().join(filename); File::create(&fullpath).unwrap(); diff --git a/test/test_unistd.rs b/test/test_unistd.rs index b97df102b5..b22c89dcf7 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -1,23 +1,24 @@ extern crate tempfile; +use libc::{self, _exit, off_t}; use nix::fcntl::{fcntl, FcntlArg, FdFlag, OFlag}; -use nix::unistd::*; -use nix::unistd::ForkResult::*; -use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction}; -use nix::sys::wait::*; +use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal}; use nix::sys::stat::{self, Mode, SFlag}; +use nix::sys::wait::*; +use nix::unistd::ForkResult::*; +use nix::unistd::*; use std::ffi::CString; use std::fs::File; use std::io::Write; use std::os::unix::prelude::*; use std::{env, iter}; -use tempfile::tempfile; -use tempfile::Builder; -use libc::{self, _exit, off_t}; +use tempfile::{tempdir, tempfile}; #[test] fn test_fork_and_waitpid() { - let _m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::FORK_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Safe: Child only calls `_exit`, which is signal-safe match fork().expect("Error: Fork Failed") { @@ -29,23 +30,24 @@ fn test_fork_and_waitpid() { let wait_status = waitpid(child, None); match wait_status { // assert that waitpid returned correct status and the pid is the one of the child - Ok(WaitStatus::Exited(pid_t, _)) => assert!(pid_t == child), + Ok(WaitStatus::Exited(pid_t, _)) => assert!(pid_t == child), // panic, must never happen s @ Ok(_) => panic!("Child exited {:?}, should never happen", s), // panic, waitpid should never fail - Err(s) => panic!("Error: waitpid returned Err({:?}", s) + Err(s) => panic!("Error: waitpid returned Err({:?}", s), } - - }, + } } } #[test] fn test_wait() { // Grab FORK_MTX so wait doesn't reap a different test's child process - let _m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::FORK_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Safe: Child only calls `_exit`, which is signal-safe match fork().expect("Error: Fork Failed") { @@ -55,7 +57,7 @@ fn test_wait() { // just assert that (any) one child returns with WaitStatus::Exited assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0))); - }, + } } } @@ -69,8 +71,8 @@ fn test_mkstemp() { Ok((fd, path)) => { close(fd).unwrap(); unlink(path.as_path()).unwrap(); - }, - Err(e) => panic!("mkstemp failed: {}", e) + } + Err(e) => panic!("mkstemp failed: {}", e), } } @@ -82,7 +84,7 @@ fn test_mkstemp_directory() { #[test] fn test_mkfifo() { - let tempdir = Builder::new().prefix("nix-test_mkfifo").tempdir().unwrap(); + let tempdir = tempdir().unwrap(); let mkfifo_fifo = tempdir.path().join("mkfifo_fifo"); mkfifo(&mkfifo_fifo, Mode::S_IRUSR).unwrap(); @@ -132,7 +134,9 @@ fn test_setgroups() { // Skip this test when not run as root as `setgroups()` requires root. skip_if_not_root!("test_setgroups"); - let _m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::GROUPS_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Save the existing groups let old_groups = getgroups().unwrap(); @@ -156,7 +160,9 @@ fn test_initgroups() { // require root. skip_if_not_root!("test_initgroups"); - let _m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::GROUPS_MTX + .lock() + .expect("Mutex got poisoned by another test"); // Save the existing groups let old_groups = getgroups().unwrap(); @@ -268,9 +274,11 @@ cfg_if!{ #[test] fn test_fchdir() { // fchdir changes the process's cwd - let _m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::CWD_MTX + .lock() + .expect("Mutex got poisoned by another test"); - let tmpdir = Builder::new().prefix("test_fchdir").tempdir().unwrap(); + let tmpdir = tempdir().unwrap(); let tmpdir_path = tmpdir.path().canonicalize().unwrap(); let tmpdir_fd = File::open(&tmpdir_path).unwrap().into_raw_fd(); @@ -283,9 +291,11 @@ fn test_fchdir() { #[test] fn test_getcwd() { // chdir changes the process's cwd - let _m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::CWD_MTX + .lock() + .expect("Mutex got poisoned by another test"); - let tmpdir = Builder::new().prefix("test_getcwd").tempdir().unwrap(); + let tmpdir = tempdir().unwrap(); let tmpdir_path = tmpdir.path().canonicalize().unwrap(); assert!(chdir(&tmpdir_path).is_ok()); assert_eq!(getcwd().unwrap(), tmpdir_path); @@ -343,21 +353,33 @@ fn test_fpathconf_limited() { let f = tempfile().unwrap(); // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX); - assert!(path_max.expect("fpathconf failed").expect("PATH_MAX is unlimited") > 0); + assert!( + path_max + .expect("fpathconf failed") + .expect("PATH_MAX is unlimited") > 0 + ); } #[test] fn test_pathconf_limited() { // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test let path_max = pathconf("/", PathconfVar::PATH_MAX); - assert!(path_max.expect("pathconf failed").expect("PATH_MAX is unlimited") > 0); + assert!( + path_max + .expect("pathconf failed") + .expect("PATH_MAX is unlimited") > 0 + ); } #[test] fn test_sysconf_limited() { // AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test let open_max = sysconf(SysconfVar::OPEN_MAX); - assert!(open_max.expect("sysconf failed").expect("OPEN_MAX is unlimited") > 0); + assert!( + open_max + .expect("sysconf failed") + .expect("OPEN_MAX is unlimited") > 0 + ); } #[cfg(target_os = "freebsd")] @@ -397,20 +419,26 @@ fn test_pipe2() { static mut ALARM_CALLED: bool = false; // Used in `test_alarm`. -pub extern fn alarm_signal_handler(raw_signal: libc::c_int) { - assert_eq!(raw_signal, libc::SIGALRM, "unexpected signal: {}", raw_signal); +pub extern "C" fn alarm_signal_handler(raw_signal: libc::c_int) { + assert_eq!( + raw_signal, + libc::SIGALRM, + "unexpected signal: {}", + raw_signal + ); unsafe { ALARM_CALLED = true }; } #[test] fn test_alarm() { - let _m = ::SIGNAL_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::SIGNAL_MTX + .lock() + .expect("Mutex got poisoned by another test"); let handler = SigHandler::Handler(alarm_signal_handler); let signal_action = SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); let old_handler = unsafe { - sigaction(Signal::SIGALRM, &signal_action) - .expect("unable to set signal handler for alarm") + sigaction(Signal::SIGALRM, &signal_action).expect("unable to set signal handler for alarm") }; // Set an alarm. @@ -422,18 +450,23 @@ fn test_alarm() { // We should be woken up after 1 second by the alarm, so we'll sleep for 2 // seconds to be sure. sleep(2); - assert_eq!(unsafe { ALARM_CALLED }, true, "expected our alarm signal handler to be called"); + assert_eq!( + unsafe { ALARM_CALLED }, + true, + "expected our alarm signal handler to be called" + ); // Reset the signal. unsafe { - sigaction(Signal::SIGALRM, &old_handler) - .expect("unable to set signal handler for alarm"); + sigaction(Signal::SIGALRM, &old_handler).expect("unable to set signal handler for alarm"); } } #[test] fn test_canceling_alarm() { - let _m = ::SIGNAL_MTX.lock().expect("Mutex got poisoned by another test"); + let _m = ::SIGNAL_MTX + .lock() + .expect("Mutex got poisoned by another test"); assert_eq!(alarm::cancel(), None);