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>
38 /** Structure for specifying output methods for different printf clones. */
40 /* Output function, returns count of printed characters or EOF. */
41 int (*write) (void *, size_t, void *);
42 /* Support data - output stream specification, its state, locks, ... */
46 /** Show prefixes 0x or 0. */
47 #define __PRINTF_FLAG_PREFIX 0x00000001
48 /** Signed / unsigned number. */
49 #define __PRINTF_FLAG_SIGNED 0x00000002
50 /** Print leading zeroes. */
51 #define __PRINTF_FLAG_ZEROPADDED 0x00000004
53 #define __PRINTF_FLAG_LEFTALIGNED 0x00000010
54 /** Always show + sign. */
55 #define __PRINTF_FLAG_SHOWPLUS 0x00000020
56 /** Print space instead of plus. */
57 #define __PRINTF_FLAG_SPACESIGN 0x00000040
58 /** Show big characters. */
59 #define __PRINTF_FLAG_BIGCHARS 0x00000080
60 /** Number has - sign. */
61 #define __PRINTF_FLAG_NEGATIVE 0x00000100
64 * Buffer big enough for 64-bit number printed in base 2, sign, prefix and 0
65 * to terminate string (last one is only for better testing end of buffer by
66 * zero-filling subroutine).
68 #define PRINT_NUMBER_BUFFER_SIZE (64 + 5)
70 /** Enumeration of possible arguments types. */
72 PrintfQualifierByte = 0,
76 PrintfQualifierLongLong,
77 PrintfQualifierPointer,
80 static char digits_small[] = "0123456789abcdef";
81 static char digits_big[] = "0123456789ABCDEF";
84 * Print one or more characters without adding newline.
86 * @param buf Buffer of >= count bytesi size. NULL pointer is not allowed!
87 * @param count Number of characters to print.
88 * @param ps Output method and its data.
89 * @return Number of characters printed.
91 static int printf_putnchars(const char *buf, size_t count,
92 struct printf_spec *ps)
94 return ps->write((void *)buf, count, ps->data);
98 * Print a string without adding a newline.
100 * @param str String to print.
101 * @param ps Write function specification and support data.
102 * @return Number of characters printed.
104 static int printf_putstr(const char *str, struct printf_spec *ps)
109 char *nullstr = "(NULL)";
110 return printf_putnchars(nullstr, strlen(nullstr), ps);
115 return ps->write((void *)str, count, ps->data);
119 * Print one character.
121 * @param c Character to be printed.
122 * @param ps Output method.
123 * @return Number of characters printed.
125 static int printf_putchar(int c, struct printf_spec *ps)
127 unsigned char ch = c;
129 return ps->write((void *)&ch, 1, ps->data);
133 * Print one formatted character.
135 * @param c Character to print.
136 * @param width Width modifier.
137 * @param flags Flags that change the way the character is printed.
138 * @param ps Output methods spec for different printf clones.
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 * @param ps Output methods spec for different printf clones.
171 * @return Number of characters printed, negative value on failure.
173 /** Structure for specifying output methods for different printf clones. */
174 static int print_string(char *s, int width, unsigned int precision,
175 uint64_t flags, struct printf_spec *ps)
177 int counter = 0, retval;
181 return printf_putstr("(NULL)", ps);
183 /* Print leading spaces. */
188 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
189 while (width-- > 0) {
190 if (printf_putchar(' ', ps) == 1)
195 if ((retval = printf_putnchars(s, MIN(size, precision), ps)) < 0)
199 while (width-- > 0) {
200 if (printf_putchar(' ', ps) == 1)
208 * Print a number in a given base.
210 * Print significant digits of a number in given base.
212 * @param num Number to print.
213 * @param width Width modifier.h
214 * @param precision Precision modifier.
215 * @param base Base to print the number in (must be between 2 and 16).
216 * @param flags Flags that modify the way the number is printed.
217 * @param ps Output methods spec for different printf clones.
218 * @return Number of characters printed.
220 static int print_number(uint64_t num, int width, int precision, int base,
221 uint64_t flags, struct printf_spec *ps)
223 char *digits = digits_small;
224 char d[PRINT_NUMBER_BUFFER_SIZE];
225 char *ptr = &d[PRINT_NUMBER_BUFFER_SIZE - 1];
226 int size = 0; /* Size of number with all prefixes and signs. */
227 int number_size; /* Size of plain number. */
232 if (flags & __PRINTF_FLAG_BIGCHARS)
235 *ptr-- = 0; /* Put zero at end of string. */
242 *ptr-- = digits[num % base];
244 } while (num /= base);
250 * Collect the sum of all prefixes/signs/... to calculate padding and
253 if (flags & __PRINTF_FLAG_PREFIX) {
255 case 2: /* Binary formating is not standard, but useful. */
268 if (flags & __PRINTF_FLAG_SIGNED) {
269 if (flags & __PRINTF_FLAG_NEGATIVE) {
272 } else if (flags & __PRINTF_FLAG_SHOWPLUS) {
275 } else if (flags & __PRINTF_FLAG_SPACESIGN) {
281 if (flags & __PRINTF_FLAG_LEFTALIGNED)
282 flags &= ~__PRINTF_FLAG_ZEROPADDED;
285 * If the number is left-aligned or precision is specified then
286 * zero-padding is ignored.
288 if (flags & __PRINTF_FLAG_ZEROPADDED) {
289 if ((precision == 0) && (width > size))
290 precision = width - size + number_size;
293 /* Print leading spaces. */
294 if (number_size > precision) {
295 /* Print the whole number not only a part. */
296 precision = number_size;
299 width -= precision + size - number_size;
301 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
302 while (width-- > 0) {
303 if (printf_putchar(' ', ps) == 1)
310 if (printf_putchar(sgn, ps) == 1)
315 if (flags & __PRINTF_FLAG_PREFIX) {
317 case 2: /* Binary formating is not standard, but useful. */
318 if (printf_putchar('0', ps) == 1)
320 if (flags & __PRINTF_FLAG_BIGCHARS) {
321 if (printf_putchar('B', ps) == 1)
324 if (printf_putchar('b', ps) == 1)
329 if (printf_putchar('o', ps) == 1)
333 if (printf_putchar('0', ps) == 1)
335 if (flags & __PRINTF_FLAG_BIGCHARS) {
336 if (printf_putchar('X', ps) == 1)
339 if (printf_putchar('x', ps) == 1)
346 /* Print leading zeroes. */
347 precision -= number_size;
348 while (precision-- > 0) {
349 if (printf_putchar('0', ps) == 1)
353 /* Print number itself. */
354 if ((retval = printf_putstr(++ptr, ps)) > 0)
357 /* Print ending spaces. */
358 while (width-- > 0) {
359 if (printf_putchar(' ', ps) == 1)
367 * Print formatted string.
369 * Print string formatted according to the fmt parameter and variadic arguments.
370 * Each formatting directive must have the following form:
372 * \% [ FLAGS ] [ WIDTH ] [ .PRECISION ] [ TYPE ] CONVERSION
375 * - "#" Force to print prefix.For \%o conversion, the prefix is 0, for
376 * \%x and \%X prefixes are 0x and 0X and for conversion \%b the
379 * - "-" Align to left.
381 * - "+" Print positive sign just as negative.
383 * - " " If the printed number is positive and "+" flag is not set,
384 * print space in place of sign.
386 * - "0" Print 0 as padding instead of spaces. Zeroes are placed between
387 * sign and the rest of the number. This flag is ignored if "-"
391 * - Specify the minimal width of a printed argument. If it is bigger,
392 * width is ignored. If width is specified with a "*" character instead of
393 * number, width is taken from parameter list. And integer parameter is
394 * expected before parameter for processed conversion specification. If
395 * this value is negative its absolute value is taken and the "-" flag is
399 * - Value precision. For numbers it specifies minimum valid numbers.
400 * Smaller numbers are printed with leading zeroes. Bigger numbers are not
401 * affected. Strings with more than precision characters are cut off. Just
402 * as with width, an "*" can be used used instead of a number. An integer
403 * value is then expected in parameters. When both width and precision are
404 * specified using "*", the first parameter is used for width and the
405 * second one for precision.
408 * - "hh" Signed or unsigned char.@n
409 * - "h" Signed or unsigned short.@n
410 * - "" Signed or unsigned int (default value).@n
411 * - "l" Signed or unsigned long int.@n
412 * - "ll" Signed or unsigned long long int.@n
416 * - % Print percentile character itself.
418 * - c Print single character.
420 * - s Print zero terminated string. If a NULL value is passed as
421 * value, "(NULL)" is printed instead.
423 * - P, p Print value of a pointer. Void * value is expected and it is
424 * printed in hexadecimal notation with prefix (as with \%#X / \%#x
425 * for 32-bit or \%#X / \%#x for 64-bit long pointers).
427 * - b Print value as unsigned binary number. Prefix is not printed by
428 * default. (Nonstandard extension.)
430 * - o Print value as unsigned octal number. Prefix is not printed by
433 * - d, i Print signed decimal number. There is no difference between d
436 * - u Print unsigned decimal number.
438 * - X, x Print hexadecimal number with upper- or lower-case. Prefix is
439 * not printed by default.
441 * All other characters from fmt except the formatting directives are printed in
444 * @param fmt Formatting NULL terminated string.
447 * @return Number of characters printed, negative value on failure.
449 static int printf_core(const char *fmt, struct printf_spec *ps, va_list ap)
451 int i = 0; /* Index of the currently processed char from fmt */
452 int j = 0; /* Index to the first not printed nonformating character */
454 int counter; /* Counter of printed characters */
455 int retval; /* Used to store return values from called functions */
457 qualifier_t qualifier; /* Type of argument */
458 int base; /* Base in which a numeric parameter will be printed */
459 uint64_t number; /* Argument value */
460 size_t size; /* Byte size of integer parameter */
461 int width, precision;
466 while ((c = fmt[i])) {
467 /* Control character. */
469 /* Print common characters if any processed. */
471 if ((retval = printf_putnchars(&fmt[j],
472 (size_t) (i - j), ps)) < 0) {
474 goto out; /* Error */
480 /* Parse modifiers. */
486 switch (c = fmt[i]) {
488 flags |= __PRINTF_FLAG_PREFIX;
491 flags |= __PRINTF_FLAG_LEFTALIGNED;
494 flags |= __PRINTF_FLAG_SHOWPLUS;
497 flags |= __PRINTF_FLAG_SPACESIGN;
500 flags |= __PRINTF_FLAG_ZEROPADDED;
508 /* Width & '*' operator. */
510 if (isdigit(fmt[i])) {
511 while (isdigit(fmt[i])) {
513 width += fmt[i++] - '0';
515 } else if (fmt[i] == '*') {
516 /* Get width value from argument list. */
518 width = (int)va_arg(ap, int);
520 /* Negative width sets '-' flag. */
522 flags |= __PRINTF_FLAG_LEFTALIGNED;
526 /* Precision and '*' operator. */
530 if (isdigit(fmt[i])) {
531 while (isdigit(fmt[i])) {
533 precision += fmt[i++] - '0';
535 } else if (fmt[i] == '*') {
536 /* Get precision from argument list. */
538 precision = (int)va_arg(ap, int);
539 /* Ignore negative precision. */
546 /** @todo unimplemented qualifiers:
547 * t ptrdiff_t - ISO C 99
549 case 'h': /* char or short */
550 qualifier = PrintfQualifierShort;
553 qualifier = PrintfQualifierByte;
556 case 'l': /* long or long long */
557 qualifier = PrintfQualifierLong;
560 qualifier = PrintfQualifierLongLong;
565 qualifier = PrintfQualifierInt;
571 switch (c = fmt[i]) {
572 /* String and character conversions */
574 if ((retval = print_string(va_arg(ap, char *),
575 width, precision, flags, ps)) < 0) {
583 c = va_arg(ap, unsigned int);
584 retval = print_char(c, width, flags, ps);
594 case 'P': /* pointer */
595 flags |= __PRINTF_FLAG_BIGCHARS;
597 flags |= __PRINTF_FLAG_PREFIX;
599 qualifier = PrintfQualifierPointer;
609 flags |= __PRINTF_FLAG_SIGNED;
613 flags |= __PRINTF_FLAG_BIGCHARS;
617 case '%': /* percentile itself */
620 default: /* Bad formatting */
622 * Unknown format. Now, j is the index of '%'
623 * so we will print whole bad format sequence.
628 /* Print integers. */
631 case PrintfQualifierByte:
632 size = sizeof(unsigned char);
633 number = (uint64_t) va_arg(ap, unsigned int);
635 case PrintfQualifierShort:
636 size = sizeof(unsigned short);
637 number = (uint64_t) va_arg(ap, unsigned int);
639 case PrintfQualifierInt:
640 size = sizeof(unsigned int);
641 number = (uint64_t) va_arg(ap, unsigned int);
643 case PrintfQualifierLong:
644 size = sizeof(unsigned long);
645 number = (uint64_t) va_arg(ap, unsigned long);
647 case PrintfQualifierLongLong:
648 size = sizeof(unsigned long long);
649 number = (uint64_t) va_arg(ap, unsigned long long);
651 case PrintfQualifierPointer:
652 size = sizeof(void *);
653 number = (uint64_t) (unsigned long)va_arg(ap, void *);
655 default: /* Unknown qualifier */
660 if (flags & __PRINTF_FLAG_SIGNED) {
661 if (number & (0x1 << (size * 8 - 1))) {
662 flags |= __PRINTF_FLAG_NEGATIVE;
664 if (size == sizeof(uint64_t)) {
665 number = -((int64_t) number);
668 number &= ~(0xFFFFFFFFFFFFFFFFll << (size * 8));
674 if ((retval = print_number(number, width, precision,
675 base, flags, ps)) < 0) {
688 if ((retval = printf_putnchars(&fmt[j],
689 (u64) (i - j), ps)) < 0) {
691 goto out; /* Error */
701 int snprintf(char *str, size_t size, const char *fmt, ...)
707 ret = vsnprintf(str, size, fmt, args);
713 int sprintf(char *str, const char *fmt, ...)
719 ret = vsprintf(str, fmt, args);
725 struct vsnprintf_data {
726 size_t size; /* Total space for string */
727 size_t len; /* Count of currently used characters */
728 char *string; /* Destination string */
732 * Write string to given buffer.
734 * Write at most data->size characters including trailing zero. According to
735 * C99, snprintf() has to return number of characters that would have been
736 * written if enough space had been available. Hence the return value is not
737 * number of really printed characters but size of the input string.
738 * Number of really used characters is stored in data->len.
740 * @param str Source string to print.
741 * @param count Size of source string.
742 * @param data Structure with destination string, counter of used space
743 * and total string size.
744 * @return Number of characters to print (not characters really printed!).
746 static int vsnprintf_write(const char *str, size_t count,
747 struct vsnprintf_data *data)
751 i = data->size - data->len;
755 /* We have only one free byte left in buffer => write trailing zero. */
757 data->string[data->size - 1] = 0;
758 data->len = data->size;
763 * We have not enough space for whole string with the trailing
764 * zero => print only a part of string.
767 memcpy((void *)(data->string + data->len), (void *)str, i - 1);
768 data->string[data->size - 1] = 0;
769 data->len = data->size;
773 /* Buffer is big enough to print whole string. */
774 memcpy((void *)(data->string + data->len), (void *)str, count);
777 * Put trailing zero at end, but not count it into data->len so
778 * it could be rewritten next time.
780 data->string[data->len] = 0;
785 int vsnprintf(char *str, size_t size, const char *fmt, va_list ap)
787 struct vsnprintf_data data = { size, 0, str };
788 struct printf_spec ps =
789 { (int (*)(void *, size_t, void *))vsnprintf_write, &data };
791 /* Print 0 at end of string - fix case that nothing will be printed. */
795 /* vsnprintf_write() ensures that str will be terminated by zero. */
796 return printf_core(fmt, &ps, ap);
799 int vsprintf(char *str, const char *fmt, va_list ap)
801 return vsnprintf(str, (size_t) - 1, fmt, ap);
804 int printf(const char *fmt, ...)
810 ret = vprintf(fmt, args);
816 static int vprintf_write(const char *str, size_t count, void *unused)
820 for (i = 0; i < count; i++)
826 int vprintf(const char *fmt, va_list ap)
828 struct printf_spec ps =
829 { (int (*)(void *, size_t, void *))vprintf_write, NULL };
831 return printf_core(fmt, &ps, ap);