diff options
| author | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:04 -0500 |
|---|---|---|
| committer | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:47 -0500 |
| commit | a06baa56b95674fc626b3c3fd680d6a65357fe60 (patch) | |
| tree | cd9d867c2ca3cff5c1d6b3bd73377c44649fb075 /src/libstd/sys | |
| parent | 8eb7c58dbb7b32701af113bc58722d0d1fefb1eb (diff) | |
| download | rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.tar.gz rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.zip | |
Format the world
Diffstat (limited to 'src/libstd/sys')
42 files changed, 2501 insertions, 2460 deletions
diff --git a/src/libstd/sys/cloudabi/abi/cloudabi.rs b/src/libstd/sys/cloudabi/abi/cloudabi.rs index 38db4dd5165..d113a7b3d60 100644 --- a/src/libstd/sys/cloudabi/abi/cloudabi.rs +++ b/src/libstd/sys/cloudabi/abi/cloudabi.rs @@ -124,24 +124,24 @@ include!("bitflags.rs"); #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum advice { - /// The application expects that it will not access the - /// specified data in the near future. - DONTNEED = 1, - /// The application expects to access the specified data - /// once and then not reuse it thereafter. - NOREUSE = 2, - /// The application has no advice to give on its behavior - /// with respect to the specified data. - NORMAL = 3, - /// The application expects to access the specified data - /// in a random order. - RANDOM = 4, - /// The application expects to access the specified data - /// sequentially from lower offsets to higher offsets. - SEQUENTIAL = 5, - /// The application expects to access the specified data - /// in the near future. - WILLNEED = 6, + /// The application expects that it will not access the + /// specified data in the near future. + DONTNEED = 1, + /// The application expects to access the specified data + /// once and then not reuse it thereafter. + NOREUSE = 2, + /// The application has no advice to give on its behavior + /// with respect to the specified data. + NORMAL = 3, + /// The application expects to access the specified data + /// in a random order. + RANDOM = 4, + /// The application expects to access the specified data + /// sequentially from lower offsets to higher offsets. + SEQUENTIAL = 5, + /// The application expects to access the specified data + /// in the near future. + WILLNEED = 6, } /// Enumeration describing the kind of value stored in [`auxv`](struct.auxv.html). @@ -149,69 +149,69 @@ pub enum advice { #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum auxtype { - /// Base address of the binary argument data provided to - /// [`proc_exec()`](fn.proc_exec.html). - ARGDATA = 256, - /// Length of the binary argument data provided to - /// [`proc_exec()`](fn.proc_exec.html). - ARGDATALEN = 257, - /// Base address at which the executable is placed in - /// memory. - BASE = 7, - /// Base address of a buffer of random data that may be - /// used for non-cryptographic purposes, for example as a - /// canary for stack smashing protection. - CANARY = 258, - /// Length of a buffer of random data that may be used - /// for non-cryptographic purposes, for example as a - /// canary for stack smashing protection. - CANARYLEN = 259, - /// Number of CPUs that the system this process is running - /// on has. - NCPUS = 260, - /// Terminator of the auxiliary vector. - NULL = 0, - /// Smallest memory object size for which individual - /// memory protection controls can be configured. - PAGESZ = 6, - /// Address of the first ELF program header of the - /// executable. - PHDR = 3, - /// Number of ELF program headers of the executable. - PHNUM = 4, - /// Identifier of the process. - /// - /// This environment does not provide any simple numerical - /// process identifiers, for the reason that these are not - /// useful in distributed contexts. Instead, processes are - /// identified by a UUID. - /// - /// This record should point to sixteen bytes of binary - /// data, containing a version 4 UUID (fully random). - PID = 263, - /// Address of the ELF header of the vDSO. - /// - /// The vDSO is a shared library that is mapped in the - /// address space of the process. It provides entry points - /// for every system call supported by the environment, - /// all having a corresponding symbol that is prefixed - /// with `cloudabi_sys_`. System calls should be invoked - /// through these entry points. - /// - /// The first advantage of letting processes call into a - /// vDSO to perform system calls instead of raising - /// hardware traps is that it allows for easy emulation of - /// executables on top of existing operating systems. The - /// second advantage is that in cases where an operating - /// system provides native support for CloudABI executables, - /// it may still implement partial userspace - /// implementations of these system calls to improve - /// performance (e.g., [`clock_time_get()`](fn.clock_time_get.html)). It also provides - /// a more dynamic way of adding, removing or replacing - /// system calls. - SYSINFO_EHDR = 262, - /// Thread ID of the initial thread of the process. - TID = 261, + /// Base address of the binary argument data provided to + /// [`proc_exec()`](fn.proc_exec.html). + ARGDATA = 256, + /// Length of the binary argument data provided to + /// [`proc_exec()`](fn.proc_exec.html). + ARGDATALEN = 257, + /// Base address at which the executable is placed in + /// memory. + BASE = 7, + /// Base address of a buffer of random data that may be + /// used for non-cryptographic purposes, for example as a + /// canary for stack smashing protection. + CANARY = 258, + /// Length of a buffer of random data that may be used + /// for non-cryptographic purposes, for example as a + /// canary for stack smashing protection. + CANARYLEN = 259, + /// Number of CPUs that the system this process is running + /// on has. + NCPUS = 260, + /// Terminator of the auxiliary vector. + NULL = 0, + /// Smallest memory object size for which individual + /// memory protection controls can be configured. + PAGESZ = 6, + /// Address of the first ELF program header of the + /// executable. + PHDR = 3, + /// Number of ELF program headers of the executable. + PHNUM = 4, + /// Identifier of the process. + /// + /// This environment does not provide any simple numerical + /// process identifiers, for the reason that these are not + /// useful in distributed contexts. Instead, processes are + /// identified by a UUID. + /// + /// This record should point to sixteen bytes of binary + /// data, containing a version 4 UUID (fully random). + PID = 263, + /// Address of the ELF header of the vDSO. + /// + /// The vDSO is a shared library that is mapped in the + /// address space of the process. It provides entry points + /// for every system call supported by the environment, + /// all having a corresponding symbol that is prefixed + /// with `cloudabi_sys_`. System calls should be invoked + /// through these entry points. + /// + /// The first advantage of letting processes call into a + /// vDSO to perform system calls instead of raising + /// hardware traps is that it allows for easy emulation of + /// executables on top of existing operating systems. The + /// second advantage is that in cases where an operating + /// system provides native support for CloudABI executables, + /// it may still implement partial userspace + /// implementations of these system calls to improve + /// performance (e.g., [`clock_time_get()`](fn.clock_time_get.html)). It also provides + /// a more dynamic way of adding, removing or replacing + /// system calls. + SYSINFO_EHDR = 262, + /// Thread ID of the initial thread of the process. + TID = 261, } /// Identifiers for clocks. @@ -219,21 +219,21 @@ pub enum auxtype { #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum clockid { - /// The system-wide monotonic clock, which is defined as a - /// clock measuring real time, whose value cannot be - /// adjusted and which cannot have negative clock jumps. - /// - /// The epoch of this clock is undefined. The absolute - /// time value of this clock therefore has no meaning. - MONOTONIC = 1, - /// The CPU-time clock associated with the current - /// process. - PROCESS_CPUTIME_ID = 2, - /// The system-wide clock measuring real time. Time value - /// zero corresponds with 1970-01-01T00:00:00Z. - REALTIME = 3, - /// The CPU-time clock associated with the current thread. - THREAD_CPUTIME_ID = 4, + /// The system-wide monotonic clock, which is defined as a + /// clock measuring real time, whose value cannot be + /// adjusted and which cannot have negative clock jumps. + /// + /// The epoch of this clock is undefined. The absolute + /// time value of this clock therefore has no meaning. + MONOTONIC = 1, + /// The CPU-time clock associated with the current + /// process. + PROCESS_CPUTIME_ID = 2, + /// The system-wide clock measuring real time. Time value + /// zero corresponds with 1970-01-01T00:00:00Z. + REALTIME = 3, + /// The CPU-time clock associated with the current thread. + THREAD_CPUTIME_ID = 4, } /// A userspace condition variable. @@ -270,160 +270,160 @@ pub const DIRCOOKIE_START: dircookie = dircookie(0); #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum errno { - /// No error occurred. System call completed successfully. - SUCCESS = 0, - /// Argument list too long. - TOOBIG = 1, - /// Permission denied. - ACCES = 2, - /// Address in use. - ADDRINUSE = 3, - /// Address not available. - ADDRNOTAVAIL = 4, - /// Address family not supported. - AFNOSUPPORT = 5, - /// Resource unavailable, or operation would block. - AGAIN = 6, - /// Connection already in progress. - ALREADY = 7, - /// Bad file descriptor. - BADF = 8, - /// Bad message. - BADMSG = 9, - /// Device or resource busy. - BUSY = 10, - /// Operation canceled. - CANCELED = 11, - /// No child processes. - CHILD = 12, - /// Connection aborted. - CONNABORTED = 13, - /// Connection refused. - CONNREFUSED = 14, - /// Connection reset. - CONNRESET = 15, - /// Resource deadlock would occur. - DEADLK = 16, - /// Destination address required. - DESTADDRREQ = 17, - /// Mathematics argument out of domain of function. - DOM = 18, - /// Reserved. - DQUOT = 19, - /// File exists. - EXIST = 20, - /// Bad address. - FAULT = 21, - /// File too large. - FBIG = 22, - /// Host is unreachable. - HOSTUNREACH = 23, - /// Identifier removed. - IDRM = 24, - /// Illegal byte sequence. - ILSEQ = 25, - /// Operation in progress. - INPROGRESS = 26, - /// Interrupted function. - INTR = 27, - /// Invalid argument. - INVAL = 28, - /// I/O error. - IO = 29, - /// Socket is connected. - ISCONN = 30, - /// Is a directory. - ISDIR = 31, - /// Too many levels of symbolic links. - LOOP = 32, - /// File descriptor value too large. - MFILE = 33, - /// Too many links. - MLINK = 34, - /// Message too large. - MSGSIZE = 35, - /// Reserved. - MULTIHOP = 36, - /// Filename too long. - NAMETOOLONG = 37, - /// Network is down. - NETDOWN = 38, - /// Connection aborted by network. - NETRESET = 39, - /// Network unreachable. - NETUNREACH = 40, - /// Too many files open in system. - NFILE = 41, - /// No buffer space available. - NOBUFS = 42, - /// No such device. - NODEV = 43, - /// No such file or directory. - NOENT = 44, - /// Executable file format error. - NOEXEC = 45, - /// No locks available. - NOLCK = 46, - /// Reserved. - NOLINK = 47, - /// Not enough space. - NOMEM = 48, - /// No message of the desired type. - NOMSG = 49, - /// Protocol not available. - NOPROTOOPT = 50, - /// No space left on device. - NOSPC = 51, - /// Function not supported. - NOSYS = 52, - /// The socket is not connected. - NOTCONN = 53, - /// Not a directory or a symbolic link to a directory. - NOTDIR = 54, - /// Directory not empty. - NOTEMPTY = 55, - /// State not recoverable. - NOTRECOVERABLE = 56, - /// Not a socket. - NOTSOCK = 57, - /// Not supported, or operation not supported on socket. - NOTSUP = 58, - /// Inappropriate I/O control operation. - NOTTY = 59, - /// No such device or address. - NXIO = 60, - /// Value too large to be stored in data type. - OVERFLOW = 61, - /// Previous owner died. - OWNERDEAD = 62, - /// Operation not permitted. - PERM = 63, - /// Broken pipe. - PIPE = 64, - /// Protocol error. - PROTO = 65, - /// Protocol not supported. - PROTONOSUPPORT = 66, - /// Protocol wrong type for socket. - PROTOTYPE = 67, - /// Result too large. - RANGE = 68, - /// Read-only file system. - ROFS = 69, - /// Invalid seek. - SPIPE = 70, - /// No such process. - SRCH = 71, - /// Reserved. - STALE = 72, - /// Connection timed out. - TIMEDOUT = 73, - /// Text file busy. - TXTBSY = 74, - /// Cross-device link. - XDEV = 75, - /// Extension: Capabilities insufficient. - NOTCAPABLE = 76, + /// No error occurred. System call completed successfully. + SUCCESS = 0, + /// Argument list too long. + TOOBIG = 1, + /// Permission denied. + ACCES = 2, + /// Address in use. + ADDRINUSE = 3, + /// Address not available. + ADDRNOTAVAIL = 4, + /// Address family not supported. + AFNOSUPPORT = 5, + /// Resource unavailable, or operation would block. + AGAIN = 6, + /// Connection already in progress. + ALREADY = 7, + /// Bad file descriptor. + BADF = 8, + /// Bad message. + BADMSG = 9, + /// Device or resource busy. + BUSY = 10, + /// Operation canceled. + CANCELED = 11, + /// No child processes. + CHILD = 12, + /// Connection aborted. + CONNABORTED = 13, + /// Connection refused. + CONNREFUSED = 14, + /// Connection reset. + CONNRESET = 15, + /// Resource deadlock would occur. + DEADLK = 16, + /// Destination address required. + DESTADDRREQ = 17, + /// Mathematics argument out of domain of function. + DOM = 18, + /// Reserved. + DQUOT = 19, + /// File exists. + EXIST = 20, + /// Bad address. + FAULT = 21, + /// File too large. + FBIG = 22, + /// Host is unreachable. + HOSTUNREACH = 23, + /// Identifier removed. + IDRM = 24, + /// Illegal byte sequence. + ILSEQ = 25, + /// Operation in progress. + INPROGRESS = 26, + /// Interrupted function. + INTR = 27, + /// Invalid argument. + INVAL = 28, + /// I/O error. + IO = 29, + /// Socket is connected. + ISCONN = 30, + /// Is a directory. + ISDIR = 31, + /// Too many levels of symbolic links. + LOOP = 32, + /// File descriptor value too large. + MFILE = 33, + /// Too many links. + MLINK = 34, + /// Message too large. + MSGSIZE = 35, + /// Reserved. + MULTIHOP = 36, + /// Filename too long. + NAMETOOLONG = 37, + /// Network is down. + NETDOWN = 38, + /// Connection aborted by network. + NETRESET = 39, + /// Network unreachable. + NETUNREACH = 40, + /// Too many files open in system. + NFILE = 41, + /// No buffer space available. + NOBUFS = 42, + /// No such device. + NODEV = 43, + /// No such file or directory. + NOENT = 44, + /// Executable file format error. + NOEXEC = 45, + /// No locks available. + NOLCK = 46, + /// Reserved. + NOLINK = 47, + /// Not enough space. + NOMEM = 48, + /// No message of the desired type. + NOMSG = 49, + /// Protocol not available. + NOPROTOOPT = 50, + /// No space left on device. + NOSPC = 51, + /// Function not supported. + NOSYS = 52, + /// The socket is not connected. + NOTCONN = 53, + /// Not a directory or a symbolic link to a directory. + NOTDIR = 54, + /// Directory not empty. + NOTEMPTY = 55, + /// State not recoverable. + NOTRECOVERABLE = 56, + /// Not a socket. + NOTSOCK = 57, + /// Not supported, or operation not supported on socket. + NOTSUP = 58, + /// Inappropriate I/O control operation. + NOTTY = 59, + /// No such device or address. + NXIO = 60, + /// Value too large to be stored in data type. + OVERFLOW = 61, + /// Previous owner died. + OWNERDEAD = 62, + /// Operation not permitted. + PERM = 63, + /// Broken pipe. + PIPE = 64, + /// Protocol error. + PROTO = 65, + /// Protocol not supported. + PROTONOSUPPORT = 66, + /// Protocol wrong type for socket. + PROTOTYPE = 67, + /// Result too large. + RANGE = 68, + /// Read-only file system. + ROFS = 69, + /// Invalid seek. + SPIPE = 70, + /// No such process. + SRCH = 71, + /// Reserved. + STALE = 72, + /// Connection timed out. + TIMEDOUT = 73, + /// Text file busy. + TXTBSY = 74, + /// Cross-device link. + XDEV = 75, + /// Extension: Capabilities insufficient. + NOTCAPABLE = 76, } bitflags! { @@ -441,30 +441,30 @@ bitflags! { #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum eventtype { - /// The time value of clock [`subscription.union.clock.clock_id`](struct.subscription_clock.html#structfield.clock_id) - /// has reached timestamp [`subscription.union.clock.timeout`](struct.subscription_clock.html#structfield.timeout). - CLOCK = 1, - /// Condition variable [`subscription.union.condvar.condvar`](struct.subscription_condvar.html#structfield.condvar) has - /// been woken up and [`subscription.union.condvar.lock`](struct.subscription_condvar.html#structfield.lock) has been - /// acquired for writing. - CONDVAR = 2, - /// File descriptor [`subscription.union.fd_readwrite.fd`](struct.subscription_fd_readwrite.html#structfield.fd) has - /// data available for reading. This event always triggers - /// for regular files. - FD_READ = 3, - /// File descriptor [`subscription.union.fd_readwrite.fd`](struct.subscription_fd_readwrite.html#structfield.fd) has - /// capacity available for writing. This event always - /// triggers for regular files. - FD_WRITE = 4, - /// Lock [`subscription.union.lock.lock`](struct.subscription_lock.html#structfield.lock) has been acquired for - /// reading. - LOCK_RDLOCK = 5, - /// Lock [`subscription.union.lock.lock`](struct.subscription_lock.html#structfield.lock) has been acquired for - /// writing. - LOCK_WRLOCK = 6, - /// The process associated with process descriptor - /// [`subscription.union.proc_terminate.fd`](struct.subscription_proc_terminate.html#structfield.fd) has terminated. - PROC_TERMINATE = 7, + /// The time value of clock [`subscription.union.clock.clock_id`](struct.subscription_clock.html#structfield.clock_id) + /// has reached timestamp [`subscription.union.clock.timeout`](struct.subscription_clock.html#structfield.timeout). + CLOCK = 1, + /// Condition variable [`subscription.union.condvar.condvar`](struct.subscription_condvar.html#structfield.condvar) has + /// been woken up and [`subscription.union.condvar.lock`](struct.subscription_condvar.html#structfield.lock) has been + /// acquired for writing. + CONDVAR = 2, + /// File descriptor [`subscription.union.fd_readwrite.fd`](struct.subscription_fd_readwrite.html#structfield.fd) has + /// data available for reading. This event always triggers + /// for regular files. + FD_READ = 3, + /// File descriptor [`subscription.union.fd_readwrite.fd`](struct.subscription_fd_readwrite.html#structfield.fd) has + /// capacity available for writing. This event always + /// triggers for regular files. + FD_WRITE = 4, + /// Lock [`subscription.union.lock.lock`](struct.subscription_lock.html#structfield.lock) has been acquired for + /// reading. + LOCK_RDLOCK = 5, + /// Lock [`subscription.union.lock.lock`](struct.subscription_lock.html#structfield.lock) has been acquired for + /// writing. + LOCK_WRLOCK = 6, + /// The process associated with process descriptor + /// [`subscription.union.proc_terminate.fd`](struct.subscription_proc_terminate.html#structfield.fd) has terminated. + PROC_TERMINATE = 7, } /// Exit code generated by a process when exiting. @@ -483,7 +483,7 @@ pub struct fd(pub u32); pub const PROCESS_CHILD: fd = fd(0xffffffff); /// Passed to [`mem_map()`](fn.mem_map.html) when creating a mapping to /// anonymous memory. -pub const MAP_ANON_FD : fd = fd(0xffffffff); +pub const MAP_ANON_FD: fd = fd(0xffffffff); bitflags! { /// File descriptor flags. @@ -533,33 +533,33 @@ pub type filesize = u64; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum filetype { - /// The type of the file descriptor or file is unknown or - /// is different from any of the other types specified. - UNKNOWN = 0, - /// The file descriptor or file refers to a block device - /// inode. - BLOCK_DEVICE = 16, - /// The file descriptor or file refers to a character - /// device inode. - CHARACTER_DEVICE = 17, - /// The file descriptor or file refers to a directory - /// inode. - DIRECTORY = 32, - /// The file descriptor refers to a process handle. - PROCESS = 80, - /// The file descriptor or file refers to a regular file - /// inode. - REGULAR_FILE = 96, - /// The file descriptor refers to a shared memory object. - SHARED_MEMORY = 112, - /// The file descriptor or file refers to a datagram - /// socket. - SOCKET_DGRAM = 128, - /// The file descriptor or file refers to a byte-stream - /// socket. - SOCKET_STREAM = 130, - /// The file refers to a symbolic link inode. - SYMBOLIC_LINK = 144, + /// The type of the file descriptor or file is unknown or + /// is different from any of the other types specified. + UNKNOWN = 0, + /// The file descriptor or file refers to a block device + /// inode. + BLOCK_DEVICE = 16, + /// The file descriptor or file refers to a character + /// device inode. + CHARACTER_DEVICE = 17, + /// The file descriptor or file refers to a directory + /// inode. + DIRECTORY = 32, + /// The file descriptor refers to a process handle. + PROCESS = 80, + /// The file descriptor or file refers to a regular file + /// inode. + REGULAR_FILE = 96, + /// The file descriptor refers to a shared memory object. + SHARED_MEMORY = 112, + /// The file descriptor or file refers to a datagram + /// socket. + SOCKET_DGRAM = 128, + /// The file descriptor or file refers to a byte-stream + /// socket. + SOCKET_STREAM = 130, + /// The file refers to a symbolic link inode. + SYMBOLIC_LINK = 144, } bitflags! { @@ -599,13 +599,13 @@ pub type linkcount = u32; pub struct lock(pub u32); /// Value indicating that the lock is in its initial /// unlocked state. -pub const LOCK_UNLOCKED : lock = lock(0x00000000); +pub const LOCK_UNLOCKED: lock = lock(0x00000000); /// Bitmask indicating that the lock is write-locked. If /// set, the lower 30 bits of the lock contain the /// identifier of the thread that owns the write lock. /// Otherwise, the lower 30 bits of the lock contain the /// number of acquired read locks. -pub const LOCK_WRLOCKED : lock = lock(0x40000000); +pub const LOCK_WRLOCKED: lock = lock(0x40000000); /// Bitmask indicating that the lock is either read locked /// or write locked, and that one or more threads have /// their execution suspended, waiting to acquire the @@ -623,7 +623,7 @@ pub const LOCK_KERNEL_MANAGED: lock = lock(0x80000000); /// Value indicating that the lock is in an incorrect /// state. A lock cannot be in its initial unlocked state, /// while also managed by the kernel. -pub const LOCK_BOGUS : lock = lock(0x80000000); +pub const LOCK_BOGUS: lock = lock(0x80000000); bitflags! { /// Flags determining the method of how paths are resolved. @@ -850,10 +850,10 @@ bitflags! { #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum scope { - /// The object is stored in private memory. - PRIVATE = 4, - /// The object is stored in shared memory. - SHARED = 8, + /// The object is stored in private memory. + PRIVATE = 4, + /// The object is stored in shared memory. + SHARED = 8, } bitflags! { @@ -881,110 +881,110 @@ bitflags! { #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum signal { - /// Process abort signal. - /// - /// Action: Terminates the process. - ABRT = 1, - /// Alarm clock. - /// - /// Action: Terminates the process. - ALRM = 2, - /// Access to an undefined portion of a memory object. - /// - /// Action: Terminates the process. - BUS = 3, - /// Child process terminated, stopped, or continued. - /// - /// Action: Ignored. - CHLD = 4, - /// Continue executing, if stopped. - /// - /// Action: Continues executing, if stopped. - CONT = 5, - /// Erroneous arithmetic operation. - /// - /// Action: Terminates the process. - FPE = 6, - /// Hangup. - /// - /// Action: Terminates the process. - HUP = 7, - /// Illegal instruction. - /// - /// Action: Terminates the process. - ILL = 8, - /// Terminate interrupt signal. - /// - /// Action: Terminates the process. - INT = 9, - /// Kill. - /// - /// Action: Terminates the process. - KILL = 10, - /// Write on a pipe with no one to read it. - /// - /// Action: Ignored. - PIPE = 11, - /// Terminal quit signal. - /// - /// Action: Terminates the process. - QUIT = 12, - /// Invalid memory reference. - /// - /// Action: Terminates the process. - SEGV = 13, - /// Stop executing. - /// - /// Action: Stops executing. - STOP = 14, - /// Bad system call. - /// - /// Action: Terminates the process. - SYS = 15, - /// Termination signal. - /// - /// Action: Terminates the process. - TERM = 16, - /// Trace/breakpoint trap. - /// - /// Action: Terminates the process. - TRAP = 17, - /// Terminal stop signal. - /// - /// Action: Stops executing. - TSTP = 18, - /// Background process attempting read. - /// - /// Action: Stops executing. - TTIN = 19, - /// Background process attempting write. - /// - /// Action: Stops executing. - TTOU = 20, - /// High bandwidth data is available at a socket. - /// - /// Action: Ignored. - URG = 21, - /// User-defined signal 1. - /// - /// Action: Terminates the process. - USR1 = 22, - /// User-defined signal 2. - /// - /// Action: Terminates the process. - USR2 = 23, - /// Virtual timer expired. - /// - /// Action: Terminates the process. - VTALRM = 24, - /// CPU time limit exceeded. - /// - /// Action: Terminates the process. - XCPU = 25, - /// File size limit exceeded. - /// - /// Action: Terminates the process. - XFSZ = 26, + /// Process abort signal. + /// + /// Action: Terminates the process. + ABRT = 1, + /// Alarm clock. + /// + /// Action: Terminates the process. + ALRM = 2, + /// Access to an undefined portion of a memory object. + /// + /// Action: Terminates the process. + BUS = 3, + /// Child process terminated, stopped, or continued. + /// + /// Action: Ignored. + CHLD = 4, + /// Continue executing, if stopped. + /// + /// Action: Continues executing, if stopped. + CONT = 5, + /// Erroneous arithmetic operation. + /// + /// Action: Terminates the process. + FPE = 6, + /// Hangup. + /// + /// Action: Terminates the process. + HUP = 7, + /// Illegal instruction. + /// + /// Action: Terminates the process. + ILL = 8, + /// Terminate interrupt signal. + /// + /// Action: Terminates the process. + INT = 9, + /// Kill. + /// + /// Action: Terminates the process. + KILL = 10, + /// Write on a pipe with no one to read it. + /// + /// Action: Ignored. + PIPE = 11, + /// Terminal quit signal. + /// + /// Action: Terminates the process. + QUIT = 12, + /// Invalid memory reference. + /// + /// Action: Terminates the process. + SEGV = 13, + /// Stop executing. + /// + /// Action: Stops executing. + STOP = 14, + /// Bad system call. + /// + /// Action: Terminates the process. + SYS = 15, + /// Termination signal. + /// + /// Action: Terminates the process. + TERM = 16, + /// Trace/breakpoint trap. + /// + /// Action: Terminates the process. + TRAP = 17, + /// Terminal stop signal. + /// + /// Action: Stops executing. + TSTP = 18, + /// Background process attempting read. + /// + /// Action: Stops executing. + TTIN = 19, + /// Background process attempting write. + /// + /// Action: Stops executing. + TTOU = 20, + /// High bandwidth data is available at a socket. + /// + /// Action: Ignored. + URG = 21, + /// User-defined signal 1. + /// + /// Action: Terminates the process. + USR1 = 22, + /// User-defined signal 2. + /// + /// Action: Terminates the process. + USR2 = 23, + /// Virtual timer expired. + /// + /// Action: Terminates the process. + VTALRM = 24, + /// CPU time limit exceeded. + /// + /// Action: Terminates the process. + XCPU = 25, + /// File size limit exceeded. + /// + /// Action: Terminates the process. + XFSZ = 26, } bitflags! { @@ -1052,12 +1052,12 @@ pub type userdata = u64; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[non_exhaustive] pub enum whence { - /// Seek relative to current position. - CUR = 1, - /// Seek relative to end-of-file. - END = 2, - /// Seek relative to start-of-file. - SET = 3, + /// Seek relative to current position. + CUR = 1, + /// Seek relative to end-of-file. + END = 2, + /// Seek relative to start-of-file. + SET = 3, } /// Auxiliary vector entry. @@ -1073,631 +1073,629 @@ pub enum whence { #[repr(C)] #[derive(Copy, Clone)] pub struct auxv { - /// The type of the auxiliary vector entry. - pub a_type: auxtype, - pub union: auxv_union + /// The type of the auxiliary vector entry. + pub a_type: auxtype, + pub union: auxv_union, } /// A union inside `auxv`. #[repr(C)] #[derive(Copy, Clone)] pub union auxv_union { - /// Used when `a_type` is [`ARGDATALEN`](enum.auxtype.html#variant.ARGDATALEN), [`CANARYLEN`](enum.auxtype.html#variant.CANARYLEN), [`NCPUS`](enum.auxtype.html#variant.NCPUS), [`PAGESZ`](enum.auxtype.html#variant.PAGESZ), [`PHNUM`](enum.auxtype.html#variant.PHNUM), or [`TID`](enum.auxtype.html#variant.TID). -/// A numerical value. - pub a_val: usize, - /// Used when `a_type` is [`ARGDATA`](enum.auxtype.html#variant.ARGDATA), [`BASE`](enum.auxtype.html#variant.BASE), [`CANARY`](enum.auxtype.html#variant.CANARY), [`PHDR`](enum.auxtype.html#variant.PHDR), [`PID`](enum.auxtype.html#variant.PID), or [`SYSINFO_EHDR`](enum.auxtype.html#variant.SYSINFO_EHDR). -/// A pointer value. - pub a_ptr: *mut (), + /// Used when `a_type` is [`ARGDATALEN`](enum.auxtype.html#variant.ARGDATALEN), [`CANARYLEN`](enum.auxtype.html#variant.CANARYLEN), [`NCPUS`](enum.auxtype.html#variant.NCPUS), [`PAGESZ`](enum.auxtype.html#variant.PAGESZ), [`PHNUM`](enum.auxtype.html#variant.PHNUM), or [`TID`](enum.auxtype.html#variant.TID). + /// A numerical value. + pub a_val: usize, + /// Used when `a_type` is [`ARGDATA`](enum.auxtype.html#variant.ARGDATA), [`BASE`](enum.auxtype.html#variant.BASE), [`CANARY`](enum.auxtype.html#variant.CANARY), [`PHDR`](enum.auxtype.html#variant.PHDR), [`PID`](enum.auxtype.html#variant.PID), or [`SYSINFO_EHDR`](enum.auxtype.html#variant.SYSINFO_EHDR). + /// A pointer value. + pub a_ptr: *mut (), } #[test] #[cfg(target_pointer_width = "32")] fn auxv_layout_test_32() { - assert_eq!(core::mem::size_of::<auxv>(), 8); - assert_eq!(core::mem::align_of::<auxv>(), 4); - unsafe { - let obj: auxv = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.a_type as *const _ as usize - base, 0); - assert_eq!(&obj.union.a_val as *const _ as usize - base, 4); - assert_eq!(&obj.union.a_ptr as *const _ as usize - base, 4); - } + assert_eq!(core::mem::size_of::<auxv>(), 8); + assert_eq!(core::mem::align_of::<auxv>(), 4); + unsafe { + let obj: auxv = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.a_type as *const _ as usize - base, 0); + assert_eq!(&obj.union.a_val as *const _ as usize - base, 4); + assert_eq!(&obj.union.a_ptr as *const _ as usize - base, 4); + } } #[test] #[cfg(target_pointer_width = "64")] fn auxv_layout_test_64() { - assert_eq!(core::mem::size_of::<auxv>(), 16); - assert_eq!(core::mem::align_of::<auxv>(), 8); - unsafe { - let obj: auxv = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.a_type as *const _ as usize - base, 0); - assert_eq!(&obj.union.a_val as *const _ as usize - base, 8); - assert_eq!(&obj.union.a_ptr as *const _ as usize - base, 8); - } + assert_eq!(core::mem::size_of::<auxv>(), 16); + assert_eq!(core::mem::align_of::<auxv>(), 8); + unsafe { + let obj: auxv = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.a_type as *const _ as usize - base, 0); + assert_eq!(&obj.union.a_val as *const _ as usize - base, 8); + assert_eq!(&obj.union.a_ptr as *const _ as usize - base, 8); + } } /// A region of memory for scatter/gather writes. #[repr(C)] #[derive(Copy, Clone)] pub struct ciovec { - /// The address and length of the buffer to be written. - pub buf: (*const (), usize), + /// The address and length of the buffer to be written. + pub buf: (*const (), usize), } #[test] #[cfg(target_pointer_width = "32")] fn ciovec_layout_test_32() { - assert_eq!(core::mem::size_of::<ciovec>(), 8); - assert_eq!(core::mem::align_of::<ciovec>(), 4); - unsafe { - let obj: ciovec = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.buf.0 as *const _ as usize - base, 0); - assert_eq!(&obj.buf.1 as *const _ as usize - base, 4); - } + assert_eq!(core::mem::size_of::<ciovec>(), 8); + assert_eq!(core::mem::align_of::<ciovec>(), 4); + unsafe { + let obj: ciovec = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.buf.0 as *const _ as usize - base, 0); + assert_eq!(&obj.buf.1 as *const _ as usize - base, 4); + } } #[test] #[cfg(target_pointer_width = "64")] fn ciovec_layout_test_64() { - assert_eq!(core::mem::size_of::<ciovec>(), 16); - assert_eq!(core::mem::align_of::<ciovec>(), 8); - unsafe { - let obj: ciovec = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.buf.0 as *const _ as usize - base, 0); - assert_eq!(&obj.buf.1 as *const _ as usize - base, 8); - } + assert_eq!(core::mem::size_of::<ciovec>(), 16); + assert_eq!(core::mem::align_of::<ciovec>(), 8); + unsafe { + let obj: ciovec = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.buf.0 as *const _ as usize - base, 0); + assert_eq!(&obj.buf.1 as *const _ as usize - base, 8); + } } /// A directory entry. #[repr(C)] #[derive(Copy, Clone)] pub struct dirent { - /// The offset of the next directory entry stored in this - /// directory. - pub d_next: dircookie, - /// The serial number of the file referred to by this - /// directory entry. - pub d_ino: inode, - /// The length of the name of the directory entry. - pub d_namlen: u32, - /// The type of the file referred to by this directory - /// entry. - pub d_type: filetype, + /// The offset of the next directory entry stored in this + /// directory. + pub d_next: dircookie, + /// The serial number of the file referred to by this + /// directory entry. + pub d_ino: inode, + /// The length of the name of the directory entry. + pub d_namlen: u32, + /// The type of the file referred to by this directory + /// entry. + pub d_type: filetype, } #[test] fn dirent_layout_test() { - assert_eq!(core::mem::size_of::<dirent>(), 24); - assert_eq!(core::mem::align_of::<dirent>(), 8); - unsafe { - let obj: dirent = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.d_next as *const _ as usize - base, 0); - assert_eq!(&obj.d_ino as *const _ as usize - base, 8); - assert_eq!(&obj.d_namlen as *const _ as usize - base, 16); - assert_eq!(&obj.d_type as *const _ as usize - base, 20); - } + assert_eq!(core::mem::size_of::<dirent>(), 24); + assert_eq!(core::mem::align_of::<dirent>(), 8); + unsafe { + let obj: dirent = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.d_next as *const _ as usize - base, 0); + assert_eq!(&obj.d_ino as *const _ as usize - base, 8); + assert_eq!(&obj.d_namlen as *const _ as usize - base, 16); + assert_eq!(&obj.d_type as *const _ as usize - base, 20); + } } /// An event that occurred. #[repr(C)] #[derive(Copy, Clone)] pub struct event { - /// User-provided value that got attached to - /// [`subscription.userdata`](struct.subscription.html#structfield.userdata). - pub userdata: userdata, - /// If non-zero, an error that occurred while processing - /// the subscription request. - pub error: errno, - /// The type of the event that occurred. - pub type_: eventtype, - pub union: event_union + /// User-provided value that got attached to + /// [`subscription.userdata`](struct.subscription.html#structfield.userdata). + pub userdata: userdata, + /// If non-zero, an error that occurred while processing + /// the subscription request. + pub error: errno, + /// The type of the event that occurred. + pub type_: eventtype, + pub union: event_union, } /// A union inside `event`. #[repr(C)] #[derive(Copy, Clone)] pub union event_union { - /// Used when `type_` is [`FD_READ`](enum.eventtype.html#variant.FD_READ) or [`FD_WRITE`](enum.eventtype.html#variant.FD_WRITE). - pub fd_readwrite: event_fd_readwrite, - /// Used when `type_` is [`PROC_TERMINATE`](enum.eventtype.html#variant.PROC_TERMINATE). - pub proc_terminate: event_proc_terminate, + /// Used when `type_` is [`FD_READ`](enum.eventtype.html#variant.FD_READ) or [`FD_WRITE`](enum.eventtype.html#variant.FD_WRITE). + pub fd_readwrite: event_fd_readwrite, + /// Used when `type_` is [`PROC_TERMINATE`](enum.eventtype.html#variant.PROC_TERMINATE). + pub proc_terminate: event_proc_terminate, } #[repr(C)] #[derive(Copy, Clone)] pub struct event_fd_readwrite { - /// The number of bytes available - /// for reading or writing. - pub nbytes: filesize, - /// Obsolete. - pub unused: [u8; 4], - /// The state of the file - /// descriptor. - pub flags: eventrwflags, + /// The number of bytes available + /// for reading or writing. + pub nbytes: filesize, + /// Obsolete. + pub unused: [u8; 4], + /// The state of the file + /// descriptor. + pub flags: eventrwflags, } #[repr(C)] #[derive(Copy, Clone)] pub struct event_proc_terminate { - /// Obsolete. - pub unused: [u8; 4], - /// If zero, the process has - /// exited. - /// Otherwise, the signal - /// condition causing it to - /// terminated. - pub signal: signal, - /// If exited, the exit code of - /// the process. - pub exitcode: exitcode, + /// Obsolete. + pub unused: [u8; 4], + /// If zero, the process has + /// exited. + /// Otherwise, the signal + /// condition causing it to + /// terminated. + pub signal: signal, + /// If exited, the exit code of + /// the process. + pub exitcode: exitcode, } #[test] fn event_layout_test() { - assert_eq!(core::mem::size_of::<event>(), 32); - assert_eq!(core::mem::align_of::<event>(), 8); - unsafe { - let obj: event = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.userdata as *const _ as usize - base, 0); - assert_eq!(&obj.error as *const _ as usize - base, 8); - assert_eq!(&obj.type_ as *const _ as usize - base, 10); - assert_eq!(&obj.union.fd_readwrite.nbytes as *const _ as usize - base, 16); - assert_eq!(&obj.union.fd_readwrite.unused as *const _ as usize - base, 24); - assert_eq!(&obj.union.fd_readwrite.flags as *const _ as usize - base, 28); - assert_eq!(&obj.union.proc_terminate.unused as *const _ as usize - base, 16); - assert_eq!(&obj.union.proc_terminate.signal as *const _ as usize - base, 20); - assert_eq!(&obj.union.proc_terminate.exitcode as *const _ as usize - base, 24); - } + assert_eq!(core::mem::size_of::<event>(), 32); + assert_eq!(core::mem::align_of::<event>(), 8); + unsafe { + let obj: event = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.userdata as *const _ as usize - base, 0); + assert_eq!(&obj.error as *const _ as usize - base, 8); + assert_eq!(&obj.type_ as *const _ as usize - base, 10); + assert_eq!(&obj.union.fd_readwrite.nbytes as *const _ as usize - base, 16); + assert_eq!(&obj.union.fd_readwrite.unused as *const _ as usize - base, 24); + assert_eq!(&obj.union.fd_readwrite.flags as *const _ as usize - base, 28); + assert_eq!(&obj.union.proc_terminate.unused as *const _ as usize - base, 16); + assert_eq!(&obj.union.proc_terminate.signal as *const _ as usize - base, 20); + assert_eq!(&obj.union.proc_terminate.exitcode as *const _ as usize - base, 24); + } } /// File descriptor attributes. #[repr(C)] #[derive(Copy, Clone)] pub struct fdstat { - /// File type. - pub fs_filetype: filetype, - /// File descriptor flags. - pub fs_flags: fdflags, - /// Rights that apply to this file descriptor. - pub fs_rights_base: rights, - /// Maximum set of rights that can be installed on new - /// file descriptors that are created through this file - /// descriptor, e.g., through [`file_open()`](fn.file_open.html). - pub fs_rights_inheriting: rights, + /// File type. + pub fs_filetype: filetype, + /// File descriptor flags. + pub fs_flags: fdflags, + /// Rights that apply to this file descriptor. + pub fs_rights_base: rights, + /// Maximum set of rights that can be installed on new + /// file descriptors that are created through this file + /// descriptor, e.g., through [`file_open()`](fn.file_open.html). + pub fs_rights_inheriting: rights, } #[test] fn fdstat_layout_test() { - assert_eq!(core::mem::size_of::<fdstat>(), 24); - assert_eq!(core::mem::align_of::<fdstat>(), 8); - unsafe { - let obj: fdstat = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.fs_filetype as *const _ as usize - base, 0); - assert_eq!(&obj.fs_flags as *const _ as usize - base, 2); - assert_eq!(&obj.fs_rights_base as *const _ as usize - base, 8); - assert_eq!(&obj.fs_rights_inheriting as *const _ as usize - base, 16); - } + assert_eq!(core::mem::size_of::<fdstat>(), 24); + assert_eq!(core::mem::align_of::<fdstat>(), 8); + unsafe { + let obj: fdstat = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.fs_filetype as *const _ as usize - base, 0); + assert_eq!(&obj.fs_flags as *const _ as usize - base, 2); + assert_eq!(&obj.fs_rights_base as *const _ as usize - base, 8); + assert_eq!(&obj.fs_rights_inheriting as *const _ as usize - base, 16); + } } /// File attributes. #[repr(C)] #[derive(Copy, Clone)] pub struct filestat { - /// Device ID of device containing the file. - pub st_dev: device, - /// File serial number. - pub st_ino: inode, - /// File type. - pub st_filetype: filetype, - /// Number of hard links to the file. - pub st_nlink: linkcount, - /// For regular files, the file size in bytes. For - /// symbolic links, the length in bytes of the pathname - /// contained in the symbolic link. - pub st_size: filesize, - /// Last data access timestamp. - pub st_atim: timestamp, - /// Last data modification timestamp. - pub st_mtim: timestamp, - /// Last file status change timestamp. - pub st_ctim: timestamp, + /// Device ID of device containing the file. + pub st_dev: device, + /// File serial number. + pub st_ino: inode, + /// File type. + pub st_filetype: filetype, + /// Number of hard links to the file. + pub st_nlink: linkcount, + /// For regular files, the file size in bytes. For + /// symbolic links, the length in bytes of the pathname + /// contained in the symbolic link. + pub st_size: filesize, + /// Last data access timestamp. + pub st_atim: timestamp, + /// Last data modification timestamp. + pub st_mtim: timestamp, + /// Last file status change timestamp. + pub st_ctim: timestamp, } #[test] fn filestat_layout_test() { - assert_eq!(core::mem::size_of::<filestat>(), 56); - assert_eq!(core::mem::align_of::<filestat>(), 8); - unsafe { - let obj: filestat = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.st_dev as *const _ as usize - base, 0); - assert_eq!(&obj.st_ino as *const _ as usize - base, 8); - assert_eq!(&obj.st_filetype as *const _ as usize - base, 16); - assert_eq!(&obj.st_nlink as *const _ as usize - base, 20); - assert_eq!(&obj.st_size as *const _ as usize - base, 24); - assert_eq!(&obj.st_atim as *const _ as usize - base, 32); - assert_eq!(&obj.st_mtim as *const _ as usize - base, 40); - assert_eq!(&obj.st_ctim as *const _ as usize - base, 48); - } + assert_eq!(core::mem::size_of::<filestat>(), 56); + assert_eq!(core::mem::align_of::<filestat>(), 8); + unsafe { + let obj: filestat = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.st_dev as *const _ as usize - base, 0); + assert_eq!(&obj.st_ino as *const _ as usize - base, 8); + assert_eq!(&obj.st_filetype as *const _ as usize - base, 16); + assert_eq!(&obj.st_nlink as *const _ as usize - base, 20); + assert_eq!(&obj.st_size as *const _ as usize - base, 24); + assert_eq!(&obj.st_atim as *const _ as usize - base, 32); + assert_eq!(&obj.st_mtim as *const _ as usize - base, 40); + assert_eq!(&obj.st_ctim as *const _ as usize - base, 48); + } } /// A region of memory for scatter/gather reads. #[repr(C)] #[derive(Copy, Clone)] pub struct iovec { - /// The address and length of the buffer to be filled. - pub buf: (*mut (), usize), + /// The address and length of the buffer to be filled. + pub buf: (*mut (), usize), } #[test] #[cfg(target_pointer_width = "32")] fn iovec_layout_test_32() { - assert_eq!(core::mem::size_of::<iovec>(), 8); - assert_eq!(core::mem::align_of::<iovec>(), 4); - unsafe { - let obj: iovec = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.buf.0 as *const _ as usize - base, 0); - assert_eq!(&obj.buf.1 as *const _ as usize - base, 4); - } + assert_eq!(core::mem::size_of::<iovec>(), 8); + assert_eq!(core::mem::align_of::<iovec>(), 4); + unsafe { + let obj: iovec = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.buf.0 as *const _ as usize - base, 0); + assert_eq!(&obj.buf.1 as *const _ as usize - base, 4); + } } #[test] #[cfg(target_pointer_width = "64")] fn iovec_layout_test_64() { - assert_eq!(core::mem::size_of::<iovec>(), 16); - assert_eq!(core::mem::align_of::<iovec>(), 8); - unsafe { - let obj: iovec = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.buf.0 as *const _ as usize - base, 0); - assert_eq!(&obj.buf.1 as *const _ as usize - base, 8); - } + assert_eq!(core::mem::size_of::<iovec>(), 16); + assert_eq!(core::mem::align_of::<iovec>(), 8); + unsafe { + let obj: iovec = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.buf.0 as *const _ as usize - base, 0); + assert_eq!(&obj.buf.1 as *const _ as usize - base, 8); + } } /// Path lookup properties. #[repr(C)] #[derive(Copy, Clone)] pub struct lookup { - /// The working directory at which the resolution of the - /// path starts. - pub fd: fd, - /// Flags determining the method of how the path is - /// resolved. - pub flags: lookupflags, + /// The working directory at which the resolution of the + /// path starts. + pub fd: fd, + /// Flags determining the method of how the path is + /// resolved. + pub flags: lookupflags, } #[test] fn lookup_layout_test() { - assert_eq!(core::mem::size_of::<lookup>(), 8); - assert_eq!(core::mem::align_of::<lookup>(), 4); - unsafe { - let obj: lookup = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.fd as *const _ as usize - base, 0); - assert_eq!(&obj.flags as *const _ as usize - base, 4); - } + assert_eq!(core::mem::size_of::<lookup>(), 8); + assert_eq!(core::mem::align_of::<lookup>(), 4); + unsafe { + let obj: lookup = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.fd as *const _ as usize - base, 0); + assert_eq!(&obj.flags as *const _ as usize - base, 4); + } } /// Entry point for a process (`_start`). /// /// **auxv**: /// The auxiliary vector. See [`auxv`](struct.auxv.html). -pub type processentry = unsafe extern "C" fn( - auxv: *const auxv, -) -> (); +pub type processentry = unsafe extern "C" fn(auxv: *const auxv) -> (); /// Arguments of [`sock_recv()`](fn.sock_recv.html). #[repr(C)] #[derive(Copy, Clone)] pub struct recv_in { - /// List of scatter/gather vectors where message data - /// should be stored. - pub ri_data: (*const iovec, usize), - /// Buffer where numbers of incoming file descriptors - /// should be stored. - pub ri_fds: (*mut fd, usize), - /// Message flags. - pub ri_flags: riflags, + /// List of scatter/gather vectors where message data + /// should be stored. + pub ri_data: (*const iovec, usize), + /// Buffer where numbers of incoming file descriptors + /// should be stored. + pub ri_fds: (*mut fd, usize), + /// Message flags. + pub ri_flags: riflags, } #[test] #[cfg(target_pointer_width = "32")] fn recv_in_layout_test_32() { - assert_eq!(core::mem::size_of::<recv_in>(), 20); - assert_eq!(core::mem::align_of::<recv_in>(), 4); - unsafe { - let obj: recv_in = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.ri_data.0 as *const _ as usize - base, 0); - assert_eq!(&obj.ri_data.1 as *const _ as usize - base, 4); - assert_eq!(&obj.ri_fds.0 as *const _ as usize - base, 8); - assert_eq!(&obj.ri_fds.1 as *const _ as usize - base, 12); - assert_eq!(&obj.ri_flags as *const _ as usize - base, 16); - } + assert_eq!(core::mem::size_of::<recv_in>(), 20); + assert_eq!(core::mem::align_of::<recv_in>(), 4); + unsafe { + let obj: recv_in = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.ri_data.0 as *const _ as usize - base, 0); + assert_eq!(&obj.ri_data.1 as *const _ as usize - base, 4); + assert_eq!(&obj.ri_fds.0 as *const _ as usize - base, 8); + assert_eq!(&obj.ri_fds.1 as *const _ as usize - base, 12); + assert_eq!(&obj.ri_flags as *const _ as usize - base, 16); + } } #[test] #[cfg(target_pointer_width = "64")] fn recv_in_layout_test_64() { - assert_eq!(core::mem::size_of::<recv_in>(), 40); - assert_eq!(core::mem::align_of::<recv_in>(), 8); - unsafe { - let obj: recv_in = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.ri_data.0 as *const _ as usize - base, 0); - assert_eq!(&obj.ri_data.1 as *const _ as usize - base, 8); - assert_eq!(&obj.ri_fds.0 as *const _ as usize - base, 16); - assert_eq!(&obj.ri_fds.1 as *const _ as usize - base, 24); - assert_eq!(&obj.ri_flags as *const _ as usize - base, 32); - } + assert_eq!(core::mem::size_of::<recv_in>(), 40); + assert_eq!(core::mem::align_of::<recv_in>(), 8); + unsafe { + let obj: recv_in = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.ri_data.0 as *const _ as usize - base, 0); + assert_eq!(&obj.ri_data.1 as *const _ as usize - base, 8); + assert_eq!(&obj.ri_fds.0 as *const _ as usize - base, 16); + assert_eq!(&obj.ri_fds.1 as *const _ as usize - base, 24); + assert_eq!(&obj.ri_flags as *const _ as usize - base, 32); + } } /// Results of [`sock_recv()`](fn.sock_recv.html). #[repr(C)] #[derive(Copy, Clone)] pub struct recv_out { - /// Number of bytes stored in [`recv_in.ri_data`](struct.recv_in.html#structfield.ri_data). - pub ro_datalen: usize, - /// Number of file descriptors stored in [`recv_in.ri_fds`](struct.recv_in.html#structfield.ri_fds). - pub ro_fdslen: usize, - /// Fields that were used by previous implementations. - pub ro_unused: [u8; 40], - /// Message flags. - pub ro_flags: roflags, + /// Number of bytes stored in [`recv_in.ri_data`](struct.recv_in.html#structfield.ri_data). + pub ro_datalen: usize, + /// Number of file descriptors stored in [`recv_in.ri_fds`](struct.recv_in.html#structfield.ri_fds). + pub ro_fdslen: usize, + /// Fields that were used by previous implementations. + pub ro_unused: [u8; 40], + /// Message flags. + pub ro_flags: roflags, } #[test] #[cfg(target_pointer_width = "32")] fn recv_out_layout_test_32() { - assert_eq!(core::mem::size_of::<recv_out>(), 52); - assert_eq!(core::mem::align_of::<recv_out>(), 4); - unsafe { - let obj: recv_out = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.ro_datalen as *const _ as usize - base, 0); - assert_eq!(&obj.ro_fdslen as *const _ as usize - base, 4); - assert_eq!(&obj.ro_unused as *const _ as usize - base, 8); - assert_eq!(&obj.ro_flags as *const _ as usize - base, 48); - } + assert_eq!(core::mem::size_of::<recv_out>(), 52); + assert_eq!(core::mem::align_of::<recv_out>(), 4); + unsafe { + let obj: recv_out = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.ro_datalen as *const _ as usize - base, 0); + assert_eq!(&obj.ro_fdslen as *const _ as usize - base, 4); + assert_eq!(&obj.ro_unused as *const _ as usize - base, 8); + assert_eq!(&obj.ro_flags as *const _ as usize - base, 48); + } } #[test] #[cfg(target_pointer_width = "64")] fn recv_out_layout_test_64() { - assert_eq!(core::mem::size_of::<recv_out>(), 64); - assert_eq!(core::mem::align_of::<recv_out>(), 8); - unsafe { - let obj: recv_out = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.ro_datalen as *const _ as usize - base, 0); - assert_eq!(&obj.ro_fdslen as *const _ as usize - base, 8); - assert_eq!(&obj.ro_unused as *const _ as usize - base, 16); - assert_eq!(&obj.ro_flags as *const _ as usize - base, 56); - } + assert_eq!(core::mem::size_of::<recv_out>(), 64); + assert_eq!(core::mem::align_of::<recv_out>(), 8); + unsafe { + let obj: recv_out = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.ro_datalen as *const _ as usize - base, 0); + assert_eq!(&obj.ro_fdslen as *const _ as usize - base, 8); + assert_eq!(&obj.ro_unused as *const _ as usize - base, 16); + assert_eq!(&obj.ro_flags as *const _ as usize - base, 56); + } } /// Arguments of [`sock_send()`](fn.sock_send.html). #[repr(C)] #[derive(Copy, Clone)] pub struct send_in { - /// List of scatter/gather vectors where message data - /// should be retrieved. - pub si_data: (*const ciovec, usize), - /// File descriptors that need to be attached to the - /// message. - pub si_fds: (*const fd, usize), - /// Message flags. - pub si_flags: siflags, + /// List of scatter/gather vectors where message data + /// should be retrieved. + pub si_data: (*const ciovec, usize), + /// File descriptors that need to be attached to the + /// message. + pub si_fds: (*const fd, usize), + /// Message flags. + pub si_flags: siflags, } #[test] #[cfg(target_pointer_width = "32")] fn send_in_layout_test_32() { - assert_eq!(core::mem::size_of::<send_in>(), 20); - assert_eq!(core::mem::align_of::<send_in>(), 4); - unsafe { - let obj: send_in = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.si_data.0 as *const _ as usize - base, 0); - assert_eq!(&obj.si_data.1 as *const _ as usize - base, 4); - assert_eq!(&obj.si_fds.0 as *const _ as usize - base, 8); - assert_eq!(&obj.si_fds.1 as *const _ as usize - base, 12); - assert_eq!(&obj.si_flags as *const _ as usize - base, 16); - } + assert_eq!(core::mem::size_of::<send_in>(), 20); + assert_eq!(core::mem::align_of::<send_in>(), 4); + unsafe { + let obj: send_in = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.si_data.0 as *const _ as usize - base, 0); + assert_eq!(&obj.si_data.1 as *const _ as usize - base, 4); + assert_eq!(&obj.si_fds.0 as *const _ as usize - base, 8); + assert_eq!(&obj.si_fds.1 as *const _ as usize - base, 12); + assert_eq!(&obj.si_flags as *const _ as usize - base, 16); + } } #[test] #[cfg(target_pointer_width = "64")] fn send_in_layout_test_64() { - assert_eq!(core::mem::size_of::<send_in>(), 40); - assert_eq!(core::mem::align_of::<send_in>(), 8); - unsafe { - let obj: send_in = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.si_data.0 as *const _ as usize - base, 0); - assert_eq!(&obj.si_data.1 as *const _ as usize - base, 8); - assert_eq!(&obj.si_fds.0 as *const _ as usize - base, 16); - assert_eq!(&obj.si_fds.1 as *const _ as usize - base, 24); - assert_eq!(&obj.si_flags as *const _ as usize - base, 32); - } + assert_eq!(core::mem::size_of::<send_in>(), 40); + assert_eq!(core::mem::align_of::<send_in>(), 8); + unsafe { + let obj: send_in = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.si_data.0 as *const _ as usize - base, 0); + assert_eq!(&obj.si_data.1 as *const _ as usize - base, 8); + assert_eq!(&obj.si_fds.0 as *const _ as usize - base, 16); + assert_eq!(&obj.si_fds.1 as *const _ as usize - base, 24); + assert_eq!(&obj.si_flags as *const _ as usize - base, 32); + } } /// Results of [`sock_send()`](fn.sock_send.html). #[repr(C)] #[derive(Copy, Clone)] pub struct send_out { - /// Number of bytes transmitted. - pub so_datalen: usize, + /// Number of bytes transmitted. + pub so_datalen: usize, } #[test] #[cfg(target_pointer_width = "32")] fn send_out_layout_test_32() { - assert_eq!(core::mem::size_of::<send_out>(), 4); - assert_eq!(core::mem::align_of::<send_out>(), 4); - unsafe { - let obj: send_out = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.so_datalen as *const _ as usize - base, 0); - } + assert_eq!(core::mem::size_of::<send_out>(), 4); + assert_eq!(core::mem::align_of::<send_out>(), 4); + unsafe { + let obj: send_out = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.so_datalen as *const _ as usize - base, 0); + } } #[test] #[cfg(target_pointer_width = "64")] fn send_out_layout_test_64() { - assert_eq!(core::mem::size_of::<send_out>(), 8); - assert_eq!(core::mem::align_of::<send_out>(), 8); - unsafe { - let obj: send_out = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.so_datalen as *const _ as usize - base, 0); - } + assert_eq!(core::mem::size_of::<send_out>(), 8); + assert_eq!(core::mem::align_of::<send_out>(), 8); + unsafe { + let obj: send_out = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.so_datalen as *const _ as usize - base, 0); + } } /// Subscription to an event. #[repr(C)] #[derive(Copy, Clone)] pub struct subscription { - /// User-provided value that is attached to the - /// subscription in the kernel and returned through - /// [`event.userdata`](struct.event.html#structfield.userdata). - pub userdata: userdata, - /// Used by previous implementations. Ignored. - pub unused: u16, - /// The type of the event to which to subscribe. - /// - /// Currently, [`CONDVAR`](enum.eventtype.html#variant.CONDVAR), - /// [`LOCK_RDLOCK`](enum.eventtype.html#variant.LOCK_RDLOCK), and [`LOCK_WRLOCK`](enum.eventtype.html#variant.LOCK_WRLOCK) - /// must be provided as the first subscription and may - /// only be followed by up to one other subscription, - /// having type [`CLOCK`](enum.eventtype.html#variant.CLOCK). - pub type_: eventtype, - pub union: subscription_union + /// User-provided value that is attached to the + /// subscription in the kernel and returned through + /// [`event.userdata`](struct.event.html#structfield.userdata). + pub userdata: userdata, + /// Used by previous implementations. Ignored. + pub unused: u16, + /// The type of the event to which to subscribe. + /// + /// Currently, [`CONDVAR`](enum.eventtype.html#variant.CONDVAR), + /// [`LOCK_RDLOCK`](enum.eventtype.html#variant.LOCK_RDLOCK), and [`LOCK_WRLOCK`](enum.eventtype.html#variant.LOCK_WRLOCK) + /// must be provided as the first subscription and may + /// only be followed by up to one other subscription, + /// having type [`CLOCK`](enum.eventtype.html#variant.CLOCK). + pub type_: eventtype, + pub union: subscription_union, } /// A union inside `subscription`. #[repr(C)] #[derive(Copy, Clone)] pub union subscription_union { - /// Used when `type_` is [`CLOCK`](enum.eventtype.html#variant.CLOCK). - pub clock: subscription_clock, - /// Used when `type_` is [`CONDVAR`](enum.eventtype.html#variant.CONDVAR). - pub condvar: subscription_condvar, - /// Used when `type_` is [`FD_READ`](enum.eventtype.html#variant.FD_READ) or [`FD_WRITE`](enum.eventtype.html#variant.FD_WRITE). - pub fd_readwrite: subscription_fd_readwrite, - /// Used when `type_` is [`LOCK_RDLOCK`](enum.eventtype.html#variant.LOCK_RDLOCK) or [`LOCK_WRLOCK`](enum.eventtype.html#variant.LOCK_WRLOCK). - pub lock: subscription_lock, - /// Used when `type_` is [`PROC_TERMINATE`](enum.eventtype.html#variant.PROC_TERMINATE). - pub proc_terminate: subscription_proc_terminate, + /// Used when `type_` is [`CLOCK`](enum.eventtype.html#variant.CLOCK). + pub clock: subscription_clock, + /// Used when `type_` is [`CONDVAR`](enum.eventtype.html#variant.CONDVAR). + pub condvar: subscription_condvar, + /// Used when `type_` is [`FD_READ`](enum.eventtype.html#variant.FD_READ) or [`FD_WRITE`](enum.eventtype.html#variant.FD_WRITE). + pub fd_readwrite: subscription_fd_readwrite, + /// Used when `type_` is [`LOCK_RDLOCK`](enum.eventtype.html#variant.LOCK_RDLOCK) or [`LOCK_WRLOCK`](enum.eventtype.html#variant.LOCK_WRLOCK). + pub lock: subscription_lock, + /// Used when `type_` is [`PROC_TERMINATE`](enum.eventtype.html#variant.PROC_TERMINATE). + pub proc_terminate: subscription_proc_terminate, } #[repr(C)] #[derive(Copy, Clone)] pub struct subscription_clock { - /// The user-defined unique - /// identifier of the clock. - pub identifier: userdata, - /// The clock against which the - /// timestamp should be compared. - pub clock_id: clockid, - /// The absolute or relative - /// timestamp. - pub timeout: timestamp, - /// The amount of time that the - /// kernel may wait additionally - /// to coalesce with other events. - pub precision: timestamp, - /// Flags specifying whether the - /// timeout is absolute or - /// relative. - pub flags: subclockflags, + /// The user-defined unique + /// identifier of the clock. + pub identifier: userdata, + /// The clock against which the + /// timestamp should be compared. + pub clock_id: clockid, + /// The absolute or relative + /// timestamp. + pub timeout: timestamp, + /// The amount of time that the + /// kernel may wait additionally + /// to coalesce with other events. + pub precision: timestamp, + /// Flags specifying whether the + /// timeout is absolute or + /// relative. + pub flags: subclockflags, } #[repr(C)] #[derive(Copy, Clone)] pub struct subscription_condvar { - /// The condition variable on - /// which to wait to be woken up. - pub condvar: *mut condvar, - /// The lock that will be - /// released while waiting. - /// - /// The lock will be reacquired - /// for writing when the condition - /// variable triggers. - pub lock: *mut lock, - /// Whether the condition variable - /// is stored in private or shared - /// memory. - pub condvar_scope: scope, - /// Whether the lock is stored in - /// private or shared memory. - pub lock_scope: scope, + /// The condition variable on + /// which to wait to be woken up. + pub condvar: *mut condvar, + /// The lock that will be + /// released while waiting. + /// + /// The lock will be reacquired + /// for writing when the condition + /// variable triggers. + pub lock: *mut lock, + /// Whether the condition variable + /// is stored in private or shared + /// memory. + pub condvar_scope: scope, + /// Whether the lock is stored in + /// private or shared memory. + pub lock_scope: scope, } #[repr(C)] #[derive(Copy, Clone)] pub struct subscription_fd_readwrite { - /// The file descriptor on which - /// to wait for it to become ready - /// for reading or writing. - pub fd: fd, - /// Under which conditions to - /// trigger. - pub flags: subrwflags, + /// The file descriptor on which + /// to wait for it to become ready + /// for reading or writing. + pub fd: fd, + /// Under which conditions to + /// trigger. + pub flags: subrwflags, } #[repr(C)] #[derive(Copy, Clone)] pub struct subscription_lock { - /// The lock that will be acquired - /// for reading or writing. - pub lock: *mut lock, - /// Whether the lock is stored in - /// private or shared memory. - pub lock_scope: scope, + /// The lock that will be acquired + /// for reading or writing. + pub lock: *mut lock, + /// Whether the lock is stored in + /// private or shared memory. + pub lock_scope: scope, } #[repr(C)] #[derive(Copy, Clone)] pub struct subscription_proc_terminate { - /// The process descriptor on - /// which to wait for process - /// termination. - pub fd: fd, + /// The process descriptor on + /// which to wait for process + /// termination. + pub fd: fd, } #[test] #[cfg(target_pointer_width = "32")] fn subscription_layout_test_32() { - assert_eq!(core::mem::size_of::<subscription>(), 56); - assert_eq!(core::mem::align_of::<subscription>(), 8); - unsafe { - let obj: subscription = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.userdata as *const _ as usize - base, 0); - assert_eq!(&obj.unused as *const _ as usize - base, 8); - assert_eq!(&obj.type_ as *const _ as usize - base, 10); - assert_eq!(&obj.union.clock.identifier as *const _ as usize - base, 16); - assert_eq!(&obj.union.clock.clock_id as *const _ as usize - base, 24); - assert_eq!(&obj.union.clock.timeout as *const _ as usize - base, 32); - assert_eq!(&obj.union.clock.precision as *const _ as usize - base, 40); - assert_eq!(&obj.union.clock.flags as *const _ as usize - base, 48); - assert_eq!(&obj.union.condvar.condvar as *const _ as usize - base, 16); - assert_eq!(&obj.union.condvar.lock as *const _ as usize - base, 20); - assert_eq!(&obj.union.condvar.condvar_scope as *const _ as usize - base, 24); - assert_eq!(&obj.union.condvar.lock_scope as *const _ as usize - base, 25); - assert_eq!(&obj.union.fd_readwrite.fd as *const _ as usize - base, 16); - assert_eq!(&obj.union.fd_readwrite.flags as *const _ as usize - base, 20); - assert_eq!(&obj.union.lock.lock as *const _ as usize - base, 16); - assert_eq!(&obj.union.lock.lock_scope as *const _ as usize - base, 20); - assert_eq!(&obj.union.proc_terminate.fd as *const _ as usize - base, 16); - } + assert_eq!(core::mem::size_of::<subscription>(), 56); + assert_eq!(core::mem::align_of::<subscription>(), 8); + unsafe { + let obj: subscription = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.userdata as *const _ as usize - base, 0); + assert_eq!(&obj.unused as *const _ as usize - base, 8); + assert_eq!(&obj.type_ as *const _ as usize - base, 10); + assert_eq!(&obj.union.clock.identifier as *const _ as usize - base, 16); + assert_eq!(&obj.union.clock.clock_id as *const _ as usize - base, 24); + assert_eq!(&obj.union.clock.timeout as *const _ as usize - base, 32); + assert_eq!(&obj.union.clock.precision as *const _ as usize - base, 40); + assert_eq!(&obj.union.clock.flags as *const _ as usize - base, 48); + assert_eq!(&obj.union.condvar.condvar as *const _ as usize - base, 16); + assert_eq!(&obj.union.condvar.lock as *const _ as usize - base, 20); + assert_eq!(&obj.union.condvar.condvar_scope as *const _ as usize - base, 24); + assert_eq!(&obj.union.condvar.lock_scope as *const _ as usize - base, 25); + assert_eq!(&obj.union.fd_readwrite.fd as *const _ as usize - base, 16); + assert_eq!(&obj.union.fd_readwrite.flags as *const _ as usize - base, 20); + assert_eq!(&obj.union.lock.lock as *const _ as usize - base, 16); + assert_eq!(&obj.union.lock.lock_scope as *const _ as usize - base, 20); + assert_eq!(&obj.union.proc_terminate.fd as *const _ as usize - base, 16); + } } #[test] #[cfg(target_pointer_width = "64")] fn subscription_layout_test_64() { - assert_eq!(core::mem::size_of::<subscription>(), 56); - assert_eq!(core::mem::align_of::<subscription>(), 8); - unsafe { - let obj: subscription = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.userdata as *const _ as usize - base, 0); - assert_eq!(&obj.unused as *const _ as usize - base, 8); - assert_eq!(&obj.type_ as *const _ as usize - base, 10); - assert_eq!(&obj.union.clock.identifier as *const _ as usize - base, 16); - assert_eq!(&obj.union.clock.clock_id as *const _ as usize - base, 24); - assert_eq!(&obj.union.clock.timeout as *const _ as usize - base, 32); - assert_eq!(&obj.union.clock.precision as *const _ as usize - base, 40); - assert_eq!(&obj.union.clock.flags as *const _ as usize - base, 48); - assert_eq!(&obj.union.condvar.condvar as *const _ as usize - base, 16); - assert_eq!(&obj.union.condvar.lock as *const _ as usize - base, 24); - assert_eq!(&obj.union.condvar.condvar_scope as *const _ as usize - base, 32); - assert_eq!(&obj.union.condvar.lock_scope as *const _ as usize - base, 33); - assert_eq!(&obj.union.fd_readwrite.fd as *const _ as usize - base, 16); - assert_eq!(&obj.union.fd_readwrite.flags as *const _ as usize - base, 20); - assert_eq!(&obj.union.lock.lock as *const _ as usize - base, 16); - assert_eq!(&obj.union.lock.lock_scope as *const _ as usize - base, 24); - assert_eq!(&obj.union.proc_terminate.fd as *const _ as usize - base, 16); - } + assert_eq!(core::mem::size_of::<subscription>(), 56); + assert_eq!(core::mem::align_of::<subscription>(), 8); + unsafe { + let obj: subscription = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.userdata as *const _ as usize - base, 0); + assert_eq!(&obj.unused as *const _ as usize - base, 8); + assert_eq!(&obj.type_ as *const _ as usize - base, 10); + assert_eq!(&obj.union.clock.identifier as *const _ as usize - base, 16); + assert_eq!(&obj.union.clock.clock_id as *const _ as usize - base, 24); + assert_eq!(&obj.union.clock.timeout as *const _ as usize - base, 32); + assert_eq!(&obj.union.clock.precision as *const _ as usize - base, 40); + assert_eq!(&obj.union.clock.flags as *const _ as usize - base, 48); + assert_eq!(&obj.union.condvar.condvar as *const _ as usize - base, 16); + assert_eq!(&obj.union.condvar.lock as *const _ as usize - base, 24); + assert_eq!(&obj.union.condvar.condvar_scope as *const _ as usize - base, 32); + assert_eq!(&obj.union.condvar.lock_scope as *const _ as usize - base, 33); + assert_eq!(&obj.union.fd_readwrite.fd as *const _ as usize - base, 16); + assert_eq!(&obj.union.fd_readwrite.flags as *const _ as usize - base, 20); + assert_eq!(&obj.union.lock.lock as *const _ as usize - base, 16); + assert_eq!(&obj.union.lock.lock_scope as *const _ as usize - base, 24); + assert_eq!(&obj.union.proc_terminate.fd as *const _ as usize - base, 16); + } } /// The Thread Control Block (TCB). @@ -1722,31 +1720,31 @@ fn subscription_layout_test_64() { #[repr(C)] #[derive(Copy, Clone)] pub struct tcb { - /// Pointer that may be freely assigned by the system. Its - /// value cannot be interpreted by the application. - pub parent: *mut (), + /// Pointer that may be freely assigned by the system. Its + /// value cannot be interpreted by the application. + pub parent: *mut (), } #[test] #[cfg(target_pointer_width = "32")] fn tcb_layout_test_32() { - assert_eq!(core::mem::size_of::<tcb>(), 4); - assert_eq!(core::mem::align_of::<tcb>(), 4); - unsafe { - let obj: tcb = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.parent as *const _ as usize - base, 0); - } + assert_eq!(core::mem::size_of::<tcb>(), 4); + assert_eq!(core::mem::align_of::<tcb>(), 4); + unsafe { + let obj: tcb = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.parent as *const _ as usize - base, 0); + } } #[test] #[cfg(target_pointer_width = "64")] fn tcb_layout_test_64() { - assert_eq!(core::mem::size_of::<tcb>(), 8); - assert_eq!(core::mem::align_of::<tcb>(), 8); - unsafe { - let obj: tcb = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.parent as *const _ as usize - base, 0); - } + assert_eq!(core::mem::size_of::<tcb>(), 8); + assert_eq!(core::mem::align_of::<tcb>(), 8); + unsafe { + let obj: tcb = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.parent as *const _ as usize - base, 0); + } } /// Entry point for additionally created threads. @@ -1755,103 +1753,150 @@ fn tcb_layout_test_64() { /// /// `aux`: copy of the value stored in /// [`threadattr.argument`](struct.threadattr.html#structfield.argument). -pub type threadentry = unsafe extern "C" fn( - tid: tid, - aux: *mut (), -) -> (); +pub type threadentry = unsafe extern "C" fn(tid: tid, aux: *mut ()) -> (); /// Attributes for thread creation. #[repr(C)] #[derive(Copy, Clone)] pub struct threadattr { - /// Initial program counter value. - pub entry_point: threadentry, - /// Region allocated to serve as stack space. - pub stack: (*mut (), usize), - /// Argument to be forwarded to the entry point function. - pub argument: *mut (), + /// Initial program counter value. + pub entry_point: threadentry, + /// Region allocated to serve as stack space. + pub stack: (*mut (), usize), + /// Argument to be forwarded to the entry point function. + pub argument: *mut (), } #[test] #[cfg(target_pointer_width = "32")] fn threadattr_layout_test_32() { - assert_eq!(core::mem::size_of::<threadattr>(), 16); - assert_eq!(core::mem::align_of::<threadattr>(), 4); - unsafe { - let obj: threadattr = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.entry_point as *const _ as usize - base, 0); - assert_eq!(&obj.stack.0 as *const _ as usize - base, 4); - assert_eq!(&obj.stack.1 as *const _ as usize - base, 8); - assert_eq!(&obj.argument as *const _ as usize - base, 12); - } + assert_eq!(core::mem::size_of::<threadattr>(), 16); + assert_eq!(core::mem::align_of::<threadattr>(), 4); + unsafe { + let obj: threadattr = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.entry_point as *const _ as usize - base, 0); + assert_eq!(&obj.stack.0 as *const _ as usize - base, 4); + assert_eq!(&obj.stack.1 as *const _ as usize - base, 8); + assert_eq!(&obj.argument as *const _ as usize - base, 12); + } } #[test] #[cfg(target_pointer_width = "64")] fn threadattr_layout_test_64() { - assert_eq!(core::mem::size_of::<threadattr>(), 32); - assert_eq!(core::mem::align_of::<threadattr>(), 8); - unsafe { - let obj: threadattr = core::mem::uninitialized(); - let base = &obj as *const _ as usize; - assert_eq!(&obj.entry_point as *const _ as usize - base, 0); - assert_eq!(&obj.stack.0 as *const _ as usize - base, 8); - assert_eq!(&obj.stack.1 as *const _ as usize - base, 16); - assert_eq!(&obj.argument as *const _ as usize - base, 24); - } + assert_eq!(core::mem::size_of::<threadattr>(), 32); + assert_eq!(core::mem::align_of::<threadattr>(), 8); + unsafe { + let obj: threadattr = core::mem::uninitialized(); + let base = &obj as *const _ as usize; + assert_eq!(&obj.entry_point as *const _ as usize - base, 0); + assert_eq!(&obj.stack.0 as *const _ as usize - base, 8); + assert_eq!(&obj.stack.1 as *const _ as usize - base, 16); + assert_eq!(&obj.argument as *const _ as usize - base, 24); + } } /// The table with pointers to all syscall implementations. #[allow(improper_ctypes)] extern "C" { - fn cloudabi_sys_clock_res_get(_: clockid, _: *mut timestamp) -> errno; - fn cloudabi_sys_clock_time_get(_: clockid, _: timestamp, _: *mut timestamp) -> errno; - fn cloudabi_sys_condvar_signal(_: *mut condvar, _: scope, _: nthreads) -> errno; - fn cloudabi_sys_fd_close(_: fd) -> errno; - fn cloudabi_sys_fd_create1(_: filetype, _: *mut fd) -> errno; - fn cloudabi_sys_fd_create2(_: filetype, _: *mut fd, _: *mut fd) -> errno; - fn cloudabi_sys_fd_datasync(_: fd) -> errno; - fn cloudabi_sys_fd_dup(_: fd, _: *mut fd) -> errno; - fn cloudabi_sys_fd_pread(_: fd, _: *const iovec, _: usize, _: filesize, _: *mut usize) -> errno; - fn cloudabi_sys_fd_pwrite(_: fd, _: *const ciovec, _: usize, _: filesize, _: *mut usize) -> errno; - fn cloudabi_sys_fd_read(_: fd, _: *const iovec, _: usize, _: *mut usize) -> errno; - fn cloudabi_sys_fd_replace(_: fd, _: fd) -> errno; - fn cloudabi_sys_fd_seek(_: fd, _: filedelta, _: whence, _: *mut filesize) -> errno; - fn cloudabi_sys_fd_stat_get(_: fd, _: *mut fdstat) -> errno; - fn cloudabi_sys_fd_stat_put(_: fd, _: *const fdstat, _: fdsflags) -> errno; - fn cloudabi_sys_fd_sync(_: fd) -> errno; - fn cloudabi_sys_fd_write(_: fd, _: *const ciovec, _: usize, _: *mut usize) -> errno; - fn cloudabi_sys_file_advise(_: fd, _: filesize, _: filesize, _: advice) -> errno; - fn cloudabi_sys_file_allocate(_: fd, _: filesize, _: filesize) -> errno; - fn cloudabi_sys_file_create(_: fd, _: *const u8, _: usize, _: filetype) -> errno; - fn cloudabi_sys_file_link(_: lookup, _: *const u8, _: usize, _: fd, _: *const u8, _: usize) -> errno; - fn cloudabi_sys_file_open(_: lookup, _: *const u8, _: usize, _: oflags, _: *const fdstat, _: *mut fd) -> errno; - fn cloudabi_sys_file_readdir(_: fd, _: *mut (), _: usize, _: dircookie, _: *mut usize) -> errno; - fn cloudabi_sys_file_readlink(_: fd, _: *const u8, _: usize, _: *mut u8, _: usize, _: *mut usize) -> errno; - fn cloudabi_sys_file_rename(_: fd, _: *const u8, _: usize, _: fd, _: *const u8, _: usize) -> errno; - fn cloudabi_sys_file_stat_fget(_: fd, _: *mut filestat) -> errno; - fn cloudabi_sys_file_stat_fput(_: fd, _: *const filestat, _: fsflags) -> errno; - fn cloudabi_sys_file_stat_get(_: lookup, _: *const u8, _: usize, _: *mut filestat) -> errno; - fn cloudabi_sys_file_stat_put(_: lookup, _: *const u8, _: usize, _: *const filestat, _: fsflags) -> errno; - fn cloudabi_sys_file_symlink(_: *const u8, _: usize, _: fd, _: *const u8, _: usize) -> errno; - fn cloudabi_sys_file_unlink(_: fd, _: *const u8, _: usize, _: ulflags) -> errno; - fn cloudabi_sys_lock_unlock(_: *mut lock, _: scope) -> errno; - fn cloudabi_sys_mem_advise(_: *mut (), _: usize, _: advice) -> errno; - fn cloudabi_sys_mem_map(_: *mut (), _: usize, _: mprot, _: mflags, _: fd, _: filesize, _: *mut *mut ()) -> errno; - fn cloudabi_sys_mem_protect(_: *mut (), _: usize, _: mprot) -> errno; - fn cloudabi_sys_mem_sync(_: *mut (), _: usize, _: msflags) -> errno; - fn cloudabi_sys_mem_unmap(_: *mut (), _: usize) -> errno; - fn cloudabi_sys_poll(_: *const subscription, _: *mut event, _: usize, _: *mut usize) -> errno; - fn cloudabi_sys_proc_exec(_: fd, _: *const (), _: usize, _: *const fd, _: usize) -> errno; - fn cloudabi_sys_proc_exit(_: exitcode) -> !; - fn cloudabi_sys_proc_fork(_: *mut fd, _: *mut tid) -> errno; - fn cloudabi_sys_proc_raise(_: signal) -> errno; - fn cloudabi_sys_random_get(_: *mut (), _: usize) -> errno; - fn cloudabi_sys_sock_recv(_: fd, _: *const recv_in, _: *mut recv_out) -> errno; - fn cloudabi_sys_sock_send(_: fd, _: *const send_in, _: *mut send_out) -> errno; - fn cloudabi_sys_sock_shutdown(_: fd, _: sdflags) -> errno; - fn cloudabi_sys_thread_create(_: *mut threadattr, _: *mut tid) -> errno; - fn cloudabi_sys_thread_exit(_: *mut lock, _: scope) -> !; - fn cloudabi_sys_thread_yield() -> errno; + fn cloudabi_sys_clock_res_get(_: clockid, _: *mut timestamp) -> errno; + fn cloudabi_sys_clock_time_get(_: clockid, _: timestamp, _: *mut timestamp) -> errno; + fn cloudabi_sys_condvar_signal(_: *mut condvar, _: scope, _: nthreads) -> errno; + fn cloudabi_sys_fd_close(_: fd) -> errno; + fn cloudabi_sys_fd_create1(_: filetype, _: *mut fd) -> errno; + fn cloudabi_sys_fd_create2(_: filetype, _: *mut fd, _: *mut fd) -> errno; + fn cloudabi_sys_fd_datasync(_: fd) -> errno; + fn cloudabi_sys_fd_dup(_: fd, _: *mut fd) -> errno; + fn cloudabi_sys_fd_pread(_: fd, _: *const iovec, _: usize, _: filesize, _: *mut usize) + -> errno; + fn cloudabi_sys_fd_pwrite( + _: fd, + _: *const ciovec, + _: usize, + _: filesize, + _: *mut usize, + ) -> errno; + fn cloudabi_sys_fd_read(_: fd, _: *const iovec, _: usize, _: *mut usize) -> errno; + fn cloudabi_sys_fd_replace(_: fd, _: fd) -> errno; + fn cloudabi_sys_fd_seek(_: fd, _: filedelta, _: whence, _: *mut filesize) -> errno; + fn cloudabi_sys_fd_stat_get(_: fd, _: *mut fdstat) -> errno; + fn cloudabi_sys_fd_stat_put(_: fd, _: *const fdstat, _: fdsflags) -> errno; + fn cloudabi_sys_fd_sync(_: fd) -> errno; + fn cloudabi_sys_fd_write(_: fd, _: *const ciovec, _: usize, _: *mut usize) -> errno; + fn cloudabi_sys_file_advise(_: fd, _: filesize, _: filesize, _: advice) -> errno; + fn cloudabi_sys_file_allocate(_: fd, _: filesize, _: filesize) -> errno; + fn cloudabi_sys_file_create(_: fd, _: *const u8, _: usize, _: filetype) -> errno; + fn cloudabi_sys_file_link( + _: lookup, + _: *const u8, + _: usize, + _: fd, + _: *const u8, + _: usize, + ) -> errno; + fn cloudabi_sys_file_open( + _: lookup, + _: *const u8, + _: usize, + _: oflags, + _: *const fdstat, + _: *mut fd, + ) -> errno; + fn cloudabi_sys_file_readdir(_: fd, _: *mut (), _: usize, _: dircookie, _: *mut usize) + -> errno; + fn cloudabi_sys_file_readlink( + _: fd, + _: *const u8, + _: usize, + _: *mut u8, + _: usize, + _: *mut usize, + ) -> errno; + fn cloudabi_sys_file_rename( + _: fd, + _: *const u8, + _: usize, + _: fd, + _: *const u8, + _: usize, + ) -> errno; + fn cloudabi_sys_file_stat_fget(_: fd, _: *mut filestat) -> errno; + fn cloudabi_sys_file_stat_fput(_: fd, _: *const filestat, _: fsflags) -> errno; + fn cloudabi_sys_file_stat_get(_: lookup, _: *const u8, _: usize, _: *mut filestat) -> errno; + fn cloudabi_sys_file_stat_put( + _: lookup, + _: *const u8, + _: usize, + _: *const filestat, + _: fsflags, + ) -> errno; + fn cloudabi_sys_file_symlink(_: *const u8, _: usize, _: fd, _: *const u8, _: usize) -> errno; + fn cloudabi_sys_file_unlink(_: fd, _: *const u8, _: usize, _: ulflags) -> errno; + fn cloudabi_sys_lock_unlock(_: *mut lock, _: scope) -> errno; + fn cloudabi_sys_mem_advise(_: *mut (), _: usize, _: advice) -> errno; + fn cloudabi_sys_mem_map( + _: *mut (), + _: usize, + _: mprot, + _: mflags, + _: fd, + _: filesize, + _: *mut *mut (), + ) -> errno; + fn cloudabi_sys_mem_protect(_: *mut (), _: usize, _: mprot) -> errno; + fn cloudabi_sys_mem_sync(_: *mut (), _: usize, _: msflags) -> errno; + fn cloudabi_sys_mem_unmap(_: *mut (), _: usize) -> errno; + fn cloudabi_sys_poll(_: *const subscription, _: *mut event, _: usize, _: *mut usize) -> errno; + fn cloudabi_sys_proc_exec(_: fd, _: *const (), _: usize, _: *const fd, _: usize) -> errno; + fn cloudabi_sys_proc_exit(_: exitcode) -> !; + fn cloudabi_sys_proc_fork(_: *mut fd, _: *mut tid) -> errno; + fn cloudabi_sys_proc_raise(_: signal) -> errno; + fn cloudabi_sys_random_get(_: *mut (), _: usize) -> errno; + fn cloudabi_sys_sock_recv(_: fd, _: *const recv_in, _: *mut recv_out) -> errno; + fn cloudabi_sys_sock_send(_: fd, _: *const send_in, _: *mut send_out) -> errno; + fn cloudabi_sys_sock_shutdown(_: fd, _: sdflags) -> errno; + fn cloudabi_sys_thread_create(_: *mut threadattr, _: *mut tid) -> errno; + fn cloudabi_sys_thread_exit(_: *mut lock, _: scope) -> !; + fn cloudabi_sys_thread_yield() -> errno; } /// Obtains the resolution of a clock. @@ -1866,7 +1911,7 @@ extern "C" { /// The resolution of the clock. #[inline] pub unsafe fn clock_res_get(clock_id_: clockid, resolution_: &mut timestamp) -> errno { - cloudabi_sys_clock_res_get(clock_id_, resolution_) + cloudabi_sys_clock_res_get(clock_id_, resolution_) } /// Obtains the time value of a clock. @@ -1885,8 +1930,12 @@ pub unsafe fn clock_res_get(clock_id_: clockid, resolution_: &mut timestamp) -> /// **time**: /// The time value of the clock. #[inline] -pub unsafe fn clock_time_get(clock_id_: clockid, precision_: timestamp, time_: *mut timestamp) -> errno { - cloudabi_sys_clock_time_get(clock_id_, precision_, time_) +pub unsafe fn clock_time_get( + clock_id_: clockid, + precision_: timestamp, + time_: *mut timestamp, +) -> errno { + cloudabi_sys_clock_time_get(clock_id_, precision_, time_) } /// Wakes up threads waiting on a userspace condition variable. @@ -1913,7 +1962,7 @@ pub unsafe fn clock_time_get(clock_id_: clockid, precision_: timestamp, time_: * /// threads, all threads are woken up. #[inline] pub unsafe fn condvar_signal(condvar_: *mut condvar, scope_: scope, nwaiters_: nthreads) -> errno { - cloudabi_sys_condvar_signal(condvar_, scope_, nwaiters_) + cloudabi_sys_condvar_signal(condvar_, scope_, nwaiters_) } /// Closes a file descriptor. @@ -1924,7 +1973,7 @@ pub unsafe fn condvar_signal(condvar_: *mut condvar, scope_: scope, nwaiters_: n /// The file descriptor that needs to be closed. #[inline] pub unsafe fn fd_close(fd_: fd) -> errno { - cloudabi_sys_fd_close(fd_) + cloudabi_sys_fd_close(fd_) } /// Creates a file descriptor. @@ -1942,7 +1991,7 @@ pub unsafe fn fd_close(fd_: fd) -> errno { /// The file descriptor that has been created. #[inline] pub unsafe fn fd_create1(type_: filetype, fd_: &mut fd) -> errno { - cloudabi_sys_fd_create1(type_, fd_) + cloudabi_sys_fd_create1(type_, fd_) } /// Creates a pair of file descriptors. @@ -1965,7 +2014,7 @@ pub unsafe fn fd_create1(type_: filetype, fd_: &mut fd) -> errno { /// The second file descriptor of the pair. #[inline] pub unsafe fn fd_create2(type_: filetype, fd1_: &mut fd, fd2_: &mut fd) -> errno { - cloudabi_sys_fd_create2(type_, fd1_, fd2_) + cloudabi_sys_fd_create2(type_, fd1_, fd2_) } /// Synchronizes the data of a file to disk. @@ -1977,7 +2026,7 @@ pub unsafe fn fd_create2(type_: filetype, fd1_: &mut fd, fd2_: &mut fd) -> errno /// needs to be synchronized to disk. #[inline] pub unsafe fn fd_datasync(fd_: fd) -> errno { - cloudabi_sys_fd_datasync(fd_) + cloudabi_sys_fd_datasync(fd_) } /// Duplicates a file descriptor. @@ -1992,7 +2041,7 @@ pub unsafe fn fd_datasync(fd_: fd) -> errno { /// The new file descriptor. #[inline] pub unsafe fn fd_dup(from_: fd, fd_: &mut fd) -> errno { - cloudabi_sys_fd_dup(from_, fd_) + cloudabi_sys_fd_dup(from_, fd_) } /// Reads from a file descriptor, without using and updating the @@ -2016,7 +2065,7 @@ pub unsafe fn fd_dup(from_: fd, fd_: &mut fd) -> errno { /// The number of bytes read. #[inline] pub unsafe fn fd_pread(fd_: fd, iovs_: &[iovec], offset_: filesize, nread_: &mut usize) -> errno { - cloudabi_sys_fd_pread(fd_, iovs_.as_ptr(), iovs_.len(), offset_, nread_) + cloudabi_sys_fd_pread(fd_, iovs_.as_ptr(), iovs_.len(), offset_, nread_) } /// Writes to a file descriptor, without using and updating the @@ -2039,8 +2088,13 @@ pub unsafe fn fd_pread(fd_: fd, iovs_: &[iovec], offset_: filesize, nread_: &mut /// **nwritten**: /// The number of bytes written. #[inline] -pub unsafe fn fd_pwrite(fd_: fd, iovs_: &[ciovec], offset_: filesize, nwritten_: &mut usize) -> errno { - cloudabi_sys_fd_pwrite(fd_, iovs_.as_ptr(), iovs_.len(), offset_, nwritten_) +pub unsafe fn fd_pwrite( + fd_: fd, + iovs_: &[ciovec], + offset_: filesize, + nwritten_: &mut usize, +) -> errno { + cloudabi_sys_fd_pwrite(fd_, iovs_.as_ptr(), iovs_.len(), offset_, nwritten_) } /// Reads from a file descriptor. @@ -2059,7 +2113,7 @@ pub unsafe fn fd_pwrite(fd_: fd, iovs_: &[ciovec], offset_: filesize, nwritten_: /// The number of bytes read. #[inline] pub unsafe fn fd_read(fd_: fd, iovs_: &[iovec], nread_: &mut usize) -> errno { - cloudabi_sys_fd_read(fd_, iovs_.as_ptr(), iovs_.len(), nread_) + cloudabi_sys_fd_read(fd_, iovs_.as_ptr(), iovs_.len(), nread_) } /// Atomically replaces a file descriptor by a copy of another @@ -2085,7 +2139,7 @@ pub unsafe fn fd_read(fd_: fd, iovs_: &[iovec], nread_: &mut usize) -> errno { /// overwritten. #[inline] pub unsafe fn fd_replace(from_: fd, to_: fd) -> errno { - cloudabi_sys_fd_replace(from_, to_) + cloudabi_sys_fd_replace(from_, to_) } /// Moves the offset of the file descriptor. @@ -2107,8 +2161,13 @@ pub unsafe fn fd_replace(from_: fd, to_: fd) -> errno { /// The new offset of the file descriptor, /// relative to the start of the file. #[inline] -pub unsafe fn fd_seek(fd_: fd, offset_: filedelta, whence_: whence, newoffset_: &mut filesize) -> errno { - cloudabi_sys_fd_seek(fd_, offset_, whence_, newoffset_) +pub unsafe fn fd_seek( + fd_: fd, + offset_: filedelta, + whence_: whence, + newoffset_: &mut filesize, +) -> errno { + cloudabi_sys_fd_seek(fd_, offset_, whence_, newoffset_) } /// Gets attributes of a file descriptor. @@ -2124,7 +2183,7 @@ pub unsafe fn fd_seek(fd_: fd, offset_: filedelta, whence_: whence, newoffset_: /// attributes are stored. #[inline] pub unsafe fn fd_stat_get(fd_: fd, buf_: *mut fdstat) -> errno { - cloudabi_sys_fd_stat_get(fd_, buf_) + cloudabi_sys_fd_stat_get(fd_, buf_) } /// Adjusts attributes of a file descriptor. @@ -2144,7 +2203,7 @@ pub unsafe fn fd_stat_get(fd_: fd, buf_: *mut fdstat) -> errno { /// be adjusted. #[inline] pub unsafe fn fd_stat_put(fd_: fd, buf_: *const fdstat, flags_: fdsflags) -> errno { - cloudabi_sys_fd_stat_put(fd_, buf_, flags_) + cloudabi_sys_fd_stat_put(fd_, buf_, flags_) } /// Synchronizes the data and metadata of a file to disk. @@ -2156,7 +2215,7 @@ pub unsafe fn fd_stat_put(fd_: fd, buf_: *const fdstat, flags_: fdsflags) -> err /// and metadata needs to be synchronized to disk. #[inline] pub unsafe fn fd_sync(fd_: fd) -> errno { - cloudabi_sys_fd_sync(fd_) + cloudabi_sys_fd_sync(fd_) } /// Writes to a file descriptor. @@ -2175,7 +2234,7 @@ pub unsafe fn fd_sync(fd_: fd) -> errno { /// The number of bytes written. #[inline] pub unsafe fn fd_write(fd_: fd, iovs_: &[ciovec], nwritten_: &mut usize) -> errno { - cloudabi_sys_fd_write(fd_, iovs_.as_ptr(), iovs_.len(), nwritten_) + cloudabi_sys_fd_write(fd_, iovs_.as_ptr(), iovs_.len(), nwritten_) } /// Provides file advisory information on a file descriptor. @@ -2198,7 +2257,7 @@ pub unsafe fn fd_write(fd_: fd, iovs_: &[ciovec], nwritten_: &mut usize) -> errn /// The advice. #[inline] pub unsafe fn file_advise(fd_: fd, offset_: filesize, len_: filesize, advice_: advice) -> errno { - cloudabi_sys_file_advise(fd_, offset_, len_, advice_) + cloudabi_sys_file_advise(fd_, offset_, len_, advice_) } /// Forces the allocation of space in a file. @@ -2217,7 +2276,7 @@ pub unsafe fn file_advise(fd_: fd, offset_: filesize, len_: filesize, advice_: a /// The length of the area that is allocated. #[inline] pub unsafe fn file_allocate(fd_: fd, offset_: filesize, len_: filesize) -> errno { - cloudabi_sys_file_allocate(fd_, offset_, len_) + cloudabi_sys_file_allocate(fd_, offset_, len_) } /// Creates a file of a specified type. @@ -2238,7 +2297,7 @@ pub unsafe fn file_allocate(fd_: fd, offset_: filesize, len_: filesize) -> errno /// Creates a directory. #[inline] pub unsafe fn file_create(fd_: fd, path_: &[u8], type_: filetype) -> errno { - cloudabi_sys_file_create(fd_, path_.as_ptr(), path_.len(), type_) + cloudabi_sys_file_create(fd_, path_.as_ptr(), path_.len(), type_) } /// Creates a hard link. @@ -2262,7 +2321,7 @@ pub unsafe fn file_create(fd_: fd, path_: &[u8], type_: filetype) -> errno { /// should be created. #[inline] pub unsafe fn file_link(fd1_: lookup, path1_: &[u8], fd2_: fd, path2_: &[u8]) -> errno { - cloudabi_sys_file_link(fd1_, path1_.as_ptr(), path1_.len(), fd2_, path2_.as_ptr(), path2_.len()) + cloudabi_sys_file_link(fd1_, path1_.as_ptr(), path1_.len(), fd2_, path2_.as_ptr(), path2_.len()) } /// Opens a file. @@ -2297,8 +2356,14 @@ pub unsafe fn file_link(fd1_: lookup, path1_: &[u8], fd2_: fd, path2_: &[u8]) -> /// The file descriptor of the file that has been /// opened. #[inline] -pub unsafe fn file_open(dirfd_: lookup, path_: &[u8], oflags_: oflags, fds_: *const fdstat, fd_: &mut fd) -> errno { - cloudabi_sys_file_open(dirfd_, path_.as_ptr(), path_.len(), oflags_, fds_, fd_) +pub unsafe fn file_open( + dirfd_: lookup, + path_: &[u8], + oflags_: oflags, + fds_: *const fdstat, + fd_: &mut fd, +) -> errno { + cloudabi_sys_file_open(dirfd_, path_.as_ptr(), path_.len(), oflags_, fds_, fd_) } /// Reads directory entries from a directory. @@ -2332,8 +2397,13 @@ pub unsafe fn file_open(dirfd_: lookup, path_: &[u8], oflags_: oflags, fds_: *co /// If less than the size of the read buffer, the /// end of the directory has been reached. #[inline] -pub unsafe fn file_readdir(fd_: fd, buf_: &mut [u8], cookie_: dircookie, bufused_: &mut usize) -> errno { - cloudabi_sys_file_readdir(fd_, buf_.as_mut_ptr() as *mut (), buf_.len(), cookie_, bufused_) +pub unsafe fn file_readdir( + fd_: fd, + buf_: &mut [u8], + cookie_: dircookie, + bufused_: &mut usize, +) -> errno { + cloudabi_sys_file_readdir(fd_, buf_.as_mut_ptr() as *mut (), buf_.len(), cookie_, bufused_) } /// Reads the contents of a symbolic link. @@ -2356,7 +2426,14 @@ pub unsafe fn file_readdir(fd_: fd, buf_: &mut [u8], cookie_: dircookie, bufused /// The number of bytes placed in the buffer. #[inline] pub unsafe fn file_readlink(fd_: fd, path_: &[u8], buf_: &mut [u8], bufused_: &mut usize) -> errno { - cloudabi_sys_file_readlink(fd_, path_.as_ptr(), path_.len(), buf_.as_mut_ptr(), buf_.len(), bufused_) + cloudabi_sys_file_readlink( + fd_, + path_.as_ptr(), + path_.len(), + buf_.as_mut_ptr(), + buf_.len(), + bufused_, + ) } /// Renames a file. @@ -2380,7 +2457,14 @@ pub unsafe fn file_readlink(fd_: fd, path_: &[u8], buf_: &mut [u8], bufused_: &m /// be renamed. #[inline] pub unsafe fn file_rename(fd1_: fd, path1_: &[u8], fd2_: fd, path2_: &[u8]) -> errno { - cloudabi_sys_file_rename(fd1_, path1_.as_ptr(), path1_.len(), fd2_, path2_.as_ptr(), path2_.len()) + cloudabi_sys_file_rename( + fd1_, + path1_.as_ptr(), + path1_.len(), + fd2_, + path2_.as_ptr(), + path2_.len(), + ) } /// Gets attributes of a file by file descriptor. @@ -2396,7 +2480,7 @@ pub unsafe fn file_rename(fd1_: fd, path1_: &[u8], fd2_: fd, path2_: &[u8]) -> e /// stored. #[inline] pub unsafe fn file_stat_fget(fd_: fd, buf_: *mut filestat) -> errno { - cloudabi_sys_file_stat_fget(fd_, buf_) + cloudabi_sys_file_stat_fget(fd_, buf_) } /// Adjusts attributes of a file by file descriptor. @@ -2416,7 +2500,7 @@ pub unsafe fn file_stat_fget(fd_: fd, buf_: *mut filestat) -> errno { /// be adjusted. #[inline] pub unsafe fn file_stat_fput(fd_: fd, buf_: *const filestat, flags_: fsflags) -> errno { - cloudabi_sys_file_stat_fput(fd_, buf_, flags_) + cloudabi_sys_file_stat_fput(fd_, buf_, flags_) } /// Gets attributes of a file by path. @@ -2437,7 +2521,7 @@ pub unsafe fn file_stat_fput(fd_: fd, buf_: *const filestat, flags_: fsflags) -> /// stored. #[inline] pub unsafe fn file_stat_get(fd_: lookup, path_: &[u8], buf_: *mut filestat) -> errno { - cloudabi_sys_file_stat_get(fd_, path_.as_ptr(), path_.len(), buf_) + cloudabi_sys_file_stat_get(fd_, path_.as_ptr(), path_.len(), buf_) } /// Adjusts attributes of a file by path. @@ -2461,8 +2545,13 @@ pub unsafe fn file_stat_get(fd_: lookup, path_: &[u8], buf_: *mut filestat) -> e /// A bitmask indicating which attributes have to /// be adjusted. #[inline] -pub unsafe fn file_stat_put(fd_: lookup, path_: &[u8], buf_: *const filestat, flags_: fsflags) -> errno { - cloudabi_sys_file_stat_put(fd_, path_.as_ptr(), path_.len(), buf_, flags_) +pub unsafe fn file_stat_put( + fd_: lookup, + path_: &[u8], + buf_: *const filestat, + flags_: fsflags, +) -> errno { + cloudabi_sys_file_stat_put(fd_, path_.as_ptr(), path_.len(), buf_, flags_) } /// Creates a symbolic link. @@ -2481,7 +2570,7 @@ pub unsafe fn file_stat_put(fd_: lookup, path_: &[u8], buf_: *const filestat, fl /// link should be created. #[inline] pub unsafe fn file_symlink(path1_: &[u8], fd_: fd, path2_: &[u8]) -> errno { - cloudabi_sys_file_symlink(path1_.as_ptr(), path1_.len(), fd_, path2_.as_ptr(), path2_.len()) + cloudabi_sys_file_symlink(path1_.as_ptr(), path1_.len(), fd_, path2_.as_ptr(), path2_.len()) } /// Unlinks a file, or removes a directory. @@ -2503,7 +2592,7 @@ pub unsafe fn file_symlink(path1_: &[u8], fd_: fd, path2_: &[u8]) -> errno { /// Otherwise, unlink a file. #[inline] pub unsafe fn file_unlink(fd_: fd, path_: &[u8], flags_: ulflags) -> errno { - cloudabi_sys_file_unlink(fd_, path_.as_ptr(), path_.len(), flags_) + cloudabi_sys_file_unlink(fd_, path_.as_ptr(), path_.len(), flags_) } /// Unlocks a write-locked userspace lock. @@ -2530,7 +2619,7 @@ pub unsafe fn file_unlink(fd_: fd, path_: &[u8], flags_: ulflags) -> errno { /// shared memory. #[inline] pub unsafe fn lock_unlock(lock_: *mut lock, scope_: scope) -> errno { - cloudabi_sys_lock_unlock(lock_, scope_) + cloudabi_sys_lock_unlock(lock_, scope_) } /// Provides memory advisory information on a region of memory. @@ -2545,7 +2634,7 @@ pub unsafe fn lock_unlock(lock_: *mut lock, scope_: scope) -> errno { /// The advice. #[inline] pub unsafe fn mem_advise(mapping_: &mut [u8], advice_: advice) -> errno { - cloudabi_sys_mem_advise(mapping_.as_mut_ptr() as *mut (), mapping_.len(), advice_) + cloudabi_sys_mem_advise(mapping_.as_mut_ptr() as *mut (), mapping_.len(), advice_) } /// Creates a memory mapping, making the contents of a file @@ -2585,8 +2674,16 @@ pub unsafe fn mem_advise(mapping_: &mut [u8], advice_: advice) -> errno { /// **mem**: /// The starting address of the memory mapping. #[inline] -pub unsafe fn mem_map(addr_: *mut (), len_: usize, prot_: mprot, flags_: mflags, fd_: fd, off_: filesize, mem_: &mut *mut ()) -> errno { - cloudabi_sys_mem_map(addr_, len_, prot_, flags_, fd_, off_, mem_) +pub unsafe fn mem_map( + addr_: *mut (), + len_: usize, + prot_: mprot, + flags_: mflags, + fd_: fd, + off_: filesize, + mem_: &mut *mut (), +) -> errno { + cloudabi_sys_mem_map(addr_, len_, prot_, flags_, fd_, off_, mem_) } /// Changes the protection of a memory mapping. @@ -2600,7 +2697,7 @@ pub unsafe fn mem_map(addr_: *mut (), len_: usize, prot_: mprot, flags_: mflags, /// New protection options. #[inline] pub unsafe fn mem_protect(mapping_: &mut [u8], prot_: mprot) -> errno { - cloudabi_sys_mem_protect(mapping_.as_mut_ptr() as *mut (), mapping_.len(), prot_) + cloudabi_sys_mem_protect(mapping_.as_mut_ptr() as *mut (), mapping_.len(), prot_) } /// Synchronizes a region of memory with its physical storage. @@ -2614,7 +2711,7 @@ pub unsafe fn mem_protect(mapping_: &mut [u8], prot_: mprot) -> errno { /// The method of synchronization. #[inline] pub unsafe fn mem_sync(mapping_: &mut [u8], flags_: msflags) -> errno { - cloudabi_sys_mem_sync(mapping_.as_mut_ptr() as *mut (), mapping_.len(), flags_) + cloudabi_sys_mem_sync(mapping_.as_mut_ptr() as *mut (), mapping_.len(), flags_) } /// Unmaps a region of memory. @@ -2625,7 +2722,7 @@ pub unsafe fn mem_sync(mapping_: &mut [u8], flags_: msflags) -> errno { /// The pages that needs to be unmapped. #[inline] pub unsafe fn mem_unmap(mapping_: &mut [u8]) -> errno { - cloudabi_sys_mem_unmap(mapping_.as_mut_ptr() as *mut (), mapping_.len()) + cloudabi_sys_mem_unmap(mapping_.as_mut_ptr() as *mut (), mapping_.len()) } /// Concurrently polls for the occurrence of a set of events. @@ -2644,8 +2741,13 @@ pub unsafe fn mem_unmap(mapping_: &mut [u8]) -> errno { /// **nevents**: /// The number of events stored. #[inline] -pub unsafe fn poll(in_: *const subscription, out_: *mut event, nsubscriptions_: usize, nevents_: *mut usize) -> errno { - cloudabi_sys_poll(in_, out_, nsubscriptions_, nevents_) +pub unsafe fn poll( + in_: *const subscription, + out_: *mut event, + nsubscriptions_: usize, + nevents_: *mut usize, +) -> errno { + cloudabi_sys_poll(in_, out_, nsubscriptions_, nevents_) } /// Replaces the process by a new executable. @@ -2683,7 +2785,7 @@ pub unsafe fn poll(in_: *const subscription, out_: *mut event, nsubscriptions_: /// execution. #[inline] pub unsafe fn proc_exec(fd_: fd, data_: &[u8], fds_: &[fd]) -> errno { - cloudabi_sys_proc_exec(fd_, data_.as_ptr() as *const (), data_.len(), fds_.as_ptr(), fds_.len()) + cloudabi_sys_proc_exec(fd_, data_.as_ptr() as *const (), data_.len(), fds_.as_ptr(), fds_.len()) } /// Terminates the process normally. @@ -2696,7 +2798,7 @@ pub unsafe fn proc_exec(fd_: fd, data_: &[u8], fds_: &[fd]) -> errno { /// through [`event.union.proc_terminate.exitcode`](struct.event_proc_terminate.html#structfield.exitcode). #[inline] pub unsafe fn proc_exit(rval_: exitcode) -> ! { - cloudabi_sys_proc_exit(rval_) + cloudabi_sys_proc_exit(rval_) } /// Forks the process of the calling thread. @@ -2721,7 +2823,7 @@ pub unsafe fn proc_exit(rval_: exitcode) -> ! { /// initial thread of the child process. #[inline] pub unsafe fn proc_fork(fd_: &mut fd, tid_: &mut tid) -> errno { - cloudabi_sys_proc_fork(fd_, tid_) + cloudabi_sys_proc_fork(fd_, tid_) } /// Sends a signal to the process of the calling thread. @@ -2736,7 +2838,7 @@ pub unsafe fn proc_fork(fd_: &mut fd, tid_: &mut tid) -> errno { /// [`event.union.proc_terminate.signal`](struct.event_proc_terminate.html#structfield.signal). #[inline] pub unsafe fn proc_raise(sig_: signal) -> errno { - cloudabi_sys_proc_raise(sig_) + cloudabi_sys_proc_raise(sig_) } /// Obtains random data from the kernel random number generator. @@ -2752,7 +2854,7 @@ pub unsafe fn proc_raise(sig_: signal) -> errno { /// data. #[inline] pub unsafe fn random_get(buf_: &mut [u8]) -> errno { - cloudabi_sys_random_get(buf_.as_mut_ptr() as *mut (), buf_.len()) + cloudabi_sys_random_get(buf_.as_mut_ptr() as *mut (), buf_.len()) } /// Receives a message on a socket. @@ -2770,7 +2872,7 @@ pub unsafe fn random_get(buf_: &mut [u8]) -> errno { /// Output parameters. #[inline] pub unsafe fn sock_recv(sock_: fd, in_: *const recv_in, out_: *mut recv_out) -> errno { - cloudabi_sys_sock_recv(sock_, in_, out_) + cloudabi_sys_sock_recv(sock_, in_, out_) } /// Sends a message on a socket. @@ -2787,7 +2889,7 @@ pub unsafe fn sock_recv(sock_: fd, in_: *const recv_in, out_: *mut recv_out) -> /// Output parameters. #[inline] pub unsafe fn sock_send(sock_: fd, in_: *const send_in, out_: *mut send_out) -> errno { - cloudabi_sys_sock_send(sock_, in_, out_) + cloudabi_sys_sock_send(sock_, in_, out_) } /// Shuts down socket send and receive channels. @@ -2802,7 +2904,7 @@ pub unsafe fn sock_send(sock_: fd, in_: *const send_in, out_: *mut send_out) -> /// down. #[inline] pub unsafe fn sock_shutdown(sock_: fd, how_: sdflags) -> errno { - cloudabi_sys_sock_shutdown(sock_, how_) + cloudabi_sys_sock_shutdown(sock_, how_) } /// Creates a new thread within the current process. @@ -2816,7 +2918,7 @@ pub unsafe fn sock_shutdown(sock_: fd, how_: sdflags) -> errno { /// The thread ID of the new thread. #[inline] pub unsafe fn thread_create(attr_: *mut threadattr, tid_: &mut tid) -> errno { - cloudabi_sys_thread_create(attr_, tid_) + cloudabi_sys_thread_create(attr_, tid_) } /// Terminates the calling thread. @@ -2836,11 +2938,11 @@ pub unsafe fn thread_create(attr_: *mut threadattr, tid_: &mut tid) -> errno { /// shared memory. #[inline] pub unsafe fn thread_exit(lock_: *mut lock, scope_: scope) -> ! { - cloudabi_sys_thread_exit(lock_, scope_) + cloudabi_sys_thread_exit(lock_, scope_) } /// Temporarily yields execution of the calling thread. #[inline] pub unsafe fn thread_yield() -> errno { - cloudabi_sys_thread_yield() + cloudabi_sys_thread_yield() } diff --git a/src/libstd/sys/cloudabi/condvar.rs b/src/libstd/sys/cloudabi/condvar.rs index ec1fca7805a..3ba51d77494 100644 --- a/src/libstd/sys/cloudabi/condvar.rs +++ b/src/libstd/sys/cloudabi/condvar.rs @@ -18,9 +18,8 @@ pub struct Condvar { unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} -const NEW: Condvar = Condvar { - condvar: UnsafeCell::new(AtomicU32::new(abi::CONDVAR_HAS_NO_WAITERS.0)), -}; +const NEW: Condvar = + Condvar { condvar: UnsafeCell::new(AtomicU32::new(abi::CONDVAR_HAS_NO_WAITERS.0)) }; impl Condvar { pub const fn new() -> Condvar { @@ -33,11 +32,7 @@ impl Condvar { let condvar = self.condvar.get(); if (*condvar).load(Ordering::Relaxed) != abi::CONDVAR_HAS_NO_WAITERS.0 { let ret = abi::condvar_signal(condvar as *mut abi::condvar, abi::scope::PRIVATE, 1); - assert_eq!( - ret, - abi::errno::SUCCESS, - "Failed to signal on condition variable" - ); + assert_eq!(ret, abi::errno::SUCCESS, "Failed to signal on condition variable"); } } @@ -49,11 +44,7 @@ impl Condvar { abi::scope::PRIVATE, abi::nthreads::max_value(), ); - assert_eq!( - ret, - abi::errno::SUCCESS, - "Failed to broadcast on condition variable" - ); + assert_eq!(ret, abi::errno::SUCCESS, "Failed to broadcast on condition variable"); } } @@ -81,17 +72,8 @@ impl Condvar { }; let mut event: mem::MaybeUninit<abi::event> = mem::MaybeUninit::uninit(); let mut nevents: mem::MaybeUninit<usize> = mem::MaybeUninit::uninit(); - let ret = abi::poll( - &subscription, - event.as_mut_ptr(), - 1, - nevents.as_mut_ptr() - ); - assert_eq!( - ret, - abi::errno::SUCCESS, - "Failed to wait on condition variable" - ); + let ret = abi::poll(&subscription, event.as_mut_ptr(), 1, nevents.as_mut_ptr()); + assert_eq!(ret, abi::errno::SUCCESS, "Failed to wait on condition variable"); assert_eq!( event.assume_init().error, abi::errno::SUCCESS, @@ -109,8 +91,8 @@ impl Condvar { // Call into the kernel to wait on the condition variable. let condvar = self.condvar.get(); - let timeout = checked_dur2intervals(&dur) - .expect("overflow converting duration to nanoseconds"); + let timeout = + checked_dur2intervals(&dur).expect("overflow converting duration to nanoseconds"); let subscriptions = [ abi::subscription { type_: abi::eventtype::CONDVAR, @@ -142,13 +124,9 @@ impl Condvar { subscriptions.as_ptr(), mem::MaybeUninit::first_ptr_mut(&mut events), 2, - nevents.as_mut_ptr() - ); - assert_eq!( - ret, - abi::errno::SUCCESS, - "Failed to wait on condition variable" + nevents.as_mut_ptr(), ); + assert_eq!(ret, abi::errno::SUCCESS, "Failed to wait on condition variable"); let nevents = nevents.assume_init(); for i in 0..nevents { assert_eq!( diff --git a/src/libstd/sys/cloudabi/mod.rs b/src/libstd/sys/cloudabi/mod.rs index 2fb10cc370a..e5f1dd98435 100644 --- a/src/libstd/sys/cloudabi/mod.rs +++ b/src/libstd/sys/cloudabi/mod.rs @@ -60,10 +60,7 @@ pub use libc::strlen; pub fn hashmap_random_keys() -> (u64, u64) { unsafe { let mut v: mem::MaybeUninit<(u64, u64)> = mem::MaybeUninit::uninit(); - libc::arc4random_buf( - v.as_mut_ptr() as *mut libc::c_void, - mem::size_of_val(&v) - ); + libc::arc4random_buf(v.as_mut_ptr() as *mut libc::c_void, mem::size_of_val(&v)); v.assume_init() } } diff --git a/src/libstd/sys/cloudabi/mutex.rs b/src/libstd/sys/cloudabi/mutex.rs index 0e30d3a1c6c..4aa25e25052 100644 --- a/src/libstd/sys/cloudabi/mutex.rs +++ b/src/libstd/sys/cloudabi/mutex.rs @@ -56,7 +56,7 @@ impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { ReentrantMutex { lock: UnsafeCell::new(MaybeUninit::uninit()), - recursion: UnsafeCell::new(MaybeUninit::uninit()) + recursion: UnsafeCell::new(MaybeUninit::uninit()), } } diff --git a/src/libstd/sys/cloudabi/rwlock.rs b/src/libstd/sys/cloudabi/rwlock.rs index 73499d65a06..b8af5af1d70 100644 --- a/src/libstd/sys/cloudabi/rwlock.rs +++ b/src/libstd/sys/cloudabi/rwlock.rs @@ -23,9 +23,7 @@ pub unsafe fn raw(r: &RWLock) -> *mut AtomicU32 { unsafe impl Send for RWLock {} unsafe impl Sync for RWLock {} -const NEW: RWLock = RWLock { - lock: UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)), -}; +const NEW: RWLock = RWLock { lock: UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)) }; impl RWLock { pub const fn new() -> RWLock { @@ -79,11 +77,7 @@ impl RWLock { let ret = abi::poll(&subscription, event.as_mut_ptr(), 1, nevents.as_mut_ptr()); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire read lock"); let event = event.assume_init(); - assert_eq!( - event.error, - abi::errno::SUCCESS, - "Failed to acquire read lock" - ); + assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire read lock"); RDLOCKS_ACQUIRED += 1; } @@ -122,11 +116,7 @@ impl RWLock { } else { // No threads waiting or not the last read lock. Just decrement // the read lock count. - assert_ne!( - old & !abi::LOCK_KERNEL_MANAGED.0, - 0, - "This rwlock is not locked" - ); + assert_ne!(old & !abi::LOCK_KERNEL_MANAGED.0, 0, "This rwlock is not locked"); assert_eq!( old & abi::LOCK_WRLOCKED.0, 0, @@ -189,11 +179,7 @@ impl RWLock { let ret = abi::poll(&subscription, event.as_mut_ptr(), 1, nevents.as_mut_ptr()); assert_eq!(ret, abi::errno::SUCCESS, "Failed to acquire write lock"); let event = event.assume_init(); - assert_eq!( - event.error, - abi::errno::SUCCESS, - "Failed to acquire write lock" - ); + assert_eq!(event.error, abi::errno::SUCCESS, "Failed to acquire write lock"); } } diff --git a/src/libstd/sys/sgx/condvar.rs b/src/libstd/sys/sgx/condvar.rs index cc1c04a83e7..9c5c086184d 100644 --- a/src/libstd/sys/sgx/condvar.rs +++ b/src/libstd/sys/sgx/condvar.rs @@ -1,7 +1,7 @@ use crate::sys::mutex::Mutex; use crate::time::Duration; -use super::waitqueue::{WaitVariable, WaitQueue, SpinMutex}; +use super::waitqueue::{SpinMutex, WaitQueue, WaitVariable}; pub struct Condvar { inner: SpinMutex<WaitVariable<()>>, diff --git a/src/libstd/sys/sgx/mod.rs b/src/libstd/sys/sgx/mod.rs index 601957acd5c..83cee0cf35a 100644 --- a/src/libstd/sys/sgx/mod.rs +++ b/src/libstd/sys/sgx/mod.rs @@ -28,16 +28,15 @@ pub mod pipe; pub mod process; pub mod rwlock; pub mod stack_overflow; +pub mod stdio; pub mod thread; pub mod thread_local; pub mod time; -pub mod stdio; pub use crate::sys_common::os_str_bytes as os_str; #[cfg(not(test))] -pub fn init() { -} +pub fn init() {} /// This function is used to implement functionality that simply doesn't exist. /// Programs relying on this functionality will need to deal with the error. @@ -46,8 +45,7 @@ pub fn unsupported<T>() -> crate::io::Result<T> { } pub fn unsupported_err() -> crate::io::Error { - crate::io::Error::new(ErrorKind::Other, - "operation not supported on SGX yet") + crate::io::Error::new(ErrorKind::Other, "operation not supported on SGX yet") } /// This function is used to implement various functions that doesn't exist, @@ -58,8 +56,10 @@ pub fn unsupported_err() -> crate::io::Error { pub fn sgx_ineffective<T>(v: T) -> crate::io::Result<T> { static SGX_INEFFECTIVE_ERROR: AtomicBool = AtomicBool::new(false); if SGX_INEFFECTIVE_ERROR.load(Ordering::Relaxed) { - Err(crate::io::Error::new(ErrorKind::Other, - "operation can't be trusted to have any effect on SGX")) + Err(crate::io::Error::new( + ErrorKind::Other, + "operation can't be trusted to have any effect on SGX", + )) } else { Ok(v) } @@ -121,7 +121,7 @@ pub unsafe fn strlen(mut s: *const c_char) -> usize { n += 1; s = s.offset(1); } - return n + return n; } pub unsafe fn abort_internal() -> ! { diff --git a/src/libstd/sys/sgx/mutex.rs b/src/libstd/sys/sgx/mutex.rs index 662da8b3f66..eebbea1b285 100644 --- a/src/libstd/sys/sgx/mutex.rs +++ b/src/libstd/sys/sgx/mutex.rs @@ -2,7 +2,7 @@ use fortanix_sgx_abi::Tcs; use super::abi::thread; -use super::waitqueue::{WaitVariable, WaitQueue, SpinMutex, NotifiedTcs, try_lock_or_false}; +use super::waitqueue::{try_lock_or_false, NotifiedTcs, SpinMutex, WaitQueue, WaitVariable}; pub struct Mutex { inner: SpinMutex<WaitVariable<bool>>, @@ -22,8 +22,8 @@ impl Mutex { let mut guard = self.inner.lock(); if *guard.lock_var() { // Another thread has the lock, wait - WaitQueue::wait(guard, ||{}) - // Another thread has passed the lock to us + WaitQueue::wait(guard, || {}) + // Another thread has passed the lock to us } else { // We are just now obtaining the lock *guard.lock_var_mut() = true; @@ -60,7 +60,7 @@ impl Mutex { struct ReentrantLock { owner: Option<Tcs>, - count: usize + count: usize, } pub struct ReentrantMutex { @@ -70,7 +70,7 @@ pub struct ReentrantMutex { impl ReentrantMutex { pub const fn uninitialized() -> ReentrantMutex { ReentrantMutex { - inner: SpinMutex::new(WaitVariable::new(ReentrantLock { owner: None, count: 0 })) + inner: SpinMutex::new(WaitVariable::new(ReentrantLock { owner: None, count: 0 })), } } @@ -83,14 +83,14 @@ impl ReentrantMutex { match guard.lock_var().owner { Some(tcs) if tcs != thread::current() => { // Another thread has the lock, wait - WaitQueue::wait(guard, ||{}); + WaitQueue::wait(guard, || {}); // Another thread has passed the lock to us - }, + } _ => { // We are just now obtaining the lock guard.lock_var_mut().owner = Some(thread::current()); guard.lock_var_mut().count += 1; - }, + } } } @@ -105,7 +105,7 @@ impl ReentrantMutex { // No other waiters, unlock guard.lock_var_mut().count = 0; guard.lock_var_mut().owner = None; - }, + } Ok(mut guard) => { // There was a thread waiting, just pass the lock if let NotifiedTcs::Single(tcs) = guard.notified_tcs() { @@ -125,13 +125,13 @@ impl ReentrantMutex { Some(tcs) if tcs != thread::current() => { // Another thread has the lock false - }, + } _ => { // We are just now obtaining the lock guard.lock_var_mut().owner = Some(thread::current()); guard.lock_var_mut().count += 1; true - }, + } } } diff --git a/src/libstd/sys/sgx/rwlock.rs b/src/libstd/sys/sgx/rwlock.rs index e2f94b1d928..fda2bb504d4 100644 --- a/src/libstd/sys/sgx/rwlock.rs +++ b/src/libstd/sys/sgx/rwlock.rs @@ -31,8 +31,8 @@ impl RWLock { if *wguard.lock_var() || !wguard.queue_empty() { // Another thread has or is waiting for the write lock, wait drop(wguard); - WaitQueue::wait(rguard, ||{}); - // Another thread has passed the lock to us + WaitQueue::wait(rguard, || {}); + // Another thread has passed the lock to us } else { // No waiting writers, acquire the read lock *rguard.lock_var_mut() = @@ -62,8 +62,8 @@ impl RWLock { if *wguard.lock_var() || rguard.lock_var().is_some() { // Another thread has the lock, wait drop(rguard); - WaitQueue::wait(wguard, ||{}); - // Another thread has passed the lock to us + WaitQueue::wait(wguard, || {}); + // Another thread has passed the lock to us } else { // We are just now obtaining the lock *wguard.lock_var_mut() = true; @@ -133,7 +133,7 @@ impl RWLock { } else { // No readers waiting, the lock is released } - }, + } Ok(wguard) => { // There was a thread waiting for write, just pass the lock wguard.drop_after(rguard); @@ -202,8 +202,8 @@ pub unsafe extern "C" fn __rust_rwlock_unlock(p: *mut RWLock) -> i32 { #[cfg(test)] mod tests { use super::*; - use core::array::FixedSizeArray; use crate::mem::{self, MaybeUninit}; + use core::array::FixedSizeArray; // Verify that the bytes of initialized RWLock are the same as in // libunwind. If they change, `src/UnwindRustSgx.h` in libunwind needs to @@ -211,22 +211,14 @@ mod tests { #[test] fn test_c_rwlock_initializer() { const RWLOCK_INIT: &[u8] = &[ - 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ]; #[inline(never)] @@ -247,10 +239,7 @@ mod tests { zero_stack(); let mut init = MaybeUninit::<RWLock>::zeroed(); rwlock_new(&mut init); - assert_eq!( - mem::transmute::<_, [u8; 128]>(init.assume_init()).as_slice(), - RWLOCK_INIT - ) + assert_eq!(mem::transmute::<_, [u8; 128]>(init.assume_init()).as_slice(), RWLOCK_INIT) }; } } diff --git a/src/libstd/sys/sgx/waitqueue.rs b/src/libstd/sys/sgx/waitqueue.rs index 3cb40e509b6..6e50f161b3b 100644 --- a/src/libstd/sys/sgx/waitqueue.rs +++ b/src/libstd/sys/sgx/waitqueue.rs @@ -1,3 +1,4 @@ +use crate::num::NonZeroUsize; /// A simple queue implementation for synchronization primitives. /// /// This queue is used to implement condition variable and mutexes. @@ -9,23 +10,21 @@ /// Since userspace may send spurious wake-ups, the wakeup event state is /// recorded in the enclave. The wakeup event state is protected by a spinlock. /// The queue and associated wait state are stored in a `WaitVariable`. - use crate::ops::{Deref, DerefMut}; -use crate::num::NonZeroUsize; -use fortanix_sgx_abi::{Tcs, EV_UNPARK, WAIT_INDEFINITE}; -use super::abi::usercalls; use super::abi::thread; +use super::abi::usercalls; +use fortanix_sgx_abi::{Tcs, EV_UNPARK, WAIT_INDEFINITE}; +pub use self::spin_mutex::{try_lock_or_false, SpinMutex, SpinMutexGuard}; use self::unsafe_list::{UnsafeList, UnsafeListEntry}; -pub use self::spin_mutex::{SpinMutex, SpinMutexGuard, try_lock_or_false}; /// An queue entry in a `WaitQueue`. struct WaitEntry { /// TCS address of the thread that is waiting tcs: Tcs, /// Whether this thread has been notified to be awoken - wake: bool + wake: bool, } /// Data stored with a `WaitQueue` alongside it. This ensures accesses to the @@ -36,15 +35,12 @@ struct WaitEntry { #[derive(Default)] pub struct WaitVariable<T> { queue: WaitQueue, - lock: T + lock: T, } impl<T> WaitVariable<T> { pub const fn new(var: T) -> Self { - WaitVariable { - queue: WaitQueue::new(), - lock: var - } + WaitVariable { queue: WaitQueue::new(), lock: var } } pub fn queue_empty(&self) -> bool { @@ -63,14 +59,14 @@ impl<T> WaitVariable<T> { #[derive(Copy, Clone)] pub enum NotifiedTcs { Single(Tcs), - All { count: NonZeroUsize } + All { count: NonZeroUsize }, } /// An RAII guard that will notify a set of target threads as well as unlock /// a mutex on drop. pub struct WaitGuard<'a, T: 'a> { mutex_guard: Option<SpinMutexGuard<'a, WaitVariable<T>>>, - notified_tcs: NotifiedTcs + notified_tcs: NotifiedTcs, } /// A queue of threads that are waiting on some synchronization primitive. @@ -125,7 +121,7 @@ impl<'a, T> Drop for WaitGuard<'a, T> { drop(self.mutex_guard.take()); let target_tcs = match self.notified_tcs { NotifiedTcs::Single(tcs) => Some(tcs), - NotifiedTcs::All { .. } => None + NotifiedTcs::All { .. } => None, }; rtunwrap!(Ok, usercalls::send(EV_UNPARK, target_tcs)); } @@ -133,9 +129,7 @@ impl<'a, T> Drop for WaitGuard<'a, T> { impl WaitQueue { pub const fn new() -> Self { - WaitQueue { - inner: UnsafeList::new() - } + WaitQueue { inner: UnsafeList::new() } } pub fn is_empty(&self) -> bool { @@ -151,7 +145,7 @@ impl WaitQueue { unsafe { let mut entry = UnsafeListEntry::new(SpinMutex::new(WaitEntry { tcs: thread::current(), - wake: false + wake: false, })); let entry = guard.queue.inner.push(&mut entry); drop(guard); @@ -169,19 +163,16 @@ impl WaitQueue { /// /// If a waiter is found, a `WaitGuard` is returned which will notify the /// waiter when it is dropped. - pub fn notify_one<T>(mut guard: SpinMutexGuard<'_, WaitVariable<T>>) - -> Result<WaitGuard<'_, T>, SpinMutexGuard<'_, WaitVariable<T>>> - { + pub fn notify_one<T>( + mut guard: SpinMutexGuard<'_, WaitVariable<T>>, + ) -> Result<WaitGuard<'_, T>, SpinMutexGuard<'_, WaitVariable<T>>> { unsafe { if let Some(entry) = guard.queue.inner.pop() { let mut entry_guard = entry.lock(); let tcs = entry_guard.tcs; entry_guard.wake = true; drop(entry); - Ok(WaitGuard { - mutex_guard: Some(guard), - notified_tcs: NotifiedTcs::Single(tcs) - }) + Ok(WaitGuard { mutex_guard: Some(guard), notified_tcs: NotifiedTcs::Single(tcs) }) } else { Err(guard) } @@ -193,9 +184,9 @@ impl WaitQueue { /// /// If at least one waiter is found, a `WaitGuard` is returned which will /// notify all waiters when it is dropped. - pub fn notify_all<T>(mut guard: SpinMutexGuard<'_, WaitVariable<T>>) - -> Result<WaitGuard<'_, T>, SpinMutexGuard<'_, WaitVariable<T>>> - { + pub fn notify_all<T>( + mut guard: SpinMutexGuard<'_, WaitVariable<T>>, + ) -> Result<WaitGuard<'_, T>, SpinMutexGuard<'_, WaitVariable<T>>> { unsafe { let mut count = 0; while let Some(entry) = guard.queue.inner.pop() { @@ -204,10 +195,7 @@ impl WaitQueue { entry_guard.wake = true; } if let Some(count) = NonZeroUsize::new(count) { - Ok(WaitGuard { - mutex_guard: Some(guard), - notified_tcs: NotifiedTcs::All { count } - }) + Ok(WaitGuard { mutex_guard: Some(guard), notified_tcs: NotifiedTcs::All { count } }) } else { Err(guard) } @@ -218,29 +206,22 @@ impl WaitQueue { /// A doubly-linked list where callers are in charge of memory allocation /// of the nodes in the list. mod unsafe_list { - use crate::ptr::NonNull; use crate::mem; + use crate::ptr::NonNull; pub struct UnsafeListEntry<T> { next: NonNull<UnsafeListEntry<T>>, prev: NonNull<UnsafeListEntry<T>>, - value: Option<T> + value: Option<T>, } impl<T> UnsafeListEntry<T> { fn dummy() -> Self { - UnsafeListEntry { - next: NonNull::dangling(), - prev: NonNull::dangling(), - value: None - } + UnsafeListEntry { next: NonNull::dangling(), prev: NonNull::dangling(), value: None } } pub fn new(value: T) -> Self { - UnsafeListEntry { - value: Some(value), - ..Self::dummy() - } + UnsafeListEntry { value: Some(value), ..Self::dummy() } } } @@ -252,10 +233,7 @@ mod unsafe_list { impl<T> UnsafeList<T> { pub const fn new() -> Self { unsafe { - UnsafeList { - head_tail: NonNull::new_unchecked(1 as _), - head_tail_entry: None - } + UnsafeList { head_tail: NonNull::new_unchecked(1 as _), head_tail_entry: None } } } @@ -416,8 +394,8 @@ mod unsafe_list { // FIXME: Perhaps use Intel TSX to avoid locking? mod spin_mutex { use crate::cell::UnsafeCell; - use crate::sync::atomic::{AtomicBool, Ordering, spin_loop_hint}; use crate::ops::{Deref, DerefMut}; + use crate::sync::atomic::{spin_loop_hint, AtomicBool, Ordering}; #[derive(Default)] pub struct SpinMutex<T> { @@ -437,20 +415,19 @@ mod spin_mutex { impl<T> SpinMutex<T> { pub const fn new(value: T) -> Self { - SpinMutex { - value: UnsafeCell::new(value), - lock: AtomicBool::new(false) - } + SpinMutex { value: UnsafeCell::new(value), lock: AtomicBool::new(false) } } #[inline(always)] pub fn lock(&self) -> SpinMutexGuard<'_, T> { loop { match self.try_lock() { - None => while self.lock.load(Ordering::Relaxed) { - spin_loop_hint() - }, - Some(guard) => return guard + None => { + while self.lock.load(Ordering::Relaxed) { + spin_loop_hint() + } + } + Some(guard) => return guard, } } } @@ -458,9 +435,7 @@ mod spin_mutex { #[inline(always)] pub fn try_lock(&self) -> Option<SpinMutexGuard<'_, T>> { if !self.lock.compare_and_swap(false, true, Ordering::Acquire) { - Some(SpinMutexGuard { - mutex: self, - }) + Some(SpinMutexGuard { mutex: self }) } else { None } @@ -468,31 +443,21 @@ mod spin_mutex { } /// Lock the Mutex or return false. - pub macro try_lock_or_false { - ($e:expr) => { - if let Some(v) = $e.try_lock() { - v - } else { - return false - } - } + pub macro try_lock_or_false($e:expr) { + if let Some(v) = $e.try_lock() { v } else { return false } } impl<'a, T> Deref for SpinMutexGuard<'a, T> { type Target = T; fn deref(&self) -> &T { - unsafe { - &*self.mutex.value.get() - } + unsafe { &*self.mutex.value.get() } } } impl<'a, T> DerefMut for SpinMutexGuard<'a, T> { fn deref_mut(&mut self) -> &mut T { - unsafe { - &mut*self.mutex.value.get() - } + unsafe { &mut *self.mutex.value.get() } } } @@ -509,7 +474,7 @@ mod spin_mutex { use super::*; use crate::sync::Arc; use crate::thread; - use crate::time::{SystemTime, Duration}; + use crate::time::{Duration, SystemTime}; #[test] fn sleep() { @@ -552,7 +517,7 @@ mod tests { assert!(WaitQueue::notify_one(wq2.lock()).is_ok()); }); - WaitQueue::wait(locked, ||{}); + WaitQueue::wait(locked, || {}); t1.join().unwrap(); } diff --git a/src/libstd/sys/unix/args.rs b/src/libstd/sys/unix/args.rs index 2ed1585395e..09acc3f6e3e 100644 --- a/src/libstd/sys/unix/args.rs +++ b/src/libstd/sys/unix/args.rs @@ -10,10 +10,14 @@ use crate::marker::PhantomData; use crate::vec; /// One-time global initialization. -pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) } +pub unsafe fn init(argc: isize, argv: *const *const u8) { + imp::init(argc, argv) +} /// One-time global cleanup. -pub unsafe fn cleanup() { imp::cleanup() } +pub unsafe fn cleanup() { + imp::cleanup() +} /// Returns the command line arguments pub fn args() -> Args { @@ -33,36 +37,46 @@ impl Args { impl Iterator for Args { type Item = OsString; - fn next(&mut self) -> Option<OsString> { self.iter.next() } - fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } + fn next(&mut self) -> Option<OsString> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } } impl ExactSizeIterator for Args { - fn len(&self) -> usize { self.iter.len() } + fn len(&self) -> usize { + self.iter.len() + } } impl DoubleEndedIterator for Args { - fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() } + fn next_back(&mut self) -> Option<OsString> { + self.iter.next_back() + } } -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris", - target_os = "emscripten", - target_os = "haiku", - target_os = "l4re", - target_os = "fuchsia", - target_os = "redox"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "netbsd", + target_os = "openbsd", + target_os = "solaris", + target_os = "emscripten", + target_os = "haiku", + target_os = "l4re", + target_os = "fuchsia", + target_os = "redox" +))] mod imp { - use crate::os::unix::prelude::*; - use crate::ptr; + use super::Args; use crate::ffi::{CStr, OsString}; use crate::marker::PhantomData; - use super::Args; + use crate::os::unix::prelude::*; + use crate::ptr; use crate::sys_common::mutex::Mutex; @@ -83,10 +97,7 @@ mod imp { // On Linux-GNU, we rely on `ARGV_INIT_ARRAY` below to initialize // `ARGC` and `ARGV`. But in Miri that does not actually happen so we // still initialize here. - #[cfg(any( - miri, - not(all(target_os = "linux", target_env = "gnu")) - ))] + #[cfg(any(miri, not(all(target_os = "linux", target_env = "gnu"))))] really_init(_argc, _argv); } @@ -119,57 +130,52 @@ mod imp { } pub fn args() -> Args { - Args { - iter: clone().into_iter(), - _dont_send_or_sync_me: PhantomData - } + Args { iter: clone().into_iter(), _dont_send_or_sync_me: PhantomData } } fn clone() -> Vec<OsString> { unsafe { let _guard = LOCK.lock(); - (0..ARGC).map(|i| { - let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char); - OsStringExt::from_vec(cstr.to_bytes().to_vec()) - }).collect() + (0..ARGC) + .map(|i| { + let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char); + OsStringExt::from_vec(cstr.to_bytes().to_vec()) + }) + .collect() } } } -#[cfg(any(target_os = "macos", - target_os = "ios"))] +#[cfg(any(target_os = "macos", target_os = "ios"))] mod imp { + use super::Args; use crate::ffi::CStr; use crate::marker::PhantomData; - use super::Args; - pub unsafe fn init(_argc: isize, _argv: *const *const u8) { - } + pub unsafe fn init(_argc: isize, _argv: *const *const u8) {} - pub fn cleanup() { - } + pub fn cleanup() {} #[cfg(target_os = "macos")] pub fn args() -> Args { use crate::os::unix::prelude::*; - extern { + extern "C" { // These functions are in crt_externs.h. fn _NSGetArgc() -> *mut libc::c_int; fn _NSGetArgv() -> *mut *mut *mut libc::c_char; } let vec = unsafe { - let (argc, argv) = (*_NSGetArgc() as isize, - *_NSGetArgv() as *const *const libc::c_char); - (0.. argc as isize).map(|i| { - let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec(); - OsStringExt::from_vec(bytes) - }).collect::<Vec<_>>() + let (argc, argv) = + (*_NSGetArgc() as isize, *_NSGetArgv() as *const *const libc::c_char); + (0..argc as isize) + .map(|i| { + let bytes = CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec(); + OsStringExt::from_vec(bytes) + }) + .collect::<Vec<_>>() }; - Args { - iter: vec.into_iter(), - _dont_send_or_sync_me: PhantomData, - } + Args { iter: vec.into_iter(), _dont_send_or_sync_me: PhantomData } } // As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs @@ -190,22 +196,22 @@ mod imp { use crate::mem; use crate::str; - extern { + extern "C" { fn sel_registerName(name: *const libc::c_uchar) -> Sel; fn objc_getClass(class_name: *const libc::c_uchar) -> NsId; } - #[cfg(target_arch="aarch64")] - extern { + #[cfg(target_arch = "aarch64")] + extern "C" { fn objc_msgSend(obj: NsId, sel: Sel) -> NsId; - #[link_name="objc_msgSend"] + #[link_name = "objc_msgSend"] fn objc_msgSend_ul(obj: NsId, sel: Sel, i: libc::c_ulong) -> NsId; } - #[cfg(not(target_arch="aarch64"))] - extern { + #[cfg(not(target_arch = "aarch64"))] + extern "C" { fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId; - #[link_name="objc_msgSend"] + #[link_name = "objc_msgSend"] fn objc_msgSend_ul(obj: NsId, sel: Sel, ...) -> NsId; } @@ -228,8 +234,7 @@ mod imp { let cnt: usize = mem::transmute(objc_msgSend(args, count_sel)); for i in 0..cnt { let tmp = objc_msgSend_ul(args, object_at_sel, i as libc::c_ulong); - let utf_c_str: *const libc::c_char = - mem::transmute(objc_msgSend(tmp, utf8_sel)); + let utf_c_str: *const libc::c_char = mem::transmute(objc_msgSend(tmp, utf8_sel)); let bytes = CStr::from_ptr(utf_c_str).to_bytes(); res.push(OsString::from(str::from_utf8(bytes).unwrap())) } diff --git a/src/libstd/sys/unix/condvar.rs b/src/libstd/sys/unix/condvar.rs index 6be844ded19..b4896b7ad74 100644 --- a/src/libstd/sys/unix/condvar.rs +++ b/src/libstd/sys/unix/condvar.rs @@ -2,15 +2,15 @@ use crate::cell::UnsafeCell; use crate::sys::mutex::{self, Mutex}; use crate::time::Duration; -pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t> } +pub struct Condvar { + inner: UnsafeCell<libc::pthread_cond_t>, +} unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} -const TIMESPEC_MAX: libc::timespec = libc::timespec { - tv_sec: <libc::time_t>::max_value(), - tv_nsec: 1_000_000_000 - 1, -}; +const TIMESPEC_MAX: libc::timespec = + libc::timespec { tv_sec: <libc::time_t>::max_value(), tv_nsec: 1_000_000_000 - 1 }; fn saturating_cast_to_time_t(value: u64) -> libc::time_t { if value > <libc::time_t>::max_value() as u64 { @@ -27,18 +27,22 @@ impl Condvar { Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) } } - #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "l4re", - target_os = "android", - target_os = "redox"))] + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "l4re", + target_os = "android", + target_os = "redox" + ))] pub unsafe fn init(&mut self) {} - #[cfg(not(any(target_os = "macos", - target_os = "ios", - target_os = "l4re", - target_os = "android", - target_os = "redox")))] + #[cfg(not(any( + target_os = "macos", + target_os = "ios", + target_os = "l4re", + target_os = "android", + target_os = "redox" + )))] pub unsafe fn init(&mut self) { use crate::mem::MaybeUninit; let mut attr = MaybeUninit::<libc::pthread_condattr_t>::uninit(); @@ -74,9 +78,7 @@ impl Condvar { // where we configure condition variable to use monotonic clock (instead of // default system clock). This approach avoids all problems that result // from changes made to the system time. - #[cfg(not(any(target_os = "macos", - target_os = "ios", - target_os = "android")))] + #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool { use crate::mem; @@ -92,17 +94,14 @@ impl Condvar { .and_then(|s| s.checked_add(now.tv_sec)); let nsec = nsec % 1_000_000_000; - let timeout = sec.map(|s| { - libc::timespec { tv_sec: s, tv_nsec: nsec as _} - }).unwrap_or(TIMESPEC_MAX); + let timeout = + sec.map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec as _ }).unwrap_or(TIMESPEC_MAX); - let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), - &timeout); + let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout); assert!(r == libc::ETIMEDOUT || r == 0); r == 0 } - // This implementation is modeled after libcxx's condition_variable // https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46 // https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367 @@ -138,21 +137,20 @@ impl Condvar { let r = libc::gettimeofday(&mut sys_now, ptr::null_mut()); debug_assert_eq!(r, 0); - let nsec = dur.subsec_nanos() as libc::c_long + - (sys_now.tv_usec * 1000) as libc::c_long; + let nsec = dur.subsec_nanos() as libc::c_long + (sys_now.tv_usec * 1000) as libc::c_long; let extra = (nsec / 1_000_000_000) as libc::time_t; let nsec = nsec % 1_000_000_000; let seconds = saturating_cast_to_time_t(dur.as_secs()); - let timeout = sys_now.tv_sec.checked_add(extra).and_then(|s| { - s.checked_add(seconds) - }).map(|s| { - libc::timespec { tv_sec: s, tv_nsec: nsec } - }).unwrap_or(TIMESPEC_MAX); + let timeout = sys_now + .tv_sec + .checked_add(extra) + .and_then(|s| s.checked_add(seconds)) + .map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec }) + .unwrap_or(TIMESPEC_MAX); // And wait! - let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), - &timeout); + let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout); debug_assert!(r == libc::ETIMEDOUT || r == 0); // ETIMEDOUT is not a totally reliable method of determining timeout due diff --git a/src/libstd/sys/unix/ext/mod.rs b/src/libstd/sys/unix/ext/mod.rs index 78a3fd05c73..cbdb1c10049 100644 --- a/src/libstd/sys/unix/ext/mod.rs +++ b/src/libstd/sys/unix/ext/mod.rs @@ -29,31 +29,38 @@ #![doc(cfg(unix))] #![allow(missing_docs)] -pub mod io; pub mod ffi; pub mod fs; +pub mod io; +pub mod net; pub mod process; pub mod raw; pub mod thread; -pub mod net; /// A prelude for conveniently writing platform-specific code. /// /// Includes all extension traits, and some important type definitions. #[stable(feature = "rust1", since = "1.0.0")] pub mod prelude { - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use super::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] pub use super::ffi::{OsStrExt, OsStringExt}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use super::fs::{PermissionsExt, OpenOptionsExt, MetadataExt, FileTypeExt}; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] pub use super::fs::DirEntryExt; - #[doc(no_inline)] #[stable(feature = "file_offset", since = "1.15.0")] + #[doc(no_inline)] + #[stable(feature = "file_offset", since = "1.15.0")] pub use super::fs::FileExt; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] - pub use super::thread::JoinHandleExt; - #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use super::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use super::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] pub use super::process::{CommandExt, ExitStatusExt}; + #[doc(no_inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use super::thread::JoinHandleExt; } diff --git a/src/libstd/sys/unix/ext/net.rs b/src/libstd/sys/unix/ext/net.rs index 5177cce628c..e0e6e02a443 100644 --- a/src/libstd/sys/unix/ext/net.rs +++ b/src/libstd/sys/unix/ext/net.rs @@ -22,22 +22,32 @@ use crate::io::{self, Initializer, IoSlice, IoSliceMut}; use crate::mem; use crate::net::{self, Shutdown}; use crate::os::unix::ffi::OsStrExt; -use crate::os::unix::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd}; +use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use crate::path::Path; -use crate::time::Duration; -use crate::sys::{self, cvt}; use crate::sys::net::Socket; +use crate::sys::{self, cvt}; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; +use crate::time::Duration; -#[cfg(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" +))] use libc::MSG_NOSIGNAL; -#[cfg(not(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku")))] +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" +)))] const MSG_NOSIGNAL: libc::c_int = 0x0; fn sun_path_offset(addr: &libc::sockaddr_un) -> usize { @@ -54,13 +64,17 @@ unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::sockl let bytes = path.as_os_str().as_bytes(); if bytes.contains(&0) { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "paths may not contain interior null bytes")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "paths may not contain interior null bytes", + )); } if bytes.len() >= addr.sun_path.len() { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "path must be shorter than SUN_LEN")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "path must be shorter than SUN_LEN", + )); } for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) { *dst = *src as libc::c_char; @@ -107,7 +121,8 @@ pub struct SocketAddr { impl SocketAddr { fn new<F>(f: F) -> io::Result<SocketAddr> - where F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int + where + F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int, { unsafe { let mut addr: libc::sockaddr_un = mem::zeroed(); @@ -121,16 +136,15 @@ impl SocketAddr { if len == 0 { // When there is a datagram from unnamed unix socket // linux returns zero bytes of address - len = sun_path_offset(&addr) as libc::socklen_t; // i.e., zero-length address + len = sun_path_offset(&addr) as libc::socklen_t; // i.e., zero-length address } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "file descriptor did not correspond to a Unix socket")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "file descriptor did not correspond to a Unix socket", + )); } - Ok(SocketAddr { - addr, - len, - }) + Ok(SocketAddr { addr, len }) } /// Returns `true` if the address is unnamed. @@ -164,11 +178,7 @@ impl SocketAddr { /// ``` #[stable(feature = "unix_socket", since = "1.10.0")] pub fn is_unnamed(&self) -> bool { - if let AddressKind::Unnamed = self.address() { - true - } else { - false - } + if let AddressKind::Unnamed = self.address() { true } else { false } } /// Returns the contents of this address if it is a `pathname` address. @@ -203,11 +213,7 @@ impl SocketAddr { /// ``` #[stable(feature = "unix_socket", since = "1.10.0")] pub fn as_pathname(&self) -> Option<&Path> { - if let AddressKind::Pathname(path) = self.address() { - Some(path) - } else { - None - } + if let AddressKind::Pathname(path) = self.address() { Some(path) } else { None } } fn address(&self) -> AddressKind<'_> { @@ -682,17 +688,23 @@ impl IntoRawFd for UnixStream { #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net::TcpStream { - fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() } + fn as_raw_fd(&self) -> RawFd { + *self.as_inner().socket().as_inner() + } } #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net::TcpListener { - fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() } + fn as_raw_fd(&self) -> RawFd { + *self.as_inner().socket().as_inner() + } } #[stable(feature = "rust1", since = "1.0.0")] impl AsRawFd for net::UdpSocket { - fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() } + fn as_raw_fd(&self) -> RawFd { + *self.as_inner().socket().as_inner() + } } #[stable(feature = "from_raw_os", since = "1.1.0")] @@ -1287,21 +1299,21 @@ impl UnixDatagram { #[stable(feature = "unix_socket", since = "1.10.0")] pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { let mut count = 0; - let addr = SocketAddr::new(|addr, len| { - unsafe { - count = libc::recvfrom(*self.0.as_inner(), - buf.as_mut_ptr() as *mut _, - buf.len(), - 0, - addr, - len); - if count > 0 { - 1 - } else if count == 0 { - 0 - } else { - -1 - } + let addr = SocketAddr::new(|addr, len| unsafe { + count = libc::recvfrom( + *self.0.as_inner(), + buf.as_mut_ptr() as *mut _, + buf.len(), + 0, + addr, + len, + ); + if count > 0 { + 1 + } else if count == 0 { + 0 + } else { + -1 } })?; @@ -1350,12 +1362,14 @@ impl UnixDatagram { unsafe { let (addr, len) = sockaddr_un(path)?; - let count = cvt(libc::sendto(*d.0.as_inner(), - buf.as_ptr() as *const _, - buf.len(), - MSG_NOSIGNAL, - &addr as *const _ as *const _, - len))?; + let count = cvt(libc::sendto( + *d.0.as_inner(), + buf.as_ptr() as *const _, + buf.len(), + MSG_NOSIGNAL, + &addr as *const _ as *const _, + len, + ))?; Ok(count as usize) } } @@ -1606,11 +1620,11 @@ impl IntoRawFd for UnixDatagram { #[cfg(all(test, not(target_os = "emscripten")))] mod test { - use crate::thread; - use crate::io::{self, ErrorKind}; use crate::io::prelude::*; - use crate::time::Duration; + use crate::io::{self, ErrorKind}; use crate::sys_common::io::test::tmpdir; + use crate::thread; + use crate::time::Duration; use super::*; @@ -1620,7 +1634,7 @@ mod test { Ok(e) => e, Err(e) => panic!("{}", e), } - } + }; } #[test] @@ -1640,8 +1654,7 @@ mod test { }); let mut stream = or_panic!(UnixStream::connect(&socket_path)); - assert_eq!(Some(&*socket_path), - stream.peer_addr().unwrap().as_pathname()); + assert_eq!(Some(&*socket_path), stream.peer_addr().unwrap().as_pathname()); or_panic!(stream.write_all(msg1)); let mut buf = vec![]; or_panic!(stream.read_to_end(&mut buf)); @@ -1655,16 +1668,18 @@ mod test { fn vectored() { let (mut s1, mut s2) = or_panic!(UnixStream::pair()); - let len = or_panic!(s1.write_vectored( - &[IoSlice::new(b"hello"), IoSlice::new(b" "), IoSlice::new(b"world!")], - )); + let len = or_panic!(s1.write_vectored(&[ + IoSlice::new(b"hello"), + IoSlice::new(b" "), + IoSlice::new(b"world!") + ],)); assert_eq!(len, 12); let mut buf1 = [0; 6]; let mut buf2 = [0; 7]; - let len = or_panic!(s2.read_vectored( - &mut [IoSliceMut::new(&mut buf1), IoSliceMut::new(&mut buf2)], - )); + let len = or_panic!( + s2.read_vectored(&mut [IoSliceMut::new(&mut buf1), IoSliceMut::new(&mut buf2)],) + ); assert_eq!(len, 12); assert_eq!(&buf1, b"hello "); assert_eq!(&buf2, b"world!\0"); @@ -1744,9 +1759,10 @@ mod test { #[test] fn long_path() { let dir = tmpdir(); - let socket_path = dir.path() - .join("asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\ - sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf"); + let socket_path = dir.path().join( + "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\ + sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf", + ); match UnixStream::connect(&socket_path) { Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {} Err(e) => panic!("unexpected error {}", e), @@ -1805,8 +1821,11 @@ mod test { let mut buf = [0; 10]; let kind = stream.read_exact(&mut buf).err().expect("expected error").kind(); - assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, - "unexpected_error: {:?}", kind); + assert!( + kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, + "unexpected_error: {:?}", + kind + ); } #[test] @@ -1827,8 +1846,11 @@ mod test { assert_eq!(b"hello world", &buf[..]); let kind = stream.read_exact(&mut buf).err().expect("expected error").kind(); - assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, - "unexpected_error: {:?}", kind); + assert!( + kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut, + "unexpected_error: {:?}", + kind + ); } // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index 8669c48e3bb..26fb0bf10fe 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -1,8 +1,8 @@ use crate::os::unix::prelude::*; -use crate::ffi::{CString, CStr, OsString, OsStr}; +use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; -use crate::io::{self, Error, ErrorKind, SeekFrom, IoSlice, IoSliceMut}; +use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut, SeekFrom}; use crate::mem; use crate::path::{Path, PathBuf}; use crate::ptr; @@ -14,28 +14,38 @@ use crate::sys_common::{AsInner, FromInner}; use libc::{c_int, mode_t}; -#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))] -use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64, dirent64, readdir64_r, open64}; -#[cfg(any(target_os = "linux", target_os = "emscripten"))] -use libc::fstatat64; #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))] use libc::dirfd; +#[cfg(any(target_os = "linux", target_os = "emscripten"))] +use libc::fstatat64; +#[cfg(not(any( + target_os = "linux", + target_os = "emscripten", + target_os = "solaris", + target_os = "l4re", + target_os = "fuchsia", + target_os = "redox" +)))] +use libc::readdir_r as readdir64_r; #[cfg(target_os = "android")] -use libc::{stat as stat64, fstat as fstat64, fstatat as fstatat64, lstat as lstat64, lseek64, - dirent as dirent64, open as open64}; -#[cfg(not(any(target_os = "linux", - target_os = "emscripten", - target_os = "l4re", - target_os = "android")))] -use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t, - ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64}; -#[cfg(not(any(target_os = "linux", - target_os = "emscripten", - target_os = "solaris", - target_os = "l4re", - target_os = "fuchsia", - target_os = "redox")))] -use libc::{readdir_r as readdir64_r}; +use libc::{ + dirent as dirent64, fstat as fstat64, fstatat as fstatat64, lseek64, lstat as lstat64, + open as open64, stat as stat64, +}; +#[cfg(not(any( + target_os = "linux", + target_os = "emscripten", + target_os = "l4re", + target_os = "android" +)))] +use libc::{ + dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64, + lstat as lstat64, off_t as off64_t, open as open64, stat as stat64, +}; +#[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))] +use libc::{ + dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, readdir64_r, stat64, +}; pub use crate::sys_common::fs::remove_dir_all; @@ -211,7 +221,7 @@ pub struct DirEntry { // array to store the name, b) its lifetime between readdir // calls is not guaranteed. #[cfg(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox"))] - name: Box<[u8]> + name: Box<[u8]>, } #[derive(Clone, Debug)] @@ -229,13 +239,19 @@ pub struct OpenOptions { } #[derive(Clone, PartialEq, Eq, Debug)] -pub struct FilePermissions { mode: mode_t } +pub struct FilePermissions { + mode: mode_t, +} #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct FileType { mode: mode_t } +pub struct FileType { + mode: mode_t, +} #[derive(Debug)] -pub struct DirBuilder { mode: mode_t } +pub struct DirBuilder { + mode: mode_t, +} cfg_has_statx! {{ impl FileAttr { @@ -252,7 +268,9 @@ cfg_has_statx! {{ }} impl FileAttr { - pub fn size(&self) -> u64 { self.stat.st_size as u64 } + pub fn size(&self) -> u64 { + self.stat.st_size as u64 + } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) } } @@ -302,10 +320,12 @@ impl FileAttr { })) } - #[cfg(any(target_os = "freebsd", - target_os = "openbsd", - target_os = "macos", - target_os = "ios"))] + #[cfg(any( + target_os = "freebsd", + target_os = "openbsd", + target_os = "macos", + target_os = "ios" + ))] pub fn created(&self) -> io::Result<SystemTime> { Ok(SystemTime::from(libc::timespec { tv_sec: self.stat.st_birthtime as libc::time_t, @@ -313,10 +333,12 @@ impl FileAttr { })) } - #[cfg(not(any(target_os = "freebsd", - target_os = "openbsd", - target_os = "macos", - target_os = "ios")))] + #[cfg(not(any( + target_os = "freebsd", + target_os = "openbsd", + target_os = "macos", + target_os = "ios" + )))] pub fn created(&self) -> io::Result<SystemTime> { cfg_has_statx! { if let Some(ext) = &self.statx_extra_fields { @@ -334,14 +356,18 @@ impl FileAttr { } } - Err(io::Error::new(io::ErrorKind::Other, - "creation time is not available on this platform \ - currently")) + Err(io::Error::new( + io::ErrorKind::Other, + "creation time is not available on this platform \ + currently", + )) } } impl AsInner<stat64> for FileAttr { - fn as_inner(&self) -> &stat64 { &self.stat } + fn as_inner(&self) -> &stat64 { + &self.stat + } } impl FilePermissions { @@ -359,15 +385,25 @@ impl FilePermissions { self.mode |= 0o222; } } - pub fn mode(&self) -> u32 { self.mode as u32 } + pub fn mode(&self) -> u32 { + self.mode as u32 + } } impl FileType { - pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) } - pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) } - pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) } + pub fn is_dir(&self) -> bool { + self.is(libc::S_IFDIR) + } + pub fn is_file(&self) -> bool { + self.is(libc::S_IFREG) + } + pub fn is_symlink(&self) -> bool { + self.is(libc::S_IFLNK) + } - pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode } + pub fn is(&self, mode: mode_t) -> bool { + self.mode & libc::S_IFMT == mode + } } impl FromInner<u32> for FilePermissions { @@ -405,7 +441,7 @@ impl Iterator for ReadDir { return match super::os::errno() { 0 => None, e => Some(Err(Error::from_raw_os_error(e))), - } + }; } let name = (*entry_ptr).d_name.as_ptr(); @@ -413,12 +449,13 @@ impl Iterator for ReadDir { let ret = DirEntry { entry: *entry_ptr, - name: slice::from_raw_parts(name as *const u8, - namelen as usize).to_owned().into_boxed_slice(), - dir: self.clone() + name: slice::from_raw_parts(name as *const u8, namelen as usize) + .to_owned() + .into_boxed_slice(), + dir: self.clone(), }; if ret.name_bytes() != b"." && ret.name_bytes() != b".." { - return Some(Ok(ret)) + return Some(Ok(ret)); } } } @@ -431,10 +468,7 @@ impl Iterator for ReadDir { } unsafe { - let mut ret = DirEntry { - entry: mem::zeroed(), - dir: self.clone(), - }; + let mut ret = DirEntry { entry: mem::zeroed(), dir: self.clone() }; let mut entry_ptr = ptr::null_mut(); loop { if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 { @@ -445,13 +479,13 @@ impl Iterator for ReadDir { // (instead of looping forever) self.end_of_stream = true; } - return Some(Err(Error::last_os_error())) + return Some(Err(Error::last_os_error())); } if entry_ptr.is_null() { - return None + return None; } if ret.name_bytes() != b"." && ret.name_bytes() != b".." { - return Some(Ok(ret)) + return Some(Ok(ret)); } } } @@ -491,9 +525,7 @@ impl DirEntry { } let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) - })?; + cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?; Ok(FileAttr::from_stat64(stat)) } @@ -521,54 +553,60 @@ impl DirEntry { } } - #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "linux", - target_os = "emscripten", - target_os = "android", - target_os = "solaris", - target_os = "haiku", - target_os = "l4re", - target_os = "fuchsia", - target_os = "redox"))] + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "linux", + target_os = "emscripten", + target_os = "android", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re", + target_os = "fuchsia", + target_os = "redox" + ))] pub fn ino(&self) -> u64 { self.entry.d_ino as u64 } - #[cfg(any(target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - target_os = "dragonfly"))] + #[cfg(any( + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "dragonfly" + ))] pub fn ino(&self) -> u64 { self.entry.d_fileno as u64 } - #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "netbsd", - target_os = "openbsd", - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "openbsd", + target_os = "freebsd", + target_os = "dragonfly" + ))] fn name_bytes(&self) -> &[u8] { use crate::slice; unsafe { - slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8, - self.entry.d_namlen as usize) + slice::from_raw_parts( + self.entry.d_name.as_ptr() as *const u8, + self.entry.d_namlen as usize, + ) } } - #[cfg(any(target_os = "android", - target_os = "linux", - target_os = "emscripten", - target_os = "l4re", - target_os = "haiku"))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "emscripten", + target_os = "l4re", + target_os = "haiku" + ))] fn name_bytes(&self) -> &[u8] { - unsafe { - CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes() - } + unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes() } } - #[cfg(any(target_os = "solaris", - target_os = "fuchsia", - target_os = "redox"))] + #[cfg(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox"))] fn name_bytes(&self) -> &[u8] { &*self.name } @@ -590,23 +628,39 @@ impl OpenOptions { } } - pub fn read(&mut self, read: bool) { self.read = read; } - pub fn write(&mut self, write: bool) { self.write = write; } - pub fn append(&mut self, append: bool) { self.append = append; } - pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; } - pub fn create(&mut self, create: bool) { self.create = create; } - pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; } + pub fn read(&mut self, read: bool) { + self.read = read; + } + pub fn write(&mut self, write: bool) { + self.write = write; + } + pub fn append(&mut self, append: bool) { + self.append = append; + } + pub fn truncate(&mut self, truncate: bool) { + self.truncate = truncate; + } + pub fn create(&mut self, create: bool) { + self.create = create; + } + pub fn create_new(&mut self, create_new: bool) { + self.create_new = create_new; + } - pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; } - pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; } + pub fn custom_flags(&mut self, flags: i32) { + self.custom_flags = flags; + } + pub fn mode(&mut self, mode: u32) { + self.mode = mode as mode_t; + } fn get_access_mode(&self) -> io::Result<c_int> { match (self.read, self.write, self.append) { - (true, false, false) => Ok(libc::O_RDONLY), - (false, true, false) => Ok(libc::O_WRONLY), - (true, true, false) => Ok(libc::O_RDWR), - (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND), - (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND), + (true, false, false) => Ok(libc::O_RDONLY), + (false, true, false) => Ok(libc::O_WRONLY), + (true, true, false) => Ok(libc::O_RDWR), + (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND), + (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND), (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)), } } @@ -614,23 +668,25 @@ impl OpenOptions { fn get_creation_mode(&self) -> io::Result<c_int> { match (self.write, self.append) { (true, false) => {} - (false, false) => + (false, false) => { if self.truncate || self.create || self.create_new { return Err(Error::from_raw_os_error(libc::EINVAL)); - }, - (_, true) => + } + } + (_, true) => { if self.truncate && !self.create_new { return Err(Error::from_raw_os_error(libc::EINVAL)); - }, + } + } } Ok(match (self.create, self.truncate, self.create_new) { - (false, false, false) => 0, - (true, false, false) => libc::O_CREAT, - (false, true, false) => libc::O_TRUNC, - (true, true, false) => libc::O_CREAT | libc::O_TRUNC, - (_, _, true) => libc::O_CREAT | libc::O_EXCL, - }) + (false, false, false) => 0, + (true, false, false) => libc::O_CREAT, + (false, true, false) => libc::O_TRUNC, + (true, true, false) => libc::O_CREAT | libc::O_TRUNC, + (_, _, true) => libc::O_CREAT | libc::O_EXCL, + }) } } @@ -641,13 +697,11 @@ impl File { } pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> { - let flags = libc::O_CLOEXEC | - opts.get_access_mode()? | - opts.get_creation_mode()? | - (opts.custom_flags as c_int & !libc::O_ACCMODE); - let fd = cvt_r(|| unsafe { - open64(path.as_ptr(), flags, opts.mode as c_int) - })?; + let flags = libc::O_CLOEXEC + | opts.get_access_mode()? + | opts.get_creation_mode()? + | (opts.custom_flags as c_int & !libc::O_ACCMODE); + let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?; let fd = FileDesc::new(fd); // Currently the standard library supports Linux 2.6.18 which did not @@ -672,12 +726,15 @@ impl File { match OPEN_CLOEXEC.load(Ordering::Relaxed) { OPEN_CLOEXEC_UNKNOWN => { need_to_set = !fd.get_cloexec()?; - OPEN_CLOEXEC.store(if need_to_set { - OPEN_CLOEXEC_NOTSUPPORTED - } else { - OPEN_CLOEXEC_SUPPORTED - }, Ordering::Relaxed); - }, + OPEN_CLOEXEC.store( + if need_to_set { + OPEN_CLOEXEC_NOTSUPPORTED + } else { + OPEN_CLOEXEC_SUPPORTED + }, + Ordering::Relaxed, + ); + } OPEN_CLOEXEC_SUPPORTED => need_to_set = false, OPEN_CLOEXEC_NOTSUPPORTED => need_to_set = true, _ => unreachable!(), @@ -712,9 +769,7 @@ impl File { } let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - fstat64(fd, &mut stat) - })?; + cvt(unsafe { fstat64(fd, &mut stat) })?; Ok(FileAttr::from_stat64(stat)) } @@ -727,7 +782,9 @@ impl File { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(not(any(target_os = "macos", target_os = "ios")))] - unsafe fn os_fsync(fd: c_int) -> c_int { libc::fsync(fd) } + unsafe fn os_fsync(fd: c_int) -> c_int { + libc::fsync(fd) + } } pub fn datasync(&self) -> io::Result<()> { @@ -739,11 +796,13 @@ impl File { libc::fcntl(fd, libc::F_FULLFSYNC) } #[cfg(target_os = "linux")] - unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) } - #[cfg(not(any(target_os = "macos", - target_os = "ios", - target_os = "linux")))] - unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } + unsafe fn os_datasync(fd: c_int) -> c_int { + libc::fdatasync(fd) + } + #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))] + unsafe fn os_datasync(fd: c_int) -> c_int { + libc::fsync(fd) + } } pub fn truncate(&self, size: u64) -> io::Result<()> { @@ -753,12 +812,9 @@ impl File { #[cfg(not(target_os = "android"))] { use crate::convert::TryInto; - let size: off64_t = size - .try_into() - .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; - cvt_r(|| unsafe { - ftruncate64(self.0.raw(), size) - }).map(|_| ()) + let size: off64_t = + size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + cvt_r(|| unsafe { ftruncate64(self.0.raw(), size) }).map(|_| ()) } } @@ -786,7 +842,9 @@ impl File { self.0.write_at(buf, offset) } - pub fn flush(&self) -> io::Result<()> { Ok(()) } + pub fn flush(&self) -> io::Result<()> { + Ok(()) + } pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { @@ -804,9 +862,13 @@ impl File { self.0.duplicate().map(File) } - pub fn fd(&self) -> &FileDesc { &self.0 } + pub fn fd(&self) -> &FileDesc { + &self.0 + } - pub fn into_fd(self) -> FileDesc { self.0 } + pub fn into_fd(self) -> FileDesc { + self.0 + } pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> { cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?; @@ -856,7 +918,7 @@ impl fmt::Debug for File { // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no // alternatives. If a better method is invented, it should be used // instead. - let mut buf = vec![0;libc::PATH_MAX as usize]; + let mut buf = vec![0; libc::PATH_MAX as usize]; let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) }; if n == -1 { return None; @@ -883,7 +945,7 @@ impl fmt::Debug for File { libc::O_RDONLY => Some((true, false)), libc::O_RDWR => Some((true, true)), libc::O_WRONLY => Some((false, true)), - _ => None + _ => None, } } @@ -915,10 +977,7 @@ pub fn readdir(p: &Path) -> io::Result<ReadDir> { Err(Error::last_os_error()) } else { let inner = InnerReadDir { dirp: Dir(ptr), root }; - Ok(ReadDir{ - inner: Arc::new(inner), - end_of_stream: false, - }) + Ok(ReadDir { inner: Arc::new(inner), end_of_stream: false }) } } } @@ -955,11 +1014,12 @@ pub fn readlink(p: &Path) -> io::Result<PathBuf> { let mut buf = Vec::with_capacity(256); loop { - let buf_read = cvt(unsafe { - libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) - })? as usize; + let buf_read = + cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize; - unsafe { buf.set_len(buf_read); } + unsafe { + buf.set_len(buf_read); + } if buf_read != buf.capacity() { buf.shrink_to_fit(); @@ -1003,9 +1063,7 @@ pub fn stat(p: &Path) -> io::Result<FileAttr> { } let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - stat64(p.as_ptr(), &mut stat) - })?; + cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?; Ok(FileAttr::from_stat64(stat)) } @@ -1024,9 +1082,7 @@ pub fn lstat(p: &Path) -> io::Result<FileAttr> { } let mut stat: stat64 = unsafe { mem::zeroed() }; - cvt(unsafe { - lstat64(p.as_ptr(), &mut stat) - })?; + cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?; Ok(FileAttr::from_stat64(stat)) } @@ -1036,7 +1092,7 @@ pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { unsafe { let r = libc::realpath(path.as_ptr(), ptr::null_mut()); if r.is_null() { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } buf = CStr::from_ptr(r).to_bytes().to_vec(); libc::free(r as *mut _); @@ -1083,10 +1139,12 @@ fn open_to_and_set_permissions( Ok((writer, writer_metadata)) } -#[cfg(not(any(target_os = "linux", - target_os = "android", - target_os = "macos", - target_os = "ios")))] +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "macos", + target_os = "ios" +)))] pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { let (mut reader, reader_metadata) = open_from(from)?; let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?; @@ -1111,15 +1169,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { len: libc::size_t, flags: libc::c_uint, ) -> libc::c_long { - libc::syscall( - libc::SYS_copy_file_range, - fd_in, - off_in, - fd_out, - off_out, - len, - flags, - ) + libc::syscall(libc::SYS_copy_file_range, fd_in, off_in, fd_out, off_out, len, flags) } let (mut reader, reader_metadata) = open_from(from)?; @@ -1160,19 +1210,19 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { Err(err) => { match err.raw_os_error() { Some(os_err) - if os_err == libc::ENOSYS - || os_err == libc::EXDEV - || os_err == libc::EINVAL - || os_err == libc::EPERM => - { - // Try fallback io::copy if either: - // - Kernel version is < 4.5 (ENOSYS) - // - Files are mounted on different fs (EXDEV) - // - copy_file_range is disallowed, for example by seccomp (EPERM) - // - copy_file_range cannot be used with pipes or device nodes (EINVAL) - assert_eq!(written, 0); - return io::copy(&mut reader, &mut writer); - } + if os_err == libc::ENOSYS + || os_err == libc::EXDEV + || os_err == libc::EINVAL + || os_err == libc::EPERM => + { + // Try fallback io::copy if either: + // - Kernel version is < 4.5 (ENOSYS) + // - Files are mounted on different fs (EXDEV) + // - copy_file_range is disallowed, for example by seccomp (EPERM) + // - copy_file_range cannot be used with pipes or device nodes (EINVAL) + assert_eq!(written, 0); + return io::copy(&mut reader, &mut writer); + } _ => return Err(err), } } @@ -1248,14 +1298,8 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { // using `fclonefileat`. if HAS_FCLONEFILEAT.load(Ordering::Relaxed) { let to = cstr(to)?; - let clonefile_result = cvt(unsafe { - fclonefileat( - reader.as_raw_fd(), - libc::AT_FDCWD, - to.as_ptr(), - 0, - ) - }); + let clonefile_result = + cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) }); match clonefile_result { Ok(_) => return Ok(reader_metadata.len()), Err(err) => match err.raw_os_error() { @@ -1266,7 +1310,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (), Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed), _ => return Err(err), - } + }, } } @@ -1283,20 +1327,9 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { FreeOnDrop(state) }; - let flags = if writer_metadata.is_file() { - COPYFILE_ALL - } else { - COPYFILE_DATA - }; + let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA }; - cvt(unsafe { - fcopyfile( - reader.as_raw_fd(), - writer.as_raw_fd(), - state.0, - flags, - ) - })?; + cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?; let mut bytes_copied: libc::off_t = 0; cvt(unsafe { diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index bf0166ceb6f..06876cb0614 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -2,21 +2,35 @@ use crate::io::ErrorKind; -#[cfg(any(doc, target_os = "linux"))] pub use crate::os::linux as platform; - -#[cfg(all(not(doc), target_os = "android"))] pub use crate::os::android as platform; -#[cfg(all(not(doc), target_os = "dragonfly"))] pub use crate::os::dragonfly as platform; -#[cfg(all(not(doc), target_os = "freebsd"))] pub use crate::os::freebsd as platform; -#[cfg(all(not(doc), target_os = "haiku"))] pub use crate::os::haiku as platform; -#[cfg(all(not(doc), target_os = "ios"))] pub use crate::os::ios as platform; -#[cfg(all(not(doc), target_os = "macos"))] pub use crate::os::macos as platform; -#[cfg(all(not(doc), target_os = "netbsd"))] pub use crate::os::netbsd as platform; -#[cfg(all(not(doc), target_os = "openbsd"))] pub use crate::os::openbsd as platform; -#[cfg(all(not(doc), target_os = "solaris"))] pub use crate::os::solaris as platform; -#[cfg(all(not(doc), target_os = "emscripten"))] pub use crate::os::emscripten as platform; -#[cfg(all(not(doc), target_os = "fuchsia"))] pub use crate::os::fuchsia as platform; -#[cfg(all(not(doc), target_os = "l4re"))] pub use crate::os::linux as platform; -#[cfg(all(not(doc), target_os = "redox"))] pub use crate::os::redox as platform; +#[cfg(any(doc, target_os = "linux"))] +pub use crate::os::linux as platform; + +#[cfg(all(not(doc), target_os = "android"))] +pub use crate::os::android as platform; +#[cfg(all(not(doc), target_os = "dragonfly"))] +pub use crate::os::dragonfly as platform; +#[cfg(all(not(doc), target_os = "emscripten"))] +pub use crate::os::emscripten as platform; +#[cfg(all(not(doc), target_os = "freebsd"))] +pub use crate::os::freebsd as platform; +#[cfg(all(not(doc), target_os = "fuchsia"))] +pub use crate::os::fuchsia as platform; +#[cfg(all(not(doc), target_os = "haiku"))] +pub use crate::os::haiku as platform; +#[cfg(all(not(doc), target_os = "ios"))] +pub use crate::os::ios as platform; +#[cfg(all(not(doc), target_os = "l4re"))] +pub use crate::os::linux as platform; +#[cfg(all(not(doc), target_os = "macos"))] +pub use crate::os::macos as platform; +#[cfg(all(not(doc), target_os = "netbsd"))] +pub use crate::os::netbsd as platform; +#[cfg(all(not(doc), target_os = "openbsd"))] +pub use crate::os::openbsd as platform; +#[cfg(all(not(doc), target_os = "redox"))] +pub use crate::os::redox as platform; +#[cfg(all(not(doc), target_os = "solaris"))] +pub use crate::os::solaris as platform; pub use self::rand::hashmap_random_keys; pub use libc::strlen; @@ -25,8 +39,8 @@ pub use libc::strlen; pub mod weak; pub mod alloc; -pub mod args; pub mod android; +pub mod args; pub mod cmath; pub mod condvar; pub mod env; @@ -34,14 +48,14 @@ pub mod ext; pub mod fast_thread_local; pub mod fd; pub mod fs; -pub mod memchr; pub mod io; +#[cfg(target_os = "l4re")] +mod l4re; +pub mod memchr; pub mod mutex; #[cfg(not(target_os = "l4re"))] pub mod net; #[cfg(target_os = "l4re")] -mod l4re; -#[cfg(target_os = "l4re")] pub use self::l4re::net; pub mod os; pub mod path; @@ -50,10 +64,10 @@ pub mod process; pub mod rand; pub mod rwlock; pub mod stack_overflow; +pub mod stdio; pub mod thread; pub mod thread_local; pub mod time; -pub mod stdio; pub use crate::sys_common::os_str_bytes as os_str; @@ -102,8 +116,7 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind { // These two constants can have the same value on some systems, // but different values on others, so we can't use a match // clause - x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => - ErrorKind::WouldBlock, + x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => ErrorKind::WouldBlock, _ => ErrorKind::Other, } @@ -125,16 +138,13 @@ macro_rules! impl_is_minus_one { impl_is_minus_one! { i8 i16 i32 i64 isize } pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> { - if t.is_minus_one() { - Err(crate::io::Error::last_os_error()) - } else { - Ok(t) - } + if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) } } pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T> - where T: IsMinusOne, - F: FnMut() -> T +where + T: IsMinusOne, + F: FnMut() -> T, { loop { match cvt(f()) { diff --git a/src/libstd/sys/unix/mutex.rs b/src/libstd/sys/unix/mutex.rs index b43af8fdcaa..b38375a2e03 100644 --- a/src/libstd/sys/unix/mutex.rs +++ b/src/libstd/sys/unix/mutex.rs @@ -1,7 +1,9 @@ use crate::cell::UnsafeCell; use crate::mem::MaybeUninit; -pub struct Mutex { inner: UnsafeCell<libc::pthread_mutex_t> } +pub struct Mutex { + inner: UnsafeCell<libc::pthread_mutex_t>, +} #[inline] pub unsafe fn raw(m: &Mutex) -> *mut libc::pthread_mutex_t { @@ -82,7 +84,9 @@ impl Mutex { } } -pub struct ReentrantMutex { inner: UnsafeCell<libc::pthread_mutex_t> } +pub struct ReentrantMutex { + inner: UnsafeCell<libc::pthread_mutex_t>, +} unsafe impl Send for ReentrantMutex {} unsafe impl Sync for ReentrantMutex {} @@ -96,8 +100,8 @@ impl ReentrantMutex { let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit(); let result = libc::pthread_mutexattr_init(attr.as_mut_ptr()); debug_assert_eq!(result, 0); - let result = libc::pthread_mutexattr_settype(attr.as_mut_ptr(), - libc::PTHREAD_MUTEX_RECURSIVE); + let result = + libc::pthread_mutexattr_settype(attr.as_mut_ptr(), libc::PTHREAD_MUTEX_RECURSIVE); debug_assert_eq!(result, 0); let result = libc::pthread_mutex_init(self.inner.get(), attr.as_ptr()); debug_assert_eq!(result, 0); diff --git a/src/libstd/sys/unix/process/process_unix.rs b/src/libstd/sys/unix/process/process_unix.rs index 45e4d195f17..85c30abe452 100644 --- a/src/libstd/sys/unix/process/process_unix.rs +++ b/src/libstd/sys/unix/process/process_unix.rs @@ -1,9 +1,9 @@ use crate::fmt; use crate::io::{self, Error, ErrorKind}; use crate::ptr; +use crate::sys; use crate::sys::cvt; use crate::sys::process::process_common::*; -use crate::sys; use libc::{c_int, gid_t, pid_t, uid_t}; @@ -12,21 +12,23 @@ use libc::{c_int, gid_t, pid_t, uid_t}; //////////////////////////////////////////////////////////////////////////////// impl Command { - pub fn spawn(&mut self, default: Stdio, needs_stdin: bool) - -> io::Result<(Process, StdioPipes)> { + pub fn spawn( + &mut self, + default: Stdio, + needs_stdin: bool, + ) -> io::Result<(Process, StdioPipes)> { const CLOEXEC_MSG_FOOTER: &[u8] = b"NOEX"; let envp = self.capture_env(); if self.saw_nul() { - return Err(io::Error::new(ErrorKind::InvalidInput, - "nul byte found in provided data")); + return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data")); } let (ours, theirs) = self.setup_io(default, needs_stdin)?; if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? { - return Ok((ret, ours)) + return Ok((ret, ours)); } let (input, output) = sys::pipe::anon_pipe()?; @@ -53,10 +55,12 @@ impl Command { let bytes = [ (errno >> 24) as u8, (errno >> 16) as u8, - (errno >> 8) as u8, - (errno >> 0) as u8, - CLOEXEC_MSG_FOOTER[0], CLOEXEC_MSG_FOOTER[1], - CLOEXEC_MSG_FOOTER[2], CLOEXEC_MSG_FOOTER[3] + (errno >> 8) as u8, + (errno >> 0) as u8, + CLOEXEC_MSG_FOOTER[0], + CLOEXEC_MSG_FOOTER[1], + CLOEXEC_MSG_FOOTER[2], + CLOEXEC_MSG_FOOTER[3], ]; // pipe I/O up to PIPE_BUF bytes should be atomic, and then // we want to be sure we *don't* run at_exit destructors as @@ -77,22 +81,23 @@ impl Command { match input.read(&mut bytes) { Ok(0) => return Ok((p, ours)), Ok(8) => { - assert!(combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4.. 8]), - "Validation on the CLOEXEC pipe failed: {:?}", bytes); - let errno = combine(&bytes[0.. 4]); - assert!(p.wait().is_ok(), - "wait() should either return Ok or panic"); - return Err(Error::from_raw_os_error(errno)) + assert!( + combine(CLOEXEC_MSG_FOOTER) == combine(&bytes[4..8]), + "Validation on the CLOEXEC pipe failed: {:?}", + bytes + ); + let errno = combine(&bytes[0..4]); + assert!(p.wait().is_ok(), "wait() should either return Ok or panic"); + return Err(Error::from_raw_os_error(errno)); } Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => { - assert!(p.wait().is_ok(), - "wait() should either return Ok or panic"); + assert!(p.wait().is_ok(), "wait() should either return Ok or panic"); panic!("the CLOEXEC pipe failed: {:?}", e) - }, - Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic - assert!(p.wait().is_ok(), - "wait() should either return Ok or panic"); + } + Ok(..) => { + // pipe I/O up to PIPE_BUF bytes should be atomic + assert!(p.wait().is_ok(), "wait() should either return Ok or panic"); panic!("short read on the CLOEXEC pipe") } } @@ -112,8 +117,7 @@ impl Command { let envp = self.capture_env(); if self.saw_nul() { - return io::Error::new(ErrorKind::InvalidInput, - "nul byte found in provided data") + return io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"); } match self.setup_io(default, true) { @@ -165,7 +169,7 @@ impl Command { unsafe fn do_exec( &mut self, stdio: ChildPipes, - maybe_envp: Option<&CStringArray> + maybe_envp: Option<&CStringArray>, ) -> Result<!, io::Error> { use crate::sys::{self, cvt_r}; @@ -215,11 +219,10 @@ impl Command { // we're about to run. let mut set = MaybeUninit::<libc::sigset_t>::uninit(); cvt(sigemptyset(set.as_mut_ptr()))?; - cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), - ptr::null_mut()))?; + cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), ptr::null_mut()))?; let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL); if ret == libc::SIG_ERR { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } } @@ -252,29 +255,40 @@ impl Command { Err(io::Error::last_os_error()) } - #[cfg(not(any(target_os = "macos", target_os = "freebsd", - all(target_os = "linux", target_env = "gnu"))))] - fn posix_spawn(&mut self, _: &ChildPipes, _: Option<&CStringArray>) - -> io::Result<Option<Process>> - { + #[cfg(not(any( + target_os = "macos", + target_os = "freebsd", + all(target_os = "linux", target_env = "gnu") + )))] + fn posix_spawn( + &mut self, + _: &ChildPipes, + _: Option<&CStringArray>, + ) -> io::Result<Option<Process>> { Ok(None) } // Only support platforms for which posix_spawn() can return ENOENT // directly. - #[cfg(any(target_os = "macos", target_os = "freebsd", - all(target_os = "linux", target_env = "gnu")))] - fn posix_spawn(&mut self, stdio: &ChildPipes, envp: Option<&CStringArray>) - -> io::Result<Option<Process>> - { + #[cfg(any( + target_os = "macos", + target_os = "freebsd", + all(target_os = "linux", target_env = "gnu") + ))] + fn posix_spawn( + &mut self, + stdio: &ChildPipes, + envp: Option<&CStringArray>, + ) -> io::Result<Option<Process>> { use crate::mem::MaybeUninit; use crate::sys; - if self.get_gid().is_some() || - self.get_uid().is_some() || - self.env_saw_path() || - !self.get_closures().is_empty() { - return Ok(None) + if self.get_gid().is_some() + || self.get_uid().is_some() + || self.env_saw_path() + || !self.get_closures().is_empty() + { + return Ok(None); } // Only glibc 2.24+ posix_spawn() supports returning ENOENT directly. @@ -282,10 +296,10 @@ impl Command { { if let Some(version) = sys::os::glibc_version() { if version < (2, 24) { - return Ok(None) + return Ok(None); } } else { - return Ok(None) + return Ok(None); } } @@ -337,19 +351,25 @@ impl Command { libc::posix_spawn_file_actions_init(file_actions.0.as_mut_ptr()); if let Some(fd) = stdio.stdin.fd() { - cvt(libc::posix_spawn_file_actions_adddup2(file_actions.0.as_mut_ptr(), - fd, - libc::STDIN_FILENO))?; + cvt(libc::posix_spawn_file_actions_adddup2( + file_actions.0.as_mut_ptr(), + fd, + libc::STDIN_FILENO, + ))?; } if let Some(fd) = stdio.stdout.fd() { - cvt(libc::posix_spawn_file_actions_adddup2(file_actions.0.as_mut_ptr(), - fd, - libc::STDOUT_FILENO))?; + cvt(libc::posix_spawn_file_actions_adddup2( + file_actions.0.as_mut_ptr(), + fd, + libc::STDOUT_FILENO, + ))?; } if let Some(fd) = stdio.stderr.fd() { - cvt(libc::posix_spawn_file_actions_adddup2(file_actions.0.as_mut_ptr(), - fd, - libc::STDERR_FILENO))?; + cvt(libc::posix_spawn_file_actions_adddup2( + file_actions.0.as_mut_ptr(), + fd, + libc::STDERR_FILENO, + ))?; } if let Some((f, cwd)) = addchdir { cvt(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?; @@ -357,20 +377,16 @@ impl Command { let mut set = MaybeUninit::<libc::sigset_t>::uninit(); cvt(sigemptyset(set.as_mut_ptr()))?; - cvt(libc::posix_spawnattr_setsigmask(attrs.0.as_mut_ptr(), - set.as_ptr()))?; + cvt(libc::posix_spawnattr_setsigmask(attrs.0.as_mut_ptr(), set.as_ptr()))?; cvt(sigaddset(set.as_mut_ptr(), libc::SIGPIPE))?; - cvt(libc::posix_spawnattr_setsigdefault(attrs.0.as_mut_ptr(), - set.as_ptr()))?; + cvt(libc::posix_spawnattr_setsigdefault(attrs.0.as_mut_ptr(), set.as_ptr()))?; - let flags = libc::POSIX_SPAWN_SETSIGDEF | - libc::POSIX_SPAWN_SETSIGMASK; + let flags = libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK; cvt(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?; // Make sure we synchronize access to the global `environ` resource let _env_lock = sys::os::env_lock(); - let envp = envp.map(|c| c.as_ptr()) - .unwrap_or_else(|| *sys::os::environ() as *const _); + let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::os::environ() as *const _); let ret = libc::posix_spawnp( &mut p.pid, self.get_program().as_ptr(), @@ -379,11 +395,7 @@ impl Command { self.get_argv().as_ptr() as *const _, envp as *const _, ); - if ret == 0 { - Ok(Some(p)) - } else { - Err(io::Error::from_raw_os_error(ret)) - } + if ret == 0 { Ok(Some(p)) } else { Err(io::Error::from_raw_os_error(ret)) } } } } @@ -408,8 +420,10 @@ impl Process { // and used for another process, and we probably shouldn't be killing // random processes, so just return an error. if self.status.is_some() { - Err(Error::new(ErrorKind::InvalidInput, - "invalid argument: can't kill an exited process")) + Err(Error::new( + ErrorKind::InvalidInput, + "invalid argument: can't kill an exited process", + )) } else { cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(|_| ()) } @@ -418,7 +432,7 @@ impl Process { pub fn wait(&mut self) -> io::Result<ExitStatus> { use crate::sys::cvt_r; if let Some(status) = self.status { - return Ok(status) + return Ok(status); } let mut status = 0 as c_int; cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?; @@ -428,12 +442,10 @@ impl Process { pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { if let Some(status) = self.status { - return Ok(Some(status)) + return Ok(Some(status)); } let mut status = 0 as c_int; - let pid = cvt(unsafe { - libc::waitpid(self.pid, &mut status, libc::WNOHANG) - })?; + let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?; if pid == 0 { Ok(None) } else { @@ -461,19 +473,11 @@ impl ExitStatus { } pub fn code(&self) -> Option<i32> { - if self.exited() { - Some(unsafe { libc::WEXITSTATUS(self.0) }) - } else { - None - } + if self.exited() { Some(unsafe { libc::WEXITSTATUS(self.0) }) } else { None } } pub fn signal(&self) -> Option<i32> { - if !self.exited() { - Some(unsafe { libc::WTERMSIG(self.0) }) - } else { - None - } + if !self.exited() { Some(unsafe { libc::WTERMSIG(self.0) }) } else { None } } } diff --git a/src/libstd/sys/unix/rwlock.rs b/src/libstd/sys/unix/rwlock.rs index e48bfdae610..079dea671ef 100644 --- a/src/libstd/sys/unix/rwlock.rs +++ b/src/libstd/sys/unix/rwlock.rs @@ -71,8 +71,10 @@ impl RWLock { let r = libc::pthread_rwlock_wrlock(self.inner.get()); // See comments above for why we check for EDEADLK and write_locked. We // also need to check that num_readers is 0. - if r == libc::EDEADLK || *self.write_locked.get() || - self.num_readers.load(Ordering::Relaxed) != 0 { + if r == libc::EDEADLK + || *self.write_locked.get() + || self.num_readers.load(Ordering::Relaxed) != 0 + { if r == 0 { self.raw_unlock(); } diff --git a/src/libstd/sys/unix/time.rs b/src/libstd/sys/unix/time.rs index a9122defa55..23104419978 100644 --- a/src/libstd/sys/unix/time.rs +++ b/src/libstd/sys/unix/time.rs @@ -15,20 +15,21 @@ struct Timespec { impl Timespec { const fn zero() -> Timespec { - Timespec { - t: libc::timespec { tv_sec: 0, tv_nsec: 0 }, - } + Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } } } fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> { if self >= other { Ok(if self.t.tv_nsec >= other.t.tv_nsec { - Duration::new((self.t.tv_sec - other.t.tv_sec) as u64, - (self.t.tv_nsec - other.t.tv_nsec) as u32) + Duration::new( + (self.t.tv_sec - other.t.tv_sec) as u64, + (self.t.tv_nsec - other.t.tv_nsec) as u32, + ) } else { - Duration::new((self.t.tv_sec - 1 - other.t.tv_sec) as u64, - self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) - - other.t.tv_nsec as u32) + Duration::new( + (self.t.tv_sec - 1 - other.t.tv_sec) as u64, + self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) - other.t.tv_nsec as u32, + ) }) } else { match other.sub_timespec(self) { @@ -52,12 +53,7 @@ impl Timespec { nsec -= NSEC_PER_SEC as u32; secs = secs.checked_add(1)?; } - Some(Timespec { - t: libc::timespec { - tv_sec: secs, - tv_nsec: nsec as _, - }, - }) + Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } }) } fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> { @@ -73,12 +69,7 @@ impl Timespec { nsec += NSEC_PER_SEC as i32; secs = secs.checked_sub(1)?; } - Some(Timespec { - t: libc::timespec { - tv_sec: secs, - tv_nsec: nsec as _, - }, - }) + Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } }) } } @@ -105,7 +96,7 @@ impl Ord for Timespec { } impl Hash for Timespec { - fn hash<H : Hasher>(&self, state: &mut H) { + fn hash<H: Hasher>(&self, state: &mut H) { self.t.tv_sec.hash(state); self.t.tv_nsec.hash(state); } @@ -120,12 +111,12 @@ mod inner { use crate::sys_common::mul_div_u64; use crate::time::Duration; - use super::NSEC_PER_SEC; use super::Timespec; + use super::NSEC_PER_SEC; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Instant { - t: u64 + t: u64, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -133,9 +124,7 @@ mod inner { t: Timespec, } - pub const UNIX_EPOCH: SystemTime = SystemTime { - t: Timespec::zero(), - }; + pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() }; #[repr(C)] #[derive(Copy, Clone)] @@ -170,15 +159,11 @@ mod inner { } pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> { - Some(Instant { - t: self.t.checked_add(checked_dur2intervals(other)?)?, - }) + Some(Instant { t: self.t.checked_add(checked_dur2intervals(other)?)? }) } pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> { - Some(Instant { - t: self.t.checked_sub(checked_dur2intervals(other)?)?, - }) + Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? }) } } @@ -186,18 +171,12 @@ mod inner { pub fn now() -> SystemTime { use crate::ptr; - let mut s = libc::timeval { - tv_sec: 0, - tv_usec: 0, - }; - cvt(unsafe { - libc::gettimeofday(&mut s, ptr::null_mut()) - }).unwrap(); - return SystemTime::from(s) + let mut s = libc::timeval { tv_sec: 0, tv_usec: 0 }; + cvt(unsafe { libc::gettimeofday(&mut s, ptr::null_mut()) }).unwrap(); + return SystemTime::from(s); } - pub fn sub_time(&self, other: &SystemTime) - -> Result<Duration, Duration> { + pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> { self.t.sub_timespec(&other.t) } @@ -228,25 +207,21 @@ mod inner { impl fmt::Debug for SystemTime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SystemTime") - .field("tv_sec", &self.t.t.tv_sec) - .field("tv_nsec", &self.t.t.tv_nsec) - .finish() + .field("tv_sec", &self.t.t.tv_sec) + .field("tv_nsec", &self.t.t.tv_nsec) + .finish() } } fn checked_dur2intervals(dur: &Duration) -> Option<u64> { - let nanos = dur.as_secs() - .checked_mul(NSEC_PER_SEC)? - .checked_add(dur.subsec_nanos() as u64)?; + let nanos = + dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as u64)?; let info = info(); Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64)) } fn info() -> mach_timebase_info { - static mut INFO: mach_timebase_info = mach_timebase_info { - numer: 0, - denom: 0, - }; + static mut INFO: mach_timebase_info = mach_timebase_info { numer: 0, denom: 0 }; static STATE: AtomicUsize = AtomicUsize::new(0); unsafe { @@ -258,8 +233,7 @@ mod inner { // ... otherwise learn for ourselves ... let mut info = mem::zeroed(); extern "C" { - fn mach_timebase_info(info: mach_timebase_info_t) - -> kern_return_t; + fn mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t; } mach_timebase_info(&mut info); @@ -293,9 +267,7 @@ mod inner { t: Timespec, } - pub const UNIX_EPOCH: SystemTime = SystemTime { - t: Timespec::zero(), - }; + pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() }; impl Instant { pub fn now() -> Instant { @@ -303,16 +275,14 @@ mod inner { } pub const fn zero() -> Instant { - Instant { - t: Timespec::zero(), - } + Instant { t: Timespec::zero() } } pub fn actually_monotonic() -> bool { - (cfg!(target_os = "linux") && cfg!(target_arch = "x86_64")) || - (cfg!(target_os = "linux") && cfg!(target_arch = "x86")) || - cfg!(target_os = "fuchsia") || - false // last clause, used so `||` is always trailing above + (cfg!(target_os = "linux") && cfg!(target_arch = "x86_64")) + || (cfg!(target_os = "linux") && cfg!(target_arch = "x86")) + || cfg!(target_os = "fuchsia") + || false // last clause, used so `||` is always trailing above } pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> { @@ -331,9 +301,9 @@ mod inner { impl fmt::Debug for Instant { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Instant") - .field("tv_sec", &self.t.t.tv_sec) - .field("tv_nsec", &self.t.t.tv_nsec) - .finish() + .field("tv_sec", &self.t.t.tv_sec) + .field("tv_nsec", &self.t.t.tv_nsec) + .finish() } } @@ -342,8 +312,7 @@ mod inner { SystemTime { t: now(libc::CLOCK_REALTIME) } } - pub fn sub_time(&self, other: &SystemTime) - -> Result<Duration, Duration> { + pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> { self.t.sub_timespec(&other.t) } @@ -365,9 +334,9 @@ mod inner { impl fmt::Debug for SystemTime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SystemTime") - .field("tv_sec", &self.t.t.tv_sec) - .field("tv_nsec", &self.t.t.tv_nsec) - .finish() + .field("tv_sec", &self.t.t.tv_sec) + .field("tv_nsec", &self.t.t.tv_nsec) + .finish() } } @@ -377,15 +346,8 @@ mod inner { pub type clock_t = libc::c_ulong; fn now(clock: clock_t) -> Timespec { - let mut t = Timespec { - t: libc::timespec { - tv_sec: 0, - tv_nsec: 0, - } - }; - cvt(unsafe { - libc::clock_gettime(clock, &mut t.t) - }).unwrap(); + let mut t = Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } }; + cvt(unsafe { libc::clock_gettime(clock, &mut t.t) }).unwrap(); t } } diff --git a/src/libstd/sys/vxworks/os.rs b/src/libstd/sys/vxworks/os.rs index 71e1d1626c1..b37a1790454 100644 --- a/src/libstd/sys/vxworks/os.rs +++ b/src/libstd/sys/vxworks/os.rs @@ -1,18 +1,18 @@ use crate::error::Error as StdError; -use crate::ffi::{CString, CStr, OsString, OsStr}; +use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::iter; -use libc::{self, c_int, c_char /*,c_void */}; use crate::marker::PhantomData; use crate::mem; use crate::memchr; -use crate::path::{self, PathBuf, Path}; +use crate::path::{self, Path, PathBuf}; use crate::ptr; use crate::slice; use crate::str; -use crate::sys_common::mutex::{Mutex, MutexGuard}; use crate::sys::cvt; +use crate::sys_common::mutex::{Mutex, MutexGuard}; +use libc::{self, c_char /*,c_void */, c_int}; /*use sys::fd; this one is probably important */ use crate::vec; @@ -20,7 +20,7 @@ const TMPBUF_SZ: usize = 128; // This is a terrible fix use crate::sys::os_str::Buf; -use crate::sys_common::{FromInner, IntoInner, AsInner}; +use crate::sys_common::{AsInner, FromInner, IntoInner}; pub trait OsStringExt { fn from_vec(vec: Vec<u8>) -> Self; @@ -55,18 +55,16 @@ pub fn errno() -> i32 { } pub fn set_errno(e: i32) { - unsafe { libc::errnoSet(e as c_int); } + unsafe { + libc::errnoSet(e as c_int); + } } /// Gets a detailed string description for the given error number. pub fn error_string(errno: i32) -> String { let mut buf = [0 as c_char; TMPBUF_SZ]; - extern { - fn strerror_r( - errnum: c_int, - buf: *mut c_char, - buflen: libc::size_t - ) -> c_int; + extern "C" { + fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int; } let p = buf.as_mut_ptr(); @@ -116,33 +114,41 @@ pub fn chdir(p: &path::Path) -> io::Result<()> { } pub struct SplitPaths<'a> { - iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, - fn(&'a [u8]) -> PathBuf>, + iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>, } pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> { fn bytes_to_path(b: &[u8]) -> PathBuf { PathBuf::from(<OsStr as OsStrExt>::from_bytes(b)) } - fn is_colon(b: &u8) -> bool { *b == b':' } + fn is_colon(b: &u8) -> bool { + *b == b':' + } let unparsed = unparsed.as_bytes(); SplitPaths { - iter: unparsed.split(is_colon as fn(&u8) -> bool) - .map(bytes_to_path as fn(&[u8]) -> PathBuf) + iter: unparsed + .split(is_colon as fn(&u8) -> bool) + .map(bytes_to_path as fn(&[u8]) -> PathBuf), } } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; - fn next(&mut self) -> Option<PathBuf> { self.iter.next() } - fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } + fn next(&mut self) -> Option<PathBuf> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> - where I: Iterator<Item=T>, T: AsRef<OsStr> +where + I: Iterator<Item = T>, + T: AsRef<OsStr>, { let mut joined = Vec::new(); let sep = b':'; @@ -153,7 +159,7 @@ pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> joined.push(sep) } if path.contains(&sep) { - return Err(JoinPathsError) + return Err(JoinPathsError); } joined.extend_from_slice(path); } @@ -167,7 +173,9 @@ impl fmt::Display for JoinPathsError { } impl StdError for JoinPathsError { - fn description(&self) -> &str { "failed to join paths" } + fn description(&self) -> &str { + "failed to join paths" + } } pub fn current_exe() -> io::Result<PathBuf> { @@ -189,12 +197,18 @@ pub struct Env { impl Iterator for Env { type Item = (OsString, OsString); - fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } - fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } + fn next(&mut self) -> Option<(OsString, OsString)> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } } pub unsafe fn environ() -> *mut *const *const c_char { - extern { static mut environ: *const *const c_char; } + extern "C" { + static mut environ: *const *const c_char; + } &mut environ } @@ -212,8 +226,7 @@ pub fn env() -> Env { let _guard = env_lock(); let mut environ = *environ(); if environ == ptr::null() { - panic!("os::env() failure getting env string from OS: {}", - io::Error::last_os_error()); + panic!("os::env() failure getting env string from OS: {}", io::Error::last_os_error()); } let mut result = Vec::new(); while *environ != ptr::null() { @@ -222,10 +235,7 @@ pub fn env() -> Env { } environ = environ.offset(1); } - return Env { - iter: result.into_iter(), - _dont_send_or_sync_me: PhantomData, - } + return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData }; } fn parse(input: &[u8]) -> Option<(OsString, OsString)> { @@ -237,10 +247,12 @@ pub fn env() -> Env { return None; } let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1); - pos.map(|p| ( - OsStringExt::from_vec(input[..p].to_vec()), - OsStringExt::from_vec(input[p+1..].to_vec()), - )) + pos.map(|p| { + ( + OsStringExt::from_vec(input[..p].to_vec()), + OsStringExt::from_vec(input[p + 1..].to_vec()), + ) + }) } } @@ -280,20 +292,15 @@ pub fn unsetenv(n: &OsStr) -> io::Result<()> { } pub fn page_size() -> usize { - unsafe { - libc::sysconf(libc::_SC_PAGESIZE) as usize - } + unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize } } pub fn temp_dir() -> PathBuf { - crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| { - PathBuf::from("/tmp") - }) + crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp")) } pub fn home_dir() -> Option<PathBuf> { - crate::env::var_os("HOME").or_else(|| None - ).map(PathBuf::from) + crate::env::var_os("HOME").or_else(|| None).map(PathBuf::from) } pub fn exit(code: i32) -> ! { diff --git a/src/libstd/sys/vxworks/process/process_vxworks.rs b/src/libstd/sys/vxworks/process/process_vxworks.rs index 79bfd770f8e..f926dfeb6d4 100644 --- a/src/libstd/sys/vxworks/process/process_vxworks.rs +++ b/src/libstd/sys/vxworks/process/process_vxworks.rs @@ -1,35 +1,39 @@ use crate::io::{self, Error, ErrorKind}; -use libc::{self, c_int, c_char}; -use libc::{RTP_ID}; use crate::sys; use crate::sys::cvt; use crate::sys::process::process_common::*; use crate::sys_common::thread; +use libc::RTP_ID; +use libc::{self, c_char, c_int}; //////////////////////////////////////////////////////////////////////////////// // Command //////////////////////////////////////////////////////////////////////////////// impl Command { - pub fn spawn(&mut self, default: Stdio, needs_stdin: bool) - -> io::Result<(Process, StdioPipes)> { - use crate::sys::{cvt_r}; + pub fn spawn( + &mut self, + default: Stdio, + needs_stdin: bool, + ) -> io::Result<(Process, StdioPipes)> { + use crate::sys::cvt_r; const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX"; let envp = self.capture_env(); if self.saw_nul() { - return Err(io::Error::new(ErrorKind::InvalidInput, - "nul byte found in provided data")); + return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data")); } let (ours, theirs) = self.setup_io(default, needs_stdin)?; let mut p = Process { pid: 0, status: None }; unsafe { macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => return Err(e.into()), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => return Err(e.into()), + } + }; } let mut orig_stdin = libc::STDIN_FILENO; @@ -53,7 +57,9 @@ impl Command { t!(cvt(libc::chdir(cwd.as_ptr()))); } - let c_envp = envp.as_ref().map(|c| c.as_ptr()) + let c_envp = envp + .as_ref() + .map(|c| c.as_ptr()) .unwrap_or_else(|| *sys::os::environ() as *const _); let stack_size = thread::min_stack(); @@ -61,13 +67,13 @@ impl Command { let _lock = sys::os::env_lock(); let ret = libc::rtpSpawn( - self.get_argv()[0], // executing program + self.get_argv()[0], // executing program self.get_argv().as_ptr() as *mut *const c_char, // argv c_envp as *mut *const c_char, - 100 as c_int, // initial priority - stack_size, // initial stack size. - 0, // options - 0 // task options + 100 as c_int, // initial priority + stack_size, // initial stack size. + 0, // options + 0, // task options ); // Because FileDesc was not used, each duplicated file descriptor @@ -127,8 +133,10 @@ impl Process { // and used for another process, and we probably shouldn't be killing // random processes, so just return an error. if self.status.is_some() { - Err(Error::new(ErrorKind::InvalidInput, - "invalid argument: can't kill an exited process")) + Err(Error::new( + ErrorKind::InvalidInput, + "invalid argument: can't kill an exited process", + )) } else { cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(|_| ()) } @@ -137,7 +145,7 @@ impl Process { pub fn wait(&mut self) -> io::Result<ExitStatus> { use crate::sys::cvt_r; if let Some(status) = self.status { - return Ok(status) + return Ok(status); } let mut status = 0 as c_int; cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?; @@ -147,12 +155,10 @@ impl Process { pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { if let Some(status) = self.status { - return Ok(Some(status)) + return Ok(Some(status)); } let mut status = 0 as c_int; - let pid = cvt(unsafe { - libc::waitpid(self.pid, &mut status, libc::WNOHANG) - })?; + let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?; if pid == 0 { Ok(None) } else { diff --git a/src/libstd/sys/wasi/ext/io.rs b/src/libstd/sys/wasi/ext/io.rs index be3c2d97a24..e849400d67e 100644 --- a/src/libstd/sys/wasi/ext/io.rs +++ b/src/libstd/sys/wasi/ext/io.rs @@ -4,8 +4,8 @@ use crate::fs; use crate::io; -use crate::sys; use crate::net; +use crate::sys; use crate::sys_common::{AsInner, FromInner, IntoInner}; /// Raw file descriptors. diff --git a/src/libstd/sys/wasi/io.rs b/src/libstd/sys/wasi/io.rs index 41a6e9783c0..ee20ea6dab8 100644 --- a/src/libstd/sys/wasi/io.rs +++ b/src/libstd/sys/wasi/io.rs @@ -10,13 +10,7 @@ pub struct IoSlice<'a> { impl<'a> IoSlice<'a> { #[inline] pub fn new(buf: &'a [u8]) -> IoSlice<'a> { - IoSlice { - vec: wasi::Ciovec { - buf: buf.as_ptr(), - buf_len: buf.len(), - }, - _p: PhantomData, - } + IoSlice { vec: wasi::Ciovec { buf: buf.as_ptr(), buf_len: buf.len() }, _p: PhantomData } } #[inline] @@ -33,9 +27,7 @@ impl<'a> IoSlice<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self.vec.buf as *const u8, self.vec.buf_len) - } + unsafe { slice::from_raw_parts(self.vec.buf as *const u8, self.vec.buf_len) } } } @@ -49,10 +41,7 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> { IoSliceMut { - vec: wasi::Iovec { - buf: buf.as_mut_ptr(), - buf_len: buf.len() - }, + vec: wasi::Iovec { buf: buf.as_mut_ptr(), buf_len: buf.len() }, _p: PhantomData, } } @@ -71,15 +60,11 @@ impl<'a> IoSliceMut<'a> { #[inline] pub fn as_slice(&self) -> &[u8] { - unsafe { - slice::from_raw_parts(self.vec.buf as *const u8, self.vec.buf_len) - } + unsafe { slice::from_raw_parts(self.vec.buf as *const u8, self.vec.buf_len) } } #[inline] pub fn as_mut_slice(&mut self) -> &mut [u8] { - unsafe { - slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.buf_len) - } + unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.buf_len) } } } diff --git a/src/libstd/sys/wasi/mod.rs b/src/libstd/sys/wasi/mod.rs index 83f98a19f47..241d499ca3b 100644 --- a/src/libstd/sys/wasi/mod.rs +++ b/src/libstd/sys/wasi/mod.rs @@ -27,14 +27,17 @@ pub mod condvar; pub mod env; pub mod fd; pub mod fs; +pub mod io; #[path = "../wasm/memchr.rs"] pub mod memchr; #[path = "../wasm/mutex.rs"] pub mod mutex; pub mod net; -pub mod io; pub mod os; pub use crate::sys_common::os_str_bytes as os_str; +pub mod ext; +#[path = "../wasm/fast_thread_local.rs"] +pub mod fast_thread_local; pub mod path; pub mod pipe; pub mod process; @@ -46,24 +49,17 @@ pub mod stdio; pub mod thread; #[path = "../wasm/thread_local.rs"] pub mod thread_local; -#[path = "../wasm/fast_thread_local.rs"] -pub mod fast_thread_local; pub mod time; -pub mod ext; #[cfg(not(test))] -pub fn init() { -} +pub fn init() {} pub fn unsupported<T>() -> std_io::Result<T> { Err(unsupported_err()) } pub fn unsupported_err() -> std_io::Error { - std_io::Error::new( - std_io::ErrorKind::Other, - "operation not supported on wasm yet", - ) + std_io::Error::new(std_io::ErrorKind::Other, "operation not supported on wasm yet") } pub fn decode_error_kind(errno: i32) -> std_io::ErrorKind { @@ -101,7 +97,7 @@ pub unsafe fn strlen(mut s: *const c_char) -> usize { n += 1; s = s.offset(1); } - return n + return n; } pub unsafe fn abort_internal() -> ! { @@ -115,7 +111,7 @@ pub fn hashmap_random_keys() -> (u64, u64) { let len = mem::size_of_val(&ret); wasi::random_get(base, len).expect("random_get failure"); } - return ret + return ret; } fn err2io(err: wasi::Error) -> std_io::Error { diff --git a/src/libstd/sys/wasm/alloc.rs b/src/libstd/sys/wasm/alloc.rs index 05e55334ac0..32b8b5bdaea 100644 --- a/src/libstd/sys/wasm/alloc.rs +++ b/src/libstd/sys/wasm/alloc.rs @@ -58,7 +58,7 @@ mod lock { pub fn lock() -> DropLock { loop { if LOCKED.swap(1, SeqCst) == 0 { - return DropLock + return DropLock; } // Ok so here's where things get a little depressing. At this point // in time we need to synchronously acquire a lock, but we're diff --git a/src/libstd/sys/wasm/condvar.rs b/src/libstd/sys/wasm/condvar.rs index 9c7cc3c63b1..9fd781c7282 100644 --- a/src/libstd/sys/wasm/condvar.rs +++ b/src/libstd/sys/wasm/condvar.rs @@ -1,23 +1,21 @@ use crate::sys::mutex::Mutex; use crate::time::Duration; -pub struct Condvar { } +pub struct Condvar {} impl Condvar { pub const fn new() -> Condvar { - Condvar { } + Condvar {} } #[inline] pub unsafe fn init(&mut self) {} #[inline] - pub unsafe fn notify_one(&self) { - } + pub unsafe fn notify_one(&self) {} #[inline] - pub unsafe fn notify_all(&self) { - } + pub unsafe fn notify_all(&self) {} pub unsafe fn wait(&self, _mutex: &Mutex) { panic!("can't block with web assembly") @@ -28,6 +26,5 @@ impl Condvar { } #[inline] - pub unsafe fn destroy(&self) { - } + pub unsafe fn destroy(&self) {} } diff --git a/src/libstd/sys/wasm/condvar_atomics.rs b/src/libstd/sys/wasm/condvar_atomics.rs index f452bbd3487..a4021c0ee83 100644 --- a/src/libstd/sys/wasm/condvar_atomics.rs +++ b/src/libstd/sys/wasm/condvar_atomics.rs @@ -78,7 +78,7 @@ impl Condvar { // `false` as we weren't actually notified. let ret = wasm32::i32_atomic_wait(self.ptr(), ticket, nanos as i64) != 2; mutex.lock(); - return ret + return ret; } #[inline] diff --git a/src/libstd/sys/wasm/fast_thread_local.rs b/src/libstd/sys/wasm/fast_thread_local.rs index 9bdc26ae7d6..85d66098302 100644 --- a/src/libstd/sys/wasm/fast_thread_local.rs +++ b/src/libstd/sys/wasm/fast_thread_local.rs @@ -1,6 +1,6 @@ #![unstable(feature = "thread_local_internals", issue = "none")] -pub unsafe fn register_dtor(_t: *mut u8, _dtor: unsafe extern fn(*mut u8)) { +pub unsafe fn register_dtor(_t: *mut u8, _dtor: unsafe extern "C" fn(*mut u8)) { // FIXME: right now there is no concept of "thread exit", but this is likely // going to show up at some point in the form of an exported symbol that the // wasm runtime is going to be expected to call. For now we basically just diff --git a/src/libstd/sys/wasm/mod.rs b/src/libstd/sys/wasm/mod.rs index de0bb38dc31..c115f756450 100644 --- a/src/libstd/sys/wasm/mod.rs +++ b/src/libstd/sys/wasm/mod.rs @@ -20,6 +20,7 @@ pub mod alloc; pub mod args; pub mod cmath; pub mod env; +pub mod fast_thread_local; pub mod fs; pub mod io; pub mod memchr; @@ -29,11 +30,10 @@ pub mod path; pub mod pipe; pub mod process; pub mod stack_overflow; -pub mod thread; -pub mod time; pub mod stdio; +pub mod thread; pub mod thread_local; -pub mod fast_thread_local; +pub mod time; pub use crate::sys_common::os_str_bytes as os_str; @@ -53,16 +53,14 @@ cfg_if::cfg_if! { } #[cfg(not(test))] -pub fn init() { -} +pub fn init() {} pub fn unsupported<T>() -> crate::io::Result<T> { Err(unsupported_err()) } pub fn unsupported_err() -> crate::io::Error { - crate::io::Error::new(crate::io::ErrorKind::Other, - "operation not supported on wasm yet") + crate::io::Error::new(crate::io::ErrorKind::Other, "operation not supported on wasm yet") } pub fn decode_error_kind(_code: i32) -> crate::io::ErrorKind { @@ -80,7 +78,7 @@ pub unsafe fn strlen(mut s: *const c_char) -> usize { n += 1; s = s.offset(1); } - return n + return n; } pub unsafe fn abort_internal() -> ! { diff --git a/src/libstd/sys/wasm/mutex.rs b/src/libstd/sys/wasm/mutex.rs index 9d713e9b439..07238d08730 100644 --- a/src/libstd/sys/wasm/mutex.rs +++ b/src/libstd/sys/wasm/mutex.rs @@ -13,8 +13,7 @@ impl Mutex { } #[inline] - pub unsafe fn init(&mut self) { - } + pub unsafe fn init(&mut self) {} #[inline] pub unsafe fn lock(&self) { @@ -40,18 +39,16 @@ impl Mutex { } #[inline] - pub unsafe fn destroy(&self) { - } + pub unsafe fn destroy(&self) {} } // All empty stubs because wasm has no threads yet, so lock acquisition always // succeeds. -pub struct ReentrantMutex { -} +pub struct ReentrantMutex {} impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { - ReentrantMutex { } + ReentrantMutex {} } pub unsafe fn init(&mut self) {} diff --git a/src/libstd/sys/wasm/mutex_atomics.rs b/src/libstd/sys/wasm/mutex_atomics.rs index cddd584dd22..90c628a19c2 100644 --- a/src/libstd/sys/wasm/mutex_atomics.rs +++ b/src/libstd/sys/wasm/mutex_atomics.rs @@ -1,7 +1,7 @@ use crate::arch::wasm32; use crate::cell::UnsafeCell; use crate::mem; -use crate::sync::atomic::{AtomicUsize, AtomicU32, Ordering::SeqCst}; +use crate::sync::atomic::{AtomicU32, AtomicUsize, Ordering::SeqCst}; use crate::sys::thread; pub struct Mutex { @@ -81,10 +81,7 @@ unsafe impl Sync for ReentrantMutex {} impl ReentrantMutex { pub unsafe fn uninitialized() -> ReentrantMutex { - ReentrantMutex { - owner: AtomicU32::new(0), - recursions: UnsafeCell::new(0), - } + ReentrantMutex { owner: AtomicU32::new(0), recursions: UnsafeCell::new(0) } } pub unsafe fn init(&mut self) { diff --git a/src/libstd/sys/wasm/rwlock.rs b/src/libstd/sys/wasm/rwlock.rs index a2b07c7fa1f..a59944482e9 100644 --- a/src/libstd/sys/wasm/rwlock.rs +++ b/src/libstd/sys/wasm/rwlock.rs @@ -9,9 +9,7 @@ unsafe impl Sync for RWLock {} // no threads on wasm impl RWLock { pub const fn new() -> RWLock { - RWLock { - mode: UnsafeCell::new(0), - } + RWLock { mode: UnsafeCell::new(0) } } #[inline] @@ -67,6 +65,5 @@ impl RWLock { } #[inline] - pub unsafe fn destroy(&self) { - } + pub unsafe fn destroy(&self) {} } diff --git a/src/libstd/sys/wasm/rwlock_atomics.rs b/src/libstd/sys/wasm/rwlock_atomics.rs index c705568cec9..06442e925f4 100644 --- a/src/libstd/sys/wasm/rwlock_atomics.rs +++ b/src/libstd/sys/wasm/rwlock_atomics.rs @@ -1,6 +1,6 @@ use crate::cell::UnsafeCell; -use crate::sys::mutex::Mutex; use crate::sys::condvar::Condvar; +use crate::sys::mutex::Mutex; pub struct RWLock { lock: Mutex, @@ -27,11 +27,7 @@ unsafe impl Sync for RWLock {} impl RWLock { pub const fn new() -> RWLock { - RWLock { - lock: Mutex::new(), - cond: Condvar::new(), - state: UnsafeCell::new(State::Unlocked), - } + RWLock { lock: Mutex::new(), cond: Condvar::new(), state: UnsafeCell::new(State::Unlocked) } } #[inline] @@ -48,7 +44,7 @@ impl RWLock { self.lock.lock(); let ok = (*self.state.get()).inc_readers(); self.lock.unlock(); - return ok + return ok; } #[inline] @@ -65,7 +61,7 @@ impl RWLock { self.lock.lock(); let ok = (*self.state.get()).inc_writers(); self.lock.unlock(); - return ok + return ok; } #[inline] @@ -106,7 +102,7 @@ impl State { *cnt += 1; true } - State::Writing => false + State::Writing => false, } } @@ -116,8 +112,7 @@ impl State { *self = State::Writing; true } - State::Reading(_) | - State::Writing => false + State::Reading(_) | State::Writing => false, } } @@ -127,8 +122,7 @@ impl State { *cnt -= 1; *cnt == 0 } - State::Unlocked | - State::Writing => invalid(), + State::Unlocked | State::Writing => invalid(), }; if zero { *self = State::Unlocked; @@ -139,8 +133,7 @@ impl State { fn dec_writers(&mut self) { match *self { State::Writing => {} - State::Unlocked | - State::Reading(_) => invalid(), + State::Unlocked | State::Reading(_) => invalid(), } *self = State::Unlocked; } diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index 4cdac89a864..4d377341be3 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -4,13 +4,13 @@ #![cfg_attr(test, allow(dead_code))] #![unstable(issue = "none", feature = "windows_c")] -use crate::os::raw::{c_int, c_uint, c_ulong, c_long, c_longlong, c_ushort, c_char}; +use crate::os::raw::{c_char, c_int, c_long, c_longlong, c_uint, c_ulong, c_ushort}; use crate::ptr; -use libc::{wchar_t, size_t, c_void}; +use libc::{c_void, size_t, wchar_t}; -pub use self::FILE_INFO_BY_HANDLE_CLASS::*; pub use self::EXCEPTION_DISPOSITION::*; +pub use self::FILE_INFO_BY_HANDLE_CLASS::*; pub type DWORD = c_ulong; pub type HANDLE = LPVOID; @@ -88,11 +88,12 @@ pub const SYNCHRONIZE: DWORD = 0x00100000; pub const GENERIC_READ: DWORD = 0x80000000; pub const GENERIC_WRITE: DWORD = 0x40000000; pub const STANDARD_RIGHTS_WRITE: DWORD = READ_CONTROL; -pub const FILE_GENERIC_WRITE: DWORD = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | - FILE_WRITE_ATTRIBUTES | - FILE_WRITE_EA | - FILE_APPEND_DATA | - SYNCHRONIZE; +pub const FILE_GENERIC_WRITE: DWORD = STANDARD_RIGHTS_WRITE + | FILE_WRITE_DATA + | FILE_WRITE_ATTRIBUTES + | FILE_WRITE_EA + | FILE_APPEND_DATA + | SYNCHRONIZE; pub const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000; pub const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000; @@ -115,7 +116,9 @@ pub struct WIN32_FIND_DATAW { pub cAlternateFileName: [wchar_t; 14], } impl Clone for WIN32_FIND_DATAW { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub const WSA_FLAG_OVERLAPPED: DWORD = 0x01; @@ -195,9 +198,7 @@ pub const INFINITE: DWORD = !0; pub const DUPLICATE_SAME_ACCESS: DWORD = 0x00000002; -pub const CONDITION_VARIABLE_INIT: CONDITION_VARIABLE = CONDITION_VARIABLE { - ptr: ptr::null_mut(), -}; +pub const CONDITION_VARIABLE_INIT: CONDITION_VARIABLE = CONDITION_VARIABLE { ptr: ptr::null_mut() }; pub const SRWLOCK_INIT: SRWLOCK = SRWLOCK { ptr: ptr::null_mut() }; pub const DETACHED_PROCESS: DWORD = 0x00000008; @@ -338,28 +339,28 @@ pub struct WIN32_FILE_ATTRIBUTE_DATA { #[repr(C)] #[allow(dead_code)] // we only use some variants pub enum FILE_INFO_BY_HANDLE_CLASS { - FileBasicInfo = 0, - FileStandardInfo = 1, - FileNameInfo = 2, - FileRenameInfo = 3, - FileDispositionInfo = 4, - FileAllocationInfo = 5, - FileEndOfFileInfo = 6, - FileStreamInfo = 7, - FileCompressionInfo = 8, - FileAttributeTagInfo = 9, - FileIdBothDirectoryInfo = 10, // 0xA - FileIdBothDirectoryRestartInfo = 11, // 0xB - FileIoPriorityHintInfo = 12, // 0xC - FileRemoteProtocolInfo = 13, // 0xD - FileFullDirectoryInfo = 14, // 0xE - FileFullDirectoryRestartInfo = 15, // 0xF - FileStorageInfo = 16, // 0x10 - FileAlignmentInfo = 17, // 0x11 - FileIdInfo = 18, // 0x12 - FileIdExtdDirectoryInfo = 19, // 0x13 - FileIdExtdDirectoryRestartInfo = 20, // 0x14 - MaximumFileInfoByHandlesClass + FileBasicInfo = 0, + FileStandardInfo = 1, + FileNameInfo = 2, + FileRenameInfo = 3, + FileDispositionInfo = 4, + FileAllocationInfo = 5, + FileEndOfFileInfo = 6, + FileStreamInfo = 7, + FileCompressionInfo = 8, + FileAttributeTagInfo = 9, + FileIdBothDirectoryInfo = 10, // 0xA + FileIdBothDirectoryRestartInfo = 11, // 0xB + FileIoPriorityHintInfo = 12, // 0xC + FileRemoteProtocolInfo = 13, // 0xD + FileFullDirectoryInfo = 14, // 0xE + FileFullDirectoryRestartInfo = 15, // 0xF + FileStorageInfo = 16, // 0x10 + FileAlignmentInfo = 17, // 0x11 + FileIdInfo = 18, // 0x12 + FileIdExtdDirectoryInfo = 19, // 0x13 + FileIdExtdDirectoryRestartInfo = 20, // 0x14 + MaximumFileInfoByHandlesClass, } #[repr(C)] @@ -403,22 +404,28 @@ pub struct MOUNT_POINT_REPARSE_BUFFER { pub PathBuffer: WCHAR, } -pub type LPPROGRESS_ROUTINE = crate::option::Option<unsafe extern "system" fn( - TotalFileSize: LARGE_INTEGER, - TotalBytesTransferred: LARGE_INTEGER, - StreamSize: LARGE_INTEGER, - StreamBytesTransferred: LARGE_INTEGER, - dwStreamNumber: DWORD, - dwCallbackReason: DWORD, - hSourceFile: HANDLE, - hDestinationFile: HANDLE, - lpData: LPVOID, -) -> DWORD>; +pub type LPPROGRESS_ROUTINE = crate::option::Option< + unsafe extern "system" fn( + TotalFileSize: LARGE_INTEGER, + TotalBytesTransferred: LARGE_INTEGER, + StreamSize: LARGE_INTEGER, + StreamBytesTransferred: LARGE_INTEGER, + dwStreamNumber: DWORD, + dwCallbackReason: DWORD, + hSourceFile: HANDLE, + hDestinationFile: HANDLE, + lpData: LPVOID, + ) -> DWORD, +>; #[repr(C)] -pub struct CONDITION_VARIABLE { pub ptr: LPVOID } +pub struct CONDITION_VARIABLE { + pub ptr: LPVOID, +} #[repr(C)] -pub struct SRWLOCK { pub ptr: LPVOID } +pub struct SRWLOCK { + pub ptr: LPVOID, +} #[repr(C)] pub struct CRITICAL_SECTION { CriticalSectionDebug: LPVOID, @@ -426,7 +433,7 @@ pub struct CRITICAL_SECTION { RecursionCount: LONG, OwningThread: HANDLE, LockSemaphore: HANDLE, - SpinCount: ULONG_PTR + SpinCount: ULONG_PTR, } #[repr(C)] @@ -580,7 +587,7 @@ pub enum EXCEPTION_DISPOSITION { ExceptionContinueExecution, ExceptionContinueSearch, ExceptionNestedException, - ExceptionCollidedUnwind + ExceptionCollidedUnwind, } #[repr(C)] @@ -732,37 +739,41 @@ if #[cfg(target_vendor = "uwp")] { // Shared between Desktop & UWP extern "system" { - pub fn WSAStartup(wVersionRequested: WORD, - lpWSAData: LPWSADATA) -> c_int; + pub fn WSAStartup(wVersionRequested: WORD, lpWSAData: LPWSADATA) -> c_int; pub fn WSACleanup() -> c_int; pub fn WSAGetLastError() -> c_int; - pub fn WSADuplicateSocketW(s: SOCKET, - dwProcessId: DWORD, - lpProtocolInfo: LPWSAPROTOCOL_INFO) - -> c_int; - pub fn WSASend(s: SOCKET, - lpBuffers: LPWSABUF, - dwBufferCount: DWORD, - lpNumberOfBytesSent: LPDWORD, - dwFlags: DWORD, - lpOverlapped: LPWSAOVERLAPPED, - lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE) - -> c_int; - pub fn WSARecv(s: SOCKET, - lpBuffers: LPWSABUF, - dwBufferCount: DWORD, - lpNumberOfBytesRecvd: LPDWORD, - lpFlags: LPDWORD, - lpOverlapped: LPWSAOVERLAPPED, - lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE) - -> c_int; + pub fn WSADuplicateSocketW( + s: SOCKET, + dwProcessId: DWORD, + lpProtocolInfo: LPWSAPROTOCOL_INFO, + ) -> c_int; + pub fn WSASend( + s: SOCKET, + lpBuffers: LPWSABUF, + dwBufferCount: DWORD, + lpNumberOfBytesSent: LPDWORD, + dwFlags: DWORD, + lpOverlapped: LPWSAOVERLAPPED, + lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> c_int; + pub fn WSARecv( + s: SOCKET, + lpBuffers: LPWSABUF, + dwBufferCount: DWORD, + lpNumberOfBytesRecvd: LPDWORD, + lpFlags: LPDWORD, + lpOverlapped: LPWSAOVERLAPPED, + lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> c_int; pub fn GetCurrentProcessId() -> DWORD; - pub fn WSASocketW(af: c_int, - kind: c_int, - protocol: c_int, - lpProtocolInfo: LPWSAPROTOCOL_INFO, - g: GROUP, - dwFlags: DWORD) -> SOCKET; + pub fn WSASocketW( + af: c_int, + kind: c_int, + protocol: c_int, + lpProtocolInfo: LPWSAPROTOCOL_INFO, + g: GROUP, + dwFlags: DWORD, + ) -> SOCKET; pub fn ioctlsocket(s: SOCKET, cmd: c_long, argp: *mut c_ulong) -> c_int; pub fn InitializeCriticalSection(CriticalSection: *mut CRITICAL_SECTION); pub fn EnterCriticalSection(CriticalSection: *mut CRITICAL_SECTION); @@ -771,227 +782,231 @@ extern "system" { pub fn DeleteCriticalSection(CriticalSection: *mut CRITICAL_SECTION); pub fn RemoveDirectoryW(lpPathName: LPCWSTR) -> BOOL; - pub fn SetFileAttributesW(lpFileName: LPCWSTR, - dwFileAttributes: DWORD) -> BOOL; + pub fn SetFileAttributesW(lpFileName: LPCWSTR, dwFileAttributes: DWORD) -> BOOL; pub fn SetLastError(dwErrCode: DWORD); pub fn GetCommandLineW() -> *mut LPCWSTR; - pub fn GetTempPathW(nBufferLength: DWORD, - lpBuffer: LPCWSTR) -> DWORD; + pub fn GetTempPathW(nBufferLength: DWORD, lpBuffer: LPCWSTR) -> DWORD; pub fn GetCurrentProcess() -> HANDLE; pub fn GetCurrentThread() -> HANDLE; pub fn GetStdHandle(which: DWORD) -> HANDLE; pub fn ExitProcess(uExitCode: c_uint) -> !; - pub fn DeviceIoControl(hDevice: HANDLE, - dwIoControlCode: DWORD, - lpInBuffer: LPVOID, - nInBufferSize: DWORD, - lpOutBuffer: LPVOID, - nOutBufferSize: DWORD, - lpBytesReturned: LPDWORD, - lpOverlapped: LPOVERLAPPED) -> BOOL; - pub fn CreateThread(lpThreadAttributes: LPSECURITY_ATTRIBUTES, - dwStackSize: SIZE_T, - lpStartAddress: extern "system" fn(*mut c_void) - -> DWORD, - lpParameter: LPVOID, - dwCreationFlags: DWORD, - lpThreadId: LPDWORD) -> HANDLE; - pub fn WaitForSingleObject(hHandle: HANDLE, - dwMilliseconds: DWORD) -> DWORD; + pub fn DeviceIoControl( + hDevice: HANDLE, + dwIoControlCode: DWORD, + lpInBuffer: LPVOID, + nInBufferSize: DWORD, + lpOutBuffer: LPVOID, + nOutBufferSize: DWORD, + lpBytesReturned: LPDWORD, + lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn CreateThread( + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + dwStackSize: SIZE_T, + lpStartAddress: extern "system" fn(*mut c_void) -> DWORD, + lpParameter: LPVOID, + dwCreationFlags: DWORD, + lpThreadId: LPDWORD, + ) -> HANDLE; + pub fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; pub fn SwitchToThread() -> BOOL; pub fn Sleep(dwMilliseconds: DWORD); pub fn GetProcessId(handle: HANDLE) -> DWORD; - pub fn CopyFileExW(lpExistingFileName: LPCWSTR, - lpNewFileName: LPCWSTR, - lpProgressRoutine: LPPROGRESS_ROUTINE, - lpData: LPVOID, - pbCancel: LPBOOL, - dwCopyFlags: DWORD) -> BOOL; - pub fn FormatMessageW(flags: DWORD, - lpSrc: LPVOID, - msgId: DWORD, - langId: DWORD, - buf: LPWSTR, - nsize: DWORD, - args: *const c_void) - -> DWORD; + pub fn CopyFileExW( + lpExistingFileName: LPCWSTR, + lpNewFileName: LPCWSTR, + lpProgressRoutine: LPPROGRESS_ROUTINE, + lpData: LPVOID, + pbCancel: LPBOOL, + dwCopyFlags: DWORD, + ) -> BOOL; + pub fn FormatMessageW( + flags: DWORD, + lpSrc: LPVOID, + msgId: DWORD, + langId: DWORD, + buf: LPWSTR, + nsize: DWORD, + args: *const c_void, + ) -> DWORD; pub fn TlsAlloc() -> DWORD; pub fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID; pub fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL; pub fn GetLastError() -> DWORD; pub fn QueryPerformanceFrequency(lpFrequency: *mut LARGE_INTEGER) -> BOOL; - pub fn QueryPerformanceCounter(lpPerformanceCount: *mut LARGE_INTEGER) - -> BOOL; + pub fn QueryPerformanceCounter(lpPerformanceCount: *mut LARGE_INTEGER) -> BOOL; pub fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: LPDWORD) -> BOOL; pub fn TerminateProcess(hProcess: HANDLE, uExitCode: UINT) -> BOOL; - pub fn CreateProcessW(lpApplicationName: LPCWSTR, - lpCommandLine: LPWSTR, - lpProcessAttributes: LPSECURITY_ATTRIBUTES, - lpThreadAttributes: LPSECURITY_ATTRIBUTES, - bInheritHandles: BOOL, - dwCreationFlags: DWORD, - lpEnvironment: LPVOID, - lpCurrentDirectory: LPCWSTR, - lpStartupInfo: LPSTARTUPINFO, - lpProcessInformation: LPPROCESS_INFORMATION) - -> BOOL; + pub fn CreateProcessW( + lpApplicationName: LPCWSTR, + lpCommandLine: LPWSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCWSTR, + lpStartupInfo: LPSTARTUPINFO, + lpProcessInformation: LPPROCESS_INFORMATION, + ) -> BOOL; pub fn GetEnvironmentVariableW(n: LPCWSTR, v: LPWSTR, nsize: DWORD) -> DWORD; pub fn SetEnvironmentVariableW(n: LPCWSTR, v: LPCWSTR) -> BOOL; pub fn GetEnvironmentStringsW() -> LPWCH; pub fn FreeEnvironmentStringsW(env_ptr: LPWCH) -> BOOL; - pub fn GetModuleFileNameW(hModule: HMODULE, - lpFilename: LPWSTR, - nSize: DWORD) - -> DWORD; - pub fn CreateDirectoryW(lpPathName: LPCWSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES) - -> BOOL; + pub fn GetModuleFileNameW(hModule: HMODULE, lpFilename: LPWSTR, nSize: DWORD) -> DWORD; + pub fn CreateDirectoryW( + lpPathName: LPCWSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> BOOL; pub fn DeleteFileW(lpPathName: LPCWSTR) -> BOOL; pub fn GetCurrentDirectoryW(nBufferLength: DWORD, lpBuffer: LPWSTR) -> DWORD; pub fn SetCurrentDirectoryW(lpPathName: LPCWSTR) -> BOOL; - pub fn WideCharToMultiByte(CodePage: UINT, - dwFlags: DWORD, - lpWideCharStr: LPCWSTR, - cchWideChar: c_int, - lpMultiByteStr: LPSTR, - cbMultiByte: c_int, - lpDefaultChar: LPCSTR, - lpUsedDefaultChar: LPBOOL) -> c_int; + pub fn WideCharToMultiByte( + CodePage: UINT, + dwFlags: DWORD, + lpWideCharStr: LPCWSTR, + cchWideChar: c_int, + lpMultiByteStr: LPSTR, + cbMultiByte: c_int, + lpDefaultChar: LPCSTR, + lpUsedDefaultChar: LPBOOL, + ) -> c_int; pub fn closesocket(socket: SOCKET) -> c_int; - pub fn recv(socket: SOCKET, buf: *mut c_void, len: c_int, - flags: c_int) -> c_int; - pub fn send(socket: SOCKET, buf: *const c_void, len: c_int, - flags: c_int) -> c_int; - pub fn recvfrom(socket: SOCKET, - buf: *mut c_void, - len: c_int, - flags: c_int, - addr: *mut SOCKADDR, - addrlen: *mut c_int) - -> c_int; - pub fn sendto(socket: SOCKET, - buf: *const c_void, - len: c_int, - flags: c_int, - addr: *const SOCKADDR, - addrlen: c_int) - -> c_int; + pub fn recv(socket: SOCKET, buf: *mut c_void, len: c_int, flags: c_int) -> c_int; + pub fn send(socket: SOCKET, buf: *const c_void, len: c_int, flags: c_int) -> c_int; + pub fn recvfrom( + socket: SOCKET, + buf: *mut c_void, + len: c_int, + flags: c_int, + addr: *mut SOCKADDR, + addrlen: *mut c_int, + ) -> c_int; + pub fn sendto( + socket: SOCKET, + buf: *const c_void, + len: c_int, + flags: c_int, + addr: *const SOCKADDR, + addrlen: c_int, + ) -> c_int; pub fn shutdown(socket: SOCKET, how: c_int) -> c_int; - pub fn accept(socket: SOCKET, - address: *mut SOCKADDR, - address_len: *mut c_int) - -> SOCKET; - pub fn DuplicateHandle(hSourceProcessHandle: HANDLE, - hSourceHandle: HANDLE, - hTargetProcessHandle: HANDLE, - lpTargetHandle: LPHANDLE, - dwDesiredAccess: DWORD, - bInheritHandle: BOOL, - dwOptions: DWORD) - -> BOOL; - pub fn ReadFile(hFile: HANDLE, - lpBuffer: LPVOID, - nNumberOfBytesToRead: DWORD, - lpNumberOfBytesRead: LPDWORD, - lpOverlapped: LPOVERLAPPED) - -> BOOL; - pub fn WriteFile(hFile: HANDLE, - lpBuffer: LPVOID, - nNumberOfBytesToWrite: DWORD, - lpNumberOfBytesWritten: LPDWORD, - lpOverlapped: LPOVERLAPPED) - -> BOOL; + pub fn accept(socket: SOCKET, address: *mut SOCKADDR, address_len: *mut c_int) -> SOCKET; + pub fn DuplicateHandle( + hSourceProcessHandle: HANDLE, + hSourceHandle: HANDLE, + hTargetProcessHandle: HANDLE, + lpTargetHandle: LPHANDLE, + dwDesiredAccess: DWORD, + bInheritHandle: BOOL, + dwOptions: DWORD, + ) -> BOOL; + pub fn ReadFile( + hFile: HANDLE, + lpBuffer: LPVOID, + nNumberOfBytesToRead: DWORD, + lpNumberOfBytesRead: LPDWORD, + lpOverlapped: LPOVERLAPPED, + ) -> BOOL; + pub fn WriteFile( + hFile: HANDLE, + lpBuffer: LPVOID, + nNumberOfBytesToWrite: DWORD, + lpNumberOfBytesWritten: LPDWORD, + lpOverlapped: LPOVERLAPPED, + ) -> BOOL; pub fn CloseHandle(hObject: HANDLE) -> BOOL; - pub fn MoveFileExW(lpExistingFileName: LPCWSTR, - lpNewFileName: LPCWSTR, - dwFlags: DWORD) - -> BOOL; - pub fn SetFilePointerEx(hFile: HANDLE, - liDistanceToMove: LARGE_INTEGER, - lpNewFilePointer: PLARGE_INTEGER, - dwMoveMethod: DWORD) - -> BOOL; + pub fn MoveFileExW(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, dwFlags: DWORD) + -> BOOL; + pub fn SetFilePointerEx( + hFile: HANDLE, + liDistanceToMove: LARGE_INTEGER, + lpNewFilePointer: PLARGE_INTEGER, + dwMoveMethod: DWORD, + ) -> BOOL; pub fn FlushFileBuffers(hFile: HANDLE) -> BOOL; - pub fn CreateFileW(lpFileName: LPCWSTR, - dwDesiredAccess: DWORD, - dwShareMode: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - dwCreationDisposition: DWORD, - dwFlagsAndAttributes: DWORD, - hTemplateFile: HANDLE) - -> HANDLE; - - pub fn FindFirstFileW(fileName: LPCWSTR, - findFileData: LPWIN32_FIND_DATAW) - -> HANDLE; - pub fn FindNextFileW(findFile: HANDLE, findFileData: LPWIN32_FIND_DATAW) - -> BOOL; + pub fn CreateFileW( + lpFileName: LPCWSTR, + dwDesiredAccess: DWORD, + dwShareMode: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, + hTemplateFile: HANDLE, + ) -> HANDLE; + + pub fn FindFirstFileW(fileName: LPCWSTR, findFileData: LPWIN32_FIND_DATAW) -> HANDLE; + pub fn FindNextFileW(findFile: HANDLE, findFileData: LPWIN32_FIND_DATAW) -> BOOL; pub fn FindClose(findFile: HANDLE) -> BOOL; - pub fn getsockopt(s: SOCKET, - level: c_int, - optname: c_int, - optval: *mut c_char, - optlen: *mut c_int) - -> c_int; - pub fn setsockopt(s: SOCKET, - level: c_int, - optname: c_int, - optval: *const c_void, - optlen: c_int) - -> c_int; - pub fn getsockname(socket: SOCKET, - address: *mut SOCKADDR, - address_len: *mut c_int) - -> c_int; - pub fn getpeername(socket: SOCKET, - address: *mut SOCKADDR, - address_len: *mut c_int) - -> c_int; - pub fn bind(socket: SOCKET, address: *const SOCKADDR, - address_len: socklen_t) -> c_int; + pub fn getsockopt( + s: SOCKET, + level: c_int, + optname: c_int, + optval: *mut c_char, + optlen: *mut c_int, + ) -> c_int; + pub fn setsockopt( + s: SOCKET, + level: c_int, + optname: c_int, + optval: *const c_void, + optlen: c_int, + ) -> c_int; + pub fn getsockname(socket: SOCKET, address: *mut SOCKADDR, address_len: *mut c_int) -> c_int; + pub fn getpeername(socket: SOCKET, address: *mut SOCKADDR, address_len: *mut c_int) -> c_int; + pub fn bind(socket: SOCKET, address: *const SOCKADDR, address_len: socklen_t) -> c_int; pub fn listen(socket: SOCKET, backlog: c_int) -> c_int; - pub fn connect(socket: SOCKET, address: *const SOCKADDR, len: c_int) - -> c_int; - pub fn getaddrinfo(node: *const c_char, service: *const c_char, - hints: *const ADDRINFOA, - res: *mut *mut ADDRINFOA) -> c_int; + pub fn connect(socket: SOCKET, address: *const SOCKADDR, len: c_int) -> c_int; + pub fn getaddrinfo( + node: *const c_char, + service: *const c_char, + hints: *const ADDRINFOA, + res: *mut *mut ADDRINFOA, + ) -> c_int; pub fn freeaddrinfo(res: *mut ADDRINFOA); - pub fn GetProcAddress(handle: HMODULE, - name: LPCSTR) -> *mut c_void; + pub fn GetProcAddress(handle: HMODULE, name: LPCSTR) -> *mut c_void; pub fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; pub fn GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: LPFILETIME); - pub fn CreateEventW(lpEventAttributes: LPSECURITY_ATTRIBUTES, - bManualReset: BOOL, - bInitialState: BOOL, - lpName: LPCWSTR) -> HANDLE; - pub fn WaitForMultipleObjects(nCount: DWORD, - lpHandles: *const HANDLE, - bWaitAll: BOOL, - dwMilliseconds: DWORD) -> DWORD; - pub fn CreateNamedPipeW(lpName: LPCWSTR, - dwOpenMode: DWORD, - dwPipeMode: DWORD, - nMaxInstances: DWORD, - nOutBufferSize: DWORD, - nInBufferSize: DWORD, - nDefaultTimeOut: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES) - -> HANDLE; + pub fn CreateEventW( + lpEventAttributes: LPSECURITY_ATTRIBUTES, + bManualReset: BOOL, + bInitialState: BOOL, + lpName: LPCWSTR, + ) -> HANDLE; + pub fn WaitForMultipleObjects( + nCount: DWORD, + lpHandles: *const HANDLE, + bWaitAll: BOOL, + dwMilliseconds: DWORD, + ) -> DWORD; + pub fn CreateNamedPipeW( + lpName: LPCWSTR, + dwOpenMode: DWORD, + dwPipeMode: DWORD, + nMaxInstances: DWORD, + nOutBufferSize: DWORD, + nInBufferSize: DWORD, + nDefaultTimeOut: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + ) -> HANDLE; pub fn CancelIo(handle: HANDLE) -> BOOL; - pub fn GetOverlappedResult(hFile: HANDLE, - lpOverlapped: LPOVERLAPPED, - lpNumberOfBytesTransferred: LPDWORD, - bWait: BOOL) -> BOOL; - pub fn select(nfds: c_int, - readfds: *mut fd_set, - writefds: *mut fd_set, - exceptfds: *mut fd_set, - timeout: *const timeval) -> c_int; - + pub fn GetOverlappedResult( + hFile: HANDLE, + lpOverlapped: LPOVERLAPPED, + lpNumberOfBytesTransferred: LPDWORD, + bWait: BOOL, + ) -> BOOL; + pub fn select( + nfds: c_int, + readfds: *mut fd_set, + writefds: *mut fd_set, + exceptfds: *mut fd_set, + timeout: *const timeval, + ) -> c_int; pub fn GetProcessHeap() -> HANDLE; pub fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; diff --git a/src/libstd/sys/windows/condvar.rs b/src/libstd/sys/windows/condvar.rs index 62835ea7c94..8f7f6854cc2 100644 --- a/src/libstd/sys/windows/condvar.rs +++ b/src/libstd/sys/windows/condvar.rs @@ -4,7 +4,9 @@ use crate::sys::mutex::{self, Mutex}; use crate::sys::os; use crate::time::Duration; -pub struct Condvar { inner: UnsafeCell<c::CONDITION_VARIABLE> } +pub struct Condvar { + inner: UnsafeCell<c::CONDITION_VARIABLE>, +} unsafe impl Send for Condvar {} unsafe impl Sync for Condvar {} @@ -19,18 +21,17 @@ impl Condvar { #[inline] pub unsafe fn wait(&self, mutex: &Mutex) { - let r = c::SleepConditionVariableSRW(self.inner.get(), - mutex::raw(mutex), - c::INFINITE, - 0); + let r = c::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), c::INFINITE, 0); debug_assert!(r != 0); } pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool { - let r = c::SleepConditionVariableSRW(self.inner.get(), - mutex::raw(mutex), - super::dur2timeout(dur), - 0); + let r = c::SleepConditionVariableSRW( + self.inner.get(), + mutex::raw(mutex), + super::dur2timeout(dur), + 0, + ); if r == 0 { debug_assert_eq!(os::errno() as usize, c::ERROR_TIMEOUT as usize); false diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index d59ac5959a6..a515b382ab0 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -1,16 +1,17 @@ #![allow(missing_docs, nonstandard_style)] -use crate::ptr; use crate::ffi::{OsStr, OsString}; use crate::io::ErrorKind; use crate::os::windows::ffi::{OsStrExt, OsStringExt}; use crate::path::PathBuf; +use crate::ptr; use crate::time::Duration; -pub use libc::strlen; pub use self::rand::hashmap_random_keys; +pub use libc::strlen; -#[macro_use] pub mod compat; +#[macro_use] +pub mod compat; pub mod alloc; pub mod args; @@ -49,8 +50,7 @@ cfg_if::cfg_if! { } #[cfg(not(test))] -pub fn init() { -} +pub fn init() {} pub fn decode_error_kind(errno: i32) -> ErrorKind { match errno as c::DWORD { @@ -85,8 +85,10 @@ pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> { fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> { let mut maybe_result: Vec<u16> = s.encode_wide().collect(); if maybe_result.iter().any(|&u| u == 0) { - return Err(crate::io::Error::new(ErrorKind::InvalidInput, - "strings passed to WinAPI cannot contain NULs")); + return Err(crate::io::Error::new( + ErrorKind::InvalidInput, + "strings passed to WinAPI cannot contain NULs", + )); } maybe_result.push(0); Ok(maybe_result) @@ -109,8 +111,9 @@ pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> { // yielded the data which has been read from the syscall. The return value // from this closure is then the return value of the function. fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> crate::io::Result<T> - where F1: FnMut(*mut u16, c::DWORD) -> c::DWORD, - F2: FnOnce(&[u16]) -> T +where + F1: FnMut(*mut u16, c::DWORD) -> c::DWORD, + F2: FnOnce(&[u16]) -> T, { // Start off with a stack buf but then spill over to the heap if we end up // needing more space. @@ -148,7 +151,7 @@ fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> crate::io::Result<T> } else if k >= n { n = k; } else { - return Ok(f2(&buf[..k])) + return Ok(f2(&buf[..k])); } } } @@ -159,20 +162,23 @@ fn os2path(s: &[u16]) -> PathBuf { } #[allow(dead_code)] // Only used in backtrace::gnu::get_executable_filename() -fn wide_char_to_multi_byte(code_page: u32, - flags: u32, - s: &[u16], - no_default_char: bool) - -> crate::io::Result<Vec<i8>> { +fn wide_char_to_multi_byte( + code_page: u32, + flags: u32, + s: &[u16], + no_default_char: bool, +) -> crate::io::Result<Vec<i8>> { unsafe { - let mut size = c::WideCharToMultiByte(code_page, - flags, - s.as_ptr(), - s.len() as i32, - ptr::null_mut(), - 0, - ptr::null(), - ptr::null_mut()); + let mut size = c::WideCharToMultiByte( + code_page, + flags, + s.as_ptr(), + s.len() as i32, + ptr::null_mut(), + 0, + ptr::null(), + ptr::null_mut(), + ); if size == 0 { return Err(crate::io::Error::last_os_error()); } @@ -181,21 +187,24 @@ fn wide_char_to_multi_byte(code_page: u32, buf.set_len(size as usize); let mut used_default_char = c::FALSE; - size = c::WideCharToMultiByte(code_page, - flags, - s.as_ptr(), - s.len() as i32, - buf.as_mut_ptr(), - buf.len() as i32, - ptr::null(), - if no_default_char { &mut used_default_char } - else { ptr::null_mut() }); + size = c::WideCharToMultiByte( + code_page, + flags, + s.as_ptr(), + s.len() as i32, + buf.as_mut_ptr(), + buf.len() as i32, + ptr::null(), + if no_default_char { &mut used_default_char } else { ptr::null_mut() }, + ); if size == 0 { return Err(crate::io::Error::last_os_error()); } if no_default_char && used_default_char == c::TRUE { - return Err(crate::io::Error::new(crate::io::ErrorKind::InvalidData, - "string cannot be converted to requested code page")); + return Err(crate::io::Error::new( + crate::io::ErrorKind::InvalidData, + "string cannot be converted to requested code page", + )); } buf.set_len(size as usize); @@ -208,7 +217,7 @@ pub fn truncate_utf16_at_nul(v: &[u16]) -> &[u16] { match v.iter().position(|c| *c == 0) { // don't include the 0 Some(i) => &v[..i], - None => v + None => v, } } @@ -227,11 +236,7 @@ macro_rules! impl_is_zero { impl_is_zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } pub fn cvt<I: IsZero>(i: I) -> crate::io::Result<I> { - if i.is_zero() { - Err(crate::io::Error::last_os_error()) - } else { - Ok(i) - } + if i.is_zero() { Err(crate::io::Error::last_os_error()) } else { Ok(i) } } pub fn dur2timeout(dur: Duration) -> c::DWORD { @@ -242,17 +247,12 @@ pub fn dur2timeout(dur: Duration) -> c::DWORD { // * Nanosecond precision is rounded up // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE // (never time out). - dur.as_secs().checked_mul(1000).and_then(|ms| { - ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000) - }).and_then(|ms| { - ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 {1} else {0}) - }).map(|ms| { - if ms > <c::DWORD>::max_value() as u64 { - c::INFINITE - } else { - ms as c::DWORD - } - }).unwrap_or(c::INFINITE) + dur.as_secs() + .checked_mul(1000) + .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)) + .and_then(|ms| ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 { 1 } else { 0 })) + .map(|ms| if ms > <c::DWORD>::max_value() as u64 { c::INFINITE } else { ms as c::DWORD }) + .unwrap_or(c::INFINITE) } // On Windows, use the processor-specific __fastfail mechanism. In Windows 8 diff --git a/src/libstd/sys/windows/mutex.rs b/src/libstd/sys/windows/mutex.rs index 79dec1adf4b..281eb294c65 100644 --- a/src/libstd/sys/windows/mutex.rs +++ b/src/libstd/sys/windows/mutex.rs @@ -95,12 +95,12 @@ impl Mutex { pub unsafe fn destroy(&self) { match kind() { Kind::SRWLock => {} - Kind::CriticalSection => { - match self.lock.load(Ordering::SeqCst) { - 0 => {} - n => { Box::from_raw(n as *mut ReentrantMutex).destroy(); } + Kind::CriticalSection => match self.lock.load(Ordering::SeqCst) { + 0 => {} + n => { + Box::from_raw(n as *mut ReentrantMutex).destroy(); } - } + }, } } @@ -114,7 +114,10 @@ impl Mutex { let re = Box::into_raw(re); match self.lock.compare_and_swap(0, re as usize, Ordering::SeqCst) { 0 => re, - n => { Box::from_raw(re).destroy(); n as *mut _ } + n => { + Box::from_raw(re).destroy(); + n as *mut _ + } } } @@ -125,7 +128,6 @@ impl Mutex { *self.held.get() = true; true } - } } @@ -134,9 +136,9 @@ fn kind() -> Kind { let val = KIND.load(Ordering::SeqCst); if val == Kind::SRWLock as usize { - return Kind::SRWLock + return Kind::SRWLock; } else if val == Kind::CriticalSection as usize { - return Kind::CriticalSection + return Kind::CriticalSection; } let ret = match compat::lookup("kernel32", "AcquireSRWLockExclusive") { @@ -147,7 +149,9 @@ fn kind() -> Kind { ret } -pub struct ReentrantMutex { inner: UnsafeCell<MaybeUninit<c::CRITICAL_SECTION>> } +pub struct ReentrantMutex { + inner: UnsafeCell<MaybeUninit<c::CRITICAL_SECTION>>, +} unsafe impl Send for ReentrantMutex {} unsafe impl Sync for ReentrantMutex {} diff --git a/src/libstd/sys/windows/net.rs b/src/libstd/sys/windows/net.rs index 53e08d50004..58574f5723b 100644 --- a/src/libstd/sys/windows/net.rs +++ b/src/libstd/sys/windows/net.rs @@ -1,27 +1,27 @@ #![unstable(issue = "none", feature = "windows_net")] use crate::cmp; -use crate::io::{self, Read, IoSlice, IoSliceMut}; +use crate::io::{self, IoSlice, IoSliceMut, Read}; use crate::mem; -use crate::net::{SocketAddr, Shutdown}; +use crate::net::{Shutdown, SocketAddr}; use crate::ptr; use crate::sync::Once; -use crate::sys::c; use crate::sys; -use crate::sys_common::{self, AsInner, FromInner, IntoInner}; +use crate::sys::c; use crate::sys_common::net; +use crate::sys_common::{self, AsInner, FromInner, IntoInner}; use crate::time::Duration; -use libc::{c_int, c_void, c_ulong, c_long}; +use libc::{c_int, c_long, c_ulong, c_void}; pub type wrlen_t = i32; pub mod netc { - pub use crate::sys::c::*; + pub use crate::sys::c::ADDRESS_FAMILY as sa_family_t; + pub use crate::sys::c::ADDRINFOA as addrinfo; pub use crate::sys::c::SOCKADDR as sockaddr; pub use crate::sys::c::SOCKADDR_STORAGE_LH as sockaddr_storage; - pub use crate::sys::c::ADDRINFOA as addrinfo; - pub use crate::sys::c::ADDRESS_FAMILY as sa_family_t; + pub use crate::sys::c::*; } pub struct Socket(c::SOCKET); @@ -33,11 +33,15 @@ pub fn init() { START.call_once(|| unsafe { let mut data: c::WSADATA = mem::zeroed(); - let ret = c::WSAStartup(0x202, // version 2.2 - &mut data); + let ret = c::WSAStartup( + 0x202, // version 2.2 + &mut data, + ); assert_eq!(ret, 0); - let _ = sys_common::at_exit(|| { c::WSACleanup(); }); + let _ = sys_common::at_exit(|| { + c::WSACleanup(); + }); }); } @@ -65,26 +69,19 @@ impl_is_minus_one! { i8 i16 i32 i64 isize } /// and if so, returns the last error from the Windows socket interface. This /// function must be called before another call to the socket API is made. pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> { - if t.is_minus_one() { - Err(last_error()) - } else { - Ok(t) - } + if t.is_minus_one() { Err(last_error()) } else { Ok(t) } } /// A variant of `cvt` for `getaddrinfo` which return 0 for a success. pub fn cvt_gai(err: c_int) -> io::Result<()> { - if err == 0 { - Ok(()) - } else { - Err(last_error()) - } + if err == 0 { Ok(()) } else { Err(last_error()) } } /// Just to provide the same interface as sys/unix/net.rs pub fn cvt_r<T, F>(mut f: F) -> io::Result<T> - where T: IsMinusOne, - F: FnMut() -> T +where + T: IsMinusOne, + F: FnMut() -> T, { cvt(f()) } @@ -96,23 +93,27 @@ impl Socket { SocketAddr::V6(..) => c::AF_INET6, }; let socket = unsafe { - match c::WSASocketW(fam, ty, 0, ptr::null_mut(), 0, - c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT) { - c::INVALID_SOCKET => { - match c::WSAGetLastError() { - c::WSAEPROTOTYPE | c::WSAEINVAL => { - match c::WSASocketW(fam, ty, 0, ptr::null_mut(), 0, - c::WSA_FLAG_OVERLAPPED) { - c::INVALID_SOCKET => Err(last_error()), - n => { - let s = Socket(n); - s.set_no_inherit()?; - Ok(s) - }, + match c::WSASocketW( + fam, + ty, + 0, + ptr::null_mut(), + 0, + c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT, + ) { + c::INVALID_SOCKET => match c::WSAGetLastError() { + c::WSAEPROTOTYPE | c::WSAEINVAL => { + match c::WSASocketW(fam, ty, 0, ptr::null_mut(), 0, c::WSA_FLAG_OVERLAPPED) + { + c::INVALID_SOCKET => Err(last_error()), + n => { + let s = Socket(n); + s.set_no_inherit()?; + Ok(s) } - }, - n => Err(io::Error::from_raw_os_error(n)), + } } + n => Err(io::Error::from_raw_os_error(n)), }, n => Ok(Socket(n)), } @@ -135,8 +136,10 @@ impl Socket { } if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } let mut timeout = c::timeval { @@ -157,9 +160,8 @@ impl Socket { let mut writefds = fds; let mut errorfds = fds; - let n = unsafe { - cvt(c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout))? - }; + let n = + unsafe { cvt(c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout))? }; match n { 0 => Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out")), @@ -174,8 +176,7 @@ impl Socket { } } - pub fn accept(&self, storage: *mut c::SOCKADDR, - len: *mut c_int) -> io::Result<Socket> { + pub fn accept(&self, storage: *mut c::SOCKADDR, len: *mut c_int) -> io::Result<Socket> { let socket = unsafe { match c::accept(self.0, storage, len) { c::INVALID_SOCKET => Err(last_error()), @@ -188,33 +189,35 @@ impl Socket { pub fn duplicate(&self) -> io::Result<Socket> { let socket = unsafe { let mut info: c::WSAPROTOCOL_INFO = mem::zeroed(); - cvt(c::WSADuplicateSocketW(self.0, - c::GetCurrentProcessId(), - &mut info))?; - - match c::WSASocketW(info.iAddressFamily, - info.iSocketType, - info.iProtocol, - &mut info, 0, - c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT) { - c::INVALID_SOCKET => { - match c::WSAGetLastError() { - c::WSAEPROTOTYPE | c::WSAEINVAL => { - match c::WSASocketW(info.iAddressFamily, - info.iSocketType, - info.iProtocol, - &mut info, 0, - c::WSA_FLAG_OVERLAPPED) { - c::INVALID_SOCKET => Err(last_error()), - n => { - let s = Socket(n); - s.set_no_inherit()?; - Ok(s) - }, + cvt(c::WSADuplicateSocketW(self.0, c::GetCurrentProcessId(), &mut info))?; + + match c::WSASocketW( + info.iAddressFamily, + info.iSocketType, + info.iProtocol, + &mut info, + 0, + c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT, + ) { + c::INVALID_SOCKET => match c::WSAGetLastError() { + c::WSAEPROTOTYPE | c::WSAEINVAL => { + match c::WSASocketW( + info.iAddressFamily, + info.iSocketType, + info.iProtocol, + &mut info, + 0, + c::WSA_FLAG_OVERLAPPED, + ) { + c::INVALID_SOCKET => Err(last_error()), + n => { + let s = Socket(n); + s.set_no_inherit()?; + Ok(s) } - }, - n => Err(io::Error::from_raw_os_error(n)), + } } + n => Err(io::Error::from_raw_os_error(n)), }, n => Ok(Socket(n)), } @@ -230,7 +233,7 @@ impl Socket { match c::recv(self.0, buf.as_mut_ptr() as *mut c_void, len, flags) { -1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0), -1 => Err(last_error()), - n => Ok(n as usize) + n => Ok(n as usize), } } } @@ -267,8 +270,11 @@ impl Socket { self.recv_with_flags(buf, c::MSG_PEEK) } - fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int) - -> io::Result<(usize, SocketAddr)> { + fn recv_from_with_flags( + &self, + buf: &mut [u8], + flags: c_int, + ) -> io::Result<(usize, SocketAddr)> { let mut storage: c::SOCKADDR_STORAGE_LH = unsafe { mem::zeroed() }; let mut addrlen = mem::size_of_val(&storage) as c::socklen_t; let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t; @@ -276,15 +282,17 @@ impl Socket { // On unix when a socket is shut down all further reads return 0, so we // do the same on windows to map a shut down socket to returning EOF. unsafe { - match c::recvfrom(self.0, - buf.as_mut_ptr() as *mut c_void, - len, - flags, - &mut storage as *mut _ as *mut _, - &mut addrlen) { + match c::recvfrom( + self.0, + buf.as_mut_ptr() as *mut c_void, + len, + flags, + &mut storage as *mut _ as *mut _, + &mut addrlen, + ) { -1 if c::WSAGetLastError() == c::WSAESHUTDOWN => { Ok((0, net::sockaddr_to_addr(&storage, addrlen as usize)?)) - }, + } -1 => Err(last_error()), n => Ok((n as usize, net::sockaddr_to_addr(&storage, addrlen as usize)?)), } @@ -316,18 +324,19 @@ impl Socket { Ok(nwritten as usize) } - pub fn set_timeout(&self, dur: Option<Duration>, - kind: c_int) -> io::Result<()> { + pub fn set_timeout(&self, dur: Option<Duration>, kind: c_int) -> io::Result<()> { let timeout = match dur { Some(dur) => { let timeout = sys::dur2timeout(dur); if timeout == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); } timeout } - None => 0 + None => 0, }; net::setsockopt(self, c::SOL_SOCKET, kind, timeout) } @@ -345,10 +354,8 @@ impl Socket { #[cfg(not(target_vendor = "uwp"))] fn set_no_inherit(&self) -> io::Result<()> { - sys::cvt(unsafe { - c::SetHandleInformation(self.0 as c::HANDLE, - c::HANDLE_FLAG_INHERIT, 0) - }).map(|_| ()) + sys::cvt(unsafe { c::SetHandleInformation(self.0 as c::HANDLE, c::HANDLE_FLAG_INHERIT, 0) }) + .map(|_| ()) } #[cfg(target_vendor = "uwp")] @@ -369,11 +376,7 @@ impl Socket { pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { let mut nonblocking = nonblocking as c_ulong; let r = unsafe { c::ioctlsocket(self.0, c::FIONBIO as c_int, &mut nonblocking) }; - if r == 0 { - Ok(()) - } else { - Err(io::Error::last_os_error()) - } + if r == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { @@ -387,11 +390,7 @@ impl Socket { pub fn take_error(&self) -> io::Result<Option<io::Error>> { let raw: c_int = net::getsockopt(self, c::SOL_SOCKET, c::SO_ERROR)?; - if raw == 0 { - Ok(None) - } else { - Ok(Some(io::Error::from_raw_os_error(raw as i32))) - } + if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) } } } @@ -409,11 +408,15 @@ impl Drop for Socket { } impl AsInner<c::SOCKET> for Socket { - fn as_inner(&self) -> &c::SOCKET { &self.0 } + fn as_inner(&self) -> &c::SOCKET { + &self.0 + } } impl FromInner<c::SOCKET> for Socket { - fn from_inner(sock: c::SOCKET) -> Socket { Socket(sock) } + fn from_inner(sock: c::SOCKET) -> Socket { + Socket(sock) + } } impl IntoInner<c::SOCKET> for Socket { diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index 060997be97d..a62a637393e 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -1,9 +1,10 @@ #![unstable(feature = "process_internals", issue = "none")] +use crate::borrow::Borrow; use crate::collections::BTreeMap; -use crate::env::split_paths; use crate::env; -use crate::ffi::{OsString, OsStr}; +use crate::env::split_paths; +use crate::ffi::{OsStr, OsString}; use crate::fmt; use crate::fs; use crate::io::{self, Error, ErrorKind}; @@ -11,18 +12,17 @@ use crate::mem; use crate::os::windows::ffi::OsStrExt; use crate::path::Path; use crate::ptr; -use crate::sys::mutex::Mutex; use crate::sys::c; -use crate::sys::fs::{OpenOptions, File}; +use crate::sys::cvt; +use crate::sys::fs::{File, OpenOptions}; use crate::sys::handle::Handle; +use crate::sys::mutex::Mutex; use crate::sys::pipe::{self, AnonPipe}; use crate::sys::stdio; -use crate::sys::cvt; -use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::sys_common::process::CommandEnv; -use crate::borrow::Borrow; +use crate::sys_common::{AsInner, FromInner, IntoInner}; -use libc::{c_void, EXIT_SUCCESS, EXIT_FAILURE}; +use libc::{c_void, EXIT_FAILURE, EXIT_SUCCESS}; //////////////////////////////////////////////////////////////////////////////// // Command @@ -41,18 +41,23 @@ impl From<OsString> for EnvKey { } impl From<EnvKey> for OsString { - fn from(k: EnvKey) -> Self { k.0 } + fn from(k: EnvKey) -> Self { + k.0 + } } impl Borrow<OsStr> for EnvKey { - fn borrow(&self) -> &OsStr { &self.0 } + fn borrow(&self) -> &OsStr { + &self.0 + } } impl AsRef<OsStr> for EnvKey { - fn as_ref(&self) -> &OsStr { &self.0 } + fn as_ref(&self) -> &OsStr { + &self.0 + } } - fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> { if str.as_ref().encode_wide().any(|b| b == 0) { Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data")) @@ -127,8 +132,11 @@ impl Command { self.flags = flags; } - pub fn spawn(&mut self, default: Stdio, needs_stdin: bool) - -> io::Result<(Process, StdioPipes)> { + pub fn spawn( + &mut self, + default: Stdio, + needs_stdin: bool, + ) -> io::Result<(Process, StdioPipes)> { let maybe_env = self.env.capture_if_changed(); // To have the spawning semantics of unix/windows stay the same, we need // to read the *child's* PATH if one is provided. See #15149 for more @@ -138,10 +146,11 @@ impl Command { // Split the value and test each path to see if the // program exists. for path in split_paths(&v) { - let path = path.join(self.program.to_str().unwrap()) - .with_extension(env::consts::EXE_EXTENSION); + let path = path + .join(self.program.to_str().unwrap()) + .with_extension(env::consts::EXE_EXTENSION); if fs::metadata(&path).is_ok() { - return Some(path.into_os_string()) + return Some(path.into_os_string()); } } } @@ -178,32 +187,32 @@ impl Command { static CREATE_PROCESS_LOCK: Mutex = Mutex::new(); let _guard = DropGuard::new(&CREATE_PROCESS_LOCK); - let mut pipes = StdioPipes { - stdin: None, - stdout: None, - stderr: None, - }; + let mut pipes = StdioPipes { stdin: None, stdout: None, stderr: None }; let null = Stdio::Null; - let default_stdin = if needs_stdin {&default} else {&null}; + let default_stdin = if needs_stdin { &default } else { &null }; let stdin = self.stdin.as_ref().unwrap_or(default_stdin); let stdout = self.stdout.as_ref().unwrap_or(&default); let stderr = self.stderr.as_ref().unwrap_or(&default); let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?; - let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, - &mut pipes.stdout)?; - let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, - &mut pipes.stderr)?; + let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?; + let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?; si.hStdInput = stdin.raw(); si.hStdOutput = stdout.raw(); si.hStdError = stderr.raw(); unsafe { - cvt(c::CreateProcessW(ptr::null(), - cmd_str.as_mut_ptr(), - ptr::null_mut(), - ptr::null_mut(), - c::TRUE, flags, envp, dirp, - &mut si, &mut pi)) + cvt(c::CreateProcessW( + ptr::null(), + cmd_str.as_mut_ptr(), + ptr::null_mut(), + ptr::null_mut(), + c::TRUE, + flags, + envp, + dirp, + &mut si, + &mut pi, + )) }?; // We close the thread handle because we don't care about keeping @@ -213,7 +222,6 @@ impl Command { Ok((Process { handle: Handle::new(pi.hProcess) }, pipes)) } - } impl fmt::Debug for Command { @@ -244,24 +252,20 @@ impl<'a> Drop for DropGuard<'a> { } impl Stdio { - fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) - -> io::Result<Handle> { + fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> { match *self { // If no stdio handle is available, then inherit means that it // should still be unavailable so propagate the // INVALID_HANDLE_VALUE. - Stdio::Inherit => { - match stdio::get_handle(stdio_id) { - Ok(io) => { - let io = Handle::new(io); - let ret = io.duplicate(0, true, - c::DUPLICATE_SAME_ACCESS); - io.into_raw(); - ret - } - Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)), + Stdio::Inherit => match stdio::get_handle(stdio_id) { + Ok(io) => { + let io = Handle::new(io); + let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS); + io.into_raw(); + ret } - } + Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)), + }, Stdio::MakePipe => { let ours_readable = stdio_id != c::STD_INPUT_HANDLE; @@ -270,9 +274,7 @@ impl Stdio { Ok(pipes.theirs.into_handle()) } - Stdio::Handle(ref handle) => { - handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS) - } + Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS), // Open up a reference to NUL with appropriate read/write // permissions as well as the ability to be inherited to child @@ -288,9 +290,7 @@ impl Stdio { opts.read(stdio_id == c::STD_INPUT_HANDLE); opts.write(stdio_id != c::STD_INPUT_HANDLE); opts.security_attributes(&mut sa); - File::open(Path::new("NUL"), &opts).map(|file| { - file.into_handle() - }) + File::open(Path::new("NUL"), &opts).map(|file| file.into_handle()) } } } @@ -323,23 +323,19 @@ pub struct Process { impl Process { pub fn kill(&mut self) -> io::Result<()> { - cvt(unsafe { - c::TerminateProcess(self.handle.raw(), 1) - })?; + cvt(unsafe { c::TerminateProcess(self.handle.raw(), 1) })?; Ok(()) } pub fn id(&self) -> u32 { - unsafe { - c::GetProcessId(self.handle.raw()) as u32 - } + unsafe { c::GetProcessId(self.handle.raw()) as u32 } } pub fn wait(&mut self) -> io::Result<ExitStatus> { unsafe { let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE); if res != c::WAIT_OBJECT_0 { - return Err(Error::last_os_error()) + return Err(Error::last_os_error()); } let mut status = 0; cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))?; @@ -362,9 +358,13 @@ impl Process { } } - pub fn handle(&self) -> &Handle { &self.handle } + pub fn handle(&self) -> &Handle { + &self.handle + } - pub fn into_handle(self) -> Handle { self.handle } + pub fn into_handle(self) -> Handle { + self.handle + } } #[derive(PartialEq, Eq, Clone, Copy, Debug)] @@ -441,7 +441,7 @@ fn zeroed_process_information() -> c::PROCESS_INFORMATION { hProcess: ptr::null_mut(), hThread: ptr::null_mut(), dwProcessId: 0, - dwThreadId: 0 + dwThreadId: 0, } } @@ -466,7 +466,8 @@ fn make_command_line(prog: &OsStr, args: &[OsString]) -> io::Result<Vec<u16>> { // it will be dropped entirely when parsed on the other end. ensure_no_nuls(arg)?; let arg_bytes = &arg.as_inner().inner.as_inner(); - let quote = force_quotes || arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t') + let quote = force_quotes + || arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t') || arg_bytes.is_empty(); if quote { cmd.push('"' as u16); @@ -495,8 +496,7 @@ fn make_command_line(prog: &OsStr, args: &[OsString]) -> io::Result<Vec<u16>> { } } -fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) - -> io::Result<(*mut c_void, Vec<u16>)> { +fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> { // On Windows we pass an "environment block" which is not a char**, but // rather a concatenation of null-terminated k=v\0 sequences, with a final // \0 to terminate. @@ -517,37 +517,33 @@ fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) } fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> { - match d { Some(dir) => { let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect(); dir_str.push(0); Ok((dir_str.as_ptr(), dir_str)) - }, - None => Ok((ptr::null(), Vec::new())) + } + None => Ok((ptr::null(), Vec::new())), } } #[cfg(test)] mod tests { - use crate::ffi::{OsStr, OsString}; use super::make_command_line; + use crate::ffi::{OsStr, OsString}; #[test] fn test_make_command_line() { fn test_wrapper(prog: &str, args: &[&str]) -> String { - let command_line = &make_command_line(OsStr::new(prog), - &args.iter() - .map(|a| OsString::from(a)) - .collect::<Vec<OsString>>()) - .unwrap(); + let command_line = &make_command_line( + OsStr::new(prog), + &args.iter().map(|a| OsString::from(a)).collect::<Vec<OsString>>(), + ) + .unwrap(); String::from_utf16(command_line).unwrap() } - assert_eq!( - test_wrapper("prog", &["aaa", "bbb", "ccc"]), - "\"prog\" aaa bbb ccc" - ); + assert_eq!(test_wrapper("prog", &["aaa", "bbb", "ccc"]), "\"prog\" aaa bbb ccc"); assert_eq!( test_wrapper("C:\\Program Files\\blah\\blah.exe", &["aaa"]), @@ -557,10 +553,7 @@ mod tests { test_wrapper("C:\\Program Files\\test", &["aa\"bb"]), "\"C:\\Program Files\\test\" aa\\\"bb" ); - assert_eq!( - test_wrapper("echo", &["a b c"]), - "\"echo\" \"a b c\"" - ); + assert_eq!(test_wrapper("echo", &["a b c"]), "\"echo\" \"a b c\""); assert_eq!( test_wrapper("echo", &["\" \\\" \\", "\\"]), "\"echo\" \"\\\" \\\\\\\" \\\\\" \\" diff --git a/src/libstd/sys/windows/rwlock.rs b/src/libstd/sys/windows/rwlock.rs index ef57562fc3a..a769326352c 100644 --- a/src/libstd/sys/windows/rwlock.rs +++ b/src/libstd/sys/windows/rwlock.rs @@ -1,7 +1,9 @@ use crate::cell::UnsafeCell; use crate::sys::c; -pub struct RWLock { inner: UnsafeCell<c::SRWLOCK> } +pub struct RWLock { + inner: UnsafeCell<c::SRWLOCK>, +} unsafe impl Send for RWLock {} unsafe impl Sync for RWLock {} diff --git a/src/libstd/sys/windows/time.rs b/src/libstd/sys/windows/time.rs index bd533c93d43..86667ca7ab2 100644 --- a/src/libstd/sys/windows/time.rs +++ b/src/libstd/sys/windows/time.rs @@ -1,9 +1,9 @@ use crate::cmp::Ordering; +use crate::convert::TryInto; use crate::fmt; use crate::mem; use crate::sys::c; use crate::time::Duration; -use crate::convert::TryInto; use core::hash::{Hash, Hasher}; @@ -53,8 +53,7 @@ impl Instant { // On windows there's a threshold below which we consider two timestamps // equivalent due to measurement error. For more details + doc link, // check the docs on epsilon. - let epsilon = - perf_counter::PerformanceCounterInstant::epsilon(); + let epsilon = perf_counter::PerformanceCounterInstant::epsilon(); if other.t > self.t && other.t - self.t <= epsilon { Some(Duration::new(0, 0)) } else { @@ -63,15 +62,11 @@ impl Instant { } pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> { - Some(Instant { - t: self.t.checked_add(*other)? - }) + Some(Instant { t: self.t.checked_add(*other)? }) } pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> { - Some(Instant { - t: self.t.checked_sub(*other)? - }) + Some(Instant { t: self.t.checked_sub(*other)? }) } } @@ -89,7 +84,7 @@ impl SystemTime { t: c::FILETIME { dwLowDateTime: intervals as c::DWORD, dwHighDateTime: (intervals >> 32) as c::DWORD, - } + }, } } @@ -140,9 +135,7 @@ impl Ord for SystemTime { impl fmt::Debug for SystemTime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("SystemTime") - .field("intervals", &self.intervals()) - .finish() + f.debug_struct("SystemTime").field("intervals", &self.intervals()).finish() } } @@ -153,7 +146,7 @@ impl From<c::FILETIME> for SystemTime { } impl Hash for SystemTime { - fn hash<H : Hasher>(&self, state: &mut H) { + fn hash<H: Hasher>(&self, state: &mut H) { self.intervals().hash(state) } } @@ -167,26 +160,23 @@ fn checked_dur2intervals(dur: &Duration) -> Option<i64> { } fn intervals2dur(intervals: u64) -> Duration { - Duration::new(intervals / INTERVALS_PER_SEC, - ((intervals % INTERVALS_PER_SEC) * 100) as u32) + Duration::new(intervals / INTERVALS_PER_SEC, ((intervals % INTERVALS_PER_SEC) * 100) as u32) } mod perf_counter { - use super::{NANOS_PER_SEC}; + use super::NANOS_PER_SEC; use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst}; - use crate::sys_common::mul_div_u64; use crate::sys::c; use crate::sys::cvt; + use crate::sys_common::mul_div_u64; use crate::time::Duration; pub struct PerformanceCounterInstant { - ts: c::LARGE_INTEGER + ts: c::LARGE_INTEGER, } impl PerformanceCounterInstant { pub fn now() -> Self { - Self { - ts: query() - } + Self { ts: query() } } // Per microsoft docs, the margin of error for cross-thread time comparisons @@ -202,9 +192,7 @@ mod perf_counter { fn from(other: PerformanceCounterInstant) -> Self { let freq = frequency() as u64; let instant_nsec = mul_div_u64(other.ts as u64, NANOS_PER_SEC, freq); - Self { - t: Duration::from_nanos(instant_nsec) - } + Self { t: Duration::from_nanos(instant_nsec) } } } @@ -234,9 +222,7 @@ mod perf_counter { fn query() -> c::LARGE_INTEGER { let mut qpc_value: c::LARGE_INTEGER = 0; - cvt(unsafe { - c::QueryPerformanceCounter(&mut qpc_value) - }).unwrap(); + cvt(unsafe { c::QueryPerformanceCounter(&mut qpc_value) }).unwrap(); qpc_value } } |
