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