1#include <stdlib.h>
2#include <string.h>
3#include <pthread.h>
4#include "locale_impl.h"
5#include "lock.h"
6
7static int default_locale_init_done;
8static struct __locale_struct default_locale, default_ctype_locale;
9
10int __loc_is_allocated(locale_t loc)
11{
12 return loc && loc != C_LOCALE && loc != UTF8_LOCALE
13 && loc != &default_locale && loc != &default_ctype_locale;
14}
15
16static locale_t do_newlocale(int mask, const char *name, locale_t loc)
17{
18 struct __locale_struct tmp;
19
20 for (int i=0; i<LC_ALL; i++) {
21 tmp.cat[i] = (!(mask & (1<<i)) && loc) ? loc->cat[i] :
22 __get_locale(i, (mask & (1<<i)) ? name : "");
23 if (tmp.cat[i] == LOC_MAP_FAILED)
24 return 0;
25 }
26
27 /* For locales with allocated storage, modify in-place. */
28 if (__loc_is_allocated(loc)) {
29 *loc = tmp;
30 return loc;
31 }
32
33 /* Otherwise, first see if we can use one of the builtin locales.
34 * This makes the common usage case for newlocale, getting a C locale
35 * with predictable behavior, very fast, and more importantly, fail-safe. */
36 if (!memcmp(&tmp, C_LOCALE, sizeof tmp)) return C_LOCALE;
37 if (!memcmp(&tmp, UTF8_LOCALE, sizeof tmp)) return UTF8_LOCALE;
38
39 /* And provide builtins for the initial default locale, and a
40 * variant of the C locale honoring the default locale's encoding. */
41 if (!default_locale_init_done) {
42 for (int i=0; i<LC_ALL; i++)
43 default_locale.cat[i] = __get_locale(i, "");
44 default_ctype_locale.cat[LC_CTYPE] = default_locale.cat[LC_CTYPE];
45 default_locale_init_done = 1;
46 }
47 if (!memcmp(&tmp, &default_locale, sizeof tmp)) return &default_locale;
48 if (!memcmp(&tmp, &default_ctype_locale, sizeof tmp))
49 return &default_ctype_locale;
50
51 /* If no builtin locale matched, attempt to allocate and copy. */
52 if ((loc = malloc(sizeof *loc))) *loc = tmp;
53
54 return loc;
55}
56
57locale_t __newlocale(int mask, const char *name, locale_t loc)
58{
59 LOCK(__locale_lock);
60 loc = do_newlocale(mask, name, loc);
61 UNLOCK(__locale_lock);
62 return loc;
63}
64
65weak_alias(__newlocale, newlocale);