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