Home | History | Annotate | Line # | Download | only in stdlib
      1 /*	$NetBSD: strfmon.c,v 1.27 2026/11/23 18:30:05 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2001 Alexey Zelkin <phantom (at) FreeBSD.org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  */
     29 
     30 #include <sys/cdefs.h>
     31 #if defined(LIBC_SCCS) && !defined(lint)
     32 #if 0
     33 __FBSDID("$FreeBSD: src/lib/libc/stdlib/strfmon.c,v 1.14 2003/03/20 08:18:55 ache Exp $");
     34 #else
     35 __RCSID("$NetBSD: strfmon.c,v 1.27 2026/11/23 18:30:05 kre Exp $");
     36 #endif
     37 #endif /* LIBC_SCCS and not lint */
     38 
     39 #include "namespace.h"
     40 
     41 #include <sys/types.h>
     42 #include <assert.h>
     43 #include <ctype.h>
     44 #include <errno.h>
     45 #include <limits.h>
     46 #include <locale.h>
     47 #include <monetary.h>
     48 #include <stdarg.h>
     49 #include <stddef.h>
     50 #include <stdio.h>
     51 #include <stdlib.h>
     52 #include <string.h>
     53 #include <wchar.h>
     54 
     55 #include "setlocale_local.h"
     56 
     57 /* internal flags */
     58 #define	NEED_GROUPING		0x01	/* print digits grouped (default) */
     59 #define	SIGN_POSN_USED		0x02	/* '+' or '(' usage flag */
     60 #define	LOCALE_POSN		0x04	/* use locale defined +/- (default) */
     61 #define	PARENTH_POSN		0x08	/* enclose negative amount in () */
     62 #define	SUPPRESS_CURR_SYMBOL	0x10	/* suppress the currency from output */
     63 #define	LEFT_JUSTIFY		0x20	/* left justify */
     64 #define	USE_INTL_CURRENCY	0x40	/* use international currency symbol */
     65 #define	IS_NEGATIVE		0x80	/* is argument value negative ? */
     66 
     67 /* internal macros */
     68 #define	PRINT(CH) do {						\
     69 	if (dst >= s + maxsize) 				\
     70 		goto e2big_error;				\
     71 	*dst++ = CH;						\
     72 } while (0)
     73 
     74 #define	PRINTS(STR) do {					\
     75 	const char *tmps = STR;					\
     76 	while (*tmps != '\0')					\
     77 		PRINT(*tmps++);					\
     78 } while (0)
     79 
     80 #define PRINT_WIDE(WCH, CH) do {				\
     81 	int __w__ = __add_wide_char(dst, s + maxsize, (WCH));	\
     82 	int __c__ = (CH);					\
     83 	switch (__w__) {					\
     84 	case -2:	goto e2big_error;			\
     85 	case -1:	if (__c__ != 0) PRINT(__c__);	break;	\
     86 	default:	dst += __w__;			break;	\
     87 	}							\
     88 } while (0)
     89 
     90 #define	GET_NUMBER(VAR, LOC)	do {				\
     91 	VAR = 0;						\
     92 	while (isdigit_l((unsigned char)*fmt, LOC)) {		\
     93 		if (VAR > INT_MAX / 10)				\
     94 			goto e2big_error;			\
     95 		VAR *= 10;					\
     96 		VAR += *fmt - '0';				\
     97 		if (VAR < 0)					\
     98 			goto e2big_error;			\
     99 		fmt++;						\
    100 	}							\
    101 } while (0)
    102 
    103 #define	GRPCPY(howmany) do {					\
    104 	int i = howmany;					\
    105 	while (i-- > 0) {					\
    106 		avalue_size--;					\
    107 		*--bufend = *(avalue + avalue_size + padded);	\
    108 	}							\
    109 } while (0)
    110 
    111 #define	GRPSEP do {						\
    112 	bufend -= thousands_sep_size;				\
    113 	memcpy(bufend, thousands_sep, thousands_sep_size);	\
    114 	groups++;						\
    115 } while (0)
    116 
    117 #define	RANGE_CHECK(v, op, n)					\
    118 	((*(const unsigned char *)(v) op (n)) ||		\
    119 	    (((*(const unsigned char *)(v)) & 0x80) != 0))
    120 
    121 static void __setup_vars(int, char *, char *, char *, const char **,
    122     struct lconv *);
    123 static int __calc_left_pad(int, int, int, struct lconv *);
    124 static int __calc_right_pad(int, int, int, struct lconv *);
    125 static char *__format_grouped_double(double, int *, int *, int, int,
    126     char *, size_t, struct lconv *, locale_t loc);
    127 static int __columns(const char *, locale_t);
    128 static int __count_grps(int, char *);
    129 static int __add_wide_char(char *, char *, wchar_t);
    130 
    131 static char __nullstr[] = "";
    132 
    133 /*
    134  * This would be better as MB_CUR_MAX but that isn't a constant,
    135  * and not using a constant screws with the stack protector, so
    136  * let's not do that.   15 is much too big for any rational encoding
    137  * of a single character, but still so small that an array 16 bytes
    138  * (15 +1 for a \0) on the stack isn't any kind of a problem.
    139  */
    140 #define MAX_ENCODED_CHAR_LEN	15
    141 
    142 static ssize_t
    143 vstrfmon_l(char * __restrict s, size_t maxsize, locale_t loc,
    144     const char * __restrict format, va_list ap)
    145 {
    146 	char 		*dst;		/* output destination pointer */
    147 	const char 	*fmt;		/* current format poistion pointer */
    148 	struct lconv 	*lc;		/* pointer to lconv structure */
    149 	char		*asciivalue;	/* formatted double pointer */
    150 
    151 	int		flags;		/* formatting options */
    152 	char		pad_char[MAX_ENCODED_CHAR_LEN+1];  /* padding char */
    153 	size_t		pad_char_len;
    154 	int		pad_size;	/* pad size */
    155 	int		width;		/* field width */
    156 	int		left_prec;	/* left precision */
    157 	int		right_prec;	/* right precision */
    158 	double		value;		/* just value */
    159 	wchar_t		space_char = L' '; /* space after currency */
    160 
    161 	char		cs_precedes,	/* values gathered from struct lconv */
    162 			sep_by_space,
    163 			sign_posn, osp,
    164 			*currency_symbol;
    165 	const char	*signstr, *othersign;
    166 	int		cs_cols, ss_cols, os_cols;
    167 
    168 	int		cols_used;
    169 
    170 	mbstate_t	mbs;
    171 
    172 	char		*tmpptr;	/* temporary vars */
    173 	int		sverrno;
    174 
    175 	mbstate_t	fmt_state;
    176 	wchar_t		fmt_char;
    177 	size_t		fmt_ch_len;
    178 
    179 	lc = localeconv_l(loc);
    180 	dst = s;
    181 	fmt = format;
    182 	asciivalue = NULL;
    183 	currency_symbol = NULL;
    184 
    185 	(void)mbrtowc(NULL, NULL, 0, &fmt_state);	/* init */
    186 	for (;;) {
    187 		fmt_ch_len = mbrtowc(&fmt_char, fmt, MB_CUR_MAX,
    188 		    &fmt_state);
    189 		if (fmt_ch_len == 0)
    190 			break;
    191 		if (fmt_ch_len == (size_t)-1)	/* errno == EILSEQ */
    192 			goto end_error;
    193 		if (fmt_ch_len == (size_t)-2)
    194 			goto format_error;
    195 
    196 		if (fmt_char != L'%')
    197 			goto literal;
    198 
    199 		/* '%' found ! */
    200 
    201 		/* "%%" mean just '%' */
    202 		if (fmt[1] == '%') {
    203 			fmt++;
    204 	literal:;
    205 			PRINT_WIDE(fmt_char, '?');
    206 			fmt += fmt_ch_len;
    207 			continue;
    208 		}
    209 
    210 		/* set up initial values */
    211 		flags = NEED_GROUPING | LOCALE_POSN;
    212 		pad_char[0] = ' ';	/* padding character is "space" */
    213 		pad_char[1] = '\0';
    214 		pad_char_len = 1;
    215 		pad_size = 0;		/* no padding initially */
    216 		left_prec = -1;		/* no left precision specified */
    217 		right_prec = -1;	/* no right precision specified */
    218 		width = -1;		/* no width specified */
    219 		value = 0;		/* we have no value to print now */
    220 		cols_used = 0;		/* output width in columns */
    221 
    222 		/* Flags */
    223 		for (;;) {
    224 			/*
    225 			 * Once we are in a conversion description
    226 			 * all chars are required to be ascii, except
    227 			 * the one char after a '=' flag, so we can
    228 			 * just read them as bytes ... or this is close
    229 			 * enough for now.
    230 			 */
    231 			switch (*++fmt) {
    232 			case '=':	/* fill character */
    233 				(void)mbrtowc(NULL, NULL, 0, &mbs);
    234 				pad_char_len = mbrtowc(&space_char,
    235 				    ++fmt, MAX_ENCODED_CHAR_LEN, &mbs);
    236 				if (pad_char_len == 0 ||
    237 				    pad_char_len >= MAX_ENCODED_CHAR_LEN)
    238 					goto format_error;
    239 				memcpy(pad_char, fmt, pad_char_len);
    240 				pad_char[pad_char_len] = '\0';
    241 				fmt += pad_char_len - 1;
    242 
    243 				/*
    244 				 * return the borrowed var to its
    245 				 * regularly scheduled purpose
    246 				 */
    247 				space_char = L' ';
    248 				continue;
    249 
    250 			case '^':	/* not group currency  */
    251 				flags &= ~NEED_GROUPING;
    252 				continue;
    253 
    254 			case '+':	/* use locale defined signs */
    255 				if (flags & (SIGN_POSN_USED|PARENTH_POSN))
    256 					goto format_error;
    257 				flags |= SIGN_POSN_USED;
    258 				continue;
    259 
    260 			case '(':	/* enclose negatives with () */
    261 				if (flags & SIGN_POSN_USED)
    262 					goto format_error;
    263 				flags &= ~LOCALE_POSN;	/* was dflt */
    264 				flags |= SIGN_POSN_USED | PARENTH_POSN;
    265 				continue;
    266 
    267 			case '!':	/* suppress currency symbol */
    268 				flags |= SUPPRESS_CURR_SYMBOL;
    269 				continue;
    270 
    271 			case '-':	/* alignment (left)  */
    272 				flags |= LEFT_JUSTIFY;
    273 				continue;
    274 
    275 			default:
    276 				break;
    277 			}
    278 			break;
    279 		}
    280 
    281 		/* field Width */
    282 		if (isdigit_l((unsigned char)*fmt, loc)) {
    283 			ptrdiff_t d = dst - s;
    284 
    285 			GET_NUMBER(width, loc);
    286 
    287 			/*
    288 			 * Do we have enough space to place a number of
    289 			 * the required width ?
    290 			 */
    291 			if ((size_t)(d + width) >= maxsize)
    292 				goto e2big_error;
    293 		}
    294 
    295 		/* Left precision */
    296 		if (*fmt == '#') {
    297 			if (!isdigit_l((unsigned char)*++fmt, loc))
    298 				goto format_error;
    299 			GET_NUMBER(left_prec, loc);
    300 
    301 			if ((unsigned int)left_prec >= maxsize - (dst - s))
    302 				goto e2big_error;
    303 		}
    304 
    305 		/* Right precision */
    306 		if (*fmt == '.') {
    307 			if (!isdigit_l((unsigned char)*++fmt, loc))
    308 				goto format_error;
    309 			GET_NUMBER(right_prec, loc);
    310 
    311 			if ((unsigned int)right_prec >=
    312 			    maxsize - (dst - s) - left_prec)
    313 				goto e2big_error;
    314 		}
    315 
    316 		/* Conversion Characters */
    317 		switch (*fmt++) {
    318 
    319 		case 'i':	/* use international currency format */
    320 			flags |= USE_INTL_CURRENCY;
    321 			break;
    322 
    323 		case 'n':	/* use national currency format */
    324 			flags &= ~USE_INTL_CURRENCY;
    325 			break;
    326 
    327 		default:	/* required character is missing or
    328 				   premature EOS */
    329 			goto format_error;
    330 		}
    331 
    332 		space_char = L' ';	/* to be sure, to be sure... */
    333 		if (currency_symbol != NULL)
    334 			free(currency_symbol);
    335 		if (flags & USE_INTL_CURRENCY) {
    336 			size_t l;
    337 
    338 			currency_symbol = strdup(lc->int_curr_symbol);
    339 			if (currency_symbol != NULL &&
    340 			    /*
    341 			     * should be 3 characters, not bytes
    342 			     * but the international currency symbol
    343 			     * is supposed to be from ISO4217:2015, so
    344 			     * only ASCII, so, just leave this (for now)
    345 			     */
    346 			    (l = strlen(currency_symbol)) > 3) {
    347 				size_t chlen;
    348 				const int e = errno;
    349 
    350 				(void)mbrtowc_l(NULL, NULL, 0, &mbs, loc);
    351 				/* any errno set here gets ignored, we deal */
    352 				chlen = mbrtowc_l(&space_char,
    353 				    currency_symbol + 3, l - 3, &mbs, loc);
    354 				if (chlen == 0 || chlen > l - 3 ||
    355 				    wcwidth(space_char) != 1)
    356 					space_char = L' ';
    357 				currency_symbol[3] = '\0';
    358 				errno = e;
    359 			}
    360 		} else
    361 			currency_symbol = strdup(lc->currency_symbol);
    362 
    363 		if (currency_symbol == NULL)
    364 			goto end_error;			/* ENOMEM. */
    365 
    366 		cs_cols = __columns(currency_symbol, loc);
    367 		if (cs_cols < 0) {
    368 			cs_cols = 0;
    369 			flags |= SUPPRESS_CURR_SYMBOL;
    370 		}
    371 
    372 		/* value itself */
    373 		value = va_arg(ap, double);
    374 
    375 		/* detect sign */
    376 		if (value < 0) {
    377 			flags |= IS_NEGATIVE;
    378 			value = -value;
    379 		}
    380 
    381 		/*
    382 		 * set some variables for later use
    383 		 */
    384 		/* First a couple for the other sign */
    385 		__setup_vars(flags ^ IS_NEGATIVE, &cs_precedes,
    386 		    &sep_by_space, &osp, &othersign, lc);
    387 		/* And then the the actual data to use */
    388 		__setup_vars(flags, &cs_precedes,
    389 		    &sep_by_space, &sign_posn, &signstr, lc);
    390 
    391 		ss_cols = __columns(signstr, loc);
    392 		if (ss_cols < 0) {
    393 			signstr = __nullstr;
    394 			ss_cols = 0;
    395 		}
    396 		os_cols = __columns(othersign, loc);
    397 		if (os_cols < 0) {
    398 			othersign = __nullstr;
    399 			os_cols = 0;
    400 		}
    401 
    402 #undef	CMP_SP
    403 /*
    404  * Compare +/- sign positions
    405  *
    406  * This gives true if either both are zero, or they are different
    407  * and false only when they are the same and not zero
    408  */
    409 #define CMP_SP(a, b) ((~lc-> a##_sign_posn ^ ~lc-> b##_sign_posn) != 0)
    410 
    411 		/*
    412 		 * If () will be used for negative numbers, it doesn't
    413 		 * matter what the sign strings are.
    414 		 */
    415 		if (flags & PARENTH_POSN) {
    416 			/*
    417 			 * we were given the '(' flag, so
    418 			 * everything is always OK.   **)**
    419 			 */
    420 		} else if (flags & SIGN_POSN_USED) {
    421 			/*
    422 			 * The '+' flag was used
    423 			 */
    424 			if (ss_cols == 0 && os_cols == 0)
    425 				goto format_error;
    426 
    427 			if (strcmp(signstr, othersign) == 0) {
    428 			     /* sign strings identical */
    429 			     /* error if positions the same */
    430 			     if (sign_posn == osp)
    431 				goto format_error;
    432 			}
    433 
    434 			if (sign_posn == 0)
    435 				sign_posn = 1;
    436 			/*
    437 			 * We are instructed to use signs,
    438 			 * and we have suiable strings to use
    439 			 * then all is OK
    440 			 */
    441 		} else if (sign_posn == 0) {
    442 			/*
    443 			 * here the locale has told us to use
    444 			 * parens, which is OK, unless it would
    445 			 * also tell us to use parens for the
    446 			 * values of the other sign.
    447 			 */
    448 			if (osp == 0)
    449 				goto format_error;
    450 
    451 		} else if (ss_cols != os_cols &&
    452 			    (ss_cols > 0 || os_cols > 0)) {
    453 			/*
    454 			 * signs are clearly different, no issue
    455 			 */
    456 		} else if ((ss_cols > 0 || os_cols > 0) &&
    457 			    (strcmp(signstr, othersign) != 0)) {
    458 			/*
    459 			 * sign strings are different, and at least
    460 			 * one has a visible width, also no issue
    461 			 */
    462 		} else if (!(flags & SIGN_POSN_USED) &&
    463 			    ((ss_cols > 0 || os_cols > 0) &&
    464 			     ((flags & USE_INTL_CURRENCY) ?
    465 			        CMP_SP(int_p, int_n) : CMP_SP(p, n)))) {
    466 			/*
    467 			 * '+' flag not used, and sign strings go in
    468 			 * different places, and at least one of them
    469 			 * will be visible, so OK if they look the
    470 			 * same, no issue
    471 			 */
    472 		} else if (ss_cols <= 0 && os_cols <= 0) {
    473 			/*
    474 			 * Replace the negative sign with "-"
    475 			 */
    476 			if (flags & IS_NEGATIVE) {
    477 				signstr = "-";
    478 				ss_cols = 1;
    479 			} else
    480 				os_cols = 1;	/*othersign not used*/
    481 		} else {
    482 			/*
    483 			 * arrange to place a negative sign before
    484 			 * the value, and the positive sign after it.
    485 			 * Now the cases are different!
    486 			 */
    487 			sign_posn = (flags & IS_NEGATIVE) ? 1 : 2;
    488 		}
    489 #undef	CMP_SP
    490 
    491 		if (ss_cols < 0) {
    492 			signstr = __nullstr;
    493 			ss_cols = 0;
    494 		}
    495 		if (os_cols < 0) {
    496 			/* othersign = __nullstr; // not needed */
    497 			os_cols = 0;
    498 		}
    499 
    500 		/* fill left_prec with amount of padding chars */
    501 		if (left_prec >= 0) {
    502 			pad_size = __calc_left_pad((flags ^ IS_NEGATIVE),
    503 				        cs_cols, os_cols, lc)
    504 				 - __calc_left_pad(flags, cs_cols, ss_cols, lc);
    505 
    506 			if (pad_size < 0)
    507 				pad_size = 0;
    508 		}
    509 
    510 		if (asciivalue != NULL)
    511 			free(asciivalue);
    512 		asciivalue = __format_grouped_double(value, &flags, &cols_used,
    513 		    left_prec, right_prec, pad_char, pad_char_len, lc, loc);
    514 		if (asciivalue == NULL)
    515 			goto end_error;		/* errno already set     */
    516 						/* to ENOMEM by malloc() */
    517 
    518 		/*
    519 		 * Description of some LC_MONETARY's values:
    520 		 *
    521 		 * p_cs_precedes & n_cs_precedes
    522 		 *
    523 		 * = 1 - $currency_symbol precedes the value
    524 		 *	 for a monetary quantity with a non-negative value
    525 		 * = 0 - symbol succeeds the value
    526 		 *
    527 		 * p_sep_by_space & n_sep_by_space
    528 		 *
    529 		 * = 0 - no space separates $currency_symbol
    530 		 *	 from the value for a monetary quantity with a
    531 		 *	 non-negative value
    532 		 * = 1 - space separates the symbol from the value
    533 		 * = 2 - space separates the symbol and the sign string,
    534 		 *	 if adjacent.
    535 		 *
    536 		 * p_sign_posn & n_sign_posn
    537 		 *
    538 		 * = 0 - parentheses enclose the quantity and the
    539 		 *	 $currency_symbol
    540 		 * = 1 - the sign string precedes the quantity and the
    541 		 *	 $currency_symbol
    542 		 * = 2 - the sign string succeeds the quantity and the
    543 		 *	 $currency_symbol
    544 		 * = 3 - the sign string precedes the $currency_symbol
    545 		 * = 4 - the sign string succeeds the $currency_symbol
    546 		 *
    547 		 */
    548 
    549 		tmpptr = dst;
    550 
    551 		if (flags & PARENTH_POSN)
    552 			sign_posn = 111;	/* invalid, so no signstr */
    553 
    554 		if ((sign_posn == 0 && !(flags & SIGN_POSN_USED)) ||
    555 		    (flags & (PARENTH_POSN|IS_NEGATIVE)) ==
    556 					(PARENTH_POSN|IS_NEGATIVE)) {
    557 			PRINT('(');
    558 			cols_used++;
    559 		}
    560 
    561 		while (pad_size-- > 0) {
    562 			PRINT(' ');
    563 			cols_used++;
    564 		}
    565 
    566 		if (cs_precedes == 1) {
    567 			if (sign_posn == 1 || sign_posn == 3 ||
    568 			    (sign_posn == 0 && (flags & SIGN_POSN_USED))) {
    569 				PRINTS(signstr);
    570 				cols_used += ss_cols;
    571 				if (sep_by_space == 2) {
    572 					PRINT(' ');
    573 					cols_used++;
    574 				}
    575 			}
    576 
    577 			if (!(flags & SUPPRESS_CURR_SYMBOL)) {
    578 				PRINTS(currency_symbol);
    579 				cols_used += cs_cols;
    580 
    581 				if (sign_posn == 4) {
    582 					if (sep_by_space == 2) {
    583 						PRINT(' ');
    584 						cols_used++;
    585 					}
    586 					PRINTS(signstr);
    587 					if (sep_by_space == 1) {
    588 						PRINT(' ');
    589 						cols_used++;
    590 					}
    591 				} else if (sep_by_space == 1) {
    592 					cols_used++;	/* we know width==1 */
    593 					PRINT_WIDE(space_char, ' ');
    594 				}
    595 			}
    596 		} else if (sign_posn == 1 ||
    597 			  (sign_posn == 0 && (flags & SIGN_POSN_USED))) {
    598 			PRINTS(signstr);
    599 			cols_used += ss_cols;
    600 			if (sep_by_space == 2) {
    601 				PRINT(' ');
    602 				cols_used++;
    603 			}
    604 		}
    605 
    606 		PRINTS(asciivalue);
    607 
    608 		if (cs_precedes == 0) {
    609 			if (sign_posn == 3) {
    610 				if (sep_by_space == 1) {
    611 					PRINT(' ');
    612 					cols_used++;
    613 				}
    614 				PRINTS(signstr);
    615 				cols_used += ss_cols;
    616 			}
    617 
    618 			if (!(flags & SUPPRESS_CURR_SYMBOL)) {
    619 				if ((sign_posn == 3 && sep_by_space == 2)
    620 				    || (sep_by_space == 1
    621 				    && (sign_posn == 0 || sign_posn == 1 ||
    622 					sign_posn == 2 || sign_posn == 4)  )) {
    623 						cols_used++;
    624 						PRINT_WIDE(space_char, ' ');
    625 				}
    626 
    627 				PRINTS(currency_symbol);
    628 				cols_used += cs_cols;
    629 				if (sign_posn == 4) {
    630 					if (sep_by_space == 2) {
    631 						PRINT(' ');
    632 						cols_used++;
    633 					}
    634 					PRINTS(signstr);
    635 					cols_used += ss_cols;
    636 				}
    637 			}
    638 		}
    639 
    640 		if (sign_posn == 2) {
    641 			if (sep_by_space == 2) {
    642 				PRINT(' ');
    643 				cols_used++;
    644 			}
    645 			PRINTS(signstr);
    646 			cols_used += ss_cols;
    647 		}
    648 
    649 		/* if aligning, pad the right side as well */
    650 		if (left_prec >= 0) {
    651 			pad_size = __calc_right_pad((flags ^ IS_NEGATIVE),
    652 					cs_cols, os_cols, lc) -
    653 				  __calc_right_pad(flags, cs_cols, ss_cols, lc);
    654 
    655 			if (pad_size < 0)
    656 				pad_size = 0;
    657 
    658 			while (pad_size-- > 0) {
    659 				PRINT(' ');
    660 				cols_used++;
    661 			}
    662 		}
    663 
    664 		if ((sign_posn == 0 && !(flags & SIGN_POSN_USED)) ||
    665 		    (flags & (PARENTH_POSN|IS_NEGATIVE)) ==
    666 					(PARENTH_POSN|IS_NEGATIVE)) {
    667 			PRINT(')');
    668 			cols_used++;
    669 		}
    670 
    671 		if (cols_used < width) {
    672 			if (flags & LEFT_JUSTIFY) {
    673 				while (cols_used++ < width)
    674 					PRINT(' ');
    675 			} else {
    676 				size_t wps;
    677 
    678 				wps = width - cols_used;
    679 				memmove(tmpptr + wps, tmpptr,
    680 				    (size_t)(dst - tmpptr));
    681 				memset(tmpptr, ' ', wps);
    682 				dst += wps;
    683 			}
    684 		}
    685 	}
    686 
    687 	PRINT('\0');
    688 	free(asciivalue);
    689 	free(currency_symbol);
    690 	return (dst - s - 1);	/* return size of data except trailing '\0' */
    691 
    692  e2big_error:;
    693 	errno = E2BIG;
    694 	goto end_error;
    695 
    696  format_error:;
    697 	errno = EINVAL;
    698 
    699  end_error:;
    700 	sverrno = errno;
    701 	if (asciivalue != NULL)
    702 		free(asciivalue);
    703 	if (currency_symbol != NULL)
    704 		free(currency_symbol);
    705 	errno = sverrno;
    706 	return (-1);
    707 }
    708 
    709 static int
    710 __add_wide_char(char *dst, char *limit, wchar_t wch)
    711 {
    712 	char sc[MAX_ENCODED_CHAR_LEN + 1];
    713 	int clen;
    714 	const int e = errno;
    715 
    716 	(void)wctomb(NULL, L'\0');
    717 	clen = wctomb(sc, wch);
    718 	errno = e;
    719 	if (clen > 0) {
    720 		if (dst + clen >= limit)
    721 			return -2;
    722 		memcpy(dst, sc, (size_t)clen);
    723 		return clen;
    724 	}
    725 	return -1;
    726 }
    727 
    728 static void
    729 __setup_vars(int flags, char *cs_precedes, char *sep_by_space,
    730     char *sign_posn, const char **signstr, struct lconv *lc)
    731 {
    732 
    733 	if ((flags & IS_NEGATIVE) && (flags & USE_INTL_CURRENCY)) {
    734 		*cs_precedes = lc->int_n_cs_precedes;
    735 		*sep_by_space = lc->int_n_sep_by_space;
    736 		*sign_posn = lc->int_n_sign_posn;
    737 	} else if (flags & USE_INTL_CURRENCY) {
    738 		*cs_precedes = lc->int_p_cs_precedes;
    739 		*sep_by_space = lc->int_p_sep_by_space;
    740 		*sign_posn = lc->int_p_sign_posn;
    741 	} else if (flags & IS_NEGATIVE) {
    742 		*cs_precedes = lc->n_cs_precedes;
    743 		*sep_by_space = lc->n_sep_by_space;
    744 		*sign_posn = lc->n_sign_posn;
    745 	} else {
    746 		*cs_precedes = lc->p_cs_precedes;
    747 		*sep_by_space = lc->p_sep_by_space;
    748 		*sign_posn = lc->p_sign_posn;
    749 	}
    750 	if ((flags & (PARENTH_POSN|IS_NEGATIVE)) == (PARENTH_POSN|IS_NEGATIVE))
    751 		*sign_posn = 0;
    752 
    753 	if (signstr != NULL) {
    754 		if (flags & IS_NEGATIVE)
    755 			*signstr = lc->negative_sign;
    756 		else
    757 			*signstr = lc->positive_sign;
    758 	}
    759 
    760 	/* Set default values for unspecified/invalid information. */
    761 	if (*cs_precedes != 0)
    762 		*cs_precedes = 1;
    763 	if (RANGE_CHECK(sep_by_space, >, 2))
    764 		*sep_by_space = 0;
    765 	if (RANGE_CHECK(sign_posn, >, 4))
    766 		*sign_posn = 1;
    767 }
    768 
    769 /*
    770  * Func name is misleading (but historic), this calculates the number of
    771  * characters that are inserted before the value string for a value and
    772  * using options as given by flags (+/-, $ or not, ...)
    773  *
    774  * Taking the difference between what this returns for the sign of the
    775  * value we have, and what would be used for a value of the opposite sign,
    776  * will reveal how many pad chars need to be inserted.
    777  */
    778 static int
    779 __calc_left_pad(int flags, int cs_cols, int s_cols, struct lconv *lc)
    780 {
    781 	char cs_precedes, sep_by_space, sign_posn;
    782 	int left_chars = 0;
    783 
    784 	__setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, NULL, lc);
    785 
    786 	if ((flags & (PARENTH_POSN|IS_NEGATIVE)) ==
    787 	    (PARENTH_POSN|IS_NEGATIVE) ||
    788 	    (!(flags & SIGN_POSN_USED) && sign_posn == 0)) {
    789 		left_chars++;	/* One char needed for '(' **)** */
    790 		sign_posn = 0;
    791 	}
    792 
    793 	if (cs_precedes != 0) {
    794 		/* space needed for currency symbol */
    795 		left_chars += cs_cols;
    796 		if (sep_by_space != 0)	/* either 1 or 2, space goes with $ */
    797 			left_chars++;
    798 	}
    799 
    800 	switch (sign_posn) {
    801 	case 0:
    802 		/* paren marking, handled above */
    803 		break;
    804 	case 1:
    805 		left_chars += s_cols;
    806 		break;
    807 	case 3:
    808 	case 4:
    809 		if (cs_precedes != 0)
    810 			left_chars += s_cols;
    811 		break;
    812 	}
    813 	return left_chars;
    814 }
    815 
    816 /*
    817  * The same for the right side
    818  */
    819 static int
    820 __calc_right_pad(int flags, int cs_cols, int s_cols, struct lconv *lc)
    821 {
    822 	char cs_precedes, sep_by_space, sign_posn;
    823 	int right_chars = 0;
    824 
    825 	__setup_vars(flags, &cs_precedes, &sep_by_space, &sign_posn, NULL, lc);
    826 
    827 	if ((flags & (PARENTH_POSN|IS_NEGATIVE)) ==
    828 	    (PARENTH_POSN|IS_NEGATIVE) ||
    829 	    (!(flags & SIGN_POSN_USED) && sign_posn == 0)) {
    830 		right_chars++;	/* **(** One char needed for ')' */
    831 		sign_posn = 0;
    832 	}
    833 
    834 	if (cs_precedes == 0) {
    835 		right_chars += cs_cols;
    836 		if (sep_by_space != 0)
    837 			right_chars++;
    838 	}
    839 
    840 	switch (sign_posn) {
    841 	case 0:
    842 		break;
    843 	case 2:
    844 		right_chars += s_cols;
    845 		break;
    846 	case 3:
    847 	case 4:
    848 		if (cs_precedes == 0)
    849 			right_chars += s_cols;
    850 		break;
    851 	}
    852 	return right_chars;
    853 }
    854 
    855 /*
    856  * Determine how many thousands_separator sequences will be
    857  * inserted into a string of <size> digits, using the
    858  * grouping algorithm given by <grouping>
    859  */
    860 static int
    861 __count_grps(int size, char *grouping)
    862 {
    863 	int	seps = 0;
    864 
    865 	if (*grouping == CHAR_MAX ||		/* no grouping ? */
    866 	    RANGE_CHECK(grouping, <=, 0))
    867 		return 0;
    868 
    869 	while (RANGE_CHECK(grouping, < , size)) {
    870 		seps++;
    871 		size -= (int)(unsigned char)*grouping++;
    872 
    873 		/* no more grouping ? */
    874 		if (RANGE_CHECK(grouping, ==, CHAR_MAX))
    875 			break;
    876 
    877 		/* remainder grouping with same value ? */
    878 		if (*grouping == 0) {
    879 			/* known that: grouping[-1] != 0 */
    880 			seps += (size - 1) / *(grouping - 1);
    881 			break;
    882 		}
    883 	}
    884 	return seps;
    885 }
    886 
    887 /* convert double to locale-encoded string */
    888 static char *
    889 __format_grouped_double(double value, int *flags, int *usedp, int left_prec,
    890     int right_prec, char *pad_char, size_t pad_char_len,
    891     struct lconv *lc, locale_t loc)
    892 {
    893 	char		*rslt;
    894 	char		*avalue;
    895 	int		avalue_size;
    896 
    897 	size_t		bufsize;
    898 	char		*bufend;
    899 
    900 	int		padded;
    901 
    902 	char		*grouping;
    903 	const char	*decimal_point;
    904 	const char	*thousands_sep;
    905 	size_t		decimal_point_size;
    906 	size_t		thousands_sep_size;
    907 	int		decimal_point_cols;
    908 	int		thousands_sep_cols;
    909 
    910 	int		groups = 0;
    911 	int		used = 0;
    912 
    913 	grouping = lc->mon_grouping;
    914 	decimal_point = lc->mon_decimal_point;
    915 	if (*decimal_point == '\0')		/* POSIX will say to do this */
    916 		decimal_point = lc->decimal_point;
    917 	thousands_sep = lc->mon_thousands_sep;
    918 #if 0
    919 	if (*thousands_sep == '\0')		/* but not to do this */
    920 		thousands_sep = lc->thousands_sep;
    921 #endif
    922 
    923 	decimal_point_size = strlen(decimal_point);
    924 	thousands_sep_size = strlen(thousands_sep);
    925 	decimal_point_cols = __columns(decimal_point, loc);
    926 	thousands_sep_cols = __columns(thousands_sep, loc);
    927 
    928 	/* fill left_prec with default value */
    929 	if (left_prec == -1)
    930 		left_prec = 0;
    931 
    932 	/* fill right_prec with default value */
    933 	if (right_prec == -1) {
    934 		if (*flags & USE_INTL_CURRENCY)
    935 			right_prec = lc->int_frac_digits;
    936 		else
    937 			right_prec = lc->frac_digits;
    938 
    939 		if (right_prec == CHAR_MAX)	/* POSIX locale ? */
    940 			right_prec = 0;
    941 	}
    942 
    943 	if (decimal_point_size == 0)
    944 		right_prec = 0;
    945 
    946 	if (*flags & NEED_GROUPING)
    947 		left_prec +=
    948 		    __count_grps(left_prec, grouping) * thousands_sep_cols;
    949 
    950 	/*
    951 	 * convert to string
    952 	 *
    953 	 * The field width specified allows for the minimum number of
    954 	 * digits before the decimal point (left_prec), the number after
    955 	 * it, and if that was not 0, 1 more for the '.'.
    956 	 * nb: this is using printf(3), the decimal point is always '.'
    957 	 * (and so is always 1 byte).
    958 	 */
    959 	avalue_size = asprintf_l(&avalue, loc, "%*.*f",
    960 	    left_prec + right_prec + (right_prec ? 1 : 0), right_prec, value);
    961 	if (avalue_size < 0)
    962 		return (NULL);
    963 
    964 	/*
    965 	 * make sure that we've enough space for result string
    966 	 * (it is OK to be more than enough)
    967 	 *
    968 	 * avalue_size are the digits, with often a '.', and leading
    969 	 * padding to allow for the left_precision
    970 	 *
    971 	 * In extreme cases every character in the result might need
    972 	 * a grouping character (really 1 less, but being bigger is OK)
    973 	 * where each grouping character is thousands_sep_size bytes.
    974 	 *
    975 	 * Thus: avalue_size + (avalue_size * thousands_sep_size)
    976 	 * or:   avalue_size * (1 + thousands_sep_size)
    977 	 *
    978 	 * After that we need to insert the locale radix char, which
    979 	 * is decimal_point_size bytes (we could -1 for the '.' present)
    980 	 *
    981 	 * And one more for the \0 to end it all.
    982 	 */
    983 	bufsize = avalue_size * (1 + thousands_sep_size) +
    984 	    decimal_point_size + 1;
    985 
    986 	/* skip spaces at beginning */
    987 	padded = 0;
    988 	while (avalue[padded] == ' ') {
    989 		padded++;
    990 		avalue_size--;
    991 	}
    992 	bufsize += padded * (pad_char_len - 1);
    993 
    994 	rslt = calloc(1, bufsize);
    995 	if (rslt == NULL) {
    996 		free(avalue);
    997 		return (NULL);
    998 	}
    999 	bufend = rslt + bufsize - 1;	/* reserve space for trailing '\0' */
   1000 
   1001 	if (right_prec > 0) {
   1002 		bufend -= right_prec;
   1003 		memcpy(bufend, avalue + avalue_size + padded - right_prec,
   1004 		    (size_t) right_prec);
   1005 		bufend -= decimal_point_size;
   1006 		memcpy(bufend, decimal_point, decimal_point_size);
   1007 		avalue_size -= (right_prec + 1);
   1008 		used += right_prec + decimal_point_cols;
   1009 	}
   1010 
   1011 	/*
   1012 	 * If grouping has not been suppressed, and the width of
   1013 	 * the grouping separator is > 0 columns, and there is
   1014 	 * a defined (non-null) grouping algorithm, then we
   1015 	 * perform that algorithm here.
   1016 	 */
   1017 	if ((*flags & NEED_GROUPING) &&
   1018 	    thousands_sep_cols > 0 &&
   1019 	    *grouping != CHAR_MAX && *grouping > 0) {
   1020 		/* Moving from right to left */
   1021 		while (avalue_size > (int)*grouping) {
   1022 			/* insert the digits for the group */
   1023 			GRPCPY(*grouping);
   1024 			/* then a separator */
   1025 			GRPSEP;
   1026 			used += thousands_sep_cols + *grouping;
   1027 			/* and advance to the next step */
   1028 			grouping++;
   1029 
   1030 			/* no more grouping ? */
   1031 			if (RANGE_CHECK(grouping, ==, CHAR_MAX))
   1032 				break;
   1033 
   1034 			/* rest grouping with same value ? */
   1035 			if (*grouping == 0) {
   1036 				/* go back to the last group size */
   1037 				grouping--;
   1038 				/* and use it until out of digits */
   1039 				while (avalue_size > *grouping) {
   1040 					GRPCPY(*grouping);
   1041 					GRPSEP;
   1042 					used += thousands_sep_cols + *grouping;
   1043 				}
   1044 				break;
   1045 			}
   1046 		}
   1047 		/* If digits remain uncopied, do them now */
   1048 		if (avalue_size != 0) {
   1049 			used += avalue_size;	/* must be before GRPCPY */
   1050 			GRPCPY(avalue_size);
   1051 		}
   1052 		/*
   1053 		 * we need N less padding chars for each separator inserted
   1054 		 * where N is the width of the separator
   1055 		 */
   1056 		padded -= groups * thousands_sep_cols;
   1057 	} else {
   1058 		/*
   1059 		 * No grouping to do, the easy case, just
   1060 		 * copy the digits
   1061 		 */
   1062 		bufend -= avalue_size;
   1063 		memcpy(bufend, avalue + padded, (size_t) avalue_size);
   1064 		used += avalue_size;
   1065 	}
   1066 
   1067 	/* do padding with pad_char */
   1068 	if (padded > 0) {
   1069 		used += padded;
   1070 		if (pad_char_len == 1) {
   1071 			/* the most common case */
   1072 			bufend -= padded;
   1073 			memset(bufend, pad_char[0], padded);
   1074 		} else while (padded-- > 0) {
   1075 			bufend -= pad_char_len;
   1076 			memcpy(bufend, pad_char, pad_char_len);
   1077 		}
   1078 	}
   1079 
   1080 	/* copy the formatted digit string into the output buffer */
   1081 	bufsize = rslt + bufsize - bufend;
   1082 	memmove(rslt, bufend, bufsize);
   1083 	free(avalue);		/* and we're done with that now */
   1084 	*usedp += used;
   1085 	return (rslt);
   1086 }
   1087 
   1088 /*
   1089  * Given a limited length multi-byte character string s
   1090  * return the number of columns that will be used to display
   1091  * that string.
   1092  *
   1093  * The string ends at the first \0 encountered within MAX_CH chars.
   1094  * The whole string must be consumed, but at most MAX_CH-1 wide chars
   1095  * (plus a null) can be present.
   1096  *
   1097  * This is not intended as a general purpose column counting function,
   1098  * just to determine the widths of the various symbols used in strfmon()
   1099  * - the decimmal_point, thousands_sep, and currency symbol.
   1100  *
   1101  * Returns -1 if any error is encountered (too much input, invalid
   1102  * byte sequence, ...) or the number of columns required (>= 0).
   1103  */
   1104 #define MAX_CH 8
   1105 static int
   1106 __columns(const char *s, locale_t loc)
   1107 {
   1108 	wchar_t widech[MAX_CH];	/* strings of up to 7 (wide) chars + nul */
   1109 	size_t count;
   1110 	mbstate_t ps;
   1111 
   1112 	(void)mbrtowc_l(NULL, NULL, 1, &ps, loc);	/* init state */
   1113 	count = mbsrtowcs_l(widech, &s, MAX_CH, &ps, loc);
   1114 	if (count == (size_t)-1 || count > MAX_CH - 1 || s != NULL)
   1115 		return -1;
   1116 	return wcswidth_l(widech, count, loc);
   1117 }
   1118 
   1119 ssize_t
   1120 strfmon(char * __restrict s, size_t maxsize,
   1121     const char * __restrict format, ...)
   1122 {
   1123 	ssize_t ret;
   1124 	va_list ap;
   1125 
   1126 	va_start(ap, format);
   1127 	ret = vstrfmon_l(s, maxsize, _current_locale(), format, ap);
   1128 	va_end(ap);
   1129 
   1130 	return ret;
   1131 }
   1132 
   1133 ssize_t
   1134 strfmon_l(char * __restrict s, size_t maxsize, locale_t loc,
   1135     const char * __restrict format, ...)
   1136 {
   1137 	ssize_t ret;
   1138 	va_list ap;
   1139 
   1140 	va_start(ap, format);
   1141 	ret = vstrfmon_l(s, maxsize, loc, format, ap);
   1142 	va_end(ap);
   1143 
   1144 	return ret;
   1145 }
   1146