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:
- POSIX Base Definitions: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/toc.html. Types and structures are defined within the Headers section.
- POSIX System Interfaces: https://pubs.opengroup.org/onlinepubs/9799919799/functions/toc.html. Functions are defined under the System Interfaces section.
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:
- Apple: Official manpages exist at https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man5/manpages.5.html but are severly outdated. https://developer.apple.com/documentation/kernel exists but only provides API signatures without documenttion. https://manp.gs/mac/ or https://ss64.com/mac/ are better options.
- DragonFlyBSD: https://www.dragonflybsd.org/cgi/web-man
- FreeBSD: https://man.freebsd.org/cgi/man.cgi
- IBM AIX: https://www.ibm.com/docs/en/aix/7.3.0
- Illumos: https://illumos.org/man/
- Linux:
- https://man7.org/linux/man-pages/index.html or https://linux.die.net/man/ provide documentation of Linux API as well as the C library, with a focus on glibc.
- Glibc-specific documentation is available at https://sourceware.org/glibc/manual/latest/html_mono/libc.html.
- Musl documentation states to refer to POSIX, linked above, and the C standard, available at https://www.open-std.org/JTC1/SC22/WG14/www/projects#9899 (published versions must be purchased but the drafts are free).
- NetBSD: https://man.netbsd.org/
- OpenBSD: https://man.openbsd.org/
- Solaris: https://docs.oracle.com/cd/E88353_01/
- Windows MSVC: https://learn.microsoft.com/en-us/cpp/c-runtime-library/c-run-time-library-reference?view=msvc-180
§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.
-
Never construct a
libcstruct withMaybeUninit::uninit(), call alibcfunction with it, then callassume_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 thelibcstruct but not on older versions of the platform’s C library. It is far too easy to end up with a bogusassume_initbecause not all fields have been written.Instead, use
MaybeUninit::zeroed()or theDefaultimplementations that are slowly being added. Alternatively, access fields only via raw pointer without ever usingassume_init.See also the safety docs for
MaybeUninit::assume_inithttps://doc.rust-lang.org/beta/std/mem/union.MaybeUninit.html#method.assume_init. -
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
libcversions. That is, iflibccontains 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. Forget_time, return atime_tor explicitly cast to ani64.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. -
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
libcas:ⓘstruct filestat { fs_type: c_int, // ... next: __c_anonymous_filestat, } struct __c_anonymous_filestat { stqe_next: *mut filestat }Accessing
some_filestat.next.stqe_nextis completely fine, but__c_anonymous_filestatshould not be used anywhere (e.g. in a function signature). This is done to permitlibcto switch to anonymous fields if the feature is ever added to Rust. -
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. -
Be aware of deprecation warnings. These are used as a way to migrate necessary API changes.
§Cargo Features
-
std: by defaultlibcassumes that the standard library contains link directives necessary to use the APIs in this crate. Ifstdis disabled,libcwill emit the directives instead.This feature is slated for removal in
libc1.0. The intention is that no-std users oflibcshould use their own#[link]attributes,rustc-link-libbuild script directives, or-larguments for only the system libraries they need to link, rather thanlibcpossibly linking more than is needed or available. If you are usinglibcwithout thestdfeature, consider starting to add link directives now for a smoother 1.0 transition. -
extra_traits: all types inlibcimplementClone,Copy, andDebug. Theextra_traitsfeature addsEq,Hash, andPartialEq.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, anduse_stdare 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
paddingorreservedchange type or are removed. - The length of an array type changes.
- A struct field (with available padding) is changed from
inttolong.
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
libccrate 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
voidtype 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_MAX
Deprecated - INT_MIN
Deprecated - 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
chartype. - c_
double - Equivalent to C’s
doubletype. - c_float
- Equivalent to C’s
floattype. - 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 chartype. - c_short
- Equivalent to C’s
signed short(short) type. - c_uchar
- Equivalent to C’s
unsigned chartype. - c_uint
- Equivalent to C’s
unsigned inttype. - c_ulong
- Equivalent to C’s
unsigned longtype. - c_
ulonglong - Equivalent to C’s
unsigned long longtype. - c_
ushort - Equivalent to C’s
unsigned shorttype. - clock_t
- dev_t
- errno_t
- ino_t
- int8_t
Deprecated - int16_t
Deprecated - int32_t
Deprecated - int64_t
Deprecated - intmax_
t - intptr_
t - off_t
- ptrdiff_
t - sighandler_
t - size_t
- ssize_t
- time64_
t - time_t
- uint8_t
Deprecated - uint16_
t Deprecated - uint32_
t Deprecated - uint64_
t Deprecated - uintmax_
t - uintptr_
t - wchar_t