Skip to content

Locales in libc

ebenali edited this page Dec 4, 2026 · 2 revisions

Locales in libc, and per-thread locales

A locale decides how text and numbers look to a program: which bytes are letters, how many bytes a character may take, the decimal point, the collation order, the date format, the language of messages. C had one locale per process, set with setlocale(3). POSIX 2008 added locale objects (newlocale, duplocale, freelocale), functions taking one explicitly (strtod_l, isalpha_l, strcoll_l, ...), and uselocale(3), which gives the calling thread a locale of its own without disturbing the others. C++ runtimes and many libraries rely on it to parse or format in a fixed locale.

This chapter describes how NetBSD's libc represents a locale, the one hook through which almost every locale-dependent function finds the current one, and how the public macros in <ctype.h> and <stdlib.h> stay fast while following the thread.

A locale object

struct _locale (lib/libc/locale/setlocale_local.h) is what a locale_t points to:

  • part_name[] and part_impl[], indexed by category (LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME, LC_MESSAGES): each category's name and its loaded data. For LC_CTYPE the data is a _RuneLocale, holding the classification table (rl_ctype_tab), the case tables (rl_tolower_tab, rl_toupper_tab) and the citrus converter that decides the multibyte encoding.
  • cache: what localeconv() returns (a struct lconv) and the names it was built from, computed once per object.
  • query: the composite name setlocale(LC_ALL, NULL) returns.

There are two built-in objects: _lc_C_locale (LC_C_LOCALE, the "C"/"POSIX" locale) and _lc_global_locale, the process's global locale, which setlocale(3) changes. Each category is loaded by its own setter (_citrus_LC_CTYPE_setlocale and the others, from the template nb_lc_template.h), which fills one slot of the object it is given.

The current locale: _current_locale()

Locale-dependent functions without a locale_t argument are thin wrappers over their _l forms:

double
strtod(const char *s, char **sp)
{
	return _int_strtod_l(s, sp, _current_locale());
}

localeconv, printf's decimal point, strcoll, nl_langinfo, the wide character and multibyte functions all follow this pattern. _current_locale() (setlocale_local.h, libc-internal) is therefore the one place that decides which locale applies:

static __inline struct _locale *
_current_locale(void)
{
	struct _locale *loc = _lc_thread_locale;

	return loc != NULL ? loc : &_lc_global_locale;
}

_lc_thread_locale is a __thread pointer, the calling thread's installed locale, NULL meaning "the global one". It uses the initial-exec TLS model: libc is loaded at startup, so the variable sits at a fixed offset from the thread pointer and reading it is one load, with no call into the dynamic linker (__tls_get_addr). A new thread starts with NULL, so new threads use the global locale.

uselocale(3)

lib/libc/locale/uselocale.c:

  • uselocale(loc) installs loc as the thread's locale;
  • uselocale(LC_GLOBAL_LOCALE) returns the thread to the global locale (sets the pointer to NULL);
  • uselocale((locale_t)0) changes nothing and only queries;
  • the return value is the locale that was current before: LC_GLOBAL_LOCALE if the thread had none installed.

So the usual pattern restores whatever was there:

locale_t c = newlocale(LC_ALL_MASK, "C", (locale_t)0);
locale_t old = uselocale(c);
snprintf(buf, sizeof(buf), "%g", x);	/* always a '.' */
uselocale(old);
freelocale(c);

The object must outlive its installation: freelocale of a locale some thread still uses is undefined.

setlocale(3) acts on the global locale only, setting and querying _lc_global_locale, never the thread's. A thread with an installed locale is unaffected by another thread's setlocale, and setlocale's answer in such a thread describes the global locale, not the one the thread is using.

newlocale(3) with a null base starts from the POSIX locale for the categories not in the mask, as POSIX requires. With per-thread locales, starting from "the current locale" would make the result depend on which thread asked; code that wants another starting point passes it as the base (for example a UTF-8 LC_CTYPE before adding LC_MONETARY).

The fast paths in public headers

Two kinds of locale-dependent code are compiled into programs, not called in libc:

  • the <ctype.h> macros (isalpha, toupper, ...), which index a table (sys/sys/ctype_inline.h);
  • MB_CUR_MAX in <stdlib.h>, an expression, not a function.

