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 * @param ps Output methods spec for different printf clones.
140 * @return Number of characters printed, negative value on failure.
142 static int print_char(char c, int width, uint64_t flags, struct printf_spec *ps)
146 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
147 while (--width > 0) {
148 if (printf_putchar(' ', ps) > 0)
153 if (printf_putchar(c, ps) > 0)
156 while (--width > 0) {
157 if (printf_putchar(' ', ps) > 0)
167 * @param s String to be printed.
168 * @param width Width modifier.
169 * @param precision Precision modifier.
170 * @param flags Flags that modify the way the string is printed.
171 * @param ps Output methods spec for different printf clones.
172 * @return Number of characters printed, negative value on failure.
174 /** Structure for specifying output methods for different printf clones. */
175 static int print_string(char *s, int width, unsigned int precision,
176 uint64_t flags, struct printf_spec *ps)
178 int counter = 0, retval;
182 return printf_putstr("(NULL)", ps);
184 /* Print leading spaces. */
189 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
190 while (width-- > 0) {
191 if (printf_putchar(' ', ps) == 1)
196 if ((retval = printf_putnchars(s, MIN(size, precision), ps)) < 0)
200 while (width-- > 0) {
201 if (printf_putchar(' ', ps) == 1)
209 * Print a number in a given base.
211 * Print significant digits of a number in given base.
213 * @param num Number to print.
214 * @param width Width modifier.h
215 * @param precision Precision modifier.
216 * @param base Base to print the number in (must be between 2 and 16).
217 * @param flags Flags that modify the way the number is printed.
218 * @param ps Output methods spec for different printf clones.
219 * @return Number of characters printed.
221 static int print_number(uint64_t num, int width, int precision, int base,
222 uint64_t flags, struct printf_spec *ps)
224 char *digits = digits_small;
225 char d[PRINT_NUMBER_BUFFER_SIZE];
226 char *ptr = &d[PRINT_NUMBER_BUFFER_SIZE - 1];
227 int size = 0; /* Size of number with all prefixes and signs. */
228 int number_size; /* Size of plain number. */
233 if (flags & __PRINTF_FLAG_BIGCHARS)
236 *ptr-- = 0; /* Put zero at end of string. */
243 *ptr-- = digits[num % base];
245 } while (num /= base);
251 * Collect the sum of all prefixes/signs/... to calculate padding and
254 if (flags & __PRINTF_FLAG_PREFIX) {
256 case 2: /* Binary formating is not standard, but useful. */
269 if (flags & __PRINTF_FLAG_SIGNED) {
270 if (flags & __PRINTF_FLAG_NEGATIVE) {
273 } else if (flags & __PRINTF_FLAG_SHOWPLUS) {
276 } else if (flags & __PRINTF_FLAG_SPACESIGN) {
282 if (flags & __PRINTF_FLAG_LEFTALIGNED)
283 flags &= ~__PRINTF_FLAG_ZEROPADDED;
286 * If the number is left-aligned or precision is specified then
287 * zero-padding is ignored.
289 if (flags & __PRINTF_FLAG_ZEROPADDED) {
290 if ((precision == 0) && (width > size))
291 precision = width - size + number_size;
294 /* Print leading spaces. */
295 if (number_size > precision) {
296 /* Print the whole number not only a part. */
297 precision = number_size;
300 width -= precision + size - number_size;
302 if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
303 while (width-- > 0) {
304 if (printf_putchar(' ', ps) == 1)
311 if (printf_putchar(sgn, ps) == 1)
316 if (flags & __PRINTF_FLAG_PREFIX) {
318 case 2: /* Binary formating is not standard, but useful. */
319 if (printf_putchar('0', ps) == 1)
321 if (flags & __PRINTF_FLAG_BIGCHARS) {
322 if (printf_putchar('B', ps) == 1)
325 if (printf_putchar('b', ps) == 1)
330 if (printf_putchar('o', ps) == 1)
334 if (printf_putchar('0', ps) == 1)
336 if (flags & __PRINTF_FLAG_BIGCHARS) {
337 if (printf_putchar('X', ps) == 1)
340 if (printf_putchar('x', ps) == 1)
347 /* Print leading zeroes. */
348 precision -= number_size;
349 while (precision-- > 0) {
350 if (printf_putchar('0', ps) == 1)
354 /* Print number itself. */
355 if ((retval = printf_putstr(++ptr, ps)) > 0)
358 /* Print ending spaces. */
359 while (width-- > 0) {
360 if (printf_putchar(' ', ps) == 1)
368 * Print formatted string.
370 * Print string formatted according to the fmt parameter and variadic arguments.
371 * Each formatting directive must have the following form:
373 * \% [ FLAGS ] [ WIDTH ] [ .PRECISION ] [ TYPE ] CONVERSION
376 * - "#" Force to print prefix.For \%o conversion, the prefix is 0, for
377 * \%x and \%X prefixes are 0x and 0X and for conversion \%b the
380 * - "-" Align to left.
382 * - "+" Print positive sign just as negative.
384 * - " " If the printed number is positive and "+" flag is not set,
385 * print space in place of sign.
387 * - "0" Print 0 as padding instead of spaces. Zeroes are placed between
388 * sign and the rest of the number. This flag is ignored if "-"
392 * - Specify the minimal width of a printed argument. If it is bigger,
393 * width is ignored. If width is specified with a "*" character instead of
394 * number, width is taken from parameter list. And integer parameter is
395 * expected before parameter for processed conversion specification. If
396 * this value is negative its absolute value is taken and the "-" flag is
400 * - Value precision. For numbers it specifies minimum valid numbers.
401 * Smaller numbers are printed with leading zeroes. Bigger numbers are not
402 * affected. Strings with more than precision characters are cut off. Just
403 * as with width, an "*" can be used used instead of a number. An integer
404 * value is then expected in parameters. When both width and precision are
405 * specified using "*", the first parameter is used for width and the
406 * second one for precision.
409 * - "hh" Signed or unsigned char.@n
410 * - "h" Signed or unsigned short.@n
411 * - "" Signed or unsigned int (default value).@n
412 * - "l" Signed or unsigned long int.@n
413 * - "ll" Signed or unsigned long long int.@n
417 * - % Print percentile character itself.
419 * - c Print single character.
421 * - s Print zero terminated string. If a NULL value is passed as
422 * value, "(NULL)" is printed instead.
424 * - P, p Print value of a pointer. Void * value is expected and it is
425 * printed in hexadecimal notation with prefix (as with \%#X / \%#x
426 * for 32-bit or \%#X / \%#x for 64-bit long pointers).
428 * - b Print value as unsigned binary number. Prefix is not printed by
429 * default. (Nonstandard extension.)
431 * - o Print value as unsigned octal number. Prefix is not printed by
434 * - d, i Print signed decimal number. There is no difference between d
437 * - u Print unsigned decimal number.
439 * - X, x Print hexadecimal number with upper- or lower-case. Prefix is
440 * not printed by default.
442 * All other characters from fmt except the formatting directives are printed in
445 * @param fmt Formatting NULL terminated string.
448 * @return Number of characters printed, negative value on failure.
450 static int printf_core(const char *fmt, struct printf_spec *ps, va_list ap)
452 int i = 0; /* Index of the currently processed char from fmt */
453 int j = 0; /* Index to the first not printed nonformating character */
455 int counter; /* Counter of printed characters */
456 int retval; /* Used to store return values from called functions */
458 qualifier_t qualifier; /* Type of argument */
459 int base; /* Base in which a numeric parameter will be printed */
460 uint64_t number; /* Argument value */
461 size_t size; /* Byte size of integer parameter */
462 int width, precision;
467 while ((c = fmt[i])) {
468 /* Control character. */
470 /* Print common characters if any processed. */
472 if ((retval = printf_putnchars(&fmt[j],
473 (size_t) (i - j), ps)) < 0) {
475 goto out; /* Error */
481 /* Parse modifiers. */
487 switch (c = fmt[i]) {
489 flags |= __PRINTF_FLAG_PREFIX;
492 flags |= __PRINTF_FLAG_LEFTALIGNED;
495 flags |= __PRINTF_FLAG_SHOWPLUS;
498 flags |= __PRINTF_FLAG_SPACESIGN;
501 flags |= __PRINTF_FLAG_ZEROPADDED;
509 /* Width & '*' operator. */
511 if (isdigit(fmt[i])) {
512 while (isdigit(fmt[i])) {
514 width += fmt[i++] - '0';
516 } else if (fmt[i] == '*') {
517 /* Get width value from argument list. */
519 width = (int)va_arg(ap, int);
521 /* Negative width sets '-' flag. */
523 flags |= __PRINTF_FLAG_LEFTALIGNED;
527 /* Precision and '*' operator. */
531 if (isdigit(fmt[i])) {
532 while (isdigit(fmt[i])) {
534 precision += fmt[i++] - '0';
536 } else if (fmt[i] == '*') {
537 /* Get precision from argument list. */
539 precision = (int)va_arg(ap, int);
540 /* Ignore negative precision. */
547 /** @todo unimplemented qualifiers:
548 * t ptrdiff_t - ISO C 99
550 case 'h': /* char or short */
551 qualifier = PrintfQualifierShort;
554 qualifier = PrintfQualifierByte;
557 case 'l': /* long or long long */
558 qualifier = PrintfQualifierLong;
561 qualifier = PrintfQualifierLongLong;
566 qualifier = PrintfQualifierInt;
572 switch (c = fmt[i]) {
573 /* String and character conversions */
575 if ((retval = print_string(va_arg(ap, char *),
576 width, precision, flags, ps)) < 0) {
584 c = va_arg(ap, unsigned int);
585 retval = print_char(c, width, flags, ps);
595 case 'P': /* pointer */
596 flags |= __PRINTF_FLAG_BIGCHARS;
598 flags |= __PRINTF_FLAG_PREFIX;
600 qualifier = PrintfQualifierPointer;
610 flags |= __PRINTF_FLAG_SIGNED;
614 flags |= __PRINTF_FLAG_BIGCHARS;
618 case '%': /* percentile itself */
621 default: /* Bad formatting */
623 * Unknown format. Now, j is the index of '%'
624 * so we will print whole bad format sequence.
629 /* Print integers. */
632 case PrintfQualifierByte:
633 size = sizeof(unsigned char);
634 number = (uint64_t) va_arg(ap, unsigned int);
636 case PrintfQualifierShort:
637 size = sizeof(unsigned short);
638 number = (uint64_t) va_arg(ap, unsigned int);
640 case PrintfQualifierInt:
641 size = sizeof(unsigned int);
642 number = (uint64_t) va_arg(ap, unsigned int);
644 case PrintfQualifierLong:
645 size = sizeof(unsigned long);
646 number = (uint64_t) va_arg(ap, unsigned long);
648 case PrintfQualifierLongLong:
649 size = sizeof(unsigned long long);
650 number = (uint64_t) va_arg(ap, unsigned long long);
652 case PrintfQualifierPointer:
653 size = sizeof(void *);
654 number = (uint64_t) (unsigned long)va_arg(ap, void *);
656 default: /* Unknown qualifier */
661 if (flags & __PRINTF_FLAG_SIGNED) {
662 if (number & (0x1 << (size * 8 - 1))) {
663 flags |= __PRINTF_FLAG_NEGATIVE;
665 if (size == sizeof(uint64_t)) {
666 number = -((int64_t) number);
669 number &= ~(0xFFFFFFFFFFFFFFFFll << (size * 8));
675 if ((retval = print_number(number, width, precision,
676 base, flags, ps)) < 0) {
689 if ((retval = printf_putnchars(&fmt[j],
690 (u64) (i - j), ps)) < 0) {
692 goto out; /* Error */
702 int snprintf(char *str, size_t size, const char *fmt, ...)
708 ret = vsnprintf(str, size, fmt, args);
714 int sprintf(char *str, const char *fmt, ...)
720 ret = vsprintf(str, fmt, args);
726 struct vsnprintf_data {
727 size_t size; /* Total space for string */
728 size_t len; /* Count of currently used characters */
729 char *string; /* Destination string */
733 * Write string to given buffer.
735 * Write at most data->size characters including trailing zero. According to
736 * C99, snprintf() has to return number of characters that would have been
737 * written if enough space had been available. Hence the return value is not
738 * number of really printed characters but size of the input string.
739 * Number of really used characters is stored in data->len.
741 * @param str Source string to print.
742 * @param count Size of source string.
743 * @param data Structure with destination string, counter of used space
744 * and total string size.
745 * @return Number of characters to print (not characters really printed!).
747 static int vsnprintf_write(const char *str, size_t count,
748 struct vsnprintf_data *data)
752 i = data->size - data->len;
756 /* We have only one free byte left in buffer => write trailing zero. */
758 data->string[data->size - 1] = 0;
759 data->len = data->size;
764 * We have not enough space for whole string with the trailing
765 * zero => print only a part of string.
768 memcpy((void *)(data->string + data->len), (void *)str, i - 1);
769 data->string[data->size - 1] = 0;
770 data->len = data->size;
774 /* Buffer is big enough to print whole string. */
775 memcpy((void *)(data->string + data->len), (void *)str, count);
778 * Put trailing zero at end, but not count it into data->len so
779 * it could be rewritten next time.
781 data->string[data->len] = 0;
786 int vsnprintf(char *str, size_t size, const char *fmt, va_list ap)
788 struct vsnprintf_data data = { size, 0, str };
789 struct printf_spec ps =
790 { (int (*)(void *, size_t, void *))vsnprintf_write, &data };
792 /* Print 0 at end of string - fix case that nothing will be printed. */
796 /* vsnprintf_write() ensures that str will be terminated by zero. */
797 return printf_core(fmt, &ps, ap);
800 int vsprintf(char *str, const char *fmt, va_list ap)
802 return vsnprintf(str, (size_t) - 1, fmt, ap);
805 int printf(const char *fmt, ...)
811 ret = vprintf(fmt, args);
817 static int vprintf_write(const char *str, size_t count, void *unused)
821 for (i = 0; i < count; i++)
827 int vprintf(const char *fmt, va_list ap)
829 struct printf_spec ps =
830 { (int (*)(void *, size_t, void *))vprintf_write, NULL };
832 return printf_core(fmt, &ps, ap);