Subversion Repositories HelenOS

Rev

Rev 1197 | Rev 1234 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. /*
  2.  * Copyright (C) 2001-2004 Jakub Jermar
  3.  * Copyright (C) 2006 Josef Cejka
  4.  * All rights reserved.
  5.  *
  6.  * Redistribution and use in source and binary forms, with or without
  7.  * modification, are permitted provided that the following conditions
  8.  * are met:
  9.  *
  10.  * - Redistributions of source code must retain the above copyright
  11.  *   notice, this list of conditions and the following disclaimer.
  12.  * - Redistributions in binary form must reproduce the above copyright
  13.  *   notice, this list of conditions and the following disclaimer in the
  14.  *   documentation and/or other materials provided with the distribution.
  15.  * - The name of the author may not be used to endorse or promote products
  16.  *   derived from this software without specific prior written permission.
  17.  *
  18.  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  19.  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  20.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  21.  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  22.  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  23.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24.  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25.  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27.  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28.  */
  29.  
  30. #include <stdio.h>
  31. #include <unistd.h>
  32. #include <io/io.h>
  33. #include <stdarg.h>
  34. #include <ctype.h>
  35. #include <string.h>
  36.  
  37. #define __PRINTF_FLAG_PREFIX        0x00000001  /* show prefixes 0x or 0*/
  38. #define __PRINTF_FLAG_SIGNED        0x00000002  /* signed / unsigned number */
  39. #define __PRINTF_FLAG_ZEROPADDED    0x00000004  /* print leading zeroes */
  40. #define __PRINTF_FLAG_LEFTALIGNED   0x00000010  /* align to left */
  41. #define __PRINTF_FLAG_SHOWPLUS      0x00000020  /* always show + sign */
  42. #define __PRINTF_FLAG_SPACESIGN     0x00000040  /* print space instead of plus */
  43. #define __PRINTF_FLAG_BIGCHARS      0x00000080  /* show big characters */
  44. #define __PRINTF_FLAG_NEGATIVE      0x00000100  /* number has - sign */
  45.  
  46. #define PRINT_NUMBER_BUFFER_SIZE    (64+5)      /* Buffer big enought for 64 bit number
  47.                              * printed in base 2, sign, prefix and
  48.                              * 0 to terminate string.. (last one is only for better testing
  49.                              * end of buffer by zero-filling subroutine)
  50.                              */
  51. typedef enum {
  52.     PrintfQualifierByte = 0,
  53.     PrintfQualifierShort,
  54.     PrintfQualifierInt,
  55.     PrintfQualifierLong,
  56.     PrintfQualifierLongLong,
  57.     PrintfQualifierSizeT,
  58.     PrintfQualifierPointer
  59. } qualifier_t;
  60.  
  61. static char digits_small[] = "0123456789abcdef";    /* Small hexadecimal characters */
  62. static char digits_big[] = "0123456789ABCDEF";  /* Big hexadecimal characters */
  63.  
  64.  
  65. /** Print one formatted character
  66.  * @param c character to print
  67.  * @param width
  68.  * @param flags
  69.  * @return number of printed characters or EOF
  70.  */
  71. static int print_char(char c, int width, uint64_t flags)
  72. {
  73.     int counter = 0;
  74.    
  75.     if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
  76.         while (--width > 0) {   /* one space is consumed by character itself hence predecrement */
  77.             /* FIXME: painful slow */
  78.             putchar(' ');  
  79.             ++counter;
  80.         }
  81.     }
  82.    
  83.     if (putchar(c) == EOF) {
  84.         return EOF;
  85.     }
  86.  
  87.     while (--width > 0) { /* one space is consumed by character itself hence predecrement */
  88.         putchar(' ');
  89.         ++counter;
  90.     }
  91.    
  92.     return ++counter;
  93. }
  94.  
  95. /** Print one string
  96.  * @param s string
  97.  * @param width
  98.  * @param precision
  99.  * @param flags
  100.  * @return number of printed characters or EOF
  101.  */
  102.                        
  103. static int print_string(char *s, int width, int precision, uint64_t flags)
  104. {
  105.     int counter = 0;
  106.     size_t size;
  107.  
  108.     if (s == NULL) {
  109.         return putstr("(NULL)");
  110.     }
  111.    
  112.     size = strlen(s);
  113.  
  114.     /* print leading spaces */
  115.  
  116.     if (precision == 0)
  117.         precision = size;
  118.  
  119.     width -= precision;
  120.    
  121.     if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
  122.         while (width-- > 0) {  
  123.             putchar(' ');  
  124.             counter++;
  125.         }
  126.     }
  127.  
  128.     while (precision > size) {
  129.         precision--;
  130.         putchar(' ');  
  131.         ++counter;
  132.     }
  133.    
  134.     if (putnchars(s, precision) == EOF) {
  135.         return EOF;
  136.     }
  137.  
  138.     counter += precision;
  139.  
  140.     while (width-- > 0) {
  141.         putchar(' ');  
  142.         ++counter;
  143.     }
  144.    
  145.     return ++counter;
  146. }
  147.  
  148.  
  149. /** Print number in given base
  150.  *
  151.  * Print significant digits of a number in given
  152.  * base.
  153.  *
  154.  * @param num  Number to print.
  155.  * @param width
  156.  * @param precision
  157.  * @param base Base to print the number in (should
  158.  *             be in range 2 .. 16).
  159.  * @param flags output modifiers
  160.  * @return number of written characters or EOF
  161.  *
  162.  */
  163. static int print_number(uint64_t num, int width, int precision, int base , uint64_t flags)
  164. {
  165.     char *digits = digits_small;
  166.     char d[PRINT_NUMBER_BUFFER_SIZE];   /* this is good enough even for base == 2, prefix and sign */
  167.     char *ptr = &d[PRINT_NUMBER_BUFFER_SIZE - 1];
  168.     int size = 0;
  169.     int written = 0;
  170.     char sgn;
  171.    
  172.     if (flags & __PRINTF_FLAG_BIGCHARS)
  173.         digits = digits_big;   
  174.    
  175.     *ptr-- = 0; /* Put zero at end of string */
  176.  
  177.     if (num == 0) {
  178.         *ptr-- = '0';
  179.         size++;
  180.     } else {
  181.         do {
  182.             *ptr-- = digits[num % base];
  183.             size++;
  184.         } while (num /= base);
  185.     }
  186.  
  187.     /* Collect sum of all prefixes/signs/... to calculate padding and leading zeroes */
  188.     if (flags & __PRINTF_FLAG_PREFIX) {
  189.         switch(base) {
  190.             case 2: /* Binary formating is not standard, but usefull */
  191.                 size += 2;
  192.                 break;
  193.             case 8:
  194.                 size++;
  195.                 break;
  196.             case 16:
  197.                 size += 2;
  198.                 break;
  199.         }
  200.     }
  201.  
  202.     sgn = 0;
  203.     if (flags & __PRINTF_FLAG_SIGNED) {
  204.         if (flags & __PRINTF_FLAG_NEGATIVE) {
  205.             sgn = '-';
  206.             size++;
  207.         } else if (flags & __PRINTF_FLAG_SHOWPLUS) {
  208.                 sgn = '+';
  209.                 size++;
  210.             } else if (flags & __PRINTF_FLAG_SPACESIGN) {
  211.                     sgn = ' ';
  212.                     size++;
  213.                 }
  214.     }
  215.  
  216.     if (flags & __PRINTF_FLAG_LEFTALIGNED) {
  217.         flags &= ~__PRINTF_FLAG_ZEROPADDED;
  218.     }
  219.  
  220.     /* if number is leftaligned or precision is specified then zeropadding is ignored */
  221.     if (flags & __PRINTF_FLAG_ZEROPADDED) {
  222.         if ((precision == 0) && (width > size)) {
  223.             precision = width - size;
  224.         }
  225.     }
  226.  
  227.     /* print leading spaces */
  228.     if (size > precision) /* We must print whole number not only a part */
  229.         precision = size;
  230.  
  231.     width -= precision;
  232.    
  233.     if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
  234.         while (width-- > 0) {  
  235.             putchar(' ');  
  236.             written++;
  237.         }
  238.     }
  239.    
  240.     /* print sign */
  241.     if (sgn) {
  242.         putchar(sgn);
  243.         written++;
  244.     }
  245.    
  246.     /* print prefix */
  247.    
  248.     if (flags & __PRINTF_FLAG_PREFIX) {
  249.         switch(base) {
  250.             case 2: /* Binary formating is not standard, but usefull */
  251.                 putchar('0');
  252.                 if (flags & __PRINTF_FLAG_BIGCHARS) {
  253.                     putchar('B');
  254.                 } else {
  255.                     putchar('b');
  256.                 }
  257.                 written += 2;
  258.                 break;
  259.             case 8:
  260.                 putchar('o');
  261.                 written++;
  262.                 break;
  263.             case 16:
  264.                 putchar('0');
  265.                 if (flags & __PRINTF_FLAG_BIGCHARS) {
  266.                     putchar('X');
  267.                 } else {
  268.                     putchar('x');
  269.                 }
  270.                 written += 2;
  271.                 break;
  272.         }
  273.     }
  274.  
  275.     /* print leading zeroes */
  276.     precision -= size;
  277.     while (precision-- > 0) {  
  278.         putchar('0');  
  279.         written++;
  280.     }
  281.  
  282.    
  283.     /* print number itself */
  284.  
  285.     written += putstr(++ptr);
  286.    
  287.     /* print ending spaces */
  288.    
  289.     while (width-- > 0) {  
  290.         putchar(' ');  
  291.         written++;
  292.     }
  293.  
  294.     return written;
  295. }
  296.  
  297.  
  298. /** General formatted text print
  299.  *
  300.  * Print string formatted according the fmt parameter
  301.  * and variant arguments. Each formatting directive
  302.  * must have the following form:
  303.  * % [ flags ] [ width ] [ .precision ] [ type ] conversion
  304.  *
  305.  * FLAGS:
  306.  * #    Force to print prefix. For conversion %o is prefix 0, for %x and %X are prefixes 0x and 0X and for conversion %b is prefix 0b.
  307.  * -    Align to left.
  308.  * +    Print positive sign just as negative.
  309.  *   (space)    If printed number is positive and '+' flag is not set, print space in place of sign.
  310.  * 0    Print 0 as padding instead of spaces. Zeroes are placed between sign and the rest of number. This flag is ignored if '-' flag is specified.
  311.  *
  312.  * WIDTH:
  313.  * Specify minimal width of printed argument. If it is bigger, width is ignored.
  314.  * If width is specified with a '*' character instead of number, width is taken from parameter list.
  315.  * Int parameter expected before parameter for processed conversion specification.
  316.  * If this value is negative it is taken its absolute value and the '-' flag is set.
  317.  *
  318.  * PRECISION:
  319.  * Value precision. For numbers it specifies minimum valid numbers.
  320.  * Smaller numbers are printed with leading zeroes. Bigger numbers are not affected.
  321.  * Strings with more than precision characters are cutted of.
  322.  * Just as width could be '*' used instead a number.
  323.  * A int value is then expected in parameters. When both width and precision are specified using '*',
  324.  * first parameter is used for width and second one for precision.
  325.  *
  326.  * TYPE:
  327.  * hh   signed or unsigned char
  328.  * h    signed or usigned short
  329.  *  signed or usigned int (default value)
  330.  * l    signed or usigned long int
  331.  * ll   signed or usigned long long int
  332.  * z    size_t type
  333.  *
  334.  *
  335.  * CONVERSIONS:
  336.  *
  337.  * %    Print percentage character.
  338.  *
  339.  * c    Print single character.
  340.  *
  341.  * s    Print zero terminated string. If a NULL value is passed as value, "(NULL)" is printed instead.
  342.  *
  343.  * P, p Print value of a pointer. Void * value is expected and it is printed in hexadecimal notation with prefix
  344.  * ( as with %#X or %#x for 32bit or %#X / %#x for 64bit long pointers)
  345.  *
  346.  * b    Print value as unsigned binary number.  Prefix is not printed by default. (Nonstandard extension.)
  347.  *
  348.  * o    Print value as unsigned octal number. Prefix is not printed by default.
  349.  *
  350.  * d,i  Print signed decimal number. There is no difference between d and i conversion.
  351.  *
  352.  * u    Print unsigned decimal number.
  353.  *
  354.  * X, x Print hexadecimal number with upper- or lower-case. Prefix is not printed by default.
  355.  *
  356.  * All other characters from fmt except the formatting directives
  357.  * are printed in verbatim.
  358.  *
  359.  * @param fmt Formatting NULL terminated string.
  360.  * @return count of printed characters or negative value on fail.
  361.  */
  362. int printf(const char *fmt, ...)
  363. {
  364.     int i = 0, j = 0; /* i is index of currently processed char from fmt, j is index to the first not printed nonformating character */
  365.     int end;
  366.     int counter; /* counter of printed characters */
  367.     int retval; /* used to store return values from called functions */
  368.     va_list ap;
  369.     char c;
  370.     qualifier_t qualifier;  /* type of argument */
  371.     int base;   /* base in which will be parameter (numbers only) printed */
  372.     uint64_t number; /* argument value */
  373.     size_t  size; /* byte size of integer parameter */
  374.     int width, precision;
  375.     uint64_t flags;
  376.    
  377.     counter = 0;
  378.     va_start(ap, fmt);
  379.    
  380.     while ((c = fmt[i])) {
  381.         /* control character */
  382.         if (c == '%' ) {
  383.             /* print common characters if any processed */ 
  384.             if (i > j) {
  385.                 if ((retval = putnchars(&fmt[j], (size_t)(i - j))) == EOF) { /* error */
  386.                     return -counter;
  387.                 }
  388.                 counter += retval;
  389.             }
  390.        
  391.             j = i;
  392.             /* parse modifiers */
  393.             flags = 0;
  394.             end = 0;
  395.            
  396.             do {
  397.                 ++i;
  398.                 switch (c = fmt[i]) {
  399.                     case '#': flags |= __PRINTF_FLAG_PREFIX; break;
  400.                     case '-': flags |= __PRINTF_FLAG_LEFTALIGNED; break;
  401.                     case '+': flags |= __PRINTF_FLAG_SHOWPLUS; break;
  402.                     case ' ': flags |= __PRINTF_FLAG_SPACESIGN; break;
  403.                     case '0': flags |= __PRINTF_FLAG_ZEROPADDED; break;
  404.                     default: end = 1;
  405.                 }; 
  406.                
  407.             } while (end == 0);
  408.            
  409.             /* width & '*' operator */
  410.             width = 0;
  411.             if (isdigit(fmt[i])) {
  412.                 while (isdigit(fmt[i])) {
  413.                     width *= 10;
  414.                     width += fmt[i++] - '0';
  415.                 }
  416.             } else if (fmt[i] == '*') {
  417.                 /* get width value from argument list*/
  418.                 i++;
  419.                 width = (int)va_arg(ap, int);
  420.                 if (width < 0) {
  421.                     /* negative width means to set '-' flag */
  422.                     width *= -1;
  423.                     flags |= __PRINTF_FLAG_LEFTALIGNED;
  424.                 }
  425.             }
  426.            
  427.             /* precision and '*' operator */   
  428.             precision = 0;
  429.             if (fmt[i] == '.') {
  430.                 ++i;
  431.                 if (isdigit(fmt[i])) {
  432.                     while (isdigit(fmt[i])) {
  433.                         precision *= 10;
  434.                         precision += fmt[i++] - '0';
  435.                     }
  436.                 } else if (fmt[i] == '*') {
  437.                     /* get precision value from argument list*/
  438.                     i++;
  439.                     precision = (int)va_arg(ap, int);
  440.                     if (precision < 0) {
  441.                         /* negative precision means to ignore it */
  442.                         precision = 0;
  443.                     }
  444.                 }
  445.             }
  446.  
  447.             switch (fmt[i++]) {
  448.                 /** TODO: unimplemented qualifiers:
  449.                  * t ptrdiff_t - ISO C 99
  450.                  */
  451.                 case 'h':   /* char or short */
  452.                     qualifier = PrintfQualifierShort;
  453.                     if (fmt[i] == 'h') {
  454.                         i++;
  455.                         qualifier = PrintfQualifierByte;
  456.                     }
  457.                     break;
  458.                 case 'l':   /* long or long long*/
  459.                     qualifier = PrintfQualifierLong;
  460.                     if (fmt[i] == 'l') {
  461.                         i++;
  462.                         qualifier = PrintfQualifierLongLong;
  463.                     }
  464.                     break;
  465.                 case 'z':   /* size_t */
  466.                     qualifier = PrintfQualifierSizeT;
  467.                     break;
  468.                 default:
  469.                     qualifier = PrintfQualifierInt; /* default type */
  470.                     --i;
  471.             }  
  472.            
  473.             base = 10;
  474.  
  475.             switch (c = fmt[i]) {
  476.  
  477.                 /*
  478.                 * String and character conversions.
  479.                 */
  480.                 case 's':
  481.                     if ((retval = print_string(va_arg(ap, char*), width, precision, flags)) == EOF) {
  482.                         return -counter;
  483.                     };
  484.                    
  485.                     counter += retval;
  486.                     j = i + 1;
  487.                     goto next_char;
  488.                 case 'c':
  489.                     c = va_arg(ap, unsigned int);
  490.                     if ((retval = print_char(c, width, flags )) == EOF) {
  491.                         return -counter;
  492.                     };
  493.                    
  494.                     counter += retval;
  495.                     j = i + 1;
  496.                     goto next_char;
  497.  
  498.                 /*
  499.                  * Integer values
  500.                 */
  501.                 case 'P': /* pointer */
  502.                         flags |= __PRINTF_FLAG_BIGCHARS;
  503.                 case 'p':
  504.                     flags |= __PRINTF_FLAG_PREFIX;
  505.                     base = 16;
  506.                     qualifier = PrintfQualifierPointer;
  507.                     break; 
  508.                 case 'b':
  509.                     base = 2;
  510.                     break;
  511.                 case 'o':
  512.                     base = 8;
  513.                     break;
  514.                 case 'd':
  515.                 case 'i':
  516.                     flags |= __PRINTF_FLAG_SIGNED;  
  517.                 case 'u':
  518.                     break;
  519.                 case 'X':
  520.                     flags |= __PRINTF_FLAG_BIGCHARS;
  521.                 case 'x':
  522.                     base = 16;
  523.                     break;
  524.                 /* percentile itself */
  525.                 case '%':
  526.                     j = i;
  527.                     goto next_char;
  528.                 /*
  529.                 * Bad formatting.
  530.                 */
  531.                 default:
  532.                     /* Unknown format
  533.                      *  now, the j is index of '%' so we will
  534.                      * print whole bad format sequence
  535.                      */
  536.                     goto next_char;    
  537.             }
  538.        
  539.        
  540.         /* Print integers */
  541.             /* print number */
  542.             switch (qualifier) {
  543.                 case PrintfQualifierByte:
  544.                     size = sizeof(unsigned char);
  545.                     number = (uint64_t)va_arg(ap, unsigned int);
  546.                     break;
  547.                 case PrintfQualifierShort:
  548.                     size = sizeof(unsigned short);
  549.                     number = (uint64_t)va_arg(ap, unsigned int);
  550.                     break;
  551.                 case PrintfQualifierInt:
  552.                     size = sizeof(unsigned int);
  553.                     number = (uint64_t)va_arg(ap, unsigned int);
  554.                     break;
  555.                 case PrintfQualifierLong:
  556.                     size = sizeof(unsigned long);
  557.                     number = (uint64_t)va_arg(ap, unsigned long);
  558.                     break;
  559.                 case PrintfQualifierLongLong:
  560.                     size = sizeof(unsigned long long);
  561.                     number = (uint64_t)va_arg(ap, unsigned long long);
  562.                     break;
  563.                 case PrintfQualifierPointer:
  564.                     size = sizeof(void *);
  565.                     number = (uint64_t)(unsigned long)va_arg(ap, void *);
  566.                     break;
  567.                 case PrintfQualifierSizeT:
  568.                     size = sizeof(size_t);
  569.                     number = (uint64_t)va_arg(ap, size_t);
  570.                     break;
  571.                 default: /* Unknown qualifier */
  572.                     return -counter;
  573.                    
  574.             }
  575.            
  576.             if (flags & __PRINTF_FLAG_SIGNED) {
  577.                 if (number & (0x1 << (size*8 - 1))) {
  578.                     flags |= __PRINTF_FLAG_NEGATIVE;
  579.                
  580.                     if (size == sizeof(uint64_t)) {
  581.                         number = -((int64_t)number);
  582.                     } else {
  583.                         number = ~number;
  584.                         number &= (~((0xFFFFFFFFFFFFFFFFll) <<  (size * 8)));
  585.                         number++;
  586.                     }
  587.                 }
  588.             }
  589.  
  590.             if ((retval = print_number(number, width, precision, base, flags)) == EOF ) {
  591.                 return -counter;
  592.             };
  593.  
  594.             counter += retval;
  595.             j = i + 1;
  596.         }  
  597. next_char:
  598.            
  599.         ++i;
  600.     }
  601.    
  602.     if (i > j) {
  603.         if ((retval = putnchars(&fmt[j], (size_t)(i - j))) == EOF) { /* error */
  604.             return -counter;
  605.         }
  606.         counter += retval;
  607.     }
  608.    
  609.     va_end(ap);
  610.     return counter;
  611. }
  612.  
  613.