1/* Floating point output for `printf'.
2 Copyright (C) 1995-2018 Free Software Foundation, Inc.
3
4 This file is part of the GNU C Library.
5 Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.
6
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
11
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; if not, see
19 <http://www.gnu.org/licenses/>. */
20
21/* The gmp headers need some configuration frobs. */
22#define HAVE_ALLOCA 1
23
24#include <array_length.h>
25#include <libioP.h>
26#include <alloca.h>
27#include <ctype.h>
28#include <float.h>
29#include <gmp-mparam.h>
30#include <gmp.h>
31#include <ieee754.h>
32#include <stdlib/gmp-impl.h>
33#include <stdlib/longlong.h>
34#include <stdlib/fpioconst.h>
35#include <locale/localeinfo.h>
36#include <limits.h>
37#include <math.h>
38#include <printf.h>
39#include <string.h>
40#include <unistd.h>
41#include <stdlib.h>
42#include <wchar.h>
43#include <stdbool.h>
44#include <rounding-mode.h>
45
46#ifdef COMPILE_WPRINTF
47# define CHAR_T wchar_t
48#else
49# define CHAR_T char
50#endif
51
52#include "_i18n_number.h"
53
54#ifndef NDEBUG
55# define NDEBUG /* Undefine this for debugging assertions. */
56#endif
57#include <assert.h>
58
59#define PUT(f, s, n) _IO_sputn (f, s, n)
60#define PAD(f, c, n) (wide ? _IO_wpadn (f, c, n) : _IO_padn (f, c, n))
61#undef putc
62#define putc(c, f) (wide \
63 ? (int)_IO_putwc_unlocked (c, f) : _IO_putc_unlocked (c, f))
64
65
66/* Macros for doing the actual output. */
67
68#define outchar(ch) \
69 do \
70 { \
71 const int outc = (ch); \
72 if (putc (outc, fp) == EOF) \
73 { \
74 if (buffer_malloced) \
75 free (wbuffer); \
76 return -1; \
77 } \
78 ++done; \
79 } while (0)
80
81#define PRINT(ptr, wptr, len) \
82 do \
83 { \
84 size_t outlen = (len); \
85 if (len > 20) \
86 { \
87 if (PUT (fp, wide ? (const char *) wptr : ptr, outlen) != outlen) \
88 { \
89 if (buffer_malloced) \
90 free (wbuffer); \
91 return -1; \
92 } \
93 ptr += outlen; \
94 done += outlen; \
95 } \
96 else \
97 { \
98 if (wide) \
99 while (outlen-- > 0) \
100 outchar (*wptr++); \
101 else \
102 while (outlen-- > 0) \
103 outchar (*ptr++); \
104 } \
105 } while (0)
106
107#define PADN(ch, len) \
108 do \
109 { \
110 if (PAD (fp, ch, len) != len) \
111 { \
112 if (buffer_malloced) \
113 free (wbuffer); \
114 return -1; \
115 } \
116 done += len; \
117 } \
118 while (0)
119
120/* We use the GNU MP library to handle large numbers.
121
122 An MP variable occupies a varying number of entries in its array. We keep
123 track of this number for efficiency reasons. Otherwise we would always
124 have to process the whole array. */
125#define MPN_VAR(name) mp_limb_t *name; mp_size_t name##size
126
127#define MPN_ASSIGN(dst,src) \
128 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
129#define MPN_GE(u,v) \
130 (u##size > v##size || (u##size == v##size && __mpn_cmp (u, v, u##size) >= 0))
131
132extern mp_size_t __mpn_extract_double (mp_ptr res_ptr, mp_size_t size,
133 int *expt, int *is_neg,
134 double value);
135extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
136 int *expt, int *is_neg,
137 long double value);
138
139
140static wchar_t *group_number (wchar_t *buf, wchar_t *bufend,
141 unsigned int intdig_no, const char *grouping,
142 wchar_t thousands_sep, int ngroups);
143
144struct hack_digit_param
145{
146 /* Sign of the exponent. */
147 int expsign;
148 /* The type of output format that will be used: 'e'/'E' or 'f'. */
149 int type;
150 /* and the exponent. */
151 int exponent;
152 /* The fraction of the floting-point value in question */
153 MPN_VAR(frac);
154 /* Scaling factor. */
155 MPN_VAR(scale);
156 /* Temporary bignum value. */
157 MPN_VAR(tmp);
158};
159
160static wchar_t
161hack_digit (struct hack_digit_param *p)
162{
163 mp_limb_t hi;
164
165 if (p->expsign != 0 && p->type == 'f' && p->exponent-- > 0)
166 hi = 0;
167 else if (p->scalesize == 0)
168 {
169 hi = p->frac[p->fracsize - 1];
170 p->frac[p->fracsize - 1] = __mpn_mul_1 (p->frac, p->frac,
171 p->fracsize - 1, 10);
172 }
173 else
174 {
175 if (p->fracsize < p->scalesize)
176 hi = 0;
177 else
178 {
179 hi = mpn_divmod (p->tmp, p->frac, p->fracsize,
180 p->scale, p->scalesize);
181 p->tmp[p->fracsize - p->scalesize] = hi;
182 hi = p->tmp[0];
183
184 p->fracsize = p->scalesize;
185 while (p->fracsize != 0 && p->frac[p->fracsize - 1] == 0)
186 --p->fracsize;
187 if (p->fracsize == 0)
188 {
189 /* We're not prepared for an mpn variable with zero
190 limbs. */
191 p->fracsize = 1;
192 return L'0' + hi;
193 }
194 }
195
196 mp_limb_t _cy = __mpn_mul_1 (p->frac, p->frac, p->fracsize, 10);
197 if (_cy != 0)
198 p->frac[p->fracsize++] = _cy;
199 }
200
201 return L'0' + hi;
202}
203
204int
205__printf_fp_l (FILE *fp, locale_t loc,
206 const struct printf_info *info,
207 const void *const *args)
208{
209 /* The floating-point value to output. */
210 union
211 {
212 double dbl;
213 long double ldbl;
214#if __HAVE_DISTINCT_FLOAT128
215 _Float128 f128;
216#endif
217 }
218 fpnum;
219
220 /* Locale-dependent representation of decimal point. */
221 const char *decimal;
222 wchar_t decimalwc;
223
224 /* Locale-dependent thousands separator and grouping specification. */
225 const char *thousands_sep = NULL;
226 wchar_t thousands_sepwc = 0;
227 const char *grouping;
228
229 /* "NaN" or "Inf" for the special cases. */
230 const char *special = NULL;
231 const wchar_t *wspecial = NULL;
232
233 /* When _Float128 is enabled in the library and ABI-distinct from long
234 double, we need mp_limbs enough for any of them. */
235#if __HAVE_DISTINCT_FLOAT128
236# define GREATER_MANT_DIG FLT128_MANT_DIG
237#else
238# define GREATER_MANT_DIG LDBL_MANT_DIG
239#endif
240 /* We need just a few limbs for the input before shifting to the right
241 position. */
242 mp_limb_t fp_input[(GREATER_MANT_DIG + BITS_PER_MP_LIMB - 1)
243 / BITS_PER_MP_LIMB];
244 /* We need to shift the contents of fp_input by this amount of bits. */
245 int to_shift = 0;
246
247 struct hack_digit_param p;
248 /* Sign of float number. */
249 int is_neg = 0;
250
251 /* Counter for number of written characters. */
252 int done = 0;
253
254 /* General helper (carry limb). */
255 mp_limb_t cy;
256
257 /* Nonzero if this is output on a wide character stream. */
258 int wide = info->wide;
259
260 /* Buffer in which we produce the output. */
261 wchar_t *wbuffer = NULL;
262 /* Flag whether wbuffer is malloc'ed or not. */
263 int buffer_malloced = 0;
264
265 p.expsign = 0;
266
267 /* Figure out the decimal point character. */
268 if (info->extra == 0)
269 {
270 decimal = _nl_lookup (loc, LC_NUMERIC, DECIMAL_POINT);
271 decimalwc = _nl_lookup_word
272 (loc, LC_NUMERIC, _NL_NUMERIC_DECIMAL_POINT_WC);
273 }
274 else
275 {
276 decimal = _nl_lookup (loc, LC_MONETARY, MON_DECIMAL_POINT);
277 if (*decimal == '\0')
278 decimal = _nl_lookup (loc, LC_NUMERIC, DECIMAL_POINT);
279 decimalwc = _nl_lookup_word (loc, LC_MONETARY,
280 _NL_MONETARY_DECIMAL_POINT_WC);
281 if (decimalwc == L'\0')
282 decimalwc = _nl_lookup_word (loc, LC_NUMERIC,
283 _NL_NUMERIC_DECIMAL_POINT_WC);
284 }
285 /* The decimal point character must not be zero. */
286 assert (*decimal != '\0');
287 assert (decimalwc != L'\0');
288
289 if (info->group)
290 {
291 if (info->extra == 0)
292 grouping = _nl_lookup (loc, LC_NUMERIC, GROUPING);
293 else
294 grouping = _nl_lookup (loc, LC_MONETARY, MON_GROUPING);
295
296 if (*grouping <= 0 || *grouping == CHAR_MAX)
297 grouping = NULL;
298 else
299 {
300 /* Figure out the thousands separator character. */
301 if (wide)
302 {
303 if (info->extra == 0)
304 thousands_sepwc = _nl_lookup_word
305 (loc, LC_NUMERIC, _NL_NUMERIC_THOUSANDS_SEP_WC);
306 else
307 thousands_sepwc =
308 _nl_lookup_word (loc, LC_MONETARY,
309 _NL_MONETARY_THOUSANDS_SEP_WC);
310 }
311 else
312 {
313 if (info->extra == 0)
314 thousands_sep = _nl_lookup (loc, LC_NUMERIC, THOUSANDS_SEP);
315 else
316 thousands_sep = _nl_lookup
317 (loc, LC_MONETARY, MON_THOUSANDS_SEP);
318 }
319
320 if ((wide && thousands_sepwc == L'\0')
321 || (! wide && *thousands_sep == '\0'))
322 grouping = NULL;
323 else if (thousands_sepwc == L'\0')
324 /* If we are printing multibyte characters and there is a
325 multibyte representation for the thousands separator,
326 we must ensure the wide character thousands separator
327 is available, even if it is fake. */
328 thousands_sepwc = 0xfffffffe;
329 }
330 }
331 else
332 grouping = NULL;
333
334#define PRINTF_FP_FETCH(FLOAT, VAR, SUFFIX, MANT_DIG) \
335 { \
336 (VAR) = *(const FLOAT *) args[0]; \
337 \
338 /* Check for special values: not a number or infinity. */ \
339 if (isnan (VAR)) \
340 { \
341 is_neg = signbit (VAR); \
342 if (isupper (info->spec)) \
343 { \
344 special = "NAN"; \
345 wspecial = L"NAN"; \
346 } \
347 else \
348 { \
349 special = "nan"; \
350 wspecial = L"nan"; \
351 } \
352 } \
353 else if (isinf (VAR)) \
354 { \
355 is_neg = signbit (VAR); \
356 if (isupper (info->spec)) \
357 { \
358 special = "INF"; \
359 wspecial = L"INF"; \
360 } \
361 else \
362 { \
363 special = "inf"; \
364 wspecial = L"inf"; \
365 } \
366 } \
367 else \
368 { \
369 p.fracsize = __mpn_extract_##SUFFIX \
370 (fp_input, array_length (fp_input), \
371 &p.exponent, &is_neg, VAR); \
372 to_shift = 1 + p.fracsize * BITS_PER_MP_LIMB - MANT_DIG; \
373 } \
374 }
375
376 /* Fetch the argument value. */
377#if __HAVE_DISTINCT_FLOAT128
378 if (info->is_binary128)
379 PRINTF_FP_FETCH (_Float128, fpnum.f128, float128, FLT128_MANT_DIG)
380 else
381#endif
382#ifndef __NO_LONG_DOUBLE_MATH
383 if (info->is_long_double && sizeof (long double) > sizeof (double))
384 PRINTF_FP_FETCH (long double, fpnum.ldbl, long_double, LDBL_MANT_DIG)
385 else
386#endif
387 PRINTF_FP_FETCH (double, fpnum.dbl, double, DBL_MANT_DIG)
388
389#undef PRINTF_FP_FETCH
390
391 if (special)
392 {
393 int width = info->width;
394
395 if (is_neg || info->showsign || info->space)
396 --width;
397 width -= 3;
398
399 if (!info->left && width > 0)
400 PADN (' ', width);
401
402 if (is_neg)
403 outchar ('-');
404 else if (info->showsign)
405 outchar ('+');
406 else if (info->space)
407 outchar (' ');
408
409 PRINT (special, wspecial, 3);
410
411 if (info->left && width > 0)
412 PADN (' ', width);
413
414 return done;
415 }
416
417
418 /* We need three multiprecision variables. Now that we have the p.exponent
419 of the number we can allocate the needed memory. It would be more
420 efficient to use variables of the fixed maximum size but because this
421 would be really big it could lead to memory problems. */
422 {
423 mp_size_t bignum_size = ((abs (p.exponent) + BITS_PER_MP_LIMB - 1)
424 / BITS_PER_MP_LIMB
425 + (GREATER_MANT_DIG / BITS_PER_MP_LIMB > 2
426 ? 8 : 4))
427 * sizeof (mp_limb_t);
428 p.frac = (mp_limb_t *) alloca (bignum_size);
429 p.tmp = (mp_limb_t *) alloca (bignum_size);
430 p.scale = (mp_limb_t *) alloca (bignum_size);
431 }
432
433 /* We now have to distinguish between numbers with positive and negative
434 exponents because the method used for the one is not applicable/efficient
435 for the other. */
436 p.scalesize = 0;
437 if (p.exponent > 2)
438 {
439 /* |FP| >= 8.0. */
440 int scaleexpo = 0;
441 int explog;
442#if __HAVE_DISTINCT_FLOAT128
443 if (info->is_binary128)
444 explog = FLT128_MAX_10_EXP_LOG;
445 else
446 explog = LDBL_MAX_10_EXP_LOG;
447#else
448 explog = LDBL_MAX_10_EXP_LOG;
449#endif
450 int exp10 = 0;
451 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
452 int cnt_h, cnt_l, i;
453
454 if ((p.exponent + to_shift) % BITS_PER_MP_LIMB == 0)
455 {
456 MPN_COPY_DECR (p.frac + (p.exponent + to_shift) / BITS_PER_MP_LIMB,
457 fp_input, p.fracsize);
458 p.fracsize += (p.exponent + to_shift) / BITS_PER_MP_LIMB;
459 }
460 else
461 {
462 cy = __mpn_lshift (p.frac +
463 (p.exponent + to_shift) / BITS_PER_MP_LIMB,
464 fp_input, p.fracsize,
465 (p.exponent + to_shift) % BITS_PER_MP_LIMB);
466 p.fracsize += (p.exponent + to_shift) / BITS_PER_MP_LIMB;
467 if (cy)
468 p.frac[p.fracsize++] = cy;
469 }
470 MPN_ZERO (p.frac, (p.exponent + to_shift) / BITS_PER_MP_LIMB);
471
472 assert (powers > &_fpioconst_pow10[0]);
473 do
474 {
475 --powers;
476
477 /* The number of the product of two binary numbers with n and m
478 bits respectively has m+n or m+n-1 bits. */
479 if (p.exponent >= scaleexpo + powers->p_expo - 1)
480 {
481 if (p.scalesize == 0)
482 {
483#if __HAVE_DISTINCT_FLOAT128
484 if ((FLT128_MANT_DIG
485 > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB)
486 && info->is_binary128)
487 {
488#define _FLT128_FPIO_CONST_SHIFT \
489 (((FLT128_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
490 - _FPIO_CONST_OFFSET)
491 /* 64bit const offset is not enough for
492 IEEE 854 quad long double (_Float128). */
493 p.tmpsize = powers->arraysize + _FLT128_FPIO_CONST_SHIFT;
494 memcpy (p.tmp + _FLT128_FPIO_CONST_SHIFT,
495 &__tens[powers->arrayoff],
496 p.tmpsize * sizeof (mp_limb_t));
497 MPN_ZERO (p.tmp, _FLT128_FPIO_CONST_SHIFT);
498 /* Adjust p.exponent, as scaleexpo will be this much
499 bigger too. */
500 p.exponent += _FLT128_FPIO_CONST_SHIFT * BITS_PER_MP_LIMB;
501 }
502 else
503#endif /* __HAVE_DISTINCT_FLOAT128 */
504#ifndef __NO_LONG_DOUBLE_MATH
505 if (LDBL_MANT_DIG > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB
506 && info->is_long_double)
507 {
508#define _FPIO_CONST_SHIFT \
509 (((LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
510 - _FPIO_CONST_OFFSET)
511 /* 64bit const offset is not enough for
512 IEEE quad long double. */
513 p.tmpsize = powers->arraysize + _FPIO_CONST_SHIFT;
514 memcpy (p.tmp + _FPIO_CONST_SHIFT,
515 &__tens[powers->arrayoff],
516 p.tmpsize * sizeof (mp_limb_t));
517 MPN_ZERO (p.tmp, _FPIO_CONST_SHIFT);
518 /* Adjust p.exponent, as scaleexpo will be this much
519 bigger too. */
520 p.exponent += _FPIO_CONST_SHIFT * BITS_PER_MP_LIMB;
521 }
522 else
523#endif
524 {
525 p.tmpsize = powers->arraysize;
526 memcpy (p.tmp, &__tens[powers->arrayoff],
527 p.tmpsize * sizeof (mp_limb_t));
528 }
529 }
530 else
531 {
532 cy = __mpn_mul (p.tmp, p.scale, p.scalesize,
533 &__tens[powers->arrayoff
534 + _FPIO_CONST_OFFSET],
535 powers->arraysize - _FPIO_CONST_OFFSET);
536 p.tmpsize = p.scalesize +
537 powers->arraysize - _FPIO_CONST_OFFSET;
538 if (cy == 0)
539 --p.tmpsize;
540 }
541
542 if (MPN_GE (p.frac, p.tmp))
543 {
544 int cnt;
545 MPN_ASSIGN (p.scale, p.tmp);
546 count_leading_zeros (cnt, p.scale[p.scalesize - 1]);
547 scaleexpo = (p.scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
548 exp10 |= 1 << explog;
549 }
550 }
551 --explog;
552 }
553 while (powers > &_fpioconst_pow10[0]);
554 p.exponent = exp10;
555
556 /* Optimize number representations. We want to represent the numbers
557 with the lowest number of bytes possible without losing any
558 bytes. Also the highest bit in the scaling factor has to be set
559 (this is a requirement of the MPN division routines). */
560 if (p.scalesize > 0)
561 {
562 /* Determine minimum number of zero bits at the end of
563 both numbers. */
564 for (i = 0; p.scale[i] == 0 && p.frac[i] == 0; i++)
565 ;
566
567 /* Determine number of bits the scaling factor is misplaced. */
568 count_leading_zeros (cnt_h, p.scale[p.scalesize - 1]);
569
570 if (cnt_h == 0)
571 {
572 /* The highest bit of the scaling factor is already set. So
573 we only have to remove the trailing empty limbs. */
574 if (i > 0)
575 {
576 MPN_COPY_INCR (p.scale, p.scale + i, p.scalesize - i);
577 p.scalesize -= i;
578 MPN_COPY_INCR (p.frac, p.frac + i, p.fracsize - i);
579 p.fracsize -= i;
580 }
581 }
582 else
583 {
584 if (p.scale[i] != 0)
585 {
586 count_trailing_zeros (cnt_l, p.scale[i]);
587 if (p.frac[i] != 0)
588 {
589 int cnt_l2;
590 count_trailing_zeros (cnt_l2, p.frac[i]);
591 if (cnt_l2 < cnt_l)
592 cnt_l = cnt_l2;
593 }
594 }
595 else
596 count_trailing_zeros (cnt_l, p.frac[i]);
597
598 /* Now shift the numbers to their optimal position. */
599 if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
600 {
601 /* We cannot save any memory. So just roll both numbers
602 so that the scaling factor has its highest bit set. */
603
604 (void) __mpn_lshift (p.scale, p.scale, p.scalesize, cnt_h);
605 cy = __mpn_lshift (p.frac, p.frac, p.fracsize, cnt_h);
606 if (cy != 0)
607 p.frac[p.fracsize++] = cy;
608 }
609 else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
610 {
611 /* We can save memory by removing the trailing zero limbs
612 and by packing the non-zero limbs which gain another
613 free one. */
614
615 (void) __mpn_rshift (p.scale, p.scale + i, p.scalesize - i,
616 BITS_PER_MP_LIMB - cnt_h);
617 p.scalesize -= i + 1;
618 (void) __mpn_rshift (p.frac, p.frac + i, p.fracsize - i,
619 BITS_PER_MP_LIMB - cnt_h);
620 p.fracsize -= p.frac[p.fracsize - i - 1] == 0 ? i + 1 : i;
621 }
622 else
623 {
624 /* We can only save the memory of the limbs which are zero.
625 The non-zero parts occupy the same number of limbs. */
626
627 (void) __mpn_rshift (p.scale, p.scale + (i - 1),
628 p.scalesize - (i - 1),
629 BITS_PER_MP_LIMB - cnt_h);
630 p.scalesize -= i;
631 (void) __mpn_rshift (p.frac, p.frac + (i - 1),
632 p.fracsize - (i - 1),
633 BITS_PER_MP_LIMB - cnt_h);
634 p.fracsize -=
635 p.frac[p.fracsize - (i - 1) - 1] == 0 ? i : i - 1;
636 }
637 }
638 }
639 }
640 else if (p.exponent < 0)
641 {
642 /* |FP| < 1.0. */
643 int exp10 = 0;
644 int explog;
645#if __HAVE_DISTINCT_FLOAT128
646 if (info->is_binary128)
647 explog = FLT128_MAX_10_EXP_LOG;
648 else
649 explog = LDBL_MAX_10_EXP_LOG;
650#else
651 explog = LDBL_MAX_10_EXP_LOG;
652#endif
653 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
654
655 /* Now shift the input value to its right place. */
656 cy = __mpn_lshift (p.frac, fp_input, p.fracsize, to_shift);
657 p.frac[p.fracsize++] = cy;
658 assert (cy == 1 || (p.frac[p.fracsize - 2] == 0 && p.frac[0] == 0));
659
660 p.expsign = 1;
661 p.exponent = -p.exponent;
662
663 assert (powers != &_fpioconst_pow10[0]);
664 do
665 {
666 --powers;
667
668 if (p.exponent >= powers->m_expo)
669 {
670 int i, incr, cnt_h, cnt_l;
671 mp_limb_t topval[2];
672
673 /* The __mpn_mul function expects the first argument to be
674 bigger than the second. */
675 if (p.fracsize < powers->arraysize - _FPIO_CONST_OFFSET)
676 cy = __mpn_mul (p.tmp, &__tens[powers->arrayoff
677 + _FPIO_CONST_OFFSET],
678 powers->arraysize - _FPIO_CONST_OFFSET,
679 p.frac, p.fracsize);
680 else
681 cy = __mpn_mul (p.tmp, p.frac, p.fracsize,
682 &__tens[powers->arrayoff + _FPIO_CONST_OFFSET],
683 powers->arraysize - _FPIO_CONST_OFFSET);
684 p.tmpsize = p.fracsize + powers->arraysize - _FPIO_CONST_OFFSET;
685 if (cy == 0)
686 --p.tmpsize;
687
688 count_leading_zeros (cnt_h, p.tmp[p.tmpsize - 1]);
689 incr = (p.tmpsize - p.fracsize) * BITS_PER_MP_LIMB
690 + BITS_PER_MP_LIMB - 1 - cnt_h;
691
692 assert (incr <= powers->p_expo);
693
694 /* If we increased the p.exponent by exactly 3 we have to test
695 for overflow. This is done by comparing with 10 shifted
696 to the right position. */
697 if (incr == p.exponent + 3)
698 {
699 if (cnt_h <= BITS_PER_MP_LIMB - 4)
700 {
701 topval[0] = 0;
702 topval[1]
703 = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4 - cnt_h);
704 }
705 else
706 {
707 topval[0] = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4);
708 topval[1] = 0;
709 (void) __mpn_lshift (topval, topval, 2,
710 BITS_PER_MP_LIMB - cnt_h);
711 }
712 }
713
714 /* We have to be careful when multiplying the last factor.
715 If the result is greater than 1.0 be have to test it
716 against 10.0. If it is greater or equal to 10.0 the
717 multiplication was not valid. This is because we cannot
718 determine the number of bits in the result in advance. */
719 if (incr < p.exponent + 3
720 || (incr == p.exponent + 3 &&
721 (p.tmp[p.tmpsize - 1] < topval[1]
722 || (p.tmp[p.tmpsize - 1] == topval[1]
723 && p.tmp[p.tmpsize - 2] < topval[0]))))
724 {
725 /* The factor is right. Adapt binary and decimal
726 exponents. */
727 p.exponent -= incr;
728 exp10 |= 1 << explog;
729
730 /* If this factor yields a number greater or equal to
731 1.0, we must not shift the non-fractional digits down. */
732 if (p.exponent < 0)
733 cnt_h += -p.exponent;
734
735 /* Now we optimize the number representation. */
736 for (i = 0; p.tmp[i] == 0; ++i);
737 if (cnt_h == BITS_PER_MP_LIMB - 1)
738 {
739 MPN_COPY (p.frac, p.tmp + i, p.tmpsize - i);
740 p.fracsize = p.tmpsize - i;
741 }
742 else
743 {
744 count_trailing_zeros (cnt_l, p.tmp[i]);
745
746 /* Now shift the numbers to their optimal position. */
747 if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
748 {
749 /* We cannot save any memory. Just roll the
750 number so that the leading digit is in a
751 separate limb. */
752
753 cy = __mpn_lshift (p.frac, p.tmp, p.tmpsize,
754 cnt_h + 1);
755 p.fracsize = p.tmpsize + 1;
756 p.frac[p.fracsize - 1] = cy;
757 }
758 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
759 {
760 (void) __mpn_rshift (p.frac, p.tmp + i, p.tmpsize - i,
761 BITS_PER_MP_LIMB - 1 - cnt_h);
762 p.fracsize = p.tmpsize - i;
763 }
764 else
765 {
766 /* We can only save the memory of the limbs which
767 are zero. The non-zero parts occupy the same
768 number of limbs. */
769
770 (void) __mpn_rshift (p.frac, p.tmp + (i - 1),
771 p.tmpsize - (i - 1),
772 BITS_PER_MP_LIMB - 1 - cnt_h);
773 p.fracsize = p.tmpsize - (i - 1);
774 }
775 }
776 }
777 }
778 --explog;
779 }
780 while (powers != &_fpioconst_pow10[1] && p.exponent > 0);
781 /* All factors but 10^-1 are tested now. */
782 if (p.exponent > 0)
783 {
784 int cnt_l;
785
786 cy = __mpn_mul_1 (p.tmp, p.frac, p.fracsize, 10);
787 p.tmpsize = p.fracsize;
788 assert (cy == 0 || p.tmp[p.tmpsize - 1] < 20);
789
790 count_trailing_zeros (cnt_l, p.tmp[0]);
791 if (cnt_l < MIN (4, p.exponent))
792 {
793 cy = __mpn_lshift (p.frac, p.tmp, p.tmpsize,
794 BITS_PER_MP_LIMB - MIN (4, p.exponent));
795 if (cy != 0)
796 p.frac[p.tmpsize++] = cy;
797 }
798 else
799 (void) __mpn_rshift (p.frac, p.tmp, p.tmpsize, MIN (4, p.exponent));
800 p.fracsize = p.tmpsize;
801 exp10 |= 1;
802 assert (p.frac[p.fracsize - 1] < 10);
803 }
804 p.exponent = exp10;
805 }
806 else
807 {
808 /* This is a special case. We don't need a factor because the
809 numbers are in the range of 1.0 <= |fp| < 8.0. We simply
810 shift it to the right place and divide it by 1.0 to get the
811 leading digit. (Of course this division is not really made.) */
812 assert (0 <= p.exponent && p.exponent < 3 &&
813 p.exponent + to_shift < BITS_PER_MP_LIMB);
814
815 /* Now shift the input value to its right place. */
816 cy = __mpn_lshift (p.frac, fp_input, p.fracsize, (p.exponent + to_shift));
817 p.frac[p.fracsize++] = cy;
818 p.exponent = 0;
819 }
820
821 {
822 int width = info->width;
823 wchar_t *wstartp, *wcp;
824 size_t chars_needed;
825 int expscale;
826 int intdig_max, intdig_no = 0;
827 int fracdig_min;
828 int fracdig_max;
829 int dig_max;
830 int significant;
831 int ngroups = 0;
832 char spec = _tolower (info->spec);
833
834 if (spec == 'e')
835 {
836 p.type = info->spec;
837 intdig_max = 1;
838 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
839 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
840 /* d . ddd e +- ddd */
841 dig_max = INT_MAX; /* Unlimited. */
842 significant = 1; /* Does not matter here. */
843 }
844 else if (spec == 'f')
845 {
846 p.type = 'f';
847 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
848 dig_max = INT_MAX; /* Unlimited. */
849 significant = 1; /* Does not matter here. */
850 if (p.expsign == 0)
851 {
852 intdig_max = p.exponent + 1;
853 /* This can be really big! */ /* XXX Maybe malloc if too big? */
854 chars_needed = (size_t) p.exponent + 1 + 1 + (size_t) fracdig_max;
855 }
856 else
857 {
858 intdig_max = 1;
859 chars_needed = 1 + 1 + (size_t) fracdig_max;
860 }
861 }
862 else
863 {
864 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
865 if ((p.expsign == 0 && p.exponent >= dig_max)
866 || (p.expsign != 0 && p.exponent > 4))
867 {
868 if ('g' - 'G' == 'e' - 'E')
869 p.type = 'E' + (info->spec - 'G');
870 else
871 p.type = isupper (info->spec) ? 'E' : 'e';
872 fracdig_max = dig_max - 1;
873 intdig_max = 1;
874 chars_needed = 1 + 1 + (size_t) fracdig_max + 1 + 1 + 4;
875 }
876 else
877 {
878 p.type = 'f';
879 intdig_max = p.expsign == 0 ? p.exponent + 1 : 0;
880 fracdig_max = dig_max - intdig_max;
881 /* We need space for the significant digits and perhaps
882 for leading zeros when < 1.0. The number of leading
883 zeros can be as many as would be required for
884 exponential notation with a negative two-digit
885 p.exponent, which is 4. */
886 chars_needed = (size_t) dig_max + 1 + 4;
887 }
888 fracdig_min = info->alt ? fracdig_max : 0;
889 significant = 0; /* We count significant digits. */
890 }
891
892 if (grouping)
893 {
894 /* Guess the number of groups we will make, and thus how
895 many spaces we need for separator characters. */
896 ngroups = __guess_grouping (intdig_max, grouping);
897 /* Allocate one more character in case rounding increases the
898 number of groups. */
899 chars_needed += ngroups + 1;
900 }
901
902 /* Allocate buffer for output. We need two more because while rounding
903 it is possible that we need two more characters in front of all the
904 other output. If the amount of memory we have to allocate is too
905 large use `malloc' instead of `alloca'. */
906 if (__builtin_expect (chars_needed >= (size_t) -1 / sizeof (wchar_t) - 2
907 || chars_needed < fracdig_max, 0))
908 {
909 /* Some overflow occurred. */
910 __set_errno (ERANGE);
911 return -1;
912 }
913 size_t wbuffer_to_alloc = (2 + chars_needed) * sizeof (wchar_t);
914 buffer_malloced = ! __libc_use_alloca (wbuffer_to_alloc);
915 if (__builtin_expect (buffer_malloced, 0))
916 {
917 wbuffer = (wchar_t *) malloc (wbuffer_to_alloc);
918 if (wbuffer == NULL)
919 /* Signal an error to the caller. */
920 return -1;
921 }
922 else
923 wbuffer = (wchar_t *) alloca (wbuffer_to_alloc);
924 wcp = wstartp = wbuffer + 2; /* Let room for rounding. */
925
926 /* Do the real work: put digits in allocated buffer. */
927 if (p.expsign == 0 || p.type != 'f')
928 {
929 assert (p.expsign == 0 || intdig_max == 1);
930 while (intdig_no < intdig_max)
931 {
932 ++intdig_no;
933 *wcp++ = hack_digit (&p);
934 }
935 significant = 1;
936 if (info->alt
937 || fracdig_min > 0
938 || (fracdig_max > 0 && (p.fracsize > 1 || p.frac[0] != 0)))
939 *wcp++ = decimalwc;
940 }
941 else
942 {
943 /* |fp| < 1.0 and the selected p.type is 'f', so put "0."
944 in the buffer. */
945 *wcp++ = L'0';
946 --p.exponent;
947 *wcp++ = decimalwc;
948 }
949
950 /* Generate the needed number of fractional digits. */
951 int fracdig_no = 0;
952 int added_zeros = 0;
953 while (fracdig_no < fracdig_min + added_zeros
954 || (fracdig_no < fracdig_max && (p.fracsize > 1 || p.frac[0] != 0)))
955 {
956 ++fracdig_no;
957 *wcp = hack_digit (&p);
958 if (*wcp++ != L'0')
959 significant = 1;
960 else if (significant == 0)
961 {
962 ++fracdig_max;
963 if (fracdig_min > 0)
964 ++added_zeros;
965 }
966 }
967
968 /* Do rounding. */
969 wchar_t last_digit = wcp[-1] != decimalwc ? wcp[-1] : wcp[-2];
970 wchar_t next_digit = hack_digit (&p);
971 bool more_bits;
972 if (next_digit != L'0' && next_digit != L'5')
973 more_bits = true;
974 else if (p.fracsize == 1 && p.frac[0] == 0)
975 /* Rest of the number is zero. */
976 more_bits = false;
977 else if (p.scalesize == 0)
978 {
979 /* Here we have to see whether all limbs are zero since no
980 normalization happened. */
981 size_t lcnt = p.fracsize;
982 while (lcnt >= 1 && p.frac[lcnt - 1] == 0)
983 --lcnt;
984 more_bits = lcnt > 0;
985 }
986 else
987 more_bits = true;
988 int rounding_mode = get_rounding_mode ();
989 if (round_away (is_neg, (last_digit - L'0') & 1, next_digit >= L'5',
990 more_bits, rounding_mode))
991 {
992 wchar_t *wtp = wcp;
993
994 if (fracdig_no > 0)
995 {
996 /* Process fractional digits. Terminate if not rounded or
997 radix character is reached. */
998 int removed = 0;
999 while (*--wtp != decimalwc && *wtp == L'9')
1000 {
1001 *wtp = L'0';
1002 ++removed;
1003 }
1004 if (removed == fracdig_min && added_zeros > 0)
1005 --added_zeros;
1006 if (*wtp != decimalwc)
1007 /* Round up. */
1008 (*wtp)++;
1009 else if (__builtin_expect (spec == 'g' && p.type == 'f' && info->alt
1010 && wtp == wstartp + 1
1011 && wstartp[0] == L'0',
1012 0))
1013 /* This is a special case: the rounded number is 1.0,
1014 the format is 'g' or 'G', and the alternative format
1015 is selected. This means the result must be "1.". */
1016 --added_zeros;
1017 }
1018
1019 if (fracdig_no == 0 || *wtp == decimalwc)
1020 {
1021 /* Round the integer digits. */
1022 if (*(wtp - 1) == decimalwc)
1023 --wtp;
1024
1025 while (--wtp >= wstartp && *wtp == L'9')
1026 *wtp = L'0';
1027
1028 if (wtp >= wstartp)
1029 /* Round up. */
1030 (*wtp)++;
1031 else
1032 /* It is more critical. All digits were 9's. */
1033 {
1034 if (p.type != 'f')
1035 {
1036 *wstartp = '1';
1037 p.exponent += p.expsign == 0 ? 1 : -1;
1038
1039 /* The above p.exponent adjustment could lead to 1.0e-00,
1040 e.g. for 0.999999999. Make sure p.exponent 0 always
1041 uses + sign. */
1042 if (p.exponent == 0)
1043 p.expsign = 0;
1044 }
1045 else if (intdig_no == dig_max)
1046 {
1047 /* This is the case where for p.type %g the number fits
1048 really in the range for %f output but after rounding
1049 the number of digits is too big. */
1050 *--wstartp = decimalwc;
1051 *--wstartp = L'1';
1052
1053 if (info->alt || fracdig_no > 0)
1054 {
1055 /* Overwrite the old radix character. */
1056 wstartp[intdig_no + 2] = L'0';
1057 ++fracdig_no;
1058 }
1059
1060 fracdig_no += intdig_no;
1061 intdig_no = 1;
1062 fracdig_max = intdig_max - intdig_no;
1063 ++p.exponent;
1064 /* Now we must print the p.exponent. */
1065 p.type = isupper (info->spec) ? 'E' : 'e';
1066 }
1067 else
1068 {
1069 /* We can simply add another another digit before the
1070 radix. */
1071 *--wstartp = L'1';
1072 ++intdig_no;
1073 }
1074
1075 /* While rounding the number of digits can change.
1076 If the number now exceeds the limits remove some
1077 fractional digits. */
1078 if (intdig_no + fracdig_no > dig_max)
1079 {
1080 wcp -= intdig_no + fracdig_no - dig_max;
1081 fracdig_no -= intdig_no + fracdig_no - dig_max;
1082 }
1083 }
1084 }
1085 }
1086
1087 /* Now remove unnecessary '0' at the end of the string. */
1088 while (fracdig_no > fracdig_min + added_zeros && *(wcp - 1) == L'0')
1089 {
1090 --wcp;
1091 --fracdig_no;
1092 }
1093 /* If we eliminate all fractional digits we perhaps also can remove
1094 the radix character. */
1095 if (fracdig_no == 0 && !info->alt && *(wcp - 1) == decimalwc)
1096 --wcp;
1097
1098 if (grouping)
1099 {
1100 /* Rounding might have changed the number of groups. We allocated
1101 enough memory but we need here the correct number of groups. */
1102 if (intdig_no != intdig_max)
1103 ngroups = __guess_grouping (intdig_no, grouping);
1104
1105 /* Add in separator characters, overwriting the same buffer. */
1106 wcp = group_number (wstartp, wcp, intdig_no, grouping, thousands_sepwc,
1107 ngroups);
1108 }
1109
1110 /* Write the p.exponent if it is needed. */
1111 if (p.type != 'f')
1112 {
1113 if (__glibc_unlikely (p.expsign != 0 && p.exponent == 4 && spec == 'g'))
1114 {
1115 /* This is another special case. The p.exponent of the number is
1116 really smaller than -4, which requires the 'e'/'E' format.
1117 But after rounding the number has an p.exponent of -4. */
1118 assert (wcp >= wstartp + 1);
1119 assert (wstartp[0] == L'1');
1120 __wmemcpy (wstartp, L"0.0001", 6);
1121 wstartp[1] = decimalwc;
1122 if (wcp >= wstartp + 2)
1123 {
1124 __wmemset (wstartp + 6, L'0', wcp - (wstartp + 2));
1125 wcp += 4;
1126 }
1127 else
1128 wcp += 5;
1129 }
1130 else
1131 {
1132 *wcp++ = (wchar_t) p.type;
1133 *wcp++ = p.expsign ? L'-' : L'+';
1134
1135 /* Find the magnitude of the p.exponent. */
1136 expscale = 10;
1137 while (expscale <= p.exponent)
1138 expscale *= 10;
1139
1140 if (p.exponent < 10)
1141 /* Exponent always has at least two digits. */
1142 *wcp++ = L'0';
1143 else
1144 do
1145 {
1146 expscale /= 10;
1147 *wcp++ = L'0' + (p.exponent / expscale);
1148 p.exponent %= expscale;
1149 }
1150 while (expscale > 10);
1151 *wcp++ = L'0' + p.exponent;
1152 }
1153 }
1154
1155 /* Compute number of characters which must be filled with the padding
1156 character. */
1157 if (is_neg || info->showsign || info->space)
1158 --width;
1159 width -= wcp - wstartp;
1160
1161 if (!info->left && info->pad != '0' && width > 0)
1162 PADN (info->pad, width);
1163
1164 if (is_neg)
1165 outchar ('-');
1166 else if (info->showsign)
1167 outchar ('+');
1168 else if (info->space)
1169 outchar (' ');
1170
1171 if (!info->left && info->pad == '0' && width > 0)
1172 PADN ('0', width);
1173
1174 {
1175 char *buffer = NULL;
1176 char *buffer_end = NULL;
1177 char *cp = NULL;
1178 char *tmpptr;
1179
1180 if (! wide)
1181 {
1182 /* Create the single byte string. */
1183 size_t decimal_len;
1184 size_t thousands_sep_len;
1185 wchar_t *copywc;
1186 size_t factor;
1187 if (info->i18n)
1188 factor = _nl_lookup_word (loc, LC_CTYPE, _NL_CTYPE_MB_CUR_MAX);
1189 else
1190 factor = 1;
1191
1192 decimal_len = strlen (decimal);
1193
1194 if (thousands_sep == NULL)
1195 thousands_sep_len = 0;
1196 else
1197 thousands_sep_len = strlen (thousands_sep);
1198
1199 size_t nbuffer = (2 + chars_needed * factor + decimal_len
1200 + ngroups * thousands_sep_len);
1201 if (__glibc_unlikely (buffer_malloced))
1202 {
1203 buffer = (char *) malloc (nbuffer);
1204 if (buffer == NULL)
1205 {
1206 /* Signal an error to the caller. */
1207 free (wbuffer);
1208 return -1;
1209 }
1210 }
1211 else
1212 buffer = (char *) alloca (nbuffer);
1213 buffer_end = buffer + nbuffer;
1214
1215 /* Now copy the wide character string. Since the character
1216 (except for the decimal point and thousands separator) must
1217 be coming from the ASCII range we can esily convert the
1218 string without mapping tables. */
1219 for (cp = buffer, copywc = wstartp; copywc < wcp; ++copywc)
1220 if (*copywc == decimalwc)
1221 cp = (char *) __mempcpy (cp, decimal, decimal_len);
1222 else if (*copywc == thousands_sepwc)
1223 cp = (char *) __mempcpy (cp, thousands_sep, thousands_sep_len);
1224 else
1225 *cp++ = (char) *copywc;
1226 }
1227
1228 tmpptr = buffer;
1229 if (__glibc_unlikely (info->i18n))
1230 {
1231#ifdef COMPILE_WPRINTF
1232 wstartp = _i18n_number_rewrite (wstartp, wcp,
1233 wbuffer + wbuffer_to_alloc);
1234 wcp = wbuffer + wbuffer_to_alloc;
1235 assert ((uintptr_t) wbuffer <= (uintptr_t) wstartp);
1236 assert ((uintptr_t) wstartp
1237 < (uintptr_t) wbuffer + wbuffer_to_alloc);
1238#else
1239 tmpptr = _i18n_number_rewrite (tmpptr, cp, buffer_end);
1240 cp = buffer_end;
1241 assert ((uintptr_t) buffer <= (uintptr_t) tmpptr);
1242 assert ((uintptr_t) tmpptr < (uintptr_t) buffer_end);
1243#endif
1244 }
1245
1246 PRINT (tmpptr, wstartp, wide ? wcp - wstartp : cp - tmpptr);
1247
1248 /* Free the memory if necessary. */
1249 if (__glibc_unlikely (buffer_malloced))
1250 {
1251 free (buffer);
1252 free (wbuffer);
1253 }
1254 }
1255
1256 if (info->left && width > 0)
1257 PADN (info->pad, width);
1258 }
1259 return done;
1260}
1261libc_hidden_def (__printf_fp_l)
1262
1263int
1264___printf_fp (FILE *fp, const struct printf_info *info,
1265 const void *const *args)
1266{
1267 return __printf_fp_l (fp, _NL_CURRENT_LOCALE, info, args);
1268}
1269ldbl_hidden_def (___printf_fp, __printf_fp)
1270ldbl_strong_alias (___printf_fp, __printf_fp)
1271
1272
1273/* Return the number of extra grouping characters that will be inserted
1274 into a number with INTDIG_MAX integer digits. */
1275
1276unsigned int
1277__guess_grouping (unsigned int intdig_max, const char *grouping)
1278{
1279 unsigned int groups;
1280
1281 /* We treat all negative values like CHAR_MAX. */
1282
1283 if (*grouping == CHAR_MAX || *grouping <= 0)
1284 /* No grouping should be done. */
1285 return 0;
1286
1287 groups = 0;
1288 while (intdig_max > (unsigned int) *grouping)
1289 {
1290 ++groups;
1291 intdig_max -= *grouping++;
1292
1293 if (*grouping == CHAR_MAX
1294#if CHAR_MIN < 0
1295 || *grouping < 0
1296#endif
1297 )
1298 /* No more grouping should be done. */
1299 break;
1300 else if (*grouping == 0)
1301 {
1302 /* Same grouping repeats. */
1303 groups += (intdig_max - 1) / grouping[-1];
1304 break;
1305 }
1306 }
1307
1308 return groups;
1309}
1310
1311/* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1312 There is guaranteed enough space past BUFEND to extend it.
1313 Return the new end of buffer. */
1314
1315static wchar_t *
1316group_number (wchar_t *buf, wchar_t *bufend, unsigned int intdig_no,
1317 const char *grouping, wchar_t thousands_sep, int ngroups)
1318{
1319 wchar_t *p;
1320
1321 if (ngroups == 0)
1322 return bufend;
1323
1324 /* Move the fractional part down. */
1325 __wmemmove (buf + intdig_no + ngroups, buf + intdig_no,
1326 bufend - (buf + intdig_no));
1327
1328 p = buf + intdig_no + ngroups - 1;
1329 do
1330 {
1331 unsigned int len = *grouping++;
1332 do
1333 *p-- = buf[--intdig_no];
1334 while (--len > 0);
1335 *p-- = thousands_sep;
1336
1337 if (*grouping == CHAR_MAX
1338#if CHAR_MIN < 0
1339 || *grouping < 0
1340#endif
1341 )
1342 /* No more grouping should be done. */
1343 break;
1344 else if (*grouping == 0)
1345 /* Same grouping repeats. */
1346 --grouping;
1347 } while (intdig_no > (unsigned int) *grouping);
1348
1349 /* Copy the remaining ungrouped digits. */
1350 do
1351 *p-- = buf[--intdig_no];
1352 while (p > buf);
1353
1354 return bufend + ngroups;
1355}
1356