Skip to main content

Crate libc

Crate libc 

Source
Expand description

Raw FFI bindings to platform system libraries.

§API Documentation

libc only provides the bindings, not instructions on how to use them. For this, please refer to the relevant C documentation.

POSIX provides OS-agnostic API definitions, which most platforms aim to comply with. Its specifications are often the best place to look:

For platform-specific API and caveats to the standard API, platform-specific manual pages are usually the place to look. Locally you can run commands like man 2 stat or man 3 printf (2 for kernel interfaces, 3 for standard library) to get documentation, but there are also a number of platforms with manual pages available online:

§Usage Guidelines

libc exposes non-Rust interfaces in Rust, which makes for some caveats to its use that are not present in most Rust libraries. Observing the following guidelines are recommended to help avoid soundness and stability pitfalls.

  1. Never construct a libc struct with MaybeUninit::uninit(), call a libc function with it, then call assume_init. Library functions do not always initialize all fields; this includes obvious cases like padding fields, but also less obvious cases like fields present in the libc struct but not on older versions of the platform’s C library. It is far too easy to end up with a bogus assume_init because not all fields have been written.

    Instead, use MaybeUninit::zeroed() or the Default implementations that are slowly being added. Alternatively, access fields only via raw pointer without ever using assume_init.

    See also the safety docs for MaybeUninit::assume_init https://doc.rust-lang.org/beta/std/mem/union.MaybeUninit.html#method.assume_init.

  2. Avoid relying on the exact value of constants, the exact length of arrays, or the exact types of type aliases, as they may change across libc versions. That is, if libc contains code like:

    ⓘ
    const IFNAMSIZ: usize = 16;
    
    pub struct ifreq {
        pub ifr_name: [c_char; IFNAMSIZ],
        // ...
    }
    
    extern "C" {
        pub fn time(time: *mut time_t) -> time_t;
    }

    Then avoid writing code like:

    ⓘ
    // Bad assumption that the length will always be 16.
    fn takes_ifr_name(ifr_name: [c_char; 16]) { /* ... */ }
    
    fn process_ifr(ifr: ifreq) {
        takes_ifr_name(ifr.ifr_name);
    }
    
    // Bad assumption that `time_t` will always be an `i64`. Use `-> time_t` instead, or
    // explicitly cast to an `i64`.`
    fn get_time() -> i64 {
        unsafe { time(ptr::null_mut()) }
    }
    

    For takes_ifr_name, use [c_char; IFNAMSIZ] or just &[c_char] instead. For get_time, return a time_t or explicitly cast to an i64.

    Along the same lines, if you write code along the lines of assert_eq!(libc::ELAST, 97), expect that there may be a release where this starts to fail.

  3. Do not name __c_anonymous_* types anywhere, which exist to represent anonymous fields in C. For example, FreeBSD defines:

    struct filestat {
        int fs_type;
        // ...
        struct { struct filestat stqe_next; } next;
    };

    Which is represented in libc as:

    ⓘ
    struct filestat {
        fs_type: c_int,
        // ...
        next: __c_anonymous_filestat,
    }
    
    struct __c_anonymous_filestat { stqe_next: *mut filestat }

    Accessing some_filestat.next.stqe_next is completely fine, but __c_anonymous_filestat should not be used anywhere (e.g. in a function signature). This is done to permit libc to switch to anonymous fields if the feature is ever added to Rust.

  4. Avoid accessing fields with names such as __reserved, _pad, or _spare. Usually the platform libraries use these to allow adding new fields without changing the size of a struct, but this means their types change frequently.

  5. Be aware of deprecation warnings. These are used as a way to migrate necessary API changes.

§Cargo Features

  • std: by default libc assumes that the standard library contains link directives necessary to use the APIs in this crate. If std is disabled, libc will emit the directives instead.

    This feature is slated for removal in libc 1.0. The intention is that no-std users of libc should use their own #[link] attributes, rustc-link-lib build script directives, or -l arguments for only the system libraries they need to link, rather than libc possibly linking more than is needed or available. If you are using libc without the std feature, consider starting to add link directives now for a smoother 1.0 transition.

  • extra_traits: all types in libc implement Clone, Copy, and Debug. The extra_traits feature adds Eq, Hash, and PartialEq.

    This feature is expected to be removed in libc 1.0. Libraries should instead hash or check equality of only needed fields.

  • The features const-extern-fn, align, and use_std are all deprecated and do nothing.

§Stability Expectations

Due to libc’s position in the ecosystem, it can effectively never publish semver-breaking releases. However, the API that libc binds changes all the time; sometimes in ways that are harmless, sometimes in ways that are technically API-breaking for all users but unlikely to be noticed (e.g. removing deprecated API), and sometimes in ways that are nonbreaking in C but translate to breaking changes in Rust (e.g. changing the type of an integer). libc tries to strike a balance but all of this means that unfortunately, libc must occasionally ship changes within a semver-compatible release that are technically semver-breaking.

