split internal lock API out of libc.h, creating lock.h
[musl] / src / locale / setlocale.c
1 #include <locale.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "locale_impl.h"
5 #include "libc.h"
6 #include "lock.h"
7
8 static char buf[LC_ALL*(LOCALE_NAME_MAX+1)];
9
10 static char *setlocale_one_unlocked(int cat, const char *name)
11 {
12         const struct __locale_map *lm;
13
14         if (name) libc.global_locale.cat[cat] = lm = __get_locale(cat, name);
15         else lm = libc.global_locale.cat[cat];
16
17         return lm ? (char *)lm->name : "C";
18 }
19
20 char *setlocale(int cat, const char *name)
21 {
22         static volatile int lock[1];
23
24         if ((unsigned)cat > LC_ALL) return 0;
25
26         LOCK(lock);
27
28         /* For LC_ALL, setlocale is required to return a string which
29          * encodes the current setting for all categories. The format of
30          * this string is unspecified, and only the following code, which
31          * performs both the serialization and deserialization, depends
32          * on the format, so it can easily be changed if needed. */
33         if (cat == LC_ALL) {
34                 int i;
35                 if (name) {
36                         char part[LOCALE_NAME_MAX+1] = "C.UTF-8";
37                         const char *p = name;
38                         for (i=0; i<LC_ALL; i++) {
39                                 const char *z = __strchrnul(p, ';');
40                                 if (z-p <= LOCALE_NAME_MAX) {
41                                         memcpy(part, p, z-p);
42                                         part[z-p] = 0;
43                                         if (*z) p = z+1;
44                                 }
45                                 setlocale_one_unlocked(i, part);
46                         }
47                 }
48                 char *s = buf;
49                 const char *part;
50                 int same = 0;
51                 for (i=0; i<LC_ALL; i++) {
52                         const struct __locale_map *lm =
53                                 libc.global_locale.cat[i];
54                         if (lm == libc.global_locale.cat[0]) same++;
55                         part = lm ? lm->name : "C";
56                         size_t l = strlen(part);
57                         memcpy(s, part, l);
58                         s[l] = ';';
59                         s += l+1;
60                 }
61                 *--s = 0;
62                 UNLOCK(lock);
63                 return same==LC_ALL ? (char *)part : buf;
64         }
65
66         char *ret = setlocale_one_unlocked(cat, name);
67
68         UNLOCK(lock);
69
70         return ret;
71 }