[PATCH] libstdc++/112351 - deal with __gthread_once failure during locale init
Jonathan Wakely
jwakely@redhat.com
Mon Nov 6 12:15:24 GMT 2023
On Mon, 6 Nov 2023 at 11:52, Richard Biener <rguenther@suse.de> wrote:
>
> The following makes the C++98 locale init path follow the way the
> C++11 performs initialization. This way we deal with pthread_once
> failing, falling back to non-threadsafe initialization which, given we
> initialize from the library, should be serialized by the dynamic
> loader already.
>
> Bootstrapped and tested on x86_64-unknown-linux-gnu, OK for trunk?
> And GCC 13 branch?
>
> Thanks,
> Richard.
>
> PR libstdc++/112351
> libstdc++-v3/
> * src/c++98/locale.cc (locale::facet::_S_get_c_locale):
> Always perform non-threadsafe init when threadsafe init
> failed.
> ---
> libstdc++-v3/src/c++98/locale.cc | 7 ++-----
> 1 file changed, 2 insertions(+), 5 deletions(-)
>
> diff --git a/libstdc++-v3/src/c++98/locale.cc b/libstdc++-v3/src/c++98/locale.cc
> index d308140bab7..e9bec1db3b6 100644
> --- a/libstdc++-v3/src/c++98/locale.cc
> +++ b/libstdc++-v3/src/c++98/locale.cc
> @@ -216,12 +216,9 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
> #ifdef __GTHREADS
> if (__gthread_active_p())
> __gthread_once(&_S_once, _S_initialize_once);
> - else
> #endif
> - {
> - if (!_S_c_locale)
> - _S_initialize_once();
> - }
> + if (__builtin_expect (!_S_c_locale, 0))
> + _S_initialize_once();
> return _S_c_locale;
> }
I think this has a problem, which is handled correctly in
src/c++11/locale_init.cc by checking _S_classic inside the
_S_initialize_once function.
If the first call to __gthread_once does fail then _S_once will not be
changed. We will fall through to calling _S_initialize_once directly
(which is not thread-safe) and set _S_c_locale.
The next time we call _S_initialize, __gthread_once will try to run
again, and because _S_once was not changed, it might call
_S_initialize_once() again, which writes to _S_c_locale again
(possibly causing a data race).
I don't think the slightly different code in src/c++11/locale_init.cc
is different in order to handle __gthread_once failing, I think it's
different because the effects of locale::facet::_S_initialize_once()
and locale::_S_initialize_once() are different. One is safe to call
more than once, and the other isn't.
I don't think we need to care about __gthread_once failing at all, do
we? There are no error conditions for pthread_once, it always returns
0 (previous POSIX revisions said it could return EINVAL for an
uninitialized pthread_once_t but that can't happen here as it's
correctly initialized in src/c++11/locale.cc). Is the concern that it
can fail for non-posix thread models? (I didn't check if any of them
can actually fail)
More information about the Libstdc++
mailing list