Branch data Line data Source code
1 : : /*
2 : : * Copyright (c) 1997-2010, 2012-2015 Wind River Systems, Inc.
3 : : * Copyright (c) 2020 Nordic Semiconductor ASA
4 : : *
5 : : * SPDX-License-Identifier: Apache-2.0
6 : : */
7 : :
8 : : #undef _POSIX_C_SOURCE
9 : : #define _POSIX_C_SOURCE 200809L /* for strnlen() */
10 : :
11 : : #include <ctype.h>
12 : : #include <errno.h>
13 : : #include <inttypes.h>
14 : : #include <limits.h>
15 : : #include <stdarg.h>
16 : : #include <stdbool.h>
17 : : #include <stddef.h>
18 : : #include <stdint.h>
19 : : #include <string.h>
20 : : #include <zephyr/toolchain.h>
21 : : #include <zephyr/sys/util.h>
22 : : #include <zephyr/sys/cbprintf.h>
23 : :
24 : : /* Provide typedefs used for signed and unsigned integral types
25 : : * capable of holding all convertible integral values.
26 : : */
27 : : #ifdef CONFIG_CBPRINTF_FULL_INTEGRAL
28 : : typedef intmax_t sint_value_type;
29 : : typedef uintmax_t uint_value_type;
30 : : #else
31 : : typedef int32_t sint_value_type;
32 : : typedef uint32_t uint_value_type;
33 : : #endif
34 : :
35 : : /* The maximum buffer size required is for octal formatting: one character for
36 : : * every 3 bits. Neither EOS nor alternate forms are required.
37 : : */
38 : : #define CONVERTED_INT_BUFLEN ((CHAR_BIT * sizeof(uint_value_type) + 2) / 3)
39 : :
40 : : /* The float code may extract up to 16 digits, plus a prefix, a
41 : : * leading 0, a dot, and an exponent in the form e+xxx for a total of
42 : : * 24. Add a trailing NULL so the buffer length required is 25.
43 : : */
44 : : #define CONVERTED_FP_BUFLEN 25U
45 : :
46 : : #ifdef CONFIG_CBPRINTF_FP_SUPPORT
47 : : #define CONVERTED_BUFLEN MAX(CONVERTED_INT_BUFLEN, CONVERTED_FP_BUFLEN)
48 : : #else
49 : : #define CONVERTED_BUFLEN CONVERTED_INT_BUFLEN
50 : : #endif
51 : :
52 : : /* The allowed types of length modifier. */
53 : : enum length_mod_enum {
54 : : LENGTH_NONE, /* int */
55 : : LENGTH_HH, /* char */
56 : : LENGTH_H, /* short */
57 : : LENGTH_L, /* long */
58 : : LENGTH_LL, /* long long */
59 : : LENGTH_J, /* intmax */
60 : : LENGTH_Z, /* size_t */
61 : : LENGTH_T, /* ptrdiff_t */
62 : : LENGTH_UPPER_L, /* long double */
63 : : };
64 : :
65 : : /* Categories of conversion specifiers. */
66 : : enum specifier_cat_enum {
67 : : /* unrecognized */
68 : : SPECIFIER_INVALID,
69 : : /* d, i */
70 : : SPECIFIER_SINT,
71 : : /* c, o, u, x, X */
72 : : SPECIFIER_UINT,
73 : : /* n, p, s */
74 : : SPECIFIER_PTR,
75 : : /* a, A, e, E, f, F, g, G */
76 : : SPECIFIER_FP,
77 : : };
78 : :
79 : : #define CHAR_IS_SIGNED (CHAR_MIN != 0)
80 : : #if CHAR_IS_SIGNED
81 : : #define CASE_SINT_CHAR case 'c':
82 : : #define CASE_UINT_CHAR
83 : : #else
84 : : #define CASE_SINT_CHAR
85 : : #define CASE_UINT_CHAR case 'c':
86 : : #endif
87 : :
88 : : /* We need two pieces of information about wchar_t:
89 : : * * WCHAR_IS_SIGNED: whether it's signed or unsigned;
90 : : * * WINT_TYPE: the type to use when extracting it from va_args
91 : : *
92 : : * The former can be determined from the value of WCHAR_MIN if it's defined.
93 : : * It's not for minimal libc, so treat it as whatever char is.
94 : : *
95 : : * The latter should be wint_t, but minimal libc doesn't provide it. We can
96 : : * substitute wchar_t as long as that type does not undergo default integral
97 : : * promotion as an argument. But it does for at least one toolchain (xtensa),
98 : : * and where it does we need to use the promoted type in va_arg() to avoid
99 : : * build errors, otherwise we can use the base type. We can tell that
100 : : * integral promotion occurs if WCHAR_MAX is strictly less than INT_MAX.
101 : : */
102 : : #ifndef WCHAR_MIN
103 : : #define WCHAR_IS_SIGNED CHAR_IS_SIGNED
104 : : #if WCHAR_IS_SIGNED
105 : : #define WINT_TYPE int
106 : : #else /* wchar signed */
107 : : #define WINT_TYPE unsigned int
108 : : #endif /* wchar signed */
109 : : #else /* WCHAR_MIN defined */
110 : : #define WCHAR_IS_SIGNED ((WCHAR_MIN - 0) != 0)
111 : : #if WCHAR_MAX < INT_MAX
112 : : /* Signed or unsigned, it'll be int */
113 : : #define WINT_TYPE int
114 : : #else /* wchar rank vs int */
115 : : #define WINT_TYPE wchar_t
116 : : #endif /* wchar rank vs int */
117 : : #endif /* WCHAR_MIN defined */
118 : :
119 : : /* Case label to identify conversions for signed integral values. The
120 : : * corresponding argument_value tag is sint and category is
121 : : * SPECIFIER_SINT.
122 : : */
123 : : #define SINT_CONV_CASES \
124 : : 'd': \
125 : : CASE_SINT_CHAR \
126 : : case 'i'
127 : :
128 : : /* Case label to identify conversions for signed integral arguments.
129 : : * The corresponding argument_value tag is uint and category is
130 : : * SPECIFIER_UINT.
131 : : */
132 : : #define UINT_CONV_CASES \
133 : : 'o': \
134 : : CASE_UINT_CHAR \
135 : : case 'u': \
136 : : case 'x': \
137 : : case 'X'
138 : :
139 : : /* Case label to identify conversions for floating point arguments.
140 : : * The corresponding argument_value tag is either dbl or ldbl,
141 : : * depending on length modifier, and the category is SPECIFIER_FP.
142 : : */
143 : : #define FP_CONV_CASES \
144 : : 'a': \
145 : : case 'A': \
146 : : case 'e': \
147 : : case 'E': \
148 : : case 'f': \
149 : : case 'F': \
150 : : case 'g': \
151 : : case 'G'
152 : :
153 : : /* Case label to identify conversions for pointer arguments. The
154 : : * corresponding argument_value tag is ptr and the category is
155 : : * SPECIFIER_PTR.
156 : : */
157 : : #define PTR_CONV_CASES \
158 : : 'n': \
159 : : case 'p': \
160 : : case 's'
161 : :
162 : : /* Storage for an argument value. */
163 : : union argument_value {
164 : : /* For SINT conversions */
165 : : sint_value_type sint;
166 : :
167 : : /* For UINT conversions */
168 : : uint_value_type uint;
169 : :
170 : : /* For FP conversions without L length */
171 : : double dbl;
172 : :
173 : : /* For FP conversions with L length */
174 : : long double ldbl;
175 : :
176 : : /* For PTR conversions */
177 : : void *ptr;
178 : : };
179 : :
180 : : /* Structure capturing all attributes of a conversion
181 : : * specification.
182 : : *
183 : : * Initial values come from the specification, but are updated during
184 : : * the conversion.
185 : : */
186 : : struct conversion {
187 : : /** Indicates flags are inconsistent */
188 : : bool invalid: 1;
189 : :
190 : : /** Indicates flags are valid but not supported */
191 : : bool unsupported: 1;
192 : :
193 : : /** Left-justify value in width */
194 : : bool flag_dash: 1;
195 : :
196 : : /** Explicit sign */
197 : : bool flag_plus: 1;
198 : :
199 : : /** Space for non-negative sign */
200 : : bool flag_space: 1;
201 : :
202 : : /** Alternative form */
203 : : bool flag_hash: 1;
204 : :
205 : : /** Pad with leading zeroes */
206 : : bool flag_zero: 1;
207 : :
208 : : /** Width field present */
209 : : bool width_present: 1;
210 : :
211 : : /** Width value from int argument
212 : : *
213 : : * width_value is set to the absolute value of the argument.
214 : : * If the argument is negative flag_dash is also set.
215 : : */
216 : : bool width_star: 1;
217 : :
218 : : /** Precision field present */
219 : : bool prec_present: 1;
220 : :
221 : : /** Precision from int argument
222 : : *
223 : : * prec_value is set to the value of a non-negative argument.
224 : : * If the argument is negative prec_present is cleared.
225 : : */
226 : : bool prec_star: 1;
227 : :
228 : : /** Length modifier (value from length_mod_enum) */
229 : : unsigned int length_mod: 4;
230 : :
231 : : /** Indicates an a or A conversion specifier.
232 : : *
233 : : * This affects how precision is handled.
234 : : */
235 : : bool specifier_a: 1;
236 : :
237 : : /** Conversion specifier category (value from specifier_cat_enum) */
238 : : unsigned int specifier_cat: 3;
239 : :
240 : : /** If set alternate form requires 0 before octal. */
241 : : bool altform_0: 1;
242 : :
243 : : /** If set alternate form requires 0x before hex. */
244 : : bool altform_0c: 1;
245 : :
246 : : /** Set when pad0_value zeroes are to be to be inserted after
247 : : * the decimal point in a floating point conversion.
248 : : */
249 : : bool pad_postdp: 1;
250 : :
251 : : /** Set for floating point values that have a non-zero
252 : : * pad0_prefix or pad0_pre_exp.
253 : : */
254 : : bool pad_fp: 1;
255 : :
256 : : /** Conversion specifier character */
257 : : unsigned char specifier;
258 : :
259 : : union {
260 : : /** Width value from specification.
261 : : *
262 : : * Valid until conversion begins.
263 : : */
264 : : int width_value;
265 : :
266 : : /** Number of extra zeroes to be inserted around a
267 : : * formatted value:
268 : : *
269 : : * * before a formatted integer value due to precision
270 : : * and flag_zero; or
271 : : * * before a floating point mantissa decimal point
272 : : * due to precision; or
273 : : * * after a floating point mantissa decimal point due
274 : : * to precision.
275 : : *
276 : : * For example for zero-padded hexadecimal integers
277 : : * this would insert where the angle brackets are in:
278 : : * 0x<>hhhh.
279 : : *
280 : : * For floating point numbers this would insert at
281 : : * either <1> or <2> depending on #pad_postdp:
282 : : * VVV<1>.<2>FFFFeEEE
283 : : *
284 : : * Valid after conversion begins.
285 : : */
286 : : int pad0_value;
287 : : };
288 : :
289 : : union {
290 : : /** Precision from specification.
291 : : *
292 : : * Valid until conversion begins.
293 : : */
294 : : int prec_value;
295 : :
296 : : /** Number of extra zeros to be inserted after a decimal
297 : : * point due to precision.
298 : : *
299 : : * Inserts at <> in: VVVV.FFFF<>eEE
300 : : *
301 : : * Valid after conversion begins.
302 : : */
303 : : int pad0_pre_exp;
304 : : };
305 : : };
306 : :
307 : : /** Get a size represented as a sequence of decimal digits.
308 : : *
309 : : * @param[inout] str where to read from. Updated to point to the first
310 : : * unconsumed character. There must be at least one non-digit character in
311 : : * the referenced text.
312 : : *
313 : : * @return the decoded integer value.
314 : : */
315 : 513 : static size_t extract_decimal(const char **str)
316 : : {
317 : 513 : const char *sp = *str;
318 : 513 : size_t val = 0;
319 : :
320 [ + + ]: 616 : while (isdigit((int)(unsigned char)*sp) != 0) {
321 : 103 : val = 10U * val + *sp++ - '0';
322 : : }
323 : 513 : *str = sp;
324 : 513 : return val;
325 : : }
326 : :
327 : : /** Extract C99 conversion specification flags.
328 : : *
329 : : * @param conv pointer to the conversion being defined.
330 : : *
331 : : * @param sp pointer to the first character after the % of a conversion
332 : : * specifier.
333 : : *
334 : : * @return a pointer the first character that follows the flags.
335 : : */
336 : 513 : static inline const char *extract_flags(struct conversion *conv,
337 : : const char *sp)
338 : : {
339 : 513 : bool loop = true;
340 : :
341 : 615 : do {
342 [ - - - - : 615 : switch (*sp) {
+ + ]
343 : 0 : case '-':
344 : 0 : conv->flag_dash = true;
345 : 0 : break;
346 : 0 : case '+':
347 : 0 : conv->flag_plus = true;
348 : 0 : break;
349 : 0 : case ' ':
350 : 0 : conv->flag_space = true;
351 : 0 : break;
352 : 0 : case '#':
353 : 0 : conv->flag_hash = true;
354 : 0 : break;
355 : 102 : case '0':
356 : 102 : conv->flag_zero = true;
357 : 102 : break;
358 : : default:
359 : : loop = false;
360 : : break;
361 : : }
362 : 102 : if (loop) {
363 : 102 : ++sp;
364 : : }
365 [ + + ]: 615 : } while (loop);
366 : :
367 : : /* zero && dash => !zero */
368 [ - + ]: 513 : if (conv->flag_zero && conv->flag_dash) {
369 : 0 : conv->flag_zero = false;
370 : : }
371 : :
372 : : /* space && plus => !plus, handled in emitter code */
373 : :
374 : 513 : return sp;
375 : : }
376 : :
377 : : /** Extract a C99 conversion specification width.
378 : : *
379 : : * @param conv pointer to the conversion being defined.
380 : : *
381 : : * @param sp pointer to the first character after the flags element of a
382 : : * conversion specification.
383 : : *
384 : : * @return a pointer the first character that follows the width.
385 : : */
386 : 513 : static inline const char *extract_width(struct conversion *conv,
387 : : const char *sp)
388 : : {
389 : 513 : conv->width_present = true;
390 : :
391 [ - + ]: 513 : if (*sp == '*') {
392 : 0 : conv->width_star = true;
393 : 0 : return ++sp;
394 : : }
395 : :
396 : 513 : const char *wp = sp;
397 : 513 : size_t width = extract_decimal(&sp);
398 : :
399 [ + + ]: 513 : if (sp != wp) {
400 : 103 : conv->width_present = true;
401 : 103 : conv->width_value = width;
402 : 103 : conv->unsupported |= ((conv->width_value < 0)
403 [ + - ]: 103 : || (width != (size_t)conv->width_value));
404 : : }
405 : :
406 : : return sp;
407 : : }
408 : :
409 : : /** Extract a C99 conversion specification precision.
410 : : *
411 : : * @param conv pointer to the conversion being defined.
412 : : *
413 : : * @param sp pointer to the first character after the width element of a
414 : : * conversion specification.
415 : : *
416 : : * @return a pointer the first character that follows the precision.
417 : : */
418 : 513 : static inline const char *extract_prec(struct conversion *conv,
419 : : const char *sp)
420 : : {
421 : 513 : conv->prec_present = (*sp == '.');
422 : :
423 [ - + ]: 513 : if (!conv->prec_present) {
424 : : return sp;
425 : : }
426 : 0 : ++sp;
427 : :
428 [ # # ]: 0 : if (*sp == '*') {
429 : 0 : conv->prec_star = true;
430 : 0 : return ++sp;
431 : : }
432 : :
433 : 0 : size_t prec = extract_decimal(&sp);
434 : :
435 : 0 : conv->prec_value = prec;
436 : 0 : conv->unsupported |= ((conv->prec_value < 0)
437 [ # # ]: 0 : || (prec != (size_t)conv->prec_value));
438 : :
439 : 0 : return sp;
440 : : }
441 : :
442 : : /** Extract a C99 conversion specification length.
443 : : *
444 : : * @param conv pointer to the conversion being defined.
445 : : *
446 : : * @param sp pointer to the first character after the precision element of a
447 : : * conversion specification.
448 : : *
449 : : * @return a pointer the first character that follows the precision.
450 : : */
451 : 513 : static inline const char *extract_length(struct conversion *conv,
452 : : const char *sp)
453 : : {
454 [ - - - - : 513 : switch (*sp) {
- - + ]
455 : 0 : case 'h':
456 [ # # ]: 0 : if (*++sp == 'h') {
457 : 0 : conv->length_mod = LENGTH_HH;
458 : 0 : ++sp;
459 : : } else {
460 : 0 : conv->length_mod = LENGTH_H;
461 : : }
462 : : break;
463 : 0 : case 'l':
464 [ # # ]: 0 : if (*++sp == 'l') {
465 : 0 : conv->length_mod = LENGTH_LL;
466 : 0 : ++sp;
467 : : } else {
468 : 0 : conv->length_mod = LENGTH_L;
469 : : }
470 : : break;
471 : 0 : case 'j':
472 : 0 : conv->length_mod = LENGTH_J;
473 : 0 : ++sp;
474 : 0 : break;
475 : 0 : case 'z':
476 : 0 : conv->length_mod = LENGTH_Z;
477 : 0 : ++sp;
478 : 0 : break;
479 : 0 : case 't':
480 : 0 : conv->length_mod = LENGTH_T;
481 : 0 : ++sp;
482 : 0 : break;
483 : 0 : case 'L':
484 : 0 : conv->length_mod = LENGTH_UPPER_L;
485 : 0 : ++sp;
486 : :
487 : : /* We recognize and consume these, but can't format
488 : : * them.
489 : : */
490 : 0 : conv->unsupported = true;
491 : 0 : break;
492 : 513 : default:
493 : 513 : conv->length_mod = LENGTH_NONE;
494 : 513 : break;
495 : : }
496 : 513 : return sp;
497 : : }
498 : :
499 : : /* Extract a C99 conversion specifier.
500 : : *
501 : : * This is the character that identifies the representation of the converted
502 : : * value.
503 : : *
504 : : * @param conv pointer to the conversion being defined.
505 : : *
506 : : * @param sp pointer to the first character after the length element of a
507 : : * conversion specification.
508 : : *
509 : : * @return a pointer the first character that follows the specifier.
510 : : */
511 : 513 : static inline const char *extract_specifier(struct conversion *conv,
512 : : const char *sp)
513 : : {
514 : 513 : bool unsupported = false;
515 : :
516 : 513 : conv->specifier = *sp;
517 : 513 : ++sp;
518 : :
519 [ + + - - : 513 : switch (conv->specifier) {
+ - ]
520 : 6 : case SINT_CONV_CASES:
521 : 6 : conv->specifier_cat = SPECIFIER_SINT;
522 : 6 : goto int_conv;
523 : 202 : case UINT_CONV_CASES:
524 : 202 : conv->specifier_cat = SPECIFIER_UINT;
525 : 208 : int_conv:
526 : : /* L length specifier not acceptable */
527 [ - + ]: 208 : if (conv->length_mod == LENGTH_UPPER_L) {
528 : 0 : conv->invalid = true;
529 : : }
530 : :
531 : : /* For c LENGTH_NONE and LENGTH_L would be ok,
532 : : * but we don't support formatting wide characters.
533 : : */
534 [ + - ]: 208 : if (conv->specifier == 'c') {
535 : 0 : unsupported = (conv->length_mod != LENGTH_NONE);
536 : : } else if (!IS_ENABLED(CONFIG_CBPRINTF_FULL_INTEGRAL)) {
537 : : /* Disable conversion that might produce truncated
538 : : * results with buffers sized for 32 bits.
539 : : */
540 : : switch (conv->length_mod) {
541 : : case LENGTH_L:
542 : : unsupported = sizeof(long) > 4;
543 : : break;
544 : : case LENGTH_LL:
545 : : unsupported = sizeof(long long) > 4;
546 : : break;
547 : : case LENGTH_J:
548 : : unsupported = sizeof(uintmax_t) > 4;
549 : : break;
550 : : case LENGTH_Z:
551 : : unsupported = sizeof(size_t) > 4;
552 : : break;
553 : : case LENGTH_T:
554 : : unsupported = sizeof(ptrdiff_t) > 4;
555 : : break;
556 : : default:
557 : : /* Add an empty default with break, this is a defensive
558 : : * programming. Static analysis tool won't raise a violation
559 : : * if default is empty, but has that comment.
560 : : */
561 : : break;
562 : : }
563 : : } else {
564 : : ;
565 : : }
566 : : break;
567 : :
568 : 0 : case FP_CONV_CASES:
569 : 0 : conv->specifier_cat = SPECIFIER_FP;
570 : :
571 : : /* Don't support if disabled */
572 : 0 : if (!IS_ENABLED(CONFIG_CBPRINTF_FP_SUPPORT)) {
573 : 0 : unsupported = true;
574 : 0 : break;
575 : : }
576 : :
577 : : /* When FP enabled %a support is still conditional. */
578 : : conv->specifier_a = (conv->specifier == 'a')
579 : : || (conv->specifier == 'A');
580 : : if (conv->specifier_a
581 : : && !IS_ENABLED(CONFIG_CBPRINTF_FP_A_SUPPORT)) {
582 : : unsupported = true;
583 : : break;
584 : : }
585 : :
586 : : /* The l specifier has no effect. Otherwise length
587 : : * modifiers other than L are invalid.
588 : : */
589 : : if (conv->length_mod == LENGTH_L) {
590 : : conv->length_mod = LENGTH_NONE;
591 : : } else if ((conv->length_mod != LENGTH_NONE)
592 : : && (conv->length_mod != LENGTH_UPPER_L)) {
593 : : conv->invalid = true;
594 : : } else {
595 : : ;
596 : : }
597 : :
598 : : break;
599 : :
600 : : /* PTR cases are distinct */
601 : 0 : case 'n':
602 : 0 : conv->specifier_cat = SPECIFIER_PTR;
603 : : /* Anything except L */
604 [ # # ]: 0 : if (conv->length_mod == LENGTH_UPPER_L) {
605 : 0 : unsupported = true;
606 : : }
607 : : break;
608 : :
609 : 305 : case 's':
610 : : case 'p':
611 : 305 : conv->specifier_cat = SPECIFIER_PTR;
612 : :
613 : : /* p: only LENGTH_NONE
614 : : *
615 : : * s: LENGTH_NONE or LENGTH_L but wide
616 : : * characters not supported.
617 : : */
618 [ + - ]: 305 : if (conv->length_mod != LENGTH_NONE) {
619 : 0 : unsupported = true;
620 : : }
621 : : break;
622 : :
623 : 0 : default:
624 : 0 : conv->invalid = true;
625 : 0 : break;
626 : : }
627 : :
628 : 513 : conv->unsupported |= unsupported;
629 : :
630 : 513 : return sp;
631 : : }
632 : :
633 : : /* Extract the complete C99 conversion specification.
634 : : *
635 : : * @param conv pointer to the conversion being defined.
636 : : *
637 : : * @param sp pointer to the % that introduces a conversion specification.
638 : : *
639 : : * @return pointer to the first character that follows the specification.
640 : : */
641 : 514 : static inline const char *extract_conversion(struct conversion *conv,
642 : : const char *sp)
643 : : {
644 : 514 : *conv = (struct conversion) {
645 : : .invalid = false,
646 : : };
647 : :
648 : : /* Skip over the opening %. If the conversion specifier is %,
649 : : * that's the only thing that should be there, so
650 : : * fast-exit.
651 : : */
652 : 514 : ++sp;
653 [ + + ]: 514 : if (*sp == '%') {
654 : 1 : conv->specifier = *sp;
655 : 1 : ++sp;
656 : 1 : return sp;
657 : : }
658 : :
659 : 513 : sp = extract_flags(conv, sp);
660 : 513 : sp = extract_width(conv, sp);
661 : 513 : sp = extract_prec(conv, sp);
662 : 513 : sp = extract_length(conv, sp);
663 : 513 : sp = extract_specifier(conv, sp);
664 : :
665 : 513 : return sp;
666 : : }
667 : :
668 : : #ifdef CONFIG_64BIT
669 : :
670 : : static void _ldiv5(uint64_t *v)
671 : : {
672 : : /* The compiler can optimize this on its own on 64-bit architectures */
673 : : *v /= 5U;
674 : : }
675 : :
676 : : #else /* CONFIG_64BIT */
677 : :
678 : : /*
679 : : * Tiny integer divide-by-five routine. The full 64 bit division
680 : : * implementations in libgcc are very large on some architectures, and
681 : : * currently nothing in Zephyr pulls it into the link. So it makes
682 : : * sense to define this much smaller special case here to avoid
683 : : * including it just for printf.
684 : : *
685 : : * It works by multiplying v by the reciprocal of 5 i.e.:
686 : : *
687 : : * result = v * ((1 << 64) / 5) / (1 << 64)
688 : : *
689 : : * This produces a 128-bit result, but we drop the bottom 64 bits which
690 : : * accounts for the division by (1 << 64). The product is kept to 64 bits
691 : : * by summing partial multiplications and shifting right by 32 which on
692 : : * most 32-bit architectures means only a register drop.
693 : : *
694 : : * Here the multiplier is: (1 << 64) / 5 = 0x3333333333333333
695 : : * i.e. a 62 bits value. To compensate for the reduced precision, we
696 : : * add an initial bias of 1 to v. This conveniently allows for keeping
697 : : * the multiplier in a single 32-bit register given its pattern.
698 : : * Enlarging the multiplier to 64 bits would also work but carry handling
699 : : * on the summing of partial mults would be necessary, and a final right
700 : : * shift would be needed, requiring more instructions.
701 : : */
702 : : static void _ldiv5(uint64_t *v)
703 : : {
704 : : uint32_t v_lo = *v;
705 : : uint32_t v_hi = *v >> 32;
706 : : uint32_t m = 0x33333333;
707 : : uint64_t result;
708 : :
709 : : /*
710 : : * Force the multiplier constant into a register and make it
711 : : * opaque to the compiler, otherwise gcc tries to be too smart
712 : : * for its own good with a large expansion of adds and shifts.
713 : : */
714 : : __asm__ ("" : "+r" (m));
715 : :
716 : : /*
717 : : * Apply a bias of 1 to v. We can't add it to v as this would overflow
718 : : * it when at max range. Factor it out with the multiplier upfront.
719 : : */
720 : : result = ((uint64_t)m << 32) | m;
721 : :
722 : : /* The actual multiplication. */
723 : : result += (uint64_t)v_lo * m;
724 : : result >>= 32;
725 : : result += (uint64_t)v_lo * m;
726 : : result += (uint64_t)v_hi * m;
727 : : result >>= 32;
728 : : result += (uint64_t)v_hi * m;
729 : :
730 : : *v = result;
731 : : }
732 : :
733 : : #endif /* CONFIG_64BIT */
734 : :
735 : : /* Division by 10 */
736 : : static void _ldiv10(uint64_t *v)
737 : : {
738 : : *v >>= 1;
739 : : _ldiv5(v);
740 : : }
741 : :
742 : : /* Extract the next decimal character in the converted representation of a
743 : : * fractional component.
744 : : */
745 : : static char _get_digit(uint64_t *fr, int *digit_count)
746 : : {
747 : : char rval;
748 : :
749 : : if (*digit_count > 0) {
750 : : --*digit_count;
751 : : *fr *= 10U;
752 : : rval = ((*fr >> 60) & 0xF) + '0';
753 : : *fr &= (BIT64(60) - 1U);
754 : : } else {
755 : : rval = '0';
756 : : }
757 : :
758 : : return rval;
759 : : }
760 : :
761 : 208 : static inline size_t conversion_radix(char specifier)
762 : : {
763 [ - - + ]: 208 : switch (specifier) {
764 : : default:
765 : : case 'd':
766 : : case 'i':
767 : : case 'u':
768 : : return 10;
769 : 0 : case 'o':
770 : 0 : return 8;
771 : 0 : case 'p':
772 : : case 'x':
773 : : case 'X':
774 : 0 : return 16;
775 : : }
776 : : }
777 : :
778 : : /* Writes the given value into the buffer in the specified base.
779 : : *
780 : : * Precision is applied *ONLY* within the space allowed.
781 : : *
782 : : * Alternate form value is applied to o, x, and X conversions.
783 : : *
784 : : * The buffer is filled backwards, so the input bpe is the end of the
785 : : * generated representation. The returned pointer is to the first
786 : : * character of the representation.
787 : : */
788 : 208 : static char *encode_uint(uint_value_type value,
789 : : struct conversion *conv,
790 : : char *bps,
791 : : const char *bpe)
792 : : {
793 : 208 : bool upcase = isupper((int)conv->specifier) != 0;
794 : 208 : const unsigned int radix = conversion_radix(conv->specifier);
795 : 208 : char *bp = bps + (bpe - bps);
796 : :
797 : 212 : do {
798 : 212 : unsigned int lsv = (unsigned int)(value % radix);
799 : :
800 : 212 : --bp;
801 [ + - - - ]: 212 : *bp = (lsv <= 9) ? ('0' + lsv)
802 : 0 : : upcase ? ('A' + lsv - 10) : ('a' + lsv - 10);
803 : 212 : value /= radix;
804 [ + + ]: 212 : } while ((value != 0) && (bps < bp));
805 : :
806 : : /* Record required alternate forms. This can be determined
807 : : * from the radix without re-checking specifier.
808 : : */
809 [ - + ]: 208 : if (conv->flag_hash) {
810 [ # # ]: 0 : if (radix == 8) {
811 : 0 : conv->altform_0 = true;
812 [ # # ]: 0 : } else if (radix == 16) {
813 : 0 : conv->altform_0c = true;
814 : : } else {
815 : 208 : ;
816 : : }
817 : : }
818 : :
819 : 208 : return bp;
820 : : }
821 : :
822 : : /* Number of bits in the fractional part of an IEEE 754-2008 double
823 : : * precision float.
824 : : */
825 : : #define FRACTION_BITS 52
826 : :
827 : : /* Number of hex "digits" in the fractional part of an IEEE 754-2008
828 : : * double precision float.
829 : : */
830 : : #define FRACTION_HEX DIV_ROUND_UP(FRACTION_BITS, 4)
831 : :
832 : : /* Number of bits in the exponent of an IEEE 754-2008 double precision
833 : : * float.
834 : : */
835 : : #define EXPONENT_BITS 11
836 : :
837 : : /* Mask for the sign (negative) bit of an IEEE 754-2008 double precision
838 : : * float.
839 : : */
840 : : #define SIGN_MASK BIT64(63)
841 : :
842 : : /* Mask for the high-bit of a uint64_t representation of a fractional
843 : : * value.
844 : : */
845 : : #define BIT_63 BIT64(63)
846 : :
847 : : /* Convert the IEEE 754-2008 double to text format.
848 : : *
849 : : * @param value the 64-bit floating point value.
850 : : *
851 : : * @param conv details about how the conversion is to proceed. Some fields
852 : : * are adjusted based on the value being converted.
853 : : *
854 : : * @param precision the precision for the conversion (generally digits past
855 : : * the decimal point).
856 : : *
857 : : * @param bps pointer to the first character in a buffer that will hold the
858 : : * converted value.
859 : : *
860 : : * @param bpe On entry this points to the end of the buffer reserved to hold
861 : : * the converted value. On exit it is updated to point just past the
862 : : * converted value.
863 : : *
864 : : * return a pointer to the start of the converted value. This may not be @p
865 : : * bps but will be consistent with the exit value of *bpe.
866 : : */
867 : : static char *encode_float(double value,
868 : : struct conversion *conv,
869 : : int precision,
870 : : char *sign,
871 : : char *bps,
872 : : const char **bpe)
873 : : {
874 : : union {
875 : : uint64_t u64;
876 : : double dbl;
877 : : } u = {
878 : : .dbl = value,
879 : : };
880 : : bool prune_zero = false;
881 : : char *buf = bps;
882 : :
883 : : /* Prepend the sign: '-' if negative, flags control
884 : : * non-negative behavior.
885 : : */
886 : : if ((u.u64 & SIGN_MASK) != 0U) {
887 : : *sign = '-';
888 : : } else if (conv->flag_plus) {
889 : : *sign = '+';
890 : : } else if (conv->flag_space) {
891 : : *sign = ' ';
892 : : } else {
893 : : ;
894 : : }
895 : :
896 : : /* Extract the non-negative offset exponent and fraction. Record
897 : : * whether the value is subnormal.
898 : : */
899 : : char c = conv->specifier;
900 : : int expo = (u.u64 >> FRACTION_BITS) & BIT_MASK(EXPONENT_BITS);
901 : : uint64_t fract = u.u64 & BIT64_MASK(FRACTION_BITS);
902 : : bool is_subnormal = (expo == 0) && (fract != 0);
903 : :
904 : : /* Exponent of all-ones signals infinity or NaN, which are
905 : : * text constants regardless of specifier.
906 : : */
907 : : if (expo == BIT_MASK(EXPONENT_BITS)) {
908 : : if (fract == 0) {
909 : : if (isupper((unsigned char)c) != 0) {
910 : : buf[0] = 'I';
911 : : buf[1] = 'N';
912 : : buf[2] = 'F';
913 : : buf += 3;
914 : : } else {
915 : : buf[0] = 'i';
916 : : buf[1] = 'n';
917 : : buf[2] = 'f';
918 : : buf += 3;
919 : : }
920 : : } else {
921 : : if (isupper((unsigned char)c) != 0) {
922 : : buf[0] = 'N';
923 : : buf[1] = 'A';
924 : : buf[2] = 'N';
925 : : buf += 3;
926 : : } else {
927 : : buf[0] = 'n';
928 : : buf[1] = 'a';
929 : : buf[2] = 'n';
930 : : buf += 3;
931 : : }
932 : : }
933 : :
934 : : /* No zero-padding with text values */
935 : : conv->flag_zero = false;
936 : :
937 : : *bpe = buf;
938 : : return bps;
939 : : }
940 : :
941 : : /* The case of an F specifier is no longer relevant. */
942 : : if (c == 'F') {
943 : : c = 'f';
944 : : }
945 : :
946 : : /* Handle converting to the hex representation. */
947 : : if (IS_ENABLED(CONFIG_CBPRINTF_FP_A_SUPPORT)
948 : : && (IS_ENABLED(CONFIG_CBPRINTF_FP_ALWAYS_A)
949 : : || conv->specifier_a)) {
950 : : buf[0] = '0';
951 : : buf[1] = 'x';
952 : : buf += 2;
953 : :
954 : : /* Remove the offset from the exponent, and store the
955 : : * non-fractional value. Subnormals require increasing the
956 : : * exponent as first bit isn't the implicit bit.
957 : : */
958 : : expo -= 1023;
959 : : if (is_subnormal) {
960 : : *buf = '0';
961 : : ++buf;
962 : : ++expo;
963 : : } else {
964 : : *buf = '1';
965 : : ++buf;
966 : : }
967 : :
968 : : /* If we didn't get precision from a %a specification then we
969 : : * treat it as from a %a specification with no precision: full
970 : : * range, zero-pruning enabled.
971 : : *
972 : : * Otherwise we have to cap the precision of the generated
973 : : * fraction, or possibly round it.
974 : : */
975 : : if (!(conv->specifier_a && conv->prec_present)) {
976 : : precision = FRACTION_HEX;
977 : : prune_zero = true;
978 : : } else if (precision > FRACTION_HEX) {
979 : : conv->pad0_pre_exp = precision - FRACTION_HEX;
980 : : conv->pad_fp = true;
981 : : precision = FRACTION_HEX;
982 : : } else if ((fract != 0)
983 : : && (precision < FRACTION_HEX)) {
984 : : size_t pos = 4 * (FRACTION_HEX - precision) - 1;
985 : : uint64_t mask = BIT64(pos);
986 : :
987 : : /* Round only if the bit that would round is
988 : : * set.
989 : : */
990 : : if ((fract & mask) != 0ULL) {
991 : : fract += mask;
992 : : }
993 : : }
994 : :
995 : : /* Record whether we must retain the decimal point even if we
996 : : * can prune zeros.
997 : : */
998 : : bool require_dp = ((fract != 0) || conv->flag_hash);
999 : :
1000 : : if (require_dp || (precision != 0)) {
1001 : : *buf = '.';
1002 : : ++buf;
1003 : : }
1004 : :
1005 : : /* Get the fractional value as a hexadecimal string, using x
1006 : : * for a and X for A.
1007 : : */
1008 : : struct conversion aconv = {
1009 : : .specifier = isupper((unsigned char)c) != 0 ? 'X' : 'x',
1010 : : };
1011 : : const char *spe = *bpe;
1012 : : char *sp = bps + (spe - bps);
1013 : :
1014 : : if (fract != 0) {
1015 : : sp = encode_uint(fract, &aconv, buf, spe);
1016 : : }
1017 : :
1018 : : /* Pad out to full range since this is below the decimal
1019 : : * point.
1020 : : */
1021 : : while ((spe - sp) < FRACTION_HEX) {
1022 : : --sp;
1023 : : *sp = '0';
1024 : : }
1025 : :
1026 : : /* Append the leading significant "digits". */
1027 : : while ((sp < spe) && (precision > 0)) {
1028 : : *buf = *sp;
1029 : : ++buf;
1030 : : ++sp;
1031 : : --precision;
1032 : : }
1033 : :
1034 : : if (prune_zero) {
1035 : : while (*--buf == '0') {
1036 : : ;
1037 : : }
1038 : : if ((*buf != '.') || require_dp) {
1039 : : ++buf;
1040 : : }
1041 : : }
1042 : :
1043 : : *buf = 'p';
1044 : : ++buf;
1045 : : if (expo >= 0) {
1046 : : *buf = '+';
1047 : : ++buf;
1048 : : } else {
1049 : : *buf = '-';
1050 : : ++buf;
1051 : : expo = -expo;
1052 : : }
1053 : :
1054 : : aconv.specifier = 'i';
1055 : : sp = encode_uint(expo, &aconv, buf, spe);
1056 : :
1057 : : while (sp < spe) {
1058 : : *buf = *sp;
1059 : : ++buf;
1060 : : ++sp;
1061 : : }
1062 : :
1063 : : *bpe = buf;
1064 : : return bps;
1065 : : }
1066 : :
1067 : : /* Remainder of code operates on a 64-bit fraction, so shift up (and
1068 : : * discard garbage from the exponent where the implicit 1 would be
1069 : : * stored).
1070 : : */
1071 : : fract <<= EXPONENT_BITS;
1072 : : fract &= ~SIGN_MASK;
1073 : :
1074 : : /* Non-zero values need normalization. */
1075 : : if ((expo | fract) != 0) {
1076 : : if (is_subnormal) {
1077 : : /* Fraction is subnormal. Normalize it and correct
1078 : : * the exponent.
1079 : : */
1080 : : for (fract <<= 1; (fract & BIT_63) == 0; fract <<= 1) {
1081 : : expo--;
1082 : : }
1083 : : }
1084 : : /* Adjust the offset exponent to be signed rather than offset,
1085 : : * and set the implicit 1 bit in the (shifted) 53-bit
1086 : : * fraction.
1087 : : */
1088 : : expo -= (1023 - 1); /* +1 since .1 vs 1. */
1089 : : fract |= BIT_63;
1090 : : }
1091 : :
1092 : : /*
1093 : : * Let's consider:
1094 : : *
1095 : : * value = fract * 2^expo * 10^decexp
1096 : : *
1097 : : * Initially decexp = 0. The goal is to bring exp between
1098 : : * 0 and -2 as the magnitude of a fractional decimal digit is 3 bits.
1099 : : */
1100 : : int decexp = 0;
1101 : :
1102 : : while (expo < -2) {
1103 : : /*
1104 : : * Make room to allow a multiplication by 5 without overflow.
1105 : : * We test only the top part for faster code.
1106 : : */
1107 : : do {
1108 : : fract >>= 1;
1109 : : expo++;
1110 : : } while ((uint32_t)(fract >> 32) >= (UINT32_MAX / 5U));
1111 : :
1112 : : /* Perform fract * 5 * 2 / 10 */
1113 : : fract *= 5U;
1114 : : expo++;
1115 : : decexp--;
1116 : : }
1117 : :
1118 : : while (expo > 0) {
1119 : : /*
1120 : : * Perform fract / 5 / 2 * 10.
1121 : : * The +2 is there to do round the result of the division
1122 : : * by 5 not to lose too much precision in extreme cases.
1123 : : */
1124 : : fract += 2;
1125 : : _ldiv5(&fract);
1126 : : expo--;
1127 : : decexp++;
1128 : :
1129 : : /* Bring back our fractional number to full scale */
1130 : : do {
1131 : : fract <<= 1;
1132 : : expo--;
1133 : : } while (!(fract & BIT_63));
1134 : : }
1135 : :
1136 : : /*
1137 : : * The binary fractional point is located somewhere above bit 63.
1138 : : * Move it between bits 59 and 60 to give 4 bits of room to the
1139 : : * integer part.
1140 : : */
1141 : : fract >>= (4 - expo);
1142 : :
1143 : : if ((c == 'g') || (c == 'G')) {
1144 : : /* Use the specified precision and exponent to select the
1145 : : * representation and correct the precision and zero-pruning
1146 : : * in accordance with the ISO C rule.
1147 : : */
1148 : : if ((decexp < (-4 + 1)) || (decexp > precision)) {
1149 : : c += 'e' - 'g'; /* e or E */
1150 : : if (precision > 0) {
1151 : : precision--;
1152 : : }
1153 : : } else {
1154 : : c = 'f';
1155 : : precision -= decexp;
1156 : : }
1157 : : if (!conv->flag_hash && (precision > 0)) {
1158 : : prune_zero = true;
1159 : : }
1160 : : }
1161 : :
1162 : : int decimals;
1163 : : if (c == 'f') {
1164 : : decimals = precision + decexp;
1165 : : if (decimals < 0) {
1166 : : decimals = 0;
1167 : : }
1168 : : } else {
1169 : : decimals = precision + 1;
1170 : : }
1171 : :
1172 : : int digit_count = 16;
1173 : :
1174 : : if (decimals > 16) {
1175 : : decimals = 16;
1176 : : }
1177 : :
1178 : : /* Round the value to the last digit being printed. */
1179 : : uint64_t rounding = BIT64(59); /* 0.5 */
1180 : : while (decimals-- != 0) {
1181 : : _ldiv10(&rounding);
1182 : : }
1183 : : fract += rounding;
1184 : : /* Make sure rounding didn't make fract >= 1.0 */
1185 : : if (fract >= BIT64(60)) {
1186 : : _ldiv10(&fract);
1187 : : decexp++;
1188 : : }
1189 : :
1190 : : if (c == 'f') {
1191 : : if (decexp > 0) {
1192 : : /* Emit the digits above the decimal point. */
1193 : : while ((decexp > 0) && (digit_count > 0)) {
1194 : : *buf = _get_digit(&fract, &digit_count);
1195 : : ++buf;
1196 : : decexp--;
1197 : : }
1198 : :
1199 : : conv->pad0_value = decexp;
1200 : :
1201 : : decexp = 0;
1202 : : } else {
1203 : : *buf = '0';
1204 : : ++buf;
1205 : : }
1206 : :
1207 : : /* Emit the decimal point only if required by the alternative
1208 : : * format, or if more digits are to follow.
1209 : : */
1210 : : if (conv->flag_hash || (precision > 0)) {
1211 : : *buf = '.';
1212 : : ++buf;
1213 : : }
1214 : :
1215 : : if ((decexp < 0) && (precision > 0)) {
1216 : : conv->pad0_value = -decexp;
1217 : : if (conv->pad0_value > precision) {
1218 : : conv->pad0_value = precision;
1219 : : }
1220 : :
1221 : : precision -= conv->pad0_value;
1222 : : conv->pad_postdp = (conv->pad0_value > 0);
1223 : : }
1224 : : } else { /* e or E */
1225 : : /* Emit the one digit before the decimal. If it's not zero,
1226 : : * this is significant so reduce the base-10 exponent.
1227 : : */
1228 : : *buf = _get_digit(&fract, &digit_count);
1229 : : if (*buf++ != '0') {
1230 : : decexp--;
1231 : : }
1232 : :
1233 : : /* Emit the decimal point only if required by the alternative
1234 : : * format, or if more digits are to follow.
1235 : : */
1236 : : if (conv->flag_hash || (precision > 0)) {
1237 : : *buf = '.';
1238 : : ++buf;
1239 : : }
1240 : : }
1241 : :
1242 : : while ((precision > 0) && (digit_count > 0)) {
1243 : : *buf = _get_digit(&fract, &digit_count);
1244 : : ++buf;
1245 : : precision--;
1246 : : }
1247 : :
1248 : : conv->pad0_pre_exp = precision;
1249 : :
1250 : : if (prune_zero) {
1251 : : conv->pad0_pre_exp = 0;
1252 : : do {
1253 : : --buf;
1254 : : } while (*buf == '0');
1255 : : if (*buf != '.') {
1256 : : ++buf;
1257 : : }
1258 : : }
1259 : :
1260 : : /* Emit the explicit exponent, if format requires it. */
1261 : : if ((c == 'e') || (c == 'E')) {
1262 : : *buf = c;
1263 : : ++buf;
1264 : : if (decexp < 0) {
1265 : : decexp = -decexp;
1266 : : *buf = '-';
1267 : : ++buf;
1268 : : } else {
1269 : : *buf = '+';
1270 : : ++buf;
1271 : : }
1272 : :
1273 : : /* At most 3 digits to the decimal. Spit them out. */
1274 : : if (decexp >= 100) {
1275 : : *buf = (decexp / 100) + '0';
1276 : : ++buf;
1277 : : decexp %= 100;
1278 : : }
1279 : :
1280 : : buf[0] = (decexp / 10) + '0';
1281 : : buf[1] = (decexp % 10) + '0';
1282 : : buf += 2;
1283 : : }
1284 : :
1285 : : /* Cache whether there's padding required */
1286 : : conv->pad_fp = (conv->pad0_value > 0)
1287 : : || (conv->pad0_pre_exp > 0);
1288 : :
1289 : : /* Set the end of the encoded sequence, and return its start. Also
1290 : : * store EOS as a non-digit/non-decimal value so we don't have to
1291 : : * check against bpe when iterating in multiple places.
1292 : : */
1293 : : *bpe = buf;
1294 : : *buf = 0;
1295 : : return bps;
1296 : : }
1297 : :
1298 : : /* Store a count into the pointer provided in a %n specifier.
1299 : : *
1300 : : * @param conv the specifier that indicates the size of the value into which
1301 : : * the count will be stored.
1302 : : *
1303 : : * @param dp where the count should be stored.
1304 : : *
1305 : : * @param count the count to be stored.
1306 : : */
1307 : 0 : static inline void store_count(const struct conversion *conv,
1308 : : void *dp,
1309 : : int count)
1310 : : {
1311 [ # # # # : 0 : switch ((enum length_mod_enum)conv->length_mod) {
# # # #
# ]
1312 : 0 : case LENGTH_NONE:
1313 : 0 : *(int *)dp = count;
1314 : 0 : break;
1315 : 0 : case LENGTH_HH:
1316 : 0 : *(signed char *)dp = (signed char)count;
1317 : 0 : break;
1318 : 0 : case LENGTH_H:
1319 : 0 : *(short *)dp = (short)count;
1320 : 0 : break;
1321 : 0 : case LENGTH_L:
1322 : 0 : *(long *)dp = (long)count;
1323 : 0 : break;
1324 : 0 : case LENGTH_LL:
1325 : 0 : *(long long *)dp = (long long)count;
1326 : 0 : break;
1327 : 0 : case LENGTH_J:
1328 : 0 : *(intmax_t *)dp = (intmax_t)count;
1329 : 0 : break;
1330 : 0 : case LENGTH_Z:
1331 : 0 : *(size_t *)dp = (size_t)count;
1332 : 0 : break;
1333 : 0 : case LENGTH_T:
1334 : 0 : *(ptrdiff_t *)dp = (ptrdiff_t)count;
1335 : 0 : break;
1336 : : default:
1337 : : /* Add an empty default with break, this is a defensive programming.
1338 : : * Static analysis tool won't raise a violation if default is empty,
1339 : : * but has that comment.
1340 : : */
1341 : : break;
1342 : : }
1343 : 0 : }
1344 : :
1345 : : /* Outline function to emit all characters in [sp, ep). */
1346 : 513 : static int outs(cbprintf_cb __out,
1347 : : void *ctx,
1348 : : const char *sp,
1349 : : const char *ep)
1350 : : {
1351 : 513 : size_t count = 0;
1352 : 513 : cbprintf_cb out = __out;
1353 : :
1354 [ + + - + : 4245 : while ((sp < ep) || ((ep == NULL) && *sp)) {
- - ]
1355 : : /* char -> int is implementation-defined, convert to uchar first */
1356 : 3732 : unsigned char uc = *sp;
1357 : 3732 : int rc = out((int)uc, ctx);
1358 : 3732 : ++sp;
1359 : :
1360 [ - + ]: 3732 : if (rc < 0) {
1361 : 0 : return rc;
1362 : : }
1363 : 3732 : ++count;
1364 : : }
1365 : :
1366 : 513 : return (int)count;
1367 : : }
1368 : :
1369 : 209 : int z_cbvprintf_impl(cbprintf_cb __out, void *ctx, const char *fp,
1370 : : va_list ap, uint32_t flags)
1371 : : {
1372 : 209 : char buf[CONVERTED_BUFLEN];
1373 : 209 : size_t count = 0;
1374 : 209 : sint_value_type sint;
1375 : 209 : cbprintf_cb out = __out;
1376 : :
1377 : 209 : const bool tagged_ap = (flags & Z_CBVPRINTF_PROCESS_FLAG_TAGGED_ARGS)
1378 : : == Z_CBVPRINTF_PROCESS_FLAG_TAGGED_ARGS;
1379 : :
1380 : : /* Output character, returning EOF if output failed, otherwise
1381 : : * updating count.
1382 : : *
1383 : : * NB: c is evaluated exactly once: side-effects are OK
1384 : : *
1385 : : * char -> int is implementation-defined, convert to uchar first
1386 : : */
1387 : : #define OUTC(c) do { \
1388 : : unsigned char uc = (c); \
1389 : : int rc = (*out)((int)uc, ctx); \
1390 : : \
1391 : : if (rc < 0) { \
1392 : : return rc; \
1393 : : } \
1394 : : ++count; \
1395 : : } while (false)
1396 : :
1397 : : /* Output sequence of characters, returning a negative error if output
1398 : : * failed.
1399 : : */
1400 : :
1401 : : #define OUTS(_sp, _ep) do { \
1402 : : int rc = outs(out, ctx, (_sp), (_ep)); \
1403 : : \
1404 : : if (rc < 0) { \
1405 : : return rc; \
1406 : : } \
1407 : : count += rc; \
1408 : : } while (false)
1409 : :
1410 [ + + ]: 7368 : while (*fp != 0) {
1411 [ + + ]: 7159 : if (*fp != '%') {
1412 [ - + ]: 6645 : OUTC(*fp);
1413 : 6645 : ++fp;
1414 : 6646 : continue;
1415 : : }
1416 : :
1417 : : /* Force union into RAM with conversion state to
1418 : : * mitigate LLVM code generation bug.
1419 : : */
1420 : 514 : struct {
1421 : : union argument_value value;
1422 : : struct conversion conv;
1423 : 514 : } state = {
1424 : : .value = {
1425 : : .uint = 0,
1426 : : },
1427 : : };
1428 : 514 : struct conversion *const conv = &state.conv;
1429 : 514 : union argument_value *const value = &state.value;
1430 : 514 : const char *sp = fp;
1431 : 514 : int width = -1;
1432 : 514 : int precision = -1;
1433 : 514 : const char *bps = NULL;
1434 : 514 : const char *bpe = buf + sizeof(buf);
1435 : 514 : char sign = 0;
1436 : :
1437 : 514 : fp = extract_conversion(conv, sp);
1438 : :
1439 : 514 : if (conv->specifier_cat != SPECIFIER_INVALID) {
1440 : 514 : if (IS_ENABLED(CONFIG_CBPRINTF_PACKAGE_SUPPORT_TAGGED_ARGUMENTS)
1441 : : && tagged_ap) {
1442 : : /* Skip over the argument tag as it is not being
1443 : : * used here.
1444 : : */
1445 : : (void)va_arg(ap, int);
1446 : : }
1447 : : }
1448 : :
1449 : : /* If dynamic width is specified, process it,
1450 : : * otherwise set width if present.
1451 : : */
1452 [ - + ]: 514 : if (conv->width_star) {
1453 : 0 : width = va_arg(ap, int);
1454 : :
1455 [ # # ]: 0 : if (width < 0) {
1456 : 0 : conv->flag_dash = true;
1457 : 0 : width = -width;
1458 : : }
1459 [ + + ]: 514 : } else if (conv->width_present) {
1460 : 513 : width = conv->width_value;
1461 : : } else {
1462 : 514 : ;
1463 : : }
1464 : :
1465 : : /* If dynamic precision is specified, process it, otherwise
1466 : : * set precision if present. For floating point where
1467 : : * precision is not present use 6.
1468 : : */
1469 [ - + ]: 514 : if (conv->prec_star) {
1470 : 0 : int arg = va_arg(ap, int);
1471 : :
1472 [ # # ]: 0 : if (arg < 0) {
1473 : 0 : conv->prec_present = false;
1474 : : } else {
1475 : : precision = arg;
1476 : : }
1477 [ + - ]: 514 : } else if (conv->prec_present) {
1478 : 0 : precision = conv->prec_value;
1479 : : } else {
1480 : 514 : ;
1481 : : }
1482 : :
1483 : : /* Reuse width and precision memory in conv for value
1484 : : * padding counts.
1485 : : */
1486 : 514 : conv->pad0_value = 0;
1487 : 514 : conv->pad0_pre_exp = 0;
1488 : :
1489 : : /* FP conversion requires knowing the precision. */
1490 : 514 : if (IS_ENABLED(CONFIG_CBPRINTF_FP_SUPPORT)
1491 : : && (conv->specifier_cat == SPECIFIER_FP)
1492 : : && !conv->prec_present) {
1493 : : if (conv->specifier_a) {
1494 : : precision = FRACTION_HEX;
1495 : : } else {
1496 : : precision = 6;
1497 : : }
1498 : : }
1499 : :
1500 : : /* Get the value to be converted from the args.
1501 : : *
1502 : : * This can't be extracted to a helper function because
1503 : : * passing a pointer to va_list doesn't work on x86_64. See
1504 : : * https://stackoverflow.com/a/8048892.
1505 : : */
1506 : 514 : enum specifier_cat_enum specifier_cat
1507 : 514 : = (enum specifier_cat_enum)conv->specifier_cat;
1508 : 514 : enum length_mod_enum length_mod
1509 : 514 : = (enum length_mod_enum)conv->length_mod;
1510 : :
1511 : : /* Extract the value based on the argument category and length.
1512 : : *
1513 : : * Note that the length modifier doesn't affect the value of a
1514 : : * pointer argument.
1515 : : */
1516 [ + + ]: 514 : if (specifier_cat == SPECIFIER_SINT) {
1517 [ + - - - : 6 : switch (length_mod) {
- ]
1518 : 6 : default:
1519 : : case LENGTH_NONE:
1520 : : case LENGTH_HH:
1521 : : case LENGTH_H:
1522 : 6 : value->sint = va_arg(ap, int);
1523 : 6 : break;
1524 : 0 : case LENGTH_L:
1525 : 0 : if (WCHAR_IS_SIGNED
1526 [ # # ]: 0 : && (conv->specifier == 'c')) {
1527 : 0 : value->sint = (wchar_t)va_arg(ap,
1528 : : WINT_TYPE);
1529 : : } else {
1530 : 0 : value->sint = va_arg(ap, long);
1531 : : }
1532 : : break;
1533 : 0 : case LENGTH_LL:
1534 : 0 : value->sint =
1535 : 0 : (sint_value_type)va_arg(ap, long long);
1536 : 0 : break;
1537 : 0 : case LENGTH_J:
1538 : 0 : value->sint =
1539 : 0 : (sint_value_type)va_arg(ap, intmax_t);
1540 : 0 : break;
1541 : 0 : case LENGTH_Z: /* size_t */
1542 : : case LENGTH_T: /* ptrdiff_t */
1543 : : /* Though ssize_t is the signed equivalent of
1544 : : * size_t for POSIX, there is no uptrdiff_t.
1545 : : * Assume that size_t and ptrdiff_t are the
1546 : : * unsigned and signed equivalents of each
1547 : : * other. This can be checked in a platform
1548 : : * test.
1549 : : */
1550 : 0 : value->sint =
1551 : 0 : (sint_value_type)va_arg(ap, ptrdiff_t);
1552 : 0 : break;
1553 : : }
1554 [ - + ]: 6 : if (length_mod == LENGTH_HH) {
1555 : 0 : value->sint = (signed char)value->sint;
1556 [ - + ]: 6 : } else if (length_mod == LENGTH_H) {
1557 : 0 : value->sint = (short)value->sint;
1558 : : }
1559 [ + + ]: 508 : } else if (specifier_cat == SPECIFIER_UINT) {
1560 [ + - - - : 202 : switch (length_mod) {
- ]
1561 : 202 : default:
1562 : : case LENGTH_NONE:
1563 : : case LENGTH_HH:
1564 : : case LENGTH_H:
1565 : 202 : value->uint = va_arg(ap, unsigned int);
1566 : 202 : break;
1567 : : case LENGTH_L:
1568 : 0 : if ((!WCHAR_IS_SIGNED)
1569 : : && (conv->specifier == 'c')) {
1570 : : value->uint = (wchar_t)va_arg(ap,
1571 : : WINT_TYPE);
1572 : : } else {
1573 : 0 : value->uint = va_arg(ap, unsigned long);
1574 : : }
1575 : 0 : break;
1576 : 0 : case LENGTH_LL:
1577 : 0 : value->uint =
1578 : 0 : (uint_value_type)va_arg(ap,
1579 : : unsigned long long);
1580 : 0 : break;
1581 : 0 : case LENGTH_J:
1582 : 0 : value->uint =
1583 : 0 : (uint_value_type)va_arg(ap,
1584 : : uintmax_t);
1585 : 0 : break;
1586 : 0 : case LENGTH_Z: /* size_t */
1587 : : case LENGTH_T: /* ptrdiff_t */
1588 : 0 : value->uint =
1589 : 0 : (uint_value_type)va_arg(ap, size_t);
1590 : 0 : break;
1591 : : }
1592 [ - + ]: 202 : if (length_mod == LENGTH_HH) {
1593 : 0 : value->uint = (unsigned char)value->uint;
1594 [ - + ]: 202 : } else if (length_mod == LENGTH_H) {
1595 : 0 : value->uint = (unsigned short)value->uint;
1596 : : }
1597 [ - + ]: 306 : } else if (specifier_cat == SPECIFIER_FP) {
1598 [ # # ]: 0 : if (length_mod == LENGTH_UPPER_L) {
1599 : 0 : value->ldbl = va_arg(ap, long double);
1600 : : } else {
1601 : 0 : value->dbl = va_arg(ap, double);
1602 : : }
1603 [ + + ]: 306 : } else if (specifier_cat == SPECIFIER_PTR) {
1604 : 305 : value->ptr = va_arg(ap, void *);
1605 : : }
1606 : :
1607 : : /* We've now consumed all arguments related to this
1608 : : * specification. If the conversion is invalid, or is
1609 : : * something we don't support, then output the original
1610 : : * specification and move on.
1611 : : */
1612 [ - + ]: 514 : if (conv->invalid || conv->unsupported) {
1613 [ # # ]: 0 : OUTS(sp, fp);
1614 : 0 : continue;
1615 : : }
1616 : :
1617 : : /* Do formatting, either into the buffer or
1618 : : * referencing external data.
1619 : : */
1620 [ + + - - : 514 : switch (conv->specifier) {
+ + - - ]
1621 : 1 : case '%':
1622 [ - + ]: 1 : OUTC('%');
1623 : 1 : break;
1624 : 305 : case 's': {
1625 : 305 : bps = (const char *)value->ptr;
1626 : :
1627 : 305 : size_t len;
1628 : :
1629 [ - + ]: 305 : if (precision >= 0) {
1630 : 0 : len = strnlen(bps, precision);
1631 : : } else {
1632 : 305 : len = strlen(bps);
1633 : : }
1634 : :
1635 : 305 : bpe = bps + len;
1636 : 305 : precision = -1;
1637 : :
1638 : 305 : break;
1639 : : }
1640 : 0 : case 'p':
1641 : : /* Implementation-defined: null is "(nil)", non-null
1642 : : * has 0x prefix followed by significant address hex
1643 : : * digits, no leading zeros.
1644 : : */
1645 [ # # ]: 0 : if (value->ptr != NULL) {
1646 : 0 : bps = encode_uint((uintptr_t)value->ptr, conv,
1647 : : buf, bpe);
1648 : :
1649 : : /* Use 0x prefix */
1650 : 0 : conv->altform_0c = true;
1651 : 0 : conv->specifier = 'x';
1652 : :
1653 : 0 : goto prec_int_pad0;
1654 : : }
1655 : :
1656 : : bps = "(nil)";
1657 : : bpe = bps + 5;
1658 : :
1659 : : break;
1660 : 0 : case 'c':
1661 : 0 : bps = buf;
1662 : : /* Use if-else to avoid -Wsign-compare warning */
1663 : 0 : if (CHAR_IS_SIGNED) {
1664 : 0 : buf[0] = value->sint;
1665 : : } else {
1666 : : buf[0] = value->uint;
1667 : : }
1668 : 0 : bpe = buf + 1;
1669 : 0 : break;
1670 : 6 : case 'd':
1671 : : case 'i':
1672 [ + - ]: 6 : if (conv->flag_plus) {
1673 : : sign = '+';
1674 [ - + ]: 6 : } else if (conv->flag_space) {
1675 : 0 : sign = ' ';
1676 : : }
1677 : :
1678 : : /* sint/uint overlay in the union, and so
1679 : : * can't appear in read and write operations
1680 : : * in the same statement.
1681 : : */
1682 : 6 : sint = value->sint;
1683 [ - + ]: 6 : if (sint < 0) {
1684 : 0 : sign = '-';
1685 : 0 : value->uint = (uint_value_type)-sint;
1686 : : } else {
1687 : 6 : value->uint = (uint_value_type)sint;
1688 : : }
1689 : :
1690 : 208 : __fallthrough;
1691 : : case 'o':
1692 : : case 'u':
1693 : : case 'x':
1694 : : case 'X':
1695 : 208 : bps = encode_uint(value->uint, conv, buf, bpe);
1696 : :
1697 : 208 : prec_int_pad0:
1698 : : /* Update pad0 values based on precision and converted
1699 : : * length. Note that a non-empty sign is not in the
1700 : : * converted sequence, but it does not affect the
1701 : : * padding size.
1702 : : */
1703 [ - + ]: 208 : if (precision >= 0) {
1704 : 0 : size_t len = bpe - bps;
1705 : :
1706 : : /* Zero-padding flag is ignored for integer
1707 : : * conversions with precision.
1708 : : */
1709 : 0 : conv->flag_zero = false;
1710 : :
1711 : : /* Set pad0_value to satisfy precision */
1712 [ # # ]: 0 : if (len < (size_t)precision) {
1713 : 0 : conv->pad0_value = precision - (int)len;
1714 : : }
1715 : : }
1716 : :
1717 : : break;
1718 : : case 'n':
1719 : 0 : if (IS_ENABLED(CONFIG_CBPRINTF_N_SPECIFIER)) {
1720 : 0 : store_count(conv, value->ptr, count);
1721 : : }
1722 : :
1723 : 0 : break;
1724 : :
1725 : : case FP_CONV_CASES:
1726 : : if (IS_ENABLED(CONFIG_CBPRINTF_FP_SUPPORT)) {
1727 : : bps = encode_float(value->dbl, conv, precision,
1728 : : &sign, buf, &bpe);
1729 : : }
1730 : : break;
1731 : : default:
1732 : : /* Add an empty default with break, this is a defensive
1733 : : * programming. Static analysis tool won't raise a violation
1734 : : * if default is empty, but has that comment.
1735 : : */
1736 : : break;
1737 : : }
1738 : :
1739 : : /* If we don't have a converted value to emit, move
1740 : : * on.
1741 : : */
1742 [ + + ]: 514 : if (bps == NULL) {
1743 : 1 : continue;
1744 : : }
1745 : :
1746 : : /* The converted value is now stored in [bps, bpe), excluding
1747 : : * any required zero padding.
1748 : : *
1749 : : * The unjustified output will be:
1750 : : *
1751 : : * * any sign character (sint-only)
1752 : : * * any altform prefix
1753 : : * * for FP:
1754 : : * * any pre-decimal content from the converted value
1755 : : * * any pad0_value padding (!postdp)
1756 : : * * any decimal point in the converted value
1757 : : * * any pad0_value padding (postdp)
1758 : : * * any pre-exponent content from the converted value
1759 : : * * any pad0_pre_exp padding
1760 : : * * any exponent content from the converted value
1761 : : * * for non-FP:
1762 : : * * any pad0_prefix
1763 : : * * the converted value
1764 : : */
1765 : 513 : size_t nj_len = (bpe - bps);
1766 : 513 : int pad_len = 0;
1767 : :
1768 [ - + ]: 513 : if (sign != 0) {
1769 : 0 : nj_len += 1U;
1770 : : }
1771 : :
1772 [ - + ]: 513 : if (conv->altform_0c) {
1773 : 0 : nj_len += 2U;
1774 [ - + ]: 513 : } else if (conv->altform_0) {
1775 : 0 : nj_len += 1U;
1776 : : }
1777 : :
1778 : 513 : nj_len += conv->pad0_value;
1779 [ - + ]: 513 : if (conv->pad_fp) {
1780 : 0 : nj_len += conv->pad0_pre_exp;
1781 : : }
1782 : :
1783 : : /* If we have a width update width to hold the padding we need
1784 : : * for justification. The result may be negative, which will
1785 : : * result in no padding.
1786 : : *
1787 : : * If a non-negative padding width is present and we're doing
1788 : : * right-justification, emit the padding now.
1789 : : */
1790 [ + + ]: 513 : if (width > 0) {
1791 : 103 : width -= (int)nj_len;
1792 : :
1793 [ + - ]: 103 : if (!conv->flag_dash) {
1794 : 103 : char pad = ' ';
1795 : :
1796 : : /* If we're zero-padding we have to emit the
1797 : : * sign first.
1798 : : */
1799 [ + + ]: 103 : if (conv->flag_zero) {
1800 [ - + ]: 102 : if (sign != 0) {
1801 [ # # ]: 0 : OUTC(sign);
1802 : 0 : sign = 0;
1803 : : }
1804 : 103 : pad = '0';
1805 : : }
1806 : :
1807 : 306 : while (width-- > 0) {
1808 [ - + + + ]: 306 : OUTC(pad);
1809 : : }
1810 : : }
1811 : : }
1812 : :
1813 : : /* If we have a sign that hasn't been emitted, now's the
1814 : : * time....
1815 : : */
1816 [ - + ]: 513 : if (sign != 0) {
1817 [ # # ]: 0 : OUTC(sign);
1818 : : }
1819 : :
1820 : 513 : if (IS_ENABLED(CONFIG_CBPRINTF_FP_SUPPORT) && conv->pad_fp) {
1821 : : const char *cp = bps;
1822 : :
1823 : : if (conv->specifier_a) {
1824 : : /* Only padding is pre_exp */
1825 : : while (*cp != 'p') {
1826 : : OUTC(*cp);
1827 : : ++cp;
1828 : : }
1829 : : } else {
1830 : : while (isdigit((unsigned char)*cp) != 0) {
1831 : : OUTC(*cp);
1832 : : ++cp;
1833 : : }
1834 : :
1835 : : pad_len = conv->pad0_value;
1836 : : if (!conv->pad_postdp) {
1837 : : while (pad_len-- > 0) {
1838 : : OUTC('0');
1839 : : }
1840 : : }
1841 : :
1842 : : if (*cp == '.') {
1843 : : OUTC(*cp);
1844 : : ++cp;
1845 : : /* Remaining padding is
1846 : : * post-dp.
1847 : : */
1848 : : while (pad_len-- > 0) {
1849 : : OUTC('0');
1850 : : }
1851 : : }
1852 : : while (isdigit((unsigned char)*cp) != 0) {
1853 : : OUTC(*cp);
1854 : : ++cp;
1855 : : }
1856 : : }
1857 : :
1858 : : pad_len = conv->pad0_pre_exp;
1859 : : while (pad_len-- > 0) {
1860 : : OUTC('0');
1861 : : }
1862 : :
1863 : : OUTS(cp, bpe);
1864 : : } else {
1865 [ - + ]: 513 : if ((conv->altform_0c | conv->altform_0) != 0) {
1866 [ # # ]: 0 : OUTC('0');
1867 : : }
1868 : :
1869 [ - + ]: 513 : if (conv->altform_0c) {
1870 [ # # ]: 0 : OUTC(conv->specifier);
1871 : : }
1872 : :
1873 : : pad_len = conv->pad0_value;
1874 : 513 : while (pad_len-- > 0) {
1875 [ - - - + ]: 513 : OUTC('0');
1876 : : }
1877 : :
1878 [ - + ]: 513 : OUTS(bps, bpe);
1879 : : }
1880 : :
1881 : : /* Finish left justification */
1882 [ - + ]: 513 : while (width > 0) {
1883 [ # # ]: 0 : OUTC(' ');
1884 : 0 : --width;
1885 : : }
1886 : : }
1887 : :
1888 : 209 : return count;
1889 : : #undef OUTS
1890 : : #undef OUTC
1891 : : }
|