The following are examples of changes that fall into this category:

  • Fields are added to a struct that is otherwise exhaustive.
  • Fields with names such as padding or reserved change type or are removed.
  • The length of an array type changes.
  • A struct field (with available padding) is changed from int to long.

In general, libc aims to follow platform API changes, even when this means changes that are user-visible in Rust. There are a few guidelines used here:

  • Adding struct fields is not considered breaking, nor is changing fields named reserved, padding, or similar. This is because users are expected to use field-by-field initialization.
  • Changing type aliases, values of constants, or array lengths is not considered breaking.
  • If the platform libc has accepted breakage on the C side (typically in the form of removing old API), the libc crate will follow suit.
  • Where possible, #[deprecated(...)] will be used to warn about changes before applying them. Alternative mitigations may be considered.
  • Potentially breaking changes will be well-identified in release notes.
  • Beyond this, public API is not expected to change on Tier 1 targets. Tier 2 targets have relaxed API stability requirements, and API stability is not enforced on tier 3 targets.

While this section seems scary, keep in mind that it is meant to cover worst-case scenarios. In practice, breakage is rare and following the above-discussed Usage Guidelines means that most libc users will never encounter a problem.

Structs§

FILE
This is an extern type (“opaque” or “incomplete” type in C).
fpos_t
This is an extern type (“opaque” or “incomplete” type in C).
max_align_t
sockaddr
stat
timespec
timeval
timezone
This is an extern type (“opaque” or “incomplete” type in C).
tm
utimbuf

Enums§

c_void
Equivalent to C’s void type when used as a [pointer].

Constants§

BUFSIZ
E2BIG
EACCES
EADDRINUSE
EADDRNOTAVAIL
EAFNOSUPPORT
EAGAIN
EALREADY
EBADF
EBADMSG
EBUSY
ECANCELED
ECHILD
ECONNABORTED
ECONNREFUSED
ECONNRESET
EDEADLK
EDEADLOCK
EDESTADDRREQ
EDOM
EEXIST
EFAULT
EFBIG
EHOSTUNREACH
EIDRM
EILSEQ
EINPROGRESS
EINTR
EINVAL
EIO
EISCONN
EISDIR
ELOOP
EMFILE
EMLINK
EMSGSIZE
ENAMETOOLONG
ENETDOWN
ENETRESET
ENETUNREACH
ENFILE
ENOBUFS
ENODATA
ENODEV
ENOENT
ENOEXEC
ENOLCK
ENOLINK
ENOMEM
ENOMSG
ENOPROTOOPT
ENOSPC
ENOSR
ENOSTR
ENOSYS
ENOTCONN
ENOTDIR
ENOTEMPTY
ENOTRECOVERABLE
ENOTSOCK
ENOTSUP
ENOTTY
ENXIO
EOF
EOPNOTSUPP
EOVERFLOW
EOWNERDEAD
EPERM
EPIPE
EPROTO
EPROTONOSUPPORT
EPROTOTYPE
ERANGE
EROFS
ESPIPE
ESRCH
ETIME
ETIMEDOUT
ETXTBSY
EWOULDBLOCK
EXDEV
EXIT_FAILURE
EXIT_SUCCESS
FILENAME_MAX
FOPEN_MAX
INT_MAXDeprecated
INT_MINDeprecated
LC_ALL
LC_COLLATE
LC_CTYPE
LC_MONETARY
LC_NUMERIC
LC_TIME
L_tmpnam
NSIG
O_APPEND
O_BINARY
O_CREAT
O_EXCL
O_NOINHERIT
O_RANDOM
O_RAW
O_RDONLY
O_RDWR
O_SEQUENTIAL
O_TEMPORARY
O_TEXT
O_TRUNC
O_WRONLY
RAND_MAX
SEEK_CUR
SEEK_END
SEEK_SET
SIGABRT
SIGFPE
SIGILL
SIGINT
SIGSEGV
SIGTERM
SIG_ACK
SIG_DFL
SIG_ERR
SIG_GET
SIG_IGN
SIG_SGE
STDERR_FILENO
STDIN_FILENO
STDOUT_FILENO
STRUNCATE
S_IEXEC
S_IFCHR
S_IFDIR
S_IFMT
S_IFREG
S_IREAD
S_IWRITE
TMP_MAX
_IOFBF
_IOLBF
_IONBF
_O_OBTAIN_DIR
_O_SHORT_LIVED
_O_U8TEXT
_O_U16TEXT
_O_WTEXT

