source: mainline/boot/generic/src/printf_core.c@ 39916d6

Last change on this file since 39916d6 was d7f7a4a, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 3 years ago

Replace some license headers with SPDX identifier

Headers are replaced using tools/transorm-copyright.sh only
when it can be matched verbatim with the license header used
throughout most of the codebase.

  • Property mode set to 100644
File size: 18.0 KB
Line 
1/*
2 * SPDX-FileCopyrightText: 2001-2004 Jakub Jermar
3 * SPDX-FileCopyrightText: 2006 Josef Cejka
4 * SPDX-FileCopyrightText: 2009 Martin Decky
5 *
6 * SPDX-License-Identifier: BSD-3-Clause
7 */
8
9/**
10 * @file
11 * @brief Printing functions.
12 */
13
14#include <printf_core.h>
15#include <printf.h>
16#include <stdarg.h>
17#include <stdbool.h>
18#include <stddef.h>
19#include <stdint.h>
20#include <macros.h>
21#include <str.h>
22
23/** show prefixes 0x or 0 */
24#define __PRINTF_FLAG_PREFIX 0x00000001
25
26/** signed / unsigned number */
27#define __PRINTF_FLAG_SIGNED 0x00000002
28
29/** print leading zeroes */
30#define __PRINTF_FLAG_ZEROPADDED 0x00000004
31
32/** align to left */
33#define __PRINTF_FLAG_LEFTALIGNED 0x00000010
34
35/** always show + sign */
36#define __PRINTF_FLAG_SHOWPLUS 0x00000020
37
38/** print space instead of plus */
39#define __PRINTF_FLAG_SPACESIGN 0x00000040
40
41/** show big characters */
42#define __PRINTF_FLAG_BIGCHARS 0x00000080
43
44/** number has - sign */
45#define __PRINTF_FLAG_NEGATIVE 0x00000100
46
47/**
48 * Buffer big enough for 64-bit number printed in base 2, sign, prefix and 0
49 * to terminate string... (last one is only for better testing end of buffer by
50 * zero-filling subroutine)
51 */
52#define PRINT_NUMBER_BUFFER_SIZE (64 + 5)
53
54/** Get signed or unsigned integer argument */
55#define PRINTF_GET_INT_ARGUMENT(type, ap, flags) \
56 ({ \
57 unsigned type res; \
58 \
59 if ((flags) & __PRINTF_FLAG_SIGNED) { \
60 signed type arg = va_arg((ap), signed type); \
61 \
62 if (arg < 0) { \
63 res = -arg; \
64 (flags) |= __PRINTF_FLAG_NEGATIVE; \
65 } else \
66 res = arg; \
67 } else \
68 res = va_arg((ap), unsigned type); \
69 \
70 res; \
71 })
72
73/** Enumeration of possible arguments types.
74 */
75typedef enum {
76 PrintfQualifierByte = 0,
77 PrintfQualifierShort,
78 PrintfQualifierInt,
79 PrintfQualifierLong,
80 PrintfQualifierLongLong,
81 PrintfQualifierPointer,
82 PrintfQualifierSize,
83 PrintfQualifierMax
84} qualifier_t;
85
86static const char *nullstr = "(NULL)";
87static const char *digits_small = "0123456789abcdef";
88static const char *digits_big = "0123456789ABCDEF";
89static const char invalch = U_SPECIAL;
90
91/** Print one or more characters without adding newline.
92 *
93 * @param buf Buffer holding characters with size of
94 * at least size bytes. NULL is not allowed!
95 * @param size Size of the buffer in bytes.
96 * @param ps Output method and its data.
97 *
98 * @return Number of characters printed.
99 *
100 */
101static int printf_putnchars(const char *buf, size_t size,
102 printf_spec_t *ps)
103{
104 return ps->str_write((void *) buf, size, ps->data);
105}
106
107/** Print string without adding a newline.
108 *
109 * @param str String to print.
110 * @param ps Write function specification and support data.
111 *
112 * @return Number of characters printed.
113 *
114 */
115static int printf_putstr(const char *str, printf_spec_t *ps)
116{
117 if (str == NULL)
118 return printf_putnchars(nullstr, str_size(nullstr), ps);
119
120 return ps->str_write((void *) str, str_size(str), ps->data);
121}
122
123/** Print one ASCII character.
124 *
125 * @param c ASCII character to be printed.
126 * @param ps Output method.
127 *
128 * @return Number of characters printed.
129 *
130 */
131static int printf_putchar(const char ch, printf_spec_t *ps)
132{
133 if (!ascii_check(ch))
134 return ps->str_write((void *) &invalch, 1, ps->data);
135
136 return ps->str_write(&ch, 1, ps->data);
137}
138
139/** Print one formatted ASCII character.
140 *
141 * @param ch Character to print.
142 * @param width Width modifier.
143 * @param flags Flags that change the way the character is printed.
144 *
145 * @return Number of characters printed, negative value on failure.
146 *
147 */
148static int print_char(const char ch, int width, uint32_t flags, printf_spec_t *ps)
149{
150 size_t counter = 0;
151 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
152 while (--width > 0) {
153 /*
154 * One space is consumed by the character itself, hence
155 * the predecrement.
156 */
157 if (printf_putchar(' ', ps) > 0)
158 counter++;
159 }
160 }
161
162 if (printf_putchar(ch, ps) > 0)
163 counter++;
164
165 while (--width > 0) {
166 /*
167 * One space is consumed by the character itself, hence
168 * the predecrement.
169 */
170 if (printf_putchar(' ', ps) > 0)
171 counter++;
172 }
173
174 return (int) (counter);
175}
176
177/** Print string.
178 *
179 * @param str String to be printed.
180 * @param width Width modifier.
181 * @param precision Precision modifier.
182 * @param flags Flags that modify the way the string is printed.
183 *
184 * @return Number of characters printed, negative value on failure.
185 */
186static int print_str(char *str, int width, unsigned int precision,
187 uint32_t flags, printf_spec_t *ps)
188{
189 if (str == NULL)
190 return printf_putstr(nullstr, ps);
191
192 /* Print leading spaces. */
193 size_t strw = str_length(str);
194 if ((precision == 0) || (precision > strw))
195 precision = strw;
196
197 /* Left padding */
198 size_t counter = 0;
199 width -= precision;
200 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
201 while (width-- > 0) {
202 if (printf_putchar(' ', ps) == 1)
203 counter++;
204 }
205 }
206
207 /* Part of @a str fitting into the alloted space. */
208 int retval;
209 size_t size = str_lsize(str, precision);
210 if ((retval = printf_putnchars(str, size, ps)) < 0)
211 return -counter;
212
213 counter += retval;
214
215 /* Right padding */
216 while (width-- > 0) {
217 if (printf_putchar(' ', ps) == 1)
218 counter++;
219 }
220
221 return ((int) counter);
222}
223
224/** Print a number in a given base.
225 *
226 * Print significant digits of a number in given base.
227 *
228 * @param num Number to print.
229 * @param width Width modifier.
230 * @param precision Precision modifier.
231 * @param base Base to print the number in (must be between 2 and 16).
232 * @param flags Flags that modify the way the number is printed.
233 *
234 * @return Number of characters printed.
235 *
236 */
237static int print_number(uint64_t num, int width, int precision, int base,
238 uint32_t flags, printf_spec_t *ps)
239{
240 const char *digits;
241 if (flags & __PRINTF_FLAG_BIGCHARS)
242 digits = digits_big;
243 else
244 digits = digits_small;
245
246 char data[PRINT_NUMBER_BUFFER_SIZE];
247 char *ptr = &data[PRINT_NUMBER_BUFFER_SIZE - 1];
248
249 /* Size of number with all prefixes and signs */
250 int size = 0;
251
252 /* Put zero at end of string */
253 *ptr-- = 0;
254
255 if (num == 0) {
256 *ptr-- = '0';
257 size++;
258 } else {
259 do {
260 *ptr-- = digits[num % base];
261 size++;
262 } while (num /= base);
263 }
264
265 /* Size of plain number */
266 int number_size = size;
267
268 /*
269 * Collect the sum of all prefixes/signs/etc. to calculate padding and
270 * leading zeroes.
271 */
272 if (flags & __PRINTF_FLAG_PREFIX) {
273 switch (base) {
274 case 2:
275 /* Binary formating is not standard, but usefull */
276 size += 2;
277 break;
278 case 8:
279 size++;
280 break;
281 case 16:
282 size += 2;
283 break;
284 }
285 }
286
287 char sgn = 0;
288 if (flags & __PRINTF_FLAG_SIGNED) {
289 if (flags & __PRINTF_FLAG_NEGATIVE) {
290 sgn = '-';
291 size++;
292 } else if (flags & __PRINTF_FLAG_SHOWPLUS) {
293 sgn = '+';
294 size++;
295 } else if (flags & __PRINTF_FLAG_SPACESIGN) {
296 sgn = ' ';
297 size++;
298 }
299 }
300
301 if (flags & __PRINTF_FLAG_LEFTALIGNED)
302 flags &= ~__PRINTF_FLAG_ZEROPADDED;
303
304 /*
305 * If the number is left-aligned or precision is specified then
306 * padding with zeros is ignored.
307 */
308 if (flags & __PRINTF_FLAG_ZEROPADDED) {
309 if ((precision == 0) && (width > size))
310 precision = width - size + number_size;
311 }
312
313 /* Print leading spaces */
314 if (number_size > precision) {
315 /* Print the whole number, not only a part */
316 precision = number_size;
317 }
318
319 width -= precision + size - number_size;
320 size_t counter = 0;
321
322 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
323 while (width-- > 0) {
324 if (printf_putchar(' ', ps) == 1)
325 counter++;
326 }
327 }
328
329 /* Print sign */
330 if (sgn) {
331 if (printf_putchar(sgn, ps) == 1)
332 counter++;
333 }
334
335 /* Print prefix */
336 if (flags & __PRINTF_FLAG_PREFIX) {
337 switch (base) {
338 case 2:
339 /* Binary formating is not standard, but usefull */
340 if (printf_putchar('0', ps) == 1)
341 counter++;
342 if (flags & __PRINTF_FLAG_BIGCHARS) {
343 if (printf_putchar('B', ps) == 1)
344 counter++;
345 } else {
346 if (printf_putchar('b', ps) == 1)
347 counter++;
348 }
349 break;
350 case 8:
351 if (printf_putchar('o', ps) == 1)
352 counter++;
353 break;
354 case 16:
355 if (printf_putchar('0', ps) == 1)
356 counter++;
357 if (flags & __PRINTF_FLAG_BIGCHARS) {
358 if (printf_putchar('X', ps) == 1)
359 counter++;
360 } else {
361 if (printf_putchar('x', ps) == 1)
362 counter++;
363 }
364 break;
365 }
366 }
367
368 /* Print leading zeroes */
369 precision -= number_size;
370 while (precision-- > 0) {
371 if (printf_putchar('0', ps) == 1)
372 counter++;
373 }
374
375 /* Print the number itself */
376 int retval;
377 if ((retval = printf_putstr(++ptr, ps)) > 0)
378 counter += retval;
379
380 /* Print trailing spaces */
381
382 while (width-- > 0) {
383 if (printf_putchar(' ', ps) == 1)
384 counter++;
385 }
386
387 return ((int) counter);
388}
389
390/** Print formatted string.
391 *
392 * Print string formatted according to the fmt parameter and variadic arguments.
393 * Each formatting directive must have the following form:
394 *
395 * \% [ FLAGS ] [ WIDTH ] [ .PRECISION ] [ TYPE ] CONVERSION
396 *
397 * FLAGS:@n
398 * - "#" Force to print prefix. For \%o conversion, the prefix is 0, for
399 * \%x and \%X prefixes are 0x and 0X and for conversion \%b the
400 * prefix is 0b.
401 *
402 * - "-" Align to left.
403 *
404 * - "+" Print positive sign just as negative.
405 *
406 * - " " If the printed number is positive and "+" flag is not set,
407 * print space in place of sign.
408 *
409 * - "0" Print 0 as padding instead of spaces. Zeroes are placed between
410 * sign and the rest of the number. This flag is ignored if "-"
411 * flag is specified.
412 *
413 * WIDTH:@n
414 * - Specify the minimal width of a printed argument. If it is bigger,
415 * width is ignored. If width is specified with a "*" character instead of
416 * number, width is taken from parameter list. And integer parameter is
417 * expected before parameter for processed conversion specification. If
418 * this value is negative its absolute value is taken and the "-" flag is
419 * set.
420 *
421 * PRECISION:@n
422 * - Value precision. For numbers it specifies minimum valid numbers.
423 * Smaller numbers are printed with leading zeroes. Bigger numbers are not
424 * affected. Strings with more than precision characters are cut off. Just
425 * as with width, an "*" can be used used instead of a number. An integer
426 * value is then expected in parameters. When both width and precision are
427 * specified using "*", the first parameter is used for width and the
428 * second one for precision.
429 *
430 * TYPE:@n
431 * - "hh" Signed or unsigned char.@n
432 * - "h" Signed or unsigned short.@n
433 * - "" Signed or unsigned int (default value).@n
434 * - "l" Signed or unsigned long int.@n
435 * - "ll" Signed or unsigned long long int.@n
436 *
437 * CONVERSION:@n
438 * - % Print percentile character itself.
439 *
440 * - c Print single character. The character is expected to be plain
441 * ASCII (e.g. only values 0 .. 127 are valid).@n
442 *
443 * - s Print zero terminated string. If a NULL value is passed as
444 * value, "(NULL)" is printed instead.@n
445 *
446 * - P, p Print value of a pointer. Void * value is expected and it is
447 * printed in hexadecimal notation with prefix (as with
448 * \%#0.8X / \%#0.8x for 32-bit or \%#0.16lX / \%#0.16lx for 64-bit
449 * long pointers).
450 *
451 * - b Print value as unsigned binary number. Prefix is not printed by
452 * default. (Nonstandard extension.)
453 *
454 * - o Print value as unsigned octal number. Prefix is not printed by
455 * default.
456 *
457 * - d, i Print signed decimal number. There is no difference between d
458 * and i conversion.
459 *
460 * - u Print unsigned decimal number.
461 *
462 * - X, x Print hexadecimal number with upper- or lower-case. Prefix is
463 * not printed by default.
464 *
465 * All other characters from fmt except the formatting directives are printed
466 * verbatim.
467 *
468 * @param fmt Format NULL-terminated string.
469 *
470 * @return Number of characters printed, negative value on failure.
471 *
472 */
473int printf_core(const char *fmt, printf_spec_t *ps, va_list ap)
474{
475 size_t i; /* Index of the currently processed character from fmt */
476 size_t nxt = 0; /* Index of the next character from fmt */
477 size_t j = 0; /* Index to the first not printed nonformating character */
478
479 size_t counter = 0; /* Number of characters printed */
480 int retval; /* Return values from nested functions */
481
482 while (true) {
483 i = nxt;
484 char32_t uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
485
486 if (uc == 0)
487 break;
488
489 /* Control character */
490 if (uc == '%') {
491 /* Print common characters if any processed */
492 if (i > j) {
493 if ((retval = printf_putnchars(&fmt[j], i - j, ps)) < 0) {
494 /* Error */
495 counter = -counter;
496 goto out;
497 }
498 counter += retval;
499 }
500
501 j = i;
502
503 /* Parse modifiers */
504 uint32_t flags = 0;
505 bool end = false;
506
507 do {
508 i = nxt;
509 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
510 switch (uc) {
511 case '#':
512 flags |= __PRINTF_FLAG_PREFIX;
513 break;
514 case '-':
515 flags |= __PRINTF_FLAG_LEFTALIGNED;
516 break;
517 case '+':
518 flags |= __PRINTF_FLAG_SHOWPLUS;
519 break;
520 case ' ':
521 flags |= __PRINTF_FLAG_SPACESIGN;
522 break;
523 case '0':
524 flags |= __PRINTF_FLAG_ZEROPADDED;
525 break;
526 default:
527 end = true;
528 }
529 } while (!end);
530
531 /* Width & '*' operator */
532 int width = 0;
533 if (isdigit(uc)) {
534 while (true) {
535 width *= 10;
536 width += uc - '0';
537
538 i = nxt;
539 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
540 if (uc == 0)
541 break;
542 if (!isdigit(uc))
543 break;
544 }
545 } else if (uc == '*') {
546 /* Get width value from argument list */
547 i = nxt;
548 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
549 width = (int) va_arg(ap, int);
550 if (width < 0) {
551 /* Negative width sets '-' flag */
552 width *= -1;
553 flags |= __PRINTF_FLAG_LEFTALIGNED;
554 }
555 }
556
557 /* Precision and '*' operator */
558 int precision = 0;
559 if (uc == '.') {
560 i = nxt;
561 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
562 if (isdigit(uc)) {
563 while (true) {
564 precision *= 10;
565 precision += uc - '0';
566
567 i = nxt;
568 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
569 if (uc == 0)
570 break;
571 if (!isdigit(uc))
572 break;
573 }
574 } else if (uc == '*') {
575 /* Get precision value from the argument list */
576 i = nxt;
577 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
578 precision = (int) va_arg(ap, int);
579 if (precision < 0) {
580 /* Ignore negative precision */
581 precision = 0;
582 }
583 }
584 }
585
586 qualifier_t qualifier;
587
588 switch (uc) {
589 case 't':
590 /* ptrdiff_t */
591 if (sizeof(ptrdiff_t) == sizeof(int32_t))
592 qualifier = PrintfQualifierInt;
593 else
594 qualifier = PrintfQualifierLongLong;
595 i = nxt;
596 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
597 break;
598 case 'h':
599 /* Char or short */
600 qualifier = PrintfQualifierShort;
601 i = nxt;
602 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
603 if (uc == 'h') {
604 i = nxt;
605 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
606 qualifier = PrintfQualifierByte;
607 }
608 break;
609 case 'l':
610 /* Long or long long */
611 qualifier = PrintfQualifierLong;
612 i = nxt;
613 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
614 if (uc == 'l') {
615 i = nxt;
616 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
617 qualifier = PrintfQualifierLongLong;
618 }
619 break;
620 case 'z':
621 qualifier = PrintfQualifierSize;
622 i = nxt;
623 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
624 break;
625 case 'j':
626 qualifier = PrintfQualifierMax;
627 i = nxt;
628 uc = str_decode(fmt, &nxt, STR_NO_LIMIT);
629 break;
630 default:
631 /* Default type */
632 qualifier = PrintfQualifierInt;
633 }
634
635 unsigned int base = 10;
636
637 switch (uc) {
638 /*
639 * String and character conversions.
640 */
641 case 's':
642 retval = print_str(va_arg(ap, char *), width, precision, flags, ps);
643
644 if (retval < 0) {
645 counter = -counter;
646 goto out;
647 }
648
649 counter += retval;
650 j = nxt;
651 continue;
652 case 'c':
653 retval = print_char(va_arg(ap, unsigned int), width, flags, ps);
654
655 if (retval < 0) {
656 counter = -counter;
657 goto out;
658 }
659
660 counter += retval;
661 j = nxt;
662 continue;
663
664 /*
665 * Integer values
666 */
667 case 'P':
668 /* Pointer */
669 flags |= __PRINTF_FLAG_BIGCHARS;
670 /* Fallthrough */
671 case 'p':
672 flags |= __PRINTF_FLAG_PREFIX;
673 flags |= __PRINTF_FLAG_ZEROPADDED;
674 base = 16;
675 qualifier = PrintfQualifierPointer;
676 break;
677 case 'b':
678 base = 2;
679 break;
680 case 'o':
681 base = 8;
682 break;
683 case 'd':
684 case 'i':
685 flags |= __PRINTF_FLAG_SIGNED;
686 /* Fallthrough */
687 case 'u':
688 break;
689 case 'X':
690 flags |= __PRINTF_FLAG_BIGCHARS;
691 /* Fallthrough */
692 case 'x':
693 base = 16;
694 break;
695
696 /* Percentile itself */
697 case '%':
698 j = i;
699 continue;
700
701 /*
702 * Bad formatting.
703 */
704 default:
705 /*
706 * Unknown format. Now, j is the index of '%'
707 * so we will print whole bad format sequence.
708 */
709 continue;
710 }
711
712 /* Print integers */
713 size_t size;
714 uint64_t number;
715
716 switch (qualifier) {
717 case PrintfQualifierByte:
718 size = sizeof(unsigned char);
719 number = PRINTF_GET_INT_ARGUMENT(int, ap, flags);
720 break;
721 case PrintfQualifierShort:
722 size = sizeof(unsigned short);
723 number = PRINTF_GET_INT_ARGUMENT(int, ap, flags);
724 break;
725 case PrintfQualifierInt:
726 size = sizeof(unsigned int);
727 number = PRINTF_GET_INT_ARGUMENT(int, ap, flags);
728 break;
729 case PrintfQualifierLong:
730 size = sizeof(unsigned long);
731 number = PRINTF_GET_INT_ARGUMENT(long, ap, flags);
732 break;
733 case PrintfQualifierLongLong:
734 size = sizeof(unsigned long long);
735 number = PRINTF_GET_INT_ARGUMENT(long long, ap, flags);
736 break;
737 case PrintfQualifierPointer:
738 size = sizeof(void *);
739 precision = size << 1;
740 number = (uint64_t) (uintptr_t) va_arg(ap, void *);
741 break;
742 case PrintfQualifierSize:
743 size = sizeof(size_t);
744 number = (uint64_t) va_arg(ap, size_t);
745 break;
746 case PrintfQualifierMax:
747 size = sizeof(uintmax_t);
748 number = (uint64_t) va_arg(ap, uintmax_t);
749 break;
750 default:
751 /* Unknown qualifier */
752 counter = -counter;
753 goto out;
754 }
755
756 if ((retval = print_number(number, width, precision,
757 base, flags, ps)) < 0) {
758 counter = -counter;
759 goto out;
760 }
761
762 counter += retval;
763 j = nxt;
764 }
765 }
766
767 if (i > j) {
768 if ((retval = printf_putnchars(&fmt[j], i - j, ps)) < 0) {
769 /* Error */
770 counter = -counter;
771 goto out;
772 }
773 counter += retval;
774 }
775
776out:
777 return ((int) counter);
778}
779
780/** @}
781 */
Note: See TracBrowser for help on using the repository browser.