The C Runtime Contract Gap: How Outdated Man Pages and Divergent Libcs Break Portability
Run man 3 initstate on any modern Linux distribution, scroll to the BUGS section at the bottom, and read the operational warning: "According to POSIX, initst...
Run man 3 initstate on any modern Linux distribution, scroll to the BUGS section at the bottom, and read the operational warning: "According to POSIX, initstate() should return NULL on error. In the glibc implementation, errno is (as specified) set on error, but the function does not return NULL." Copy that code into a test harness on Ubuntu 24.04 or Debian 12, compile it with GCC, pass an undersized state buffer of one byte, and assert that the returned pointer is null. The assertion succeeds without hesitation.
The manual page is describing an artifact that has not existed in production glibc builds for over thirteen years. On April 29, 2013, Andreas Jaeger committed change 9ce3b2cbd245abedc6cff147a1b91566e340edb1 to GNU libc, resolving Bug 15380 for the glibc 2.18 release. Yet the warning persisted across multiple major distribution lifecycles, surviving unchanged in manual page databases worldwide.
// Glibc stdlib/random.c: Bug 15380 fix (glibc 2.18, April 2013)
// Prior implementation ignored ret and returned stale ostate unconditionally:
// __initstate_r (seed, arg_state, n, &unsafe_state);
// return (char *) ostate;
char *
__initstate (unsigned int seed, char *arg_state, size_t n)
{
int32_t *ostate;
int ret;
__libc_lock_lock (lock);
ostate = &unsafe_state.state[-1];
ret = __initstate_r (seed, arg_state, n, &unsafe_state);
__libc_lock_release (lock);
return ret == -1 ? NULL : (char *) ostate;
}
weak_alias (__initstate, initstate)
This is not an isolated editorial slip. Inspect man 7 math_error on the same terminal, and the documentation asserts with equal gravity: "The math_errhandling identifier specified by C99 and POSIX.1 is not supported by glibc." The text goes on to characterize the situation under glibc 2.8 as inconsistent and fragmented. Glibc 2.8 was released in April 2008; glibc introduced full support for math_errhandling in version 2.11 in October 2009.
Systems engineers routinely treat Section 3 manual pages as definitive API contracts. In practice, Section 3 represents a third-party audit snapshot frozen in time, decoupled from the release cadences, bug trackers, and source repositories of the actual C runtime libraries powering the operating system.
Section 3 manual pages document an idealized hybrid: part POSIX standard specification, part kernel interface mapping, and part historical glibc behavior frozen at arbitrary publication checkpoints.
The Architecture and Decoupling of Linux Documentation
The discrepancy originates in the organizational separation between the kernel, the manual pages, and the C runtime implementations. Linux is a kernel, not an operating system distribution with a unified source tree. While FreeBSD, OpenBSD, and NetBSD maintain their kernel, C library, userland utilities, and manual pages inside a single monorepo with atomic commits across code and documentation, the Linux ecosystem operates as a loose federation of upstream projects.
The Linux man-pages project, maintained for years by Michael Kerrisk and subsequently by Alejandro Colomar, lives in its own repository at git.kernel.org. It has no build-time hooks into the GNU C Library (glibc), no integration with musl libc, and no automated verification pipeline tied to upstream libc test suites. When a developer submits a patch to glibc fixing an API deviation, there is no automated trigger to notify the manual pages repository.
- Monorepo BSD model: Kernel, libc, and man pages share commit history; documentation updates block PR merges when API signatures or error semantics change.
- Federated Linux model: Kernel documentation ships with the kernel, glibc documentation ships as Texinfo manuals inside glibc, and distribution
mancommands query an independent documentation package. - Synchronization latency: Bug fixes in glibc can take over a decade to reflect in
man-pages, while distribution packagers rarely backport documentation corrections independently.
Texinfo remains the primary documentation format favored by the GNU project. Glibc developers maintain the official GNU C Library Reference Manual in Texinfo files inside the core glibc repository. Most systems programmers, however, do not execute info libc; they invoke man 3 function_name directly from their shell or language server.
Because the manual pages project relies on manual volunteer reporting to track changes across hundreds of glibc releases, errata accumulate indefinitely. The consequence is a structural information asymmetry: the official distribution manual presents bugs that were patched a decade ago while omitting critical contract boundaries that govern alternative runtimes.
The Specification Void: What POSIX Actually Mandates
When engineers notice that initstate(3) sets errno to EINVAL on glibc when passed an invalid size, they typically assume this behavior is standardized. The manual page reinforces that assumption by detailing the error code. However, checking IEEE Std 1003.1 (POSIX) reveals a stark specification reality:
IEEE Std 1003.1-2017 (POSIX.1) Specification: initstate()
RETURN VALUE
If initstate() is called with size less than 8, it shall return NULL.
The initstate() and setstate() functions return a pointer to the previous
state information array.
ERRORS
No errors are defined.
The standard requires the function to return a null pointer if the buffer size is under eight bytes. It defines exactly zero error codes. In POSIX terminology, an interface whose ERRORS section states "No errors are defined" is prohibited from requiring callers to inspect errno to determine whether a failure occurred.
Glibc decided to turn this silent failure into a defensive API boundary. Deep inside stdlib/random_r.c, glibc implements the reentrant primitive __initstate_r with explicit precondition checks:
// Glibc stdlib/random_r.c: Defensive state validation
int
__initstate_r (unsigned int seed, char *arg_state, size_t n,
struct random_data *buf)
{
if (buf == NULL)
goto fail;
int32_t *old_state = buf->state;
// ... state transition logic ...
if (n < BREAK_0) // BREAK_0 == 8 bytes
goto fail;
// ... table configuration ...
return 0;
fail:
__set_errno (EINVAL);
return -1;
}
Because glibc routes the non-reentrant initstate through __initstate_r, callers receive a populated errno set to EINVAL. This behavior is a pure vendor extension. It teaches developers to write software that inspects errno after pseudo-random number generator initialization, masking the fact that the underlying standard makes no such promise.
When those same developers migrate their services across libc implementations, the ergonomic safety net vanishes entirely.
The Ergonomics Paradox: Glibc Defensiveness vs Musl Strictness
The divergence becomes critical when comparing glibc with alternative runtimes like musl libc. Musl powers Alpine Linux, which forms the base image for millions of containerized cloud workloads. Musl implements initstate with uncompromising adherence to the minimal POSIX mandate:
// Musl src/prng/random.c: Strict POSIX compliance
char *initstate(unsigned seed, char *state, size_t size)
{
void *old;
if (size < 8)
return 0; // Conforms to POSIX: returns NULL, leaves errno untouched
LOCK(lock);
old = savestate();
if (size < 32) n = 0;
else if (size < 64) n = 7;
else if (size < 128) n = 15;
else if (size < 256) n = 31;
else n = 63;
// Direct memory dereference: no NULL pointer check
x = (uint32_t *)state + 1;
__srandom(seed);
savestate();
LOCK_RELEASE(lock);
return old;
}
Analyze the operational differences between these two implementations under identical edge-case inputs:
- Buffer size under 8 bytes: Glibc returns
NULLand writesEINVALtoerrno. Musl returnsNULLand leaveserrnounchanged, causing callers inspectingerrnoto read stale errors from earlier system calls. - Null state pointer: Glibc returns
NULLand setserrno = EINVAL. Musl executesx = (uint32_t *)state + 1;and crashes the calling thread with an immediateSIGSEGVon line 90. - Locking overhead: Glibc encapsulates state within thread-safe structures when using reentrant variants; musl relies on a shared static lock during non-reentrant reconfiguration.
Musl maintainers deliberately omit NULL pointer checks on parameters where the standard requires a valid buffer pointer. Under the C standard, passing an invalid pointer where an object is expected invokes Undefined Behavior. Musl views defensive null-checks as code bloat that masks bugs during development and imposes unnecessary branching penalties on valid executions.
As explored in our teardown of why Swapping libc Is an Archive-Wide ABI Break, treating Linux as a monolithic runtime environment rather than distinct C library implementations leads directly to production outages. Code tested exclusively on Debian or Ubuntu silently relies on glibc's defensive parameter sanitization, only to crash when deployed to minimal container images.
The Floating-Point Exception Illusion: math_errhandling
A parallel documentation failure appears in floating-point mathematics. The C99 standard and POSIX.1 specify the macro math_errhandling in math.h. This identifier communicates whether mathematical routines signal domain and range violations via thread-local errno mutations (MATH_ERRNO, value 1) or through floating-point exceptions retrievable via fetestexcept(3) (MATH_ERREXCEPT, value 2).
For more than a decade, man 7 math_error declared that glibc lacked support for math_errhandling, citing chaotic behavior observed in glibc 2.8. In reality, glibc resolved the issue in glibc 2.11 in October 2009, enabling both error mechanisms across standard math functions.
// Inspecting math error reporting across runtime configurations
#include <stdio.h>
#include <math.h>
#include <fenv.h>
#include <errno.h>
void inspect_math_environment(void)
{
printf("math_errhandling value: %d\n", math_errhandling);
if (math_errhandling & MATH_ERRNO)
printf(" - Signals domain/range errors via errno\n");
if (math_errhandling & MATH_ERREXCEPT)
printf(" - Signals errors via floating-point hardware exceptions\n");
}
While modern glibc supports both mechanisms, musl libc takes an opposing architectural approach. In musl's include/math.h, the macro is hardcoded directly:
// Musl include/math.h
#define MATH_ERRNO 1
#define MATH_ERREXCEPT 2
#define math_errhandling 2
Musl never sets errno inside any mathematical routine. Setting errno requires resolving the thread-local storage address via __errno_location(). This write operation prevents the compiler from vectorizing transcendental operations with AVX-512 or NEON SIMD instructions, forces register spills, and introduces cache contention in multi-threaded numerical pipelines.
Compilers further compound the contract divergence. When passing optimization flags like -ffast-math or -Ofast to GCC, glibc inspects the preprocessor symbol __FAST_MATH__ and adjusts math_errhandling to expand to 0. This behavior honestly reflects that compiler optimizations have stripped IEEE 754 compliance, bypassed exception tracking, and vectorized loops under the assumption that NaNs and infinities cannot occur. Musl, conversely, continues to expand math_errhandling to 2 even when compiled under fast-math flags that invalidate hardware exception delivery.
Relying on either errno or floating-point status flags across Linux distributions is inherently brittle. The only portable error-handling strategy for numerical workloads is proactive domain validation: inspecting input arguments with isnan() and isinf() prior to execution, and checking outputs for HUGE_VAL overflow boundaries.
Architectural Rules for Systems Engineers Operating Across Libcs
When authoring cross-platform systems code, C extensions for Node.js, Go cgo integrations, or Rust FFI wrappers, engineers must decouple their assumptions from distribution manual pages. The following design rules prevent production failures caused by documentation lag and runtime divergence:
- Never treat Section 3 manual pages as authoritative ABI contracts: When verifying return codes, error branches, and reentrancy guarantees, inspect the upstream libc Git repository directly. Cross-reference glibc and musl implementations rather than trusting manual page BUGS sections.
- Check return pointers, never residual errno: If a POSIX interface lists "No errors are defined" in its specification, treat
errnoas undefined memory residue. Evaluate the return value explicitly againstNULLor error sentinels. - Enforce parameter bounds before crossing the FFI boundary: Never rely on glibc's internal defensive NULL checks. A wrapper passing a null pointer into a function that glibc tolerates will trigger a fatal segmentation fault when executed against musl libc.
- Validate numerical inputs upfront: Eliminate reliance on
math_errhandlingflags. Validate floating-point arguments using IEEE 754 predicates before invoking transcendentals to ensure consistent behavior across SIMD and fast-math builds. - Include multi-runtime validation in continuous integration: Build and test native modules inside both glibc-based (Debian/Ubuntu) and musl-based (Alpine) container images. Catching runtime divergence in continuous integration prevents silent edge-case corruption in cloud environments.