Functions§

_exit⚠
_msize⚠
abort⚠
abs⚠
accept⚠
access⚠
aligned_free⚠
aligned_malloc⚠
aligned_realloc⚠
atexit⚠
atof⚠
atoi⚠
atol⚠
atoll⚠
bind⚠
calloc⚠
chdir⚠
chmod⚠
clock⚠
close⚠
commit⚠
connect⚠
creat⚠
ctime⚠
difftime⚠
dup⚠
dup2⚠
execl⚠
execle⚠
execlp⚠
execlpe⚠
execv⚠
execve⚠
execvp⚠
execvpe⚠
exit⚠
fclose⚠
fdopen⚠
feof⚠
ferror⚠
fflush⚠
fgetc⚠
fgetpos⚠
fgets⚠
fileno⚠
fopen⚠
fprintf⚠
fputc⚠
fputs⚠
fread⚠
free⚠
freopen⚠
fscanf⚠
fseek⚠
fsetpos⚠
fstat⚠
ftell⚠
fwrite⚠
get_daylight⚠
get_dstbias⚠
get_osfhandle⚠
get_timezone⚠
get_tzname⚠
getchar⚠
getcwd⚠
getenv⚠
getpeername⚠
getpid⚠
getsockname⚠
getsockopt⚠
gmtime_s⚠
isalnum⚠
isalpha⚠
isatty⚠
isblank⚠
iscntrl⚠
isdigit⚠
isgraph⚠
islower⚠
isprint⚠
ispunct⚠
isspace⚠
isupper⚠
isxdigit⚠
labs⚠
listen⚠
localtime_s⚠
lseek⚠
lseek64⚠
malloc⚠
memchr⚠
memcmp⚠
memcpy⚠
memmove⚠
memset⚠
mkdir⚠
open⚠
open_osfhandle⚠
pclose⚠
perror⚠
pipe⚠
popen⚠
printf⚠
putchar⚠
putenv⚠
putenv_s⚠
puts⚠
qsort⚠
qsort_s⚠
raise⚠
rand⚠
read⚠
realloc⚠
recvfrom⚠
remove⚠
rename⚠
rewind⚠
rmdir⚠
scanf⚠
sendto⚠
setbuf⚠
setlocale⚠
setsockopt⚠
setvbuf⚠
signal⚠
snprintf⚠
socket⚠
sprintf⚠
srand⚠
sscanf⚠
stat⚠
strcasecmp⚠
strcat⚠
strchr⚠
strcmp⚠
strcoll⚠
strcpy⚠
strcspn⚠
strdup⚠
strerror⚠
strlen⚠
strncasecmp⚠
strncat⚠
strncmp⚠
strncpy⚠
strnlen⚠
strpbrk⚠
strrchr⚠
strspn⚠
strstr⚠
strtod⚠
strtof⚠
strtok⚠
strtol⚠
strtoll⚠
strtoul⚠
strtoull⚠
strxfrm⚠
system⚠
time⚠
tmpfile⚠
tolower⚠
toupper⚠
tzset⚠
ungetc⚠
unlink⚠
wchmod⚠
wcslen⚠
wcsnlen⚠
wcstombs⚠
wexecl⚠
wexecle⚠
wexeclp⚠
wexeclpe⚠
wexecv⚠
wexecve⚠
wexecvp⚠
wexecvpe⚠
wmemchr⚠
wopen⚠
wputenv⚠
wputenv_s⚠
write⚠
wrmdir⚠
wsetlocale⚠
wstat⚠
wutime⚠

Type Aliases§

SOCKET
c_char
Equivalent to C’s char type.
c_double
Equivalent to C’s double type.
c_float
Equivalent to C’s float type.
c_int
Equivalent to C’s signed int (int) type.
c_long
Equivalent to C’s signed long (long) type.
c_longlong
Equivalent to C’s signed long long (long long) type.
c_schar
Equivalent to C’s signed char type.
c_short
Equivalent to C’s signed short (short) type.
c_uchar
Equivalent to C’s unsigned char type.
c_uint
Equivalent to C’s unsigned int type.
c_ulong
Equivalent to C’s unsigned long type.
c_ulonglong
Equivalent to C’s unsigned long long type.
c_ushort
Equivalent to C’s unsigned short type.
clock_t
dev_t
errno_t
ino_t
int8_tDeprecated
int16_tDeprecated
int32_tDeprecated
int64_tDeprecated
intmax_t
intptr_t
off_t
ptrdiff_t
sighandler_t
size_t
ssize_t
time64_t
time_t
uint8_tDeprecated
uint16_tDeprecated
uint32_tDeprecated
uint64_tDeprecated
uintmax_t
uintptr_t
wchar_t