Historically they read globals: _ctype_tab_, _tolower_tab_, _toupper_tab_, __mb_cur_max. Only setlocale updates those: when the LC_CTYPE setter loads data into _lc_global_locale, it calls update_global (citrus_lc_ctype.c), which points the globals at the new tables. Loading into any other object leaves them alone.

A thread's own locale cannot be reached through those globals, and making every macro call a function would slow every program. The headers therefore test a process-wide flag first:

#define	_CTYPE_CUR_(tab)						\
	(__predict_true(_lc_thread_locales == 0) ? tab : tab ## cur())
#define	isalpha(c)	((int)((_CTYPE_CUR_(_ctype_tab_) + 1)[(c)] & _CTYPE_A))

#define	MB_CUR_MAX							\
	(__predict_true(_lc_thread_locales == 0) ? __mb_cur_max :	\
	    _mb_cur_max_cur())
  • _lc_thread_locales is 0 until some thread first installs a locale object with uselocale, and is never reset: a thread may keep its locale for the rest of the process, and the macros cannot know when none is left.
  • While it is 0, every thread uses the global locale, the globals are right, and the macros cost one extra load and a predicted branch.
  • Once it is set, the macros call _ctype_tab_cur(), _tolower_tab_cur(), _toupper_tab_cur() and _mb_cur_max_cur(), which return the calling thread's tables, or the globals for a thread without one.
  • The flag only goes from 0 to 1, and the thread that sets it also installs its locale; that thread sees its own store, and other threads that still read 0 for a moment are using the global locale, for which the globals are correct. No barrier is needed.

The function forms (isalpha() and the rest in lib/libc/gen/isctype.c) read the thread's tables directly, without the flag.

Header hygiene. Both <ctype.h> (through ctype_inline.h) and <stdlib.h> declare _lc_thread_locales. A program including both would see two identical extern declarations, which is legal C but an error in builds with -Wredundant-decls -Werror; a guard macro, __LC_THREAD_LOCALES_DECLARED, lets whichever header comes first declare it.

ABI. The macros are expanded at compile time, so the behaviour is the header's that the binary was built with. Binaries built against the old headers keep reading the globals: they see the global locale in every thread, exactly as before, and correctly as long as they do not call uselocale themselves. Libraries that call uselocale on behalf of such a program change only what libc's own functions see.

The dynamic linker must not use locale state

ld.elf_so is built from its own sources plus some of libc's (libc_pic). It runs before libc is initialised, it is the one that sets up the program's TLS, and it never sets a locale. Code it links from libc must therefore not touch TLS or libc's locale objects: a <ctype.h> macro now refers to _lc_thread_locales and the _cur functions, which would drag libc's locale machinery into the dynamic linker. Where it needs to classify characters (expand.c, ending a $ORIGIN-style token), it tests for ASCII letters itself (c_isalpha), which is also the right answer for a program that has not set a locale, and it no longer carries a copy of the ctype tables. The general rule: anything compiled into ld.elf_so uses self-contained helpers, never libc's TLS variables or locale state.

The rule reaches further than the dynamic linker. A header change that makes a libc macro refer to libc state (a variable, a function) changes what every user of the macro links against. Programs that link only part of libc, such as ld.elf_so, static or partial links of libc objects, boot or rescue programs built from selected sources, then need that state too, or fail to link. When a public macro gains such a reference, check every place that compiles libc sources outside libc.

Gaps

Known departures from POSIX, measured with the rest of libc by the conformance suites (Roadmap, F2):

  • newlocale with a base copies the base and does not free it, so the base, which POSIX says the call consumes, leaks;
  • newlocale ignores missing locale data instead of failing with ENOENT;
  • it does not reject invalid mask bits with EINVAL.

Source pointers

  • lib/libc/locale/setlocale_local.h — struct _locale, _current_locale(); global_locale.c — _lc_global_locale, _lc_C_locale.
  • lib/libc/locale/uselocale.c — uselocale, _lc_thread_locale, _lc_thread_locales, the _cur accessors.
  • lib/libc/locale/setlocale.c, newlocale.c, duplocale.c, freelocale.c; nb_lc_template.h (per-category setter); lib/libc/citrus/citrus_lc_ctype.c (update_global).
  • sys/sys/ctype_inline.h, include/stdlib.h (MB_CUR_MAX), lib/libc/gen/isctype.c.
  • libexec/ld.elf_so/expand.c (c_isalpha).
  • Tests: tests/lib/libc/locale/t_uselocale.c, t_newlocale.c, t_strfmon.c.

Clone this wiki locally