Crate nc

source ·
Expand description

Execute system call directly without std or libc.

Usage

Add this to Cargo.toml:

[dependencies]
nc = "0.8"

Examples

Get file stat:

let mut statbuf = nc::stat_t::default();
let path = "/etc/passwd";
#[cfg(not(target_arch = "aarch64"))]
let ret = unsafe { nc::stat(path, &mut statbuf) };
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
let ret = unsafe { nc::fstatat(nc::AT_FDCWD, path, &mut statbuf, 0) };
match ret {
    Ok(_) => println!("s: {:?}", statbuf),
    Err(errno) => eprintln!("Failed to get file status, got errno: {}", errno),
}

Fork process:

let pid = unsafe { nc::fork() };
match pid {
    Ok(pid) => {
        if pid == 0 {
            println!("child process: {}", pid);
            let args = [""];
            let env = [""];
            match unsafe { nc::execve("/bin/ls", &args, &env) } {
                Ok(_) => {},
                Err(errno) => eprintln!("`ls` got err: {}", errno),
            }
        } else if pid < 0 {
            eprintln!("fork() error!");
        } else {
            println!("parent process!");
        }
    },
    Err(errno) => eprintln!("errno: {}", errno),
}

Kill init process:

let ret = unsafe { nc::kill(1, nc::SIGTERM) };
assert_eq!(ret, Err(nc::EPERM));

Or get system info:

pub fn cstr_to_str(input: &[u8]) -> &str {
    let nul_index = input.iter().position(|&b| b == 0).unwrap_or(input.len());
    std::str::from_utf8(&input[0..nul_index]).unwrap()
}

fn main() {
    let mut uts = nc::utsname_t::default();
    let ret = unsafe { nc::uname(&mut uts) };
    assert!(ret.is_ok());

    let mut result = Vec::new();

    result.push(cstr_to_str(&uts.sysname));
    result.push(cstr_to_str(&uts.nodename));
    result.push(cstr_to_str(&uts.release));
    result.push(cstr_to_str(&uts.version));
    result.push(cstr_to_str(&uts.machine));
    let domain_name = cstr_to_str(&uts.domainname);
    if domain_name != "(none)" {
        result.push(domain_name);
    }

    let result = result.join(" ");
    println!("{}", result);
}

Stable version

For stable version of rustc, please install a C compiler (gcc or clang) first. As asm! feature is unavailable in stable version.

Supported Operating Systems and Architectures

  • linux
    • x86
    • x86-64
    • arm
    • aarch64
    • loongarch64
    • mips
    • mipsel
    • mips64
    • mips64el
    • powerpc64
    • s390x
  • android
    • aarch64
  • freebsd
    • x86-64
  • netbsd
    • x86-64
  • mac os
    • x86-64

Re-exports

pub use types::*;

Modules

Constants

Argument list too long
Permission denied
Address already in use
Cannot assign requested address
Advertise error
Address family not supported by protocol
Try again
Operation already in progress
Invalid exchange
Bad file number
File descriptor in bad state
Not a data message
Invalid request descriptor
Invalid request code
Invalid slot
Bad font file format
Device or resource busy
Operation Canceled
No child processes
Channel number out of range
Communication error on send
Software caused connection abort
Connection refused
Connection reset by peer
Resource deadlock would occur
Destination address required
Math argument out of domain of func
RFS specific error
Quota exceeded
File exists
Bad address
File too large
Host is down
No route to host
Memory page has hardware error
Identifier removed
Illegal byte sequence
Operation now in progress
Interrupted system call
Invalid argument
I/O error
Transport endpoint is already connected
Is a directory
Is a named type file
Key has expired
Key was rejected by service
Key has been revoked
Level 2 halted
Level 2 not synchronized
Level 3 halted
Level 3 reset
Can not access a needed shared library
Accessing a corrupted shared library
Cannot exec a shared library directly
Attempting to link in too many shared libraries
.lib section in a.out corrupted
Link number out of range
Too many symbolic links encountered
Wrong medium type
Too many open files
Too many links
Message too long
Multihop attempted
File name too long
No XENIX semaphores available
Network is down
Network dropped connection because of reset
Network is unreachable
File table overflow
No anode
No buffer space available
No CSI structure available
No data available
No such device
No such file or directory
Exec format error
Required key not available
No record locks available
Link has been severed
No medium found
Out of memory
No message of desired type
Machine is not on the network
Package not installed
Protocol not available
No space left on device
Out of streams resources
Device not a stream
Invalid system call number
Block device required
Transport endpoint is not connected
Not a directory
Directory not empty
Not a XENIX named type file
State not recoverable
Socket operation on non-socket
Not a typewriter
Name not unique on network
No such device or address
Operation not supported on transport endpoint
Value too large for defined data type
Owner died
Operation not permitted
Protocol family not supported
Broken pipe
Protocol error
Protocol not supported
Protocol wrong type for socket
Math result not representable
Remote address changed
Object is remote
Remote I/O error
Interrupted system call should be restarted
Operation not possible due to RF-kill
Read-only file system
Cannot send after transport endpoint shutdown
Socket type not supported
Illegal seek
No such process
Srmount error
Stale file handle
Streams pipe error
Timer expired
Connection timed out
Too many references: cannot splice
Text file busy
Structure needs cleaning
Protocol driver not attached
Too many users
Cross-device link
Exchange full

Functions

Read/write system parameters.
Accept a connection on a socket.
Accept a connection on a socket.
Check user’s permission for a file.
acct
Switch process accounting.
Add a key to the kernel’s key management facility.
Tune kernel clock. Returns clock state on success.
Set an alarm clock for delivery of a signal.
Set architecture-specific thread state.
bind
Bind a name to a socket.
bpf
Perform a command on an extended BPF map or program
brk
Change data segment size.
Get capabilities of thread.
Set capabilities of thread.
Change working directory.
Change permissions of a file.
Change ownership of a file.
Change the root directory.
Tune kernel clock. Returns clock state on success.
Get resolution(precision) of the specific clock.
Get time of specific clock.
High resolution sleep with a specific clock.
Set time of specific clock.
Create a child process.
New api to create child process.
Close a file descriptor.
Close all file descriptors in a given range
Initialize a connection on a socket.
Copy a range of data from one file to another.
Create a file.
Unlock a kernel module.
dup
Create a copy of the file descriptor oldfd, using the lowest available file descriptor.
dup2
Create a copy of the file descriptor oldfd, using the speficified file descriptor newfd.
dup3
Save as dup2(), but can set the close-on-exec flag on newfd.
Open an epoll file descriptor.
Open an epoll file descriptor.
Control interface for an epoll file descriptor.
Wait for an I/O event on an epoll file descriptor.
Wait for an I/O event on an epoll file descriptor.
Create a file descriptor for event notification.
Create a file descriptor for event notification.
Execute a new program.
Execute a new program relative to a directory file descriptor.
exit
Terminate current process.
Exit all threads in a process’s thread group.
Check user’s permission for a file.
Check user’s permission for a file.
Predeclare an access pattern for file data.
Manipulate file space.
Create and initialize fanotify group.
Add, remove, or modify an fanotify mark on a filesystem object
Change working directory.
Change permissions of a file.
Change permissions of a file.
Change ownership of a file.
Change ownership of a file.
manipulate file descriptor.
Flush all modified in-core data (exclude metadata) refered by fd to disk.
Get extended attribute value.
Load a kernel module.
List extended attribute names.
Apply or remove an advisory lock on an open file.
fork
Create a child process.
Remove an extended attribute.
Set parameters and trigger actions on a context.
Set extended attribute value.
Create a kernel mount representation for a new, prepared superblock.
Open a filesystem by name so that it can be configured for mounting.
Pick a superblock into a context for reconfiguration.
Get file status about a file descriptor.
Get filesystem statistics.
Flush all modified in-core data refered by fd to disk.
Truncate an opened file to a specified length.
Fast user-space locking.
Wait on a list of futexes.
Change timestamp of a file relative to a directory file discriptor.
Retrieve NUMA memory policy for a thread
Get list of robust futexes.
Get thread-local storage information.
Determine CPU and NUMA node on which the calling thread is running.
Get current working directory.
Get directory entries.
Get directory entries.
Get the effective group ID of the calling process.
Get the effective user ID of the calling process.
Get the real group ID of the calling process.
Get list of supplementary group Ids.
Get value of an interval timer.
Get name of connected peer socket.
Returns the PGID(process group ID) of the process specified by pid.
Get the process group ID of the calling process.
Get the process ID (PID) of the calling process.
Get the process ID of the parent of the calling process.
Get program scheduling priority.
Obtain a series of random bytes.
Get real, effect and saved group ID.
Get real, effect and saved user ID.
Get resource limit.
Get resource usage.
Get session Id.
Get current address to which the socket sockfd is bound.
Get options on sockets
Get the caller’s thread ID (TID).
Get time.
Get the real user ID of the calling process.
Get extended attribute value.
Load a kernel module.
Add a watch to an initialized inotify instance.
Initialize an inotify instance.
Initialize an inotify instance.
Remove an existing watch from an inotify instance.
Attempts to cancel an iocb previously passed to io_submit.
Destroy the aio_context specified.
Attempts to read at least min_nr events and up to nr events from the completion queue for the aio_context specified by ctx_id.
read asynchronous I/O events from the completion queue
Create an asynchronous I/O context.
Queue the nr iocbs pointed to by iocbpp for processing.
Control device.
Set port input/output permissions.
iopl
Change I/O privilege level.
Get I/O scheduling class and priority.
Set I/O scheduling class and priority.
kcmp
Compare two processes to determine if they share a kernel resource.
Load a new kernel for later execution.
Load a new kernel for later execution.
Manipulate the kernel’s key management facility.
kill
Send signal to a process.
Change ownership of a file. Does not deference symbolic link.
Get extended attribute value.
link
Make a new name for a file.
Make a new name for a file.
Listen for connections on a socket.
List extended attribute names.
List extended attribute names.
Return a directory entry’s path.
Remove an extended attribute.
Reposition file offset.
Set extended attribute value.
Get file status about a file, without following symbolic.
Give advice about use of memory.
Set memory policy for a memory range.
Issue memory barriers on a set of threads.
Create an anonymous file.
Move all pages in a process to another set of nodes
mincore() returns the memory residency status of the pages in the current process’s address space specified by [addr, addr + len). The status is returned in a vector of bytes. The least significant bit of each byte is 1 if the referenced page is in memory, otherwise it is zero.
Create a directory.
Create a directory.
Create a special or ordinary file.
Create a special or ordinary file.
Lock memory.
Lock memory.
Lock memory.
mmap
Map files or devices into memory.
Mount filesystem.
Move a mount from one place to another.
Move individual pages of a process to another node
Set protection on a region of memory.
Get/set message queue attributes
Register for notification when a message is available
Open a message queue.
Receive a message from a message queue
Send message to a message queue.
Remove a message queue.
Remap a virtual memory address
System V message control operations.
Get a System V message queue identifier.
Receive messages from a System V message queue.
Append the message to a System V message queue.
Synchronize a file with memory map.
Unlock memory.
Unlock memory.
Unmap files or devices from memory.
Obtain handle for a filename
High resolution sleep.
Get file status.
open
Open and possibly create a file.
Obtain handle for an open file
Open and possibly create a file within a directory.
Open and possibly create a file (extended)
Pause the calling process to sleep until a signal is delivered.
Set up performance monitoring.
Set the process execution domain.
Obtain a duplicate of another process’s file descriptor.
Obtain a file descriptor that refers to a process.
Signal a process through a pidfd.
pipe
Create a pipe.
Create a pipe.
Change the root filesystem.
Create a new protection key.
Free a protection key.
Set protection on a region of memory.
poll
Wait for some event on file descriptors.
Wait for some event on a file descriptor.
Operations on a process.
Read from a file descriptor without changing file offset.
Read from a file descriptor without changing file offset.
Read from a file descriptor without changing file offset.
Get/set the resource limits of an arbitary process.
Transfer data between process address spaces
Transfer data between process address spaces
Sychronous I/O multiplexing.
Process trace.
Write to a file descriptor without changing file offset.
Write to a file descriptor without changing file offset.
Write to a file descriptor without changing file offset.
Manipulate disk quotes.
read
Read from a file descriptor.
Initialize file head into page cache.
Read value of a symbolic link.
Read value of a symbolic link.
Read from a file descriptor into multiple buffers.
Reboot or enable/disable Ctrl-Alt-Del.
Receive a message from a socket.
Receives multile messages on a socket
Receive a msg from a socket.
Create a nonlinear file mapping. Deprecated.
Remove an extended attribute.
Change name or location of a file.
Change name or location of a file.
Change name or location of a file.
Request a key from kernel’s key management facility.
Restart a system call after interruption by a stop signal.
Delete a directory.
rseq
Setup restartable sequences for caller thread.
Examine and change a signal action.
Examine pending signals.
Change the list of currently blocked signals.
Queue a signal and data.
Return from signal handler and cleanup stack frame.
Wait for a signal.
Synchronously wait for queued signals.
Queue a signal and data.
Get static priority max value.
Get static priority min value.
Get a thread’s CPU affinity mask.
Get scheduling policy and attributes
Get scheduling paramters.
Get scheduling parameter.
Get the SCHED_RR interval for the named process.
Set a thread’s CPU affinity mask.
Set the RT priority of a thread.
Set scheduling paramters.
Set scheduling parameter.
Yield the processor.
Operate on Secure Computing state of the process.
Sychronous I/O multiplexing.
System V semaphore control operations
Get a System V semphore set identifier.
System V semphore operations.
System V semaphore operations
Transfer data between two file descriptors.
Send multiple messages on a socket
Send a message on a socket. Allow sending ancillary data.
Send a message on a socket.
Set default NUMA memory policy for a thread and its children
Set the robust-futex list head of a task.
Set thread-local storage information.
Set pointer to thread ID.
Set NIS domain name.
Set group identify used for filesystem checkes.
Set user identify used for filesystem checkes.
Set the group ID of the calling process to gid.
Set list of supplementary group Ids.
Set hostname.
Set value of an interval timer.
Reassociate thread with a namespace.
Set the process group ID (PGID) of the process specified by pid to pgid.
Set program scheduling priority.
Set real and effective group IDs of the calling process.
Set real, effective and saved group Ids of the calling process.
Set real, effective and saved user Ids of the calling process.
Set real and effective user IDs of the calling process.
Set resource limit.
Create a new session if the calling process is not a process group leader.
Set options on sockets.
Set system time and timezone.
Set user ID of the calling process to uid.
Set extended attribute value.
Attach the System V shared memory segment.
System V shared memory control.
Detach the System V shared memory segment.
Allocates a System V shared memory segment.
Shutdown part of a full-duplex connection.
Get/set signal stack context.
Create a file descriptor to accept signals.
Create a file descriptor to accept signals.
Create an endpoint for communication.
Create a pair of connected socket.
Splice data to/from pipe.
stat
Get file status about a file.
Get filesystem statistics.
Get file status about a file (extended).
Get errno description.
Stop swapping to file/device.
Start swapping to file/device.
Make a new name for a file.
Make a new name for a file.
sync
Commit filesystem caches to disk.
Sync a file segment to disk
Commit filesystem cache related to fd to disk.
Get filesystem type information.
Return system information.
Read and/or clear kernel message ring buffer.
tee
Duplicate pipe content.
Send a signal to a thread.
time
Get time in seconds.
Create a per-process timer
Delete a per-process timer
Get overrun count for a per-process timer.
Fetch state of per-process timer>
Arm/disarm state of per-process timer.
Create a timer that notifies via a file descriptor.
Get current timer via a file descriptor.
Set current timer via a file descriptor.
Get process times.
Send a signal to a thread (obsolete).
Truncate a file to a specified length.
Set file mode creation mask.
Umount filesystem.
Get name and information about current kernel.
Delete a name and possibly the file it refers to.
Delete a name and possibly the file it refers to.
Disassociate parts of the process execution context
Load shared library.
Create a file descriptor to handle page faults in user space.
Get filesystem statistics
Change file last access and modification time.
Change time timestamps with nanosecond precision.
Change file last access and modification time.
Create a child process and wait until it is terminated.
Virtually hang up the current terminal.
Splice user page into a pipe.
Wait for process to change state.
Wait for process to change state.
Write to a file descriptor.
Write to a file descriptor from multiple buffers.

Type Definitions

Error No.