Subversion Repositories HelenOS-historic

Rev

Rev 1199 | Blame | 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; /* size of number with all prefixes and signs */
  169.     int number_size; /* size of plain number */
  170.     int written = 0;
  171.     char sgn;
  172.    
  173.     if (flags & __PRINTF_FLAG_BIGCHARS)
  174.         digits = digits_big;   
  175.    
  176.     *ptr-- = 0; /* Put zero at end of string */
  177.  
  178.     if (num == 0) {
  179.         *ptr-- = '0';
  180.         size++;
  181.     } else {
  182.         do {
  183.             *ptr-- = digits[num % base];
  184.             size++;
  185.         } while (num /= base);
  186.     }
  187.    
  188.     number_size = size;
  189.    
  190.     /* Collect sum of all prefixes/signs/... to calculate padding and leading zeroes */
  191.     if (flags & __PRINTF_FLAG_PREFIX) {
  192.         switch(base) {
  193.             case 2: /* Binary formating is not standard, but usefull */
  194.                 size += 2;
  195.                 break;
  196.             case 8:
  197.                 size++;
  198.                 break;
  199.             case 16:
  200.                 size += 2;
  201.                 break;
  202.         }
  203.     }
  204.  
  205.     sgn = 0;
  206.     if (flags & __PRINTF_FLAG_SIGNED) {
  207.         if (flags & __PRINTF_FLAG_NEGATIVE) {
  208.             sgn = '-';
  209.             size++;
  210.         } else if (flags & __PRINTF_FLAG_SHOWPLUS) {
  211.                 sgn = '+';
  212.                 size++;
  213.             } else if (flags & __PRINTF_FLAG_SPACESIGN) {
  214.                     sgn = ' ';
  215.                     size++;
  216.                 }
  217.     }
  218.  
  219.     if (flags & __PRINTF_FLAG_LEFTALIGNED) {
  220.         flags &= ~__PRINTF_FLAG_ZEROPADDED;
  221.     }
  222.  
  223.     /* if number is leftaligned or precision is specified then zeropadding is ignored */
  224.     if (flags & __PRINTF_FLAG_ZEROPADDED) {
  225.         if ((precision == 0) && (width > size)) {
  226.             precision = width - size + number_size;
  227.         }
  228.     }
  229.  
  230.     /* print leading spaces */
  231.     if (number_size > precision) /* We must print whole number not only a part */
  232.         precision = number_size;
  233.  
  234.     width -= precision + size - number_size;
  235.    
  236.     if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
  237.         while (width-- > 0) {  
  238.             putchar(' ');  
  239.             written++;
  240.         }
  241.     }
  242.    
  243.     /* print sign */
  244.     if (sgn) {
  245.         putchar(sgn);
  246.         written++;
  247.     }
  248.    
  249.     /* print prefix */
  250.    
  251.     if (flags & __PRINTF_FLAG_PREFIX) {
  252.         switch(base) {
  253.             case 2: /* Binary formating is not standard, but usefull */
  254.                 putchar('0');
  255.                 if (flags & __PRINTF_FLAG_BIGCHARS) {
  256.                     putchar('B');
  257.                 } else {
  258.                     putchar('b');
  259.                 }
  260.                 written += 2;
  261.                 break;
  262.             case 8:
  263.                 putchar('o');
  264.                 written++;
  265.                 break;
  266.             case 16:
  267.                 putchar('0');
  268.                 if (flags & __PRINTF_FLAG_BIGCHARS) {
  269.                     putchar('X');
  270.                 } else {
  271.                     putchar('x');
  272.                 }
  273.                 written += 2;
  274.                 break;
  275.         }
  276.     }
  277.  
  278.     /* print leading zeroes */
  279.     precision -= number_size;
  280.     while (precision-- > 0) {  
  281.         putchar('0');  
  282.         written++;
  283.     }
  284.  
  285.    
  286.     /* print number itself */
  287.  
  288.     written += putstr(++ptr);
  289.    
  290.     /* print ending spaces */
  291.    
  292.     while (width-- > 0) {  
  293.         putchar(' ');  
  294.         written++;
  295.     }
  296.  
  297.     return written;
  298. }
  299.  
  300.  
  301. /** General formatted text print
  302.  *
  303.  * Print string formatted according the fmt parameter
  304.  * and variant arguments. Each formatting directive
  305.  * must have the following form:
  306.  * % [ flags ] [ width ] [ .precision ] [ type ] conversion
  307.  *
  308.  * FLAGS:
  309.  * #    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.
  310.  * -    Align to left.
  311.  * +    Print positive sign just as negative.
  312.  *   (space)    If printed number is positive and '+' flag is not set, print space in place of sign.
  313.  * 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.
  314.  *
  315.  * WIDTH:
  316.  * Specify minimal width of printed argument. If it is bigger, width is ignored.
  317.  * If width is specified with a '*' character instead of number, width is taken from parameter list.
  318.  * Int parameter expected before parameter for processed conversion specification.
  319.  * If this value is negative it is taken its absolute value and the '-' flag is set.
  320.  *
  321.  * PRECISION:
  322.  * Value precision. For numbers it specifies minimum valid numbers.
  323.  * Smaller numbers are printed with leading zeroes. Bigger numbers are not affected.
  324.  * Strings with more than precision characters are cutted of.
  325.  * Just as width could be '*' used instead a number.
  326.  * A int value is then expected in parameters. When both width and precision are specified using '*',
  327.  * first parameter is used for width and second one for precision.
  328.  *
  329.  * TYPE:
  330.  * hh   signed or unsigned char
  331.  * h    signed or usigned short
  332.  *  signed or usigned int (default value)
  333.  * l    signed or usigned long int
  334.  * ll   signed or usigned long long int
  335.  * z    size_t type
  336.  *
  337.  *
  338.  * CONVERSIONS:
  339.  *
  340.  * %    Print percentage character.
  341.  *
  342.  * c    Print single character.
  343.  *
  344.  * s    Print zero terminated string. If a NULL value is passed as value, "(NULL)" is printed instead.
  345.  *
  346.  * P, p Print value of a pointer. Void * value is expected and it is printed in hexadecimal notation with prefix
  347.  * ( as with %#X or %#x for 32bit or %#X / %#x for 64bit long pointers)
  348.  *
  349.  * b    Print value as unsigned binary number.  Prefix is not printed by default. (Nonstandard extension.)
  350.  *
  351.  * o    Print value as unsigned octal number. Prefix is not printed by default.
  352.  *
  353.  * d,i  Print signed decimal number. There is no difference between d and i conversion.
  354.  *
  355.  * u    Print unsigned decimal number.
  356.  *
  357.  * X, x Print hexadecimal number with upper- or lower-case. Prefix is not printed by default.
  358.  *
  359.  * All other characters from fmt except the formatting directives
  360.  * are printed in verbatim.
  361.  *
  362.  * @param fmt Formatting NULL terminated string.
  363.  * @return count of printed characters or negative value on fail.
  364.  */
  365. int printf(const char *fmt, ...)
  366. {
  367.     int i = 0, j = 0; /* i is index of currently processed char from fmt, j is index to the first not printed nonformating character */
  368.     int end;
  369.     int counter; /* counter of printed characters */
  370.     int retval; /* used to store return values from called functions */
  371.     va_list ap;
  372.     char c;
  373.     qualifier_t qualifier;  /* type of argument */
  374.     int base;   /* base in which will be parameter (numbers only) printed */
  375.     uint64_t number; /* argument value */
  376.     size_t  size; /* byte size of integer parameter */
  377.     int width, precision;
  378.     uint64_t flags;
  379.    
  380.     counter = 0;
  381.     va_start(ap, fmt);
  382.    
  383.     while ((c = fmt[i])) {
  384.         /* control character */
  385.         if (c == '%' ) {
  386.             /* print common characters if any processed */ 
  387.             if (i > j) {
  388.                 if ((retval = putnchars(&fmt[j], (size_t)(i - j))) == EOF) { /* error */
  389.                     return -counter;
  390.                 }
  391.                 counter += retval;
  392.             }
  393.        
  394.             j = i;
  395.             /* parse modifiers */
  396.             flags = 0;
  397.             end = 0;
  398.            
  399.             do {
  400.                 ++i;
  401.                 switch (c = fmt[i]) {
  402.                     case '#': flags |= __PRINTF_FLAG_PREFIX; break;
  403.                     case '-': flags |= __PRINTF_FLAG_LEFTALIGNED; break;
  404.                     case '+': flags |= __PRINTF_FLAG_SHOWPLUS; break;
  405.                     case ' ': flags |= __PRINTF_FLAG_SPACESIGN; break;
  406.                     case '0': flags |= __PRINTF_FLAG_ZEROPADDED; break;
  407.                     default: end = 1;
  408.                 }; 
  409.                
  410.             } while (end == 0);
  411.            
  412.             /* width & '*' operator */
  413.             width = 0;
  414.             if (isdigit(fmt[i])) {
  415.                 while (isdigit(fmt[i])) {
  416.                     width *= 10;
  417.                     width += fmt[i++] - '0';
  418.                 }
  419.             } else if (fmt[i] == '*') {
  420.                 /* get width value from argument list*/
  421.                 i++;
  422.                 width = (int)va_arg(ap, int);
  423.                 if (width < 0) {
  424.                     /* negative width means to set '-' flag */
  425.                     width *= -1;
  426.                     flags |= __PRINTF_FLAG_LEFTALIGNED;
  427.                 }
  428.             }
  429.            
  430.             /* precision and '*' operator */   
  431.             precision = 0;
  432.             if (fmt[i] == '.') {
  433.                 ++i;
  434.                 if (isdigit(fmt[i])) {
  435.                     while (isdigit(fmt[i])) {
  436.                         precision *= 10;
  437.                         precision += fmt[i++] - '0';
  438.                     }
  439.                 } else if (fmt[i] == '*') {
  440.                     /* get precision value from argument list*/
  441.                     i++;
  442.                     precision = (int)va_arg(ap, int);
  443.                     if (precision < 0) {
  444.                         /* negative precision means to ignore it */
  445.                         precision = 0;
  446.                     }
  447.                 }
  448.             }
  449.  
  450.             switch (fmt[i++]) {
  451.                 /** TODO: unimplemented qualifiers:
  452.                  * t ptrdiff_t - ISO C 99
  453.                  */
  454.                 case 'h':   /* char or short */
  455.                     qualifier = PrintfQualifierShort;
  456.                     if (fmt[i] == 'h') {
  457.                         i++;
  458.                         qualifier = PrintfQualifierByte;
  459.                     }
  460.                     break;
  461.                 case 'l':   /* long or long long*/
  462.                     qualifier = PrintfQualifierLong;
  463.                     if (fmt[i] == 'l') {
  464.                         i++;
  465.                         qualifier = PrintfQualifierLongLong;
  466.                     }
  467.                     break;
  468.                 case 'z':   /* size_t */
  469.                     qualifier = PrintfQualifierSizeT;
  470.                     break;
  471.                 default:
  472.                     qualifier = PrintfQualifierInt; /* default type */
  473.                     --i;
  474.             }  
  475.            
  476.             base = 10;
  477.  
  478.             switch (c = fmt[i]) {
  479.  
  480.                 /*
  481.                 * String and character conversions.
  482.                 */
  483.                 case 's':
  484.                     if ((retval = print_string(va_arg(ap, char*), width, precision, flags)) == EOF) {
  485.                         return -counter;
  486.                     };
  487.                    
  488.                     counter += retval;
  489.                     j = i + 1;
  490.                     goto next_char;
  491.                 case 'c':
  492.                     c = va_arg(ap, unsigned int);
  493.                     if ((retval = print_char(c, width, flags )) == EOF) {
  494.                         return -counter;
  495.                     };
  496.                    
  497.                     counter += retval;
  498.                     j = i + 1;
  499.                     goto next_char;
  500.  
  501.                 /*
  502.                  * Integer values
  503.                 */
  504.                 case 'P': /* pointer */
  505.                         flags |= __PRINTF_FLAG_BIGCHARS;
  506.                 case 'p':
  507.                     flags |= __PRINTF_FLAG_PREFIX;
  508.                     base = 16;
  509.                     qualifier = PrintfQualifierPointer;
  510.                     break; 
  511.                 case 'b':
  512.                     base = 2;
  513.                     break;
  514.                 case 'o':
  515.                     base = 8;
  516.                     break;
  517.                 case 'd':
  518.                 case 'i':
  519.                     flags |= __PRINTF_FLAG_SIGNED;  
  520.                 case 'u':
  521.                     break;
  522.                 case 'X':
  523.                     flags |= __PRINTF_FLAG_BIGCHARS;
  524.                 case 'x':
  525.                     base = 16;
  526.                     break;
  527.                 /* percentile itself */
  528.                 case '%':
  529.                     j = i;
  530.                     goto next_char;
  531.                 /*
  532.                 * Bad formatting.
  533.                 */
  534.                 default:
  535.                     /* Unknown format
  536.                      *  now, the j is index of '%' so we will
  537.                      * print whole bad format sequence
  538.                      */
  539.                     goto next_char;    
  540.             }
  541.        
  542.        
  543.         /* Print integers */
  544.             /* print number */
  545.             switch (qualifier) {
  546.                 case PrintfQualifierByte:
  547.                     size = sizeof(unsigned char);
  548.                     number = (uint64_t)va_arg(ap, unsigned int);
  549.                     break;
  550.                 case PrintfQualifierShort:
  551.                     size = sizeof(unsigned short);
  552.                     number = (uint64_t)va_arg(ap, unsigned int);
  553.                     break;
  554.                 case PrintfQualifierInt:
  555.                     size = sizeof(unsigned int);
  556.                     number = (uint64_t)va_arg(ap, unsigned int);
  557.                     break;
  558.                 case PrintfQualifierLong:
  559.                     size = sizeof(unsigned long);
  560.                     number = (uint64_t)va_arg(ap, unsigned long);
  561.                     break;
  562.                 case PrintfQualifierLongLong:
  563.                     size = sizeof(unsigned long long);
  564.                     number = (uint64_t)va_arg(ap, unsigned long long);
  565.                     break;
  566.                 case PrintfQualifierPointer:
  567.                     size = sizeof(void *);
  568.                     number = (uint64_t)(unsigned long)va_arg(ap, void *);
  569.                     break;
  570.                 case PrintfQualifierSizeT:
  571.                     size = sizeof(size_t);
  572.                     number = (uint64_t)va_arg(ap, size_t);
  573.                     break;
  574.                 default: /* Unknown qualifier */
  575.                     return -counter;
  576.                    
  577.             }
  578.            
  579.             if (flags & __PRINTF_FLAG_SIGNED) {
  580.                 if (number & (0x1 << (size*8 - 1))) {
  581.                     flags |= __PRINTF_FLAG_NEGATIVE;
  582.                
  583.                     if (size == sizeof(uint64_t)) {
  584.                         number = -((int64_t)number);
  585.                     } else {
  586.                         number = ~number;
  587.                         number &= (~((0xFFFFFFFFFFFFFFFFll) <<  (size * 8)));
  588.                         number++;
  589.                     }
  590.                 }
  591.             }
  592.  
  593.             if ((retval = print_number(number, width, precision, base, flags)) == EOF ) {
  594.                 return -counter;
  595.             };
  596.  
  597.             counter += retval;
  598.             j = i + 1;
  599.         }  
  600. next_char:
  601.            
  602.         ++i;
  603.     }
  604.    
  605.     if (i > j) {
  606.         if ((retval = putnchars(&fmt[j], (size_t)(i - j))) == EOF) { /* error */
  607.             return -counter;
  608.         }
  609.         counter += retval;
  610.     }
  611.    
  612.     va_end(ap);
  613.     return counter;
  614. }
  615.  
  616.