This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
as-needed and libstdc++ and pulling libpthread
- From: Samuel Thibault <samuel dot thibault at ens-lyon dot org>
- To: libc-alpha at sourceware dot org
- Date: Sat, 4 Jan 2020 19:07:54 +0100
- Subject: as-needed and libstdc++ and pulling libpthread
Hello,
We are having an issue with pulling libpthread with the as-needed
linking feature, which seems to be half-working only by luck on
GNU/Linux, and not working on GNU/Hurd. Basically, if I try to build:
#include <mutex>
void f(void) { }
std::once_flag flag;
int main(void) {
std::call_once(flag, f);
}
with
g++ test.cpp -o test -pthread
or
g++ test.cpp -o test -lpthread
the link does not actually add libpthread (even if libpthread.so does
get read by the linker, as seen in -Wl,-verbose), and I am getting a
runtime error:
terminate called after throwing an instance of 'std::system_error'
what(): Error in unknown error system: FFFFFFFF
because libstdc++'s call_once checks that the libpthread got linked in.
The same issue can be seen on GNU/Linux when using
g++ test.cpp -o test -lpthread
but not with
g++ test.cpp -o test -pthread
Because in the former case, libpthread is before libstdc++ on the link
command.
The "as-needed" feature is here on purpose avoiding to link against
libpthread, because it thinks it's not needed, because it doesn't know
that calling std::call_once will later on need libpthread. And libstdc++
itself doesn't link against libpthread on purpose, making all its
references to pthread function weak.
AFAICT, on GNU/Linux things work (by luck) with -pthread because
libstdc++ not only calls pthread functions, but also __errno_location.
printf("%p\n", errno); is indeed enough to emit a reference to
__errno_location, and then linking with -pthread will indeed bring
in libpthread. But that seems pure luck to me: should we remove
__errno_location from libpthread, we'd have the same situation. And it
doesn't work with -lpthread, programmers will wonder why.
I plan to "fix" the issue on GNU/Hurd by adding errno_location in
libpthread, so it gets the same behavior as on GNU/Linux to avoid being
exposed to such situations while GNU/Linux is not, but that's really
worrying for GNU/Linux too.
Samuel