2 * This file is part of the libpayload project.
4 * It has originally been taken from the HelenOS project
5 * (http://www.helenos.eu), and slightly modified for our purposes.
7 * Copyright (C) 2001-2004 Jakub Jermar
8 * Copyright (C) 2006 Josef Cejka
9 * Copyright (C) 2008 Uwe Hermann <uwe@hermann-uwe.de>
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
16 * - Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * - Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * - The name of the author may not be used to endorse or promote products
22 * derived from this software without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include <libpayload.h>
39 /** Structure for specifying output methods for different printf clones. */
41 /* Output function, returns count of printed characters or EOF. */
42 int (*write) (void *, size_t, void *);
43 /* Support data - output stream specification, its state, locks, ... */
47 /** Show prefixes 0x or 0. */
48 #define __PRINTF_FLAG_PREFIX 0x00000001
49 /** Signed / unsigned number. */
50 #define __PRINTF_FLAG_SIGNED 0x00000002
51 /** Print leading zeroes. */
52 #define __PRINTF_FLAG_ZEROPADDED 0x00000004
54 #define __PRINTF_FLAG_LEFTALIGNED 0x00000010
55 /** Always show + sign. */
56 #define __PRINTF_FLAG_SHOWPLUS 0x00000020
57 /** Print space instead of plus. */
58 #define __PRINTF_FLAG_SPACESIGN 0x00000040
59 /** Show big characters. */
60 #define __PRINTF_FLAG_BIGCHARS 0x00000080
61 /** Number has - sign. */
62 #define __PRINTF_FLAG_NEGATIVE 0x00000100
65 * Buffer big enough for 64-bit number printed in base 2, sign, prefix and 0
66 * to terminate string (last one is only for better testing end of buffer by
67 * zero-filling subroutine).
69 #define PRINT_NUMBER_BUFFER_SIZE (64 + 5)
71 /** Enumeration of possible arguments types. */
73 PrintfQualifierByte = 0,
77 PrintfQualifierLongLong,
78 PrintfQualifierPointer,
81 static char digits_small[] = "0123456789abcdef";
82 static char digits_big[] = "0123456789ABCDEF";
85 * Print one or more characters without adding newline.
87 * @param buf Buffer of >= count bytesi size. NULL pointer is not allowed!
88 * @param count Number of characters to print.
89 * @param ps Output method and its data.
90 * @return Number of characters printed.
92 static int printf_putnchars(const char *buf, size_t count,
93 struct printf_spec *ps)
95 return ps->write((void *)buf, count, ps->data);
99 * Print a string without adding a newline.
101 * @param str String to print.
102 * @param ps Write function specification and support data.
103 * @return Number of characters printed.
105 static int printf_putstr(const char *str, struct printf_spec *ps)
110 char *nullstr = "(NULL)";
111 return printf_putnchars(nullstr, strlen(nullstr), ps);
116 return ps->write((void *)str, count, ps->data);
120 * Print one character.
122 * @param c Character to be printed.
123 * @param ps Output method.
124 * @return Number of characters printed.
126 static int printf_putchar(int c, struct printf_spec *ps)
128 unsigned char ch = c;
130 return ps->write((void *)&ch, 1, ps->data);
134 * Print one formatted character.
136 * @param c Character to print.
137 * @param width Width modifier.
138 * @param flags Flags that change the way the character is printed.
139 * @return Number of characters printed, negative value on failure.
141 static int print_char(char c, int width, uint64_t flags, struct printf_spec *ps)
145 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
146 while (--width > 0) {
147 if (printf_putchar(' ', ps) > 0)
152 if (printf_putchar(c, ps) > 0)
155 while (--width > 0) {
156 if (printf_putchar(' ', ps) > 0)
166 * @param s String to be printed.
167 * @param width Width modifier.
168 * @param precision Precision modifier.
169 * @param flags Flags that modify the way the string is printed.
170 * @return Number of characters printed, negative value on failure.
172 static int print_string(char *s, int width, unsigned int precision,
173 uint64_t flags, struct printf_spec *ps)
175 int counter = 0, retval;
179 return printf_putstr("(NULL)", ps);
181 /* Print leading spaces. */
186 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
187 while (width-- > 0) {
188 if (printf_putchar(' ', ps) == 1)
193 if ((retval = printf_putnchars(s, MIN(size, precision), ps)) < 0)
197 while (width-- > 0) {
198 if (printf_putchar(' ', ps) == 1)
206 * Print a number in a given base.
208 * Print significant digits of a number in given base.
210 * @param num Number to print.
211 * @param widt Width modifier.h
212 * @param precision Precision modifier.
213 * @param base Base to print the number in (must be between 2 and 16).
214 * @param flags Flags that modify the way the number is printed.
215 * @return Number of characters printed.
217 static int print_number(uint64_t num, int width, int precision, int base,
218 uint64_t flags, struct printf_spec *ps)
220 char *digits = digits_small;
221 char d[PRINT_NUMBER_BUFFER_SIZE];
222 char *ptr = &d[PRINT_NUMBER_BUFFER_SIZE - 1];
223 int size = 0; /* Size of number with all prefixes and signs. */
224 int number_size; /* Size of plain number. */
229 if (flags & __PRINTF_FLAG_BIGCHARS)
232 *ptr-- = 0; /* Put zero at end of string. */
239 *ptr-- = digits[num % base];
241 } while (num /= base);
247 * Collect the sum of all prefixes/signs/... to calculate padding and
250 if (flags & __PRINTF_FLAG_PREFIX) {
252 case 2: /* Binary formating is not standard, but useful. */
265 if (flags & __PRINTF_FLAG_SIGNED) {
266 if (flags & __PRINTF_FLAG_NEGATIVE) {
269 } else if (flags & __PRINTF_FLAG_SHOWPLUS) {
272 } else if (flags & __PRINTF_FLAG_SPACESIGN) {
278 if (flags & __PRINTF_FLAG_LEFTALIGNED)
279 flags &= ~__PRINTF_FLAG_ZEROPADDED;
282 * If the number is left-aligned or precision is specified then
283 * zero-padding is ignored.
285 if (flags & __PRINTF_FLAG_ZEROPADDED) {
286 if ((precision == 0) && (width > size))
287 precision = width - size + number_size;
290 /* Print leading spaces. */
291 if (number_size > precision) {
292 /* Print the whole number not only a part. */
293 precision = number_size;
296 width -= precision + size - number_size;
298 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
299 while (width-- > 0) {
300 if (printf_putchar(' ', ps) == 1)
307 if (printf_putchar(sgn, ps) == 1)
312 if (flags & __PRINTF_FLAG_PREFIX) {
314 case 2: /* Binary formating is not standard, but useful. */
315 if (printf_putchar('0', ps) == 1)
317 if (flags & __PRINTF_FLAG_BIGCHARS) {
318 if (printf_putchar('B', ps) == 1)
321 if (printf_putchar('b', ps) == 1)
326 if (printf_putchar('o', ps) == 1)
330 if (printf_putchar('0', ps) == 1)
332 if (flags & __PRINTF_FLAG_BIGCHARS) {
333 if (printf_putchar('X', ps) == 1)
336 if (printf_putchar('x', ps) == 1)
343 /* Print leading zeroes. */
344 precision -= number_size;
345 while (precision-- > 0) {
346 if (printf_putchar('0', ps) == 1)
350 /* Print number itself. */
351 if ((retval = printf_putstr(++ptr, ps)) > 0)
354 /* Print ending spaces. */
355 while (width-- > 0) {
356 if (printf_putchar(' ', ps) == 1)
363 /** Print formatted string.
365 * Print string formatted according to the fmt parameter and variadic arguments.
366 * Each formatting directive must have the following form:
368 * \% [ FLAGS ] [ WIDTH ] [ .PRECISION ] [ TYPE ] CONVERSION
371 * - "#" Force to print prefix.For \%o conversion, the prefix is 0, for
372 * \%x and \%X prefixes are 0x and 0X and for conversion \%b the
375 * - "-" Align to left.
377 * - "+" Print positive sign just as negative.
379 * - " " If the printed number is positive and "+" flag is not set,
380 * print space in place of sign.
382 * - "0" Print 0 as padding instead of spaces. Zeroes are placed between
383 * sign and the rest of the number. This flag is ignored if "-"
387 * - Specify the minimal width of a printed argument. If it is bigger,
388 * width is ignored. If width is specified with a "*" character instead of
389 * number, width is taken from parameter list. And integer parameter is
390 * expected before parameter for processed conversion specification. If
391 * this value is negative its absolute value is taken and the "-" flag is
395 * - Value precision. For numbers it specifies minimum valid numbers.
396 * Smaller numbers are printed with leading zeroes. Bigger numbers are not
397 * affected. Strings with more than precision characters are cut off. Just
398 * as with width, an "*" can be used used instead of a number. An integer
399 * value is then expected in parameters. When both width and precision are
400 * specified using "*", the first parameter is used for width and the
401 * second one for precision.
404 * - "hh" Signed or unsigned char.@n
405 * - "h" Signed or unsigned short.@n
406 * - "" Signed or unsigned int (default value).@n
407 * - "l" Signed or unsigned long int.@n
408 * - "ll" Signed or unsigned long long int.@n
412 * - % Print percentile character itself.
414 * - c Print single character.
416 * - s Print zero terminated string. If a NULL value is passed as
417 * value, "(NULL)" is printed instead.
419 * - P, p Print value of a pointer. Void * value is expected and it is
420 * printed in hexadecimal notation with prefix (as with \%#X / \%#x
421 * for 32-bit or \%#X / \%#x for 64-bit long pointers).
423 * - b Print value as unsigned binary number. Prefix is not printed by
424 * default. (Nonstandard extension.)
426 * - o Print value as unsigned octal number. Prefix is not printed by
429 * - d, i Print signed decimal number. There is no difference between d
432 * - u Print unsigned decimal number.
434 * - X, x Print hexadecimal number with upper- or lower-case. Prefix is
435 * not printed by default.
437 * All other characters from fmt except the formatting directives are printed in
440 * @param fmt Formatting NULL terminated string.
443 * @return Number of characters printed, negative value on failure.
445 static int printf_core(const char *fmt, struct printf_spec *ps, va_list ap)
447 int i = 0; /* Index of the currently processed char from fmt */
448 int j = 0; /* Index to the first not printed nonformating character */
450 int counter; /* Counter of printed characters */
451 int retval; /* Used to store return values from called functions */
453 qualifier_t qualifier; /* Type of argument */
454 int base; /* Base in which a numeric parameter will be printed */
455 uint64_t number; /* Argument value */
456 size_t size; /* Byte size of integer parameter */
457 int width, precision;
462 while ((c = fmt[i])) {
463 /* Control character. */
465 /* Print common characters if any processed. */
467 if ((retval = printf_putnchars(&fmt[j],
468 (size_t) (i - j), ps)) < 0) {
470 goto out; /* Error */
476 /* Parse modifiers. */
482 switch (c = fmt[i]) {
484 flags |= __PRINTF_FLAG_PREFIX;
487 flags |= __PRINTF_FLAG_LEFTALIGNED;
490 flags |= __PRINTF_FLAG_SHOWPLUS;
493 flags |= __PRINTF_FLAG_SPACESIGN;
496 flags |= __PRINTF_FLAG_ZEROPADDED;
504 /* Width & '*' operator. */
506 if (isdigit(fmt[i])) {
507 while (isdigit(fmt[i])) {
509 width += fmt[i++] - '0';
511 } else if (fmt[i] == '*') {
512 /* Get width value from argument list. */
514 width = (int)va_arg(ap, int);
516 /* Negative width sets '-' flag. */
518 flags |= __PRINTF_FLAG_LEFTALIGNED;
522 /* Precision and '*' operator. */
526 if (isdigit(fmt[i])) {
527 while (isdigit(fmt[i])) {
529 precision += fmt[i++] - '0';
531 } else if (fmt[i] == '*') {
532 /* Get precision from argument list. */
534 precision = (int)va_arg(ap, int);
535 /* Ignore negative precision. */
542 /** @todo unimplemented qualifiers:
543 * t ptrdiff_t - ISO C 99
545 case 'h': /* char or short */
546 qualifier = PrintfQualifierShort;
549 qualifier = PrintfQualifierByte;
552 case 'l': /* long or long long */
553 qualifier = PrintfQualifierLong;
556 qualifier = PrintfQualifierLongLong;
561 qualifier = PrintfQualifierInt;
567 switch (c = fmt[i]) {
568 /* String and character conversions */
570 if ((retval = print_string(va_arg(ap, char *),
571 width, precision, flags, ps)) < 0) {
579 c = va_arg(ap, unsigned int);
580 retval = print_char(c, width, flags, ps);
590 case 'P': /* pointer */
591 flags |= __PRINTF_FLAG_BIGCHARS;
593 flags |= __PRINTF_FLAG_PREFIX;
595 qualifier = PrintfQualifierPointer;
605 flags |= __PRINTF_FLAG_SIGNED;
609 flags |= __PRINTF_FLAG_BIGCHARS;
613 case '%': /* percentile itself */
616 default: /* Bad formatting */
618 * Unknown format. Now, j is the index of '%'
619 * so we will print whole bad format sequence.
624 /* Print integers. */
627 case PrintfQualifierByte:
628 size = sizeof(unsigned char);
629 number = (uint64_t) va_arg(ap, unsigned int);
631 case PrintfQualifierShort:
632 size = sizeof(unsigned short);
633 number = (uint64_t) va_arg(ap, unsigned int);
635 case PrintfQualifierInt:
636 size = sizeof(unsigned int);
637 number = (uint64_t) va_arg(ap, unsigned int);
639 case PrintfQualifierLong:
640 size = sizeof(unsigned long);
641 number = (uint64_t) va_arg(ap, unsigned long);
643 case PrintfQualifierLongLong:
644 size = sizeof(unsigned long long);
645 number = (uint64_t) va_arg(ap, unsigned long long);
647 case PrintfQualifierPointer:
648 size = sizeof(void *);
649 number = (uint64_t) (unsigned long)va_arg(ap, void *);
651 default: /* Unknown qualifier */
656 if (flags & __PRINTF_FLAG_SIGNED) {
657 if (number & (0x1 << (size * 8 - 1))) {
658 flags |= __PRINTF_FLAG_NEGATIVE;
660 if (size == sizeof(uint64_t)) {
661 number = -((int64_t) number);
664 number &= ~(0xFFFFFFFFFFFFFFFFll << (size * 8));
670 if ((retval = print_number(number, width, precision,
671 base, flags, ps)) < 0) {
684 if ((retval = printf_putnchars(&fmt[j],
685 (u64) (i - j), ps)) < 0) {
687 goto out; /* Error */
697 int sprintf(char *str, const char *fmt, ...)
703 ret = vsprintf(str, fmt, args);
709 struct vsnprintf_data {
710 size_t size; /* Total space for string */
711 size_t len; /* Count of currently used characters */
712 char *string; /* Destination string */
716 * Write string to given buffer.
718 * Write at most data->size characters including trailing zero. According to
719 * C99, snprintf() has to return number of characters that would have been
720 * written if enough space had been available. Hence the return value is not
721 * number of really printed characters but size of the input string.
722 * Number of really used characters is stored in data->len.
724 * @param str Source string to print.
725 * @param count Size of source string.
726 * @param data Structure with destination string, counter of used space
727 * and total string size.
728 * @return Number of characters to print (not characters really printed!).
730 static int vsnprintf_write(const char *str, size_t count,
731 struct vsnprintf_data *data)
735 i = data->size - data->len;
739 /* We have only one free byte left in buffer => write trailing zero. */
741 data->string[data->size - 1] = 0;
742 data->len = data->size;
747 * We have not enough space for whole string with the trailing
748 * zero => print only a part of string.
751 memcpy((void *)(data->string + data->len), (void *)str, i - 1);
752 data->string[data->size - 1] = 0;
753 data->len = data->size;
757 /* Buffer is big enough to print whole string. */
758 memcpy((void *)(data->string + data->len), (void *)str, count);
761 * Put trailing zero at end, but not count it into data->len so
762 * it could be rewritten next time.
764 data->string[data->len] = 0;
769 int vsnprintf(char *str, size_t size, const char *fmt, va_list ap)
771 struct vsnprintf_data data = { size, 0, str };
772 struct printf_spec ps =
773 { (int (*)(void *, size_t, void *))vsnprintf_write, &data };
775 /* Print 0 at end of string - fix case that nothing will be printed. */
779 /* vsnprintf_write() ensures that str will be terminated by zero. */
780 return printf_core(fmt, &ps, ap);
783 int vsprintf(char *str, const char *fmt, va_list ap)
785 return vsnprintf(str, (size_t) - 1, fmt, ap);
788 int printf(const char *fmt, ...)
794 ret = vprintf(fmt, args);
800 static int vprintf_write(const char *str, size_t count, void *unused)
804 for (i = 0; i < count; i++)
810 int vprintf(const char *fmt, va_list ap)
812 struct printf_spec ps =
813 { (int (*)(void *, size_t, void *))vprintf_write, NULL };
815 return printf_core(fmt, &ps, ap);