Use thread-safe locale functions if available

setlocale() is not thread-safe. It can actually trigger a crash if
another thread uses locale informations at the same time in the process.
Library code should use POSIX newlocale/duplocale/uselocale/freelocale
instead. Those functions only change the locale data for the calling
thread.

Signed-off-by: Rémi Denis-Courmont <remi@remlab.net>
Signed-off-by: Jaroslav Kysela <perex@perex.cz>
This commit is contained in:
Rémi Denis-Courmont 2010-04-21 18:37:48 +02:00 committed by Jaroslav Kysela
parent 51ef640cee
commit 8d80d5f344

View file

@ -499,22 +499,38 @@ static int safe_strtod(const char *str, double *val)
{ {
char *end; char *end;
double v; double v;
#ifdef HAVE_USELOCALE
locale_t saved_locale, c_locale;
#else
char *saved_locale; char *saved_locale;
char locstr[64]; /* enough? */ char locstr[64]; /* enough? */
#endif
int err; int err;
if (!*str) if (!*str)
return -EINVAL; return -EINVAL;
#ifdef HAVE_USELOCALE
c_locale = newlocale(LC_NUMERIC_MASK, "C", 0);
saved_locale = uselocale(c_locale);
#else
saved_locale = setlocale(LC_NUMERIC, NULL); saved_locale = setlocale(LC_NUMERIC, NULL);
if (saved_locale) { if (saved_locale) {
snprintf(locstr, sizeof(locstr), "%s", saved_locale); snprintf(locstr, sizeof(locstr), "%s", saved_locale);
setlocale(LC_NUMERIC, "C"); setlocale(LC_NUMERIC, "C");
} }
#endif
errno = 0; errno = 0;
v = strtod(str, &end); v = strtod(str, &end);
err = -errno; err = -errno;
#ifdef HAVE_USELOCALE
if (c_locale != (locale_t)0) {
uselocale(saved_locale);
freelocale(c_locale);
}
#else
if (saved_locale) if (saved_locale)
setlocale(LC_NUMERIC, locstr); setlocale(LC_NUMERIC, locstr);
#endif
if (err) if (err)
return err; return err;
if (*end) if (*end)