Redeclaring an inline-only libc function as weak makes every call in that file jump to null on glibc before 2.33
Symptom#
A program, or a test, that includes a header declaring int stat(const char*, struct stat*) __attribute__((weak)); segfaults at its first stat() call on glibc 2.28 (exit code 139). brahma's test_posix died this way in Debug right after the glibc guard on the stat family was removed: the log stopped at 15 Captured openat64 call, then Error: signal 11.
Cause#
Before glibc 2.33, stat, lstat, fstat, fstatat and mknod are inline wrappers around __xstat and friends, not exported symbols. The weak redeclaration makes the compiler call the symbol stat instead of the inline wrapper. That symbol does not exist, so the address is null. From 2.33 on, stat is a real export and nothing breaks, so the bug shows only on old glibc.
Fix#
Declare the weak symbol under a private name with an asm label, and use that name for the null check, so the application's own stat is never redeclared: extern "C" { int stat_symbol(const char*, struct stat*) __asm__("stat") __attribute__((weak)); } then &stat_symbol. brahma does this with GOTCHA_MACRO_TYPEDEF_ALIAS and GOTCHA_BINDING_MACRO_ALIAS, for stat, lstat, fstat, fstatat, their 64 variants and mknod.
Evidence#
Four-line repro on manylinux_2_28 (glibc 2.28): int stat(const char*, struct stat*) __attribute__((weak)); int main(){ struct stat sb; return stat("/tmp",&sb); } gives Segmentation fault, rc=139. After the alias change brahma test_posix passes in Release and Debug on glibc 2.28, 2.34 and 2.39 (POSIX 102, 111 and 111 of the same count).
Also found by searching
- Segmentation fault calling stat() after including a header with a weak declaration of stat
- weak declaration of stat is null on glibc 2.28
- test_posix SEGFAULT stat("", NULL) after removing __GLIBC_PREREQ guard
- how do I take the address of stat to check it exists without breaking callers