Subversion Repositories HelenOS-historic

Rev

Rev 1226 | Go to most recent revision | 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 <putchar.h>
  31. #include <print.h>
  32. #include <synch/spinlock.h>
  33. #include <arch/arg.h>
  34. #include <arch/asm.h>
  35.  
  36. #include <arch.h>
  37.  
  38. SPINLOCK_INITIALIZE(printflock);            /**< printf spinlock */
  39.  
  40. #define __PRINTF_FLAG_PREFIX        0x00000001  /* show prefixes 0x or 0 */
  41. #define __PRINTF_FLAG_SIGNED        0x00000002  /* signed / unsigned number */
  42. #define __PRINTF_FLAG_ZEROPADDED    0x00000004  /* print leading zeroes */
  43. #define __PRINTF_FLAG_LEFTALIGNED   0x00000010  /* align to left */
  44. #define __PRINTF_FLAG_SHOWPLUS      0x00000020  /* always show + sign */
  45. #define __PRINTF_FLAG_SPACESIGN     0x00000040  /* print space instead of plus */
  46. #define __PRINTF_FLAG_BIGCHARS      0x00000080  /* show big characters */
  47. #define __PRINTF_FLAG_NEGATIVE      0x00000100  /* number has - sign */
  48.  
  49. #define PRINT_NUMBER_BUFFER_SIZE    (64+5)      /* Buffer big enought for 64 bit number
  50.                              * printed in base 2, sign, prefix and
  51.                              * 0 to terminate string.. (last one is only for better testing
  52.                              * end of buffer by zero-filling subroutine)
  53.                              */
  54. typedef enum {
  55.     PrintfQualifierByte = 0,
  56.     PrintfQualifierShort,
  57.     PrintfQualifierInt,
  58.     PrintfQualifierLong,
  59.     PrintfQualifierLongLong,
  60.     PrintfQualifierNative,
  61.     PrintfQualifierPointer
  62. } qualifier_t;
  63.  
  64. static char digits_small[] = "0123456789abcdef";    /* Small hexadecimal characters */
  65. static char digits_big[] = "0123456789ABCDEF";      /* Big hexadecimal characters */
  66.  
  67. static inline int isdigit(int c)
  68. {
  69.     return ((c >= '0' )&&( c <= '9'));
  70. }
  71.  
  72. static __native strlen(const char *str)
  73. {
  74.     __native counter = 0;
  75.  
  76.     while (str[counter] != 0) {
  77.         counter++;
  78.     }
  79.  
  80.     return counter;
  81. }
  82.  
  83. /** Print one string without appending '\n' to the end.
  84.  *
  85.  * Do not use this function directly - printflock is not locked here.
  86.  *
  87.  */
  88. static int putstr(const char *str)
  89. {
  90.     int count;
  91.     if (str == NULL) {
  92.         str = "(NULL)";
  93.     }
  94.    
  95.     for (count = 0; str[count] != 0; count++) {
  96.         putchar(str[count]);
  97.     }
  98.     return count;
  99. }
  100.  
  101. /** Print count characters from buffer to output.
  102.  *
  103.  * @param buffer Address of the buffer with charaters to be printed.
  104.  * @param count Number of characters to be printed.
  105.  *
  106.  * @return Number of characters printed.
  107.  */
  108. static int putnchars(const char *buffer, __native count)
  109. {
  110.     int i;
  111.     if (buffer == NULL) {
  112.         buffer = "(NULL)";
  113.         count = 6;
  114.     }
  115.  
  116.     for (i = 0; i < count; i++) {
  117.         putchar(buffer[i]);
  118.     }
  119.    
  120.     return count;
  121. }
  122.  
  123. /** Print one formatted character
  124.  *
  125.  * @param c Character to print.
  126.  * @param width
  127.  * @param flags
  128.  * @return Number of printed characters or EOF.
  129.  */
  130. static int print_char(char c, int width, __u64 flags)
  131. {
  132.     int counter = 0;
  133.    
  134.     if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
  135.         while (--width > 0) {   /* one space is consumed by character itself hence the predecrement */
  136.             /* FIXME: painfully slow */
  137.             putchar(' ');  
  138.             ++counter;
  139.         }
  140.     }
  141.    
  142.     putchar(c);
  143.     ++counter;
  144.  
  145.     while (--width > 0) { /* one space is consumed by character itself hence the predecrement */
  146.         putchar(' ');
  147.         ++counter;
  148.     }
  149.    
  150.     return counter;
  151. }
  152.  
  153. /** Print one string
  154.  * @param s string
  155.  * @param width
  156.  * @param precision
  157.  * @param flags
  158.  * @return number of printed characters or EOF
  159.  */
  160. static int print_string(char *s, int width, int precision, __u64 flags)
  161. {
  162.     int counter = 0;
  163.     __native size;
  164.  
  165.     if (s == NULL) {
  166.         return putstr("(NULL)");
  167.     }
  168.    
  169.     size = strlen(s);
  170.  
  171.     /* print leading spaces */
  172.  
  173.     if (precision == 0)
  174.         precision = size;
  175.  
  176.     width -= precision;
  177.    
  178.     if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
  179.         while (width-- > 0) {  
  180.             putchar(' ');  
  181.             counter++;
  182.         }
  183.     }
  184.  
  185.     while (precision > size) {
  186.         precision--;
  187.         putchar(' ');  
  188.         ++counter;
  189.     }
  190.    
  191.     if (putnchars(s, precision) == EOF) {
  192.         return EOF;
  193.     }
  194.  
  195.     counter += precision;
  196.  
  197.     while (width-- > 0) {
  198.         putchar(' ');  
  199.         ++counter;
  200.     }
  201.    
  202.     return ++counter;
  203. }
  204.  
  205.  
  206. /** Print number in given base
  207.  *
  208.  * Print significant digits of a number in given
  209.  * base.
  210.  *
  211.  * @param num  Number to print.
  212.  * @param width
  213.  * @param precision
  214.  * @param base Base to print the number in (should
  215.  *             be in range 2 .. 16).
  216.  * @param flags output modifiers
  217.  * @return number of written characters or EOF.
  218.  */
  219. static int print_number(__u64 num, int width, int precision, int base , __u64 flags)
  220. {
  221.     char *digits = digits_small;
  222.     char d[PRINT_NUMBER_BUFFER_SIZE];   /* this is good enough even for base == 2, prefix and sign */
  223.     char *ptr = &d[PRINT_NUMBER_BUFFER_SIZE - 1];
  224.     int size = 0;
  225.     int number_size; /* size of plain number */
  226.     int written = 0;
  227.     char sgn;
  228.    
  229.     if (flags & __PRINTF_FLAG_BIGCHARS)
  230.         digits = digits_big;   
  231.    
  232.     *ptr-- = 0; /* Put zero at end of string */
  233.  
  234.     if (num == 0) {
  235.         *ptr-- = '0';
  236.         size++;
  237.     } else {
  238.         do {
  239.             *ptr-- = digits[num % base];
  240.             size++;
  241.         } while (num /= base);
  242.     }
  243.  
  244.     number_size = size;
  245.    
  246.     /* Collect sum of all prefixes/signs/... to calculate padding and leading zeroes */
  247.     if (flags & __PRINTF_FLAG_PREFIX) {
  248.         switch(base) {
  249.             case 2: /* Binary formating is not standard, but usefull */
  250.                 size += 2;
  251.                 break;
  252.             case 8:
  253.                 size++;
  254.                 break;
  255.             case 16:
  256.                 size += 2;
  257.                 break;
  258.         }
  259.     }
  260.  
  261.     sgn = 0;
  262.     if (flags & __PRINTF_FLAG_SIGNED) {
  263.         if (flags & __PRINTF_FLAG_NEGATIVE) {
  264.             sgn = '-';
  265.             size++;
  266.         } else if (flags & __PRINTF_FLAG_SHOWPLUS) {
  267.                 sgn = '+';
  268.                 size++;
  269.             } else if (flags & __PRINTF_FLAG_SPACESIGN) {
  270.                     sgn = ' ';
  271.                     size++;
  272.                 }
  273.     }
  274.  
  275.     if (flags & __PRINTF_FLAG_LEFTALIGNED) {
  276.         flags &= ~__PRINTF_FLAG_ZEROPADDED;
  277.     }
  278.  
  279.     /* if number is leftaligned or precision is specified then zeropadding is ignored */
  280.     if (flags & __PRINTF_FLAG_ZEROPADDED) {
  281.         if ((precision == 0) && (width > size)) {
  282.             precision = width - size + number_size;
  283.         }
  284.     }
  285.  
  286.     /* print leading spaces */
  287.     if (number_size > precision) /* We must print whole number not only a part */
  288.         precision = number_size;
  289.  
  290.     width -= precision + size - number_size;
  291.    
  292.     if (!(flags & __PRINTF_FLAG_LEFTALIGNED)) {
  293.         while (width-- > 0) {  
  294.             putchar(' ');  
  295.             written++;
  296.         }
  297.     }
  298.    
  299.     /* print sign */
  300.     if (sgn) {
  301.         putchar(sgn);
  302.         written++;
  303.     }
  304.    
  305.     /* print prefix */
  306.    
  307.     if (flags & __PRINTF_FLAG_PREFIX) {
  308.         switch(base) {
  309.             case 2: /* Binary formating is not standard, but usefull */
  310.                 putchar('0');
  311.                 if (flags & __PRINTF_FLAG_BIGCHARS) {
  312.                     putchar('B');
  313.                 } else {
  314.                     putchar('b');
  315.                 }
  316.                 written += 2;
  317.                 break;
  318.             case 8:
  319.                 putchar('o');
  320.                 written++;
  321.                 break;
  322.             case 16:
  323.                 putchar('0');
  324.                 if (flags & __PRINTF_FLAG_BIGCHARS) {
  325.                     putchar('X');
  326.                 } else {
  327.                     putchar('x');
  328.                 }
  329.                 written += 2;
  330.                 break;
  331.         }
  332.     }
  333.  
  334.     /* print leading zeroes */
  335.     precision -= number_size;
  336.     while (precision-- > 0) {  
  337.         putchar('0');  
  338.         written++;
  339.     }
  340.  
  341.    
  342.     /* print number itself */
  343.  
  344.     written += putstr(++ptr);
  345.    
  346.     /* print ending spaces */
  347.    
  348.     while (width-- > 0) {  
  349.         putchar(' ');  
  350.         written++;
  351.     }
  352.  
  353.     return written;
  354. }
  355.  
  356. /** Print formatted string.
  357.  *
  358.  * Print string formatted according to the @fmt parameter
  359.  * and variadic arguments. Each formatting directive
  360.  * must have the following form:
  361.  * % [ flags ] [ width ] [ .precision ] [ type ] conversion
  362.  *
  363.  * FLAGS:
  364.  * #    Force to print prefix.
  365.  *  For conversion %o the prefix is 0, for %x and %X prefixes are 0x and 0X and for conversion %b the prefix is 0b.
  366.  * -    Align to left.
  367.  * +    Print positive sign just as negative.
  368.  *   (space)    If the printed number is positive and '+' flag is not set, print space in place of sign.
  369.  * 0    Print 0 as padding instead of spaces. Zeroes are placed between sign and the rest of the number.
  370.  *  This flag is ignored if '-' flag is specified.
  371.  *
  372.  * WIDTH:
  373.  * Specify minimal width of printed argument. If it is bigger, width is ignored.
  374.  * If width is specified with a '*' character instead of number, width is taken from parameter list.
  375.  * And integer parameter is expected before parameter for processed conversion specification.
  376.  * If this value is negative its absolute value is taken and the '-' flag is set.
  377.  *
  378.  * PRECISION:
  379.  * Value precision. For numbers it specifies minimum valid numbers.
  380.  * Smaller numbers are printed with leading zeroes. Bigger numbers are not affected.
  381.  * Strings with more than precision characters are cut off.
  382.  * Just as with width, an '*' can be used used instead of a number.
  383.  * An integer value is then expected in parameters. When both width and precision are specified using '*',
  384.  * first parameter is used for width and second one for precision.
  385.  *
  386.  * TYPE:
  387.  * hh   signed or unsigned char
  388.  * h    signed or usigned short
  389.  *  signed or usigned int (default value)
  390.  * l    signed or usigned long int
  391.  * ll   signed or usigned long long int
  392.  * z    __native (non-standard extension)
  393.  *
  394.  *
  395.  * CONVERSIONS:
  396.  *
  397.  * %    Print percentage character itself.
  398.  *
  399.  * c    Print single character.
  400.  *
  401.  * s    Print zero terminated string. If a NULL value is passed as value, "(NULL)" is printed instead.
  402.  *
  403.  * P, p Print value of a pointer. Void * value is expected and it is printed in hexadecimal notation with prefix
  404.  * (as with %#X or %#x for 32bit or %#X / %#x for 64bit long pointers).
  405.  *
  406.  * b    Print value as unsigned binary number. Prefix is not printed by default. (Nonstandard extension.)
  407.  *
  408.  * o    Print value as unsigned octal number. Prefix is not printed by default.
  409.  *
  410.  * d,i  Print signed decimal number. There is no difference between d and i conversion.
  411.  *
  412.  * u    Print unsigned decimal number.
  413.  *
  414.  * X, x Print hexadecimal number with upper- or lower-case. Prefix is not printed by default.
  415.  *
  416.  * All other characters from @fmt except the formatting directives
  417.  * are printed in verbatim.
  418.  *
  419.  * @param fmt Formatting NULL terminated string.
  420.  * @return Number of printed characters or negative value on failure.
  421.  */
  422. int printf(const char *fmt, ...)
  423. {
  424.     int irqpri;
  425.     int i = 0, j = 0; /* i is index of currently processed char from fmt, j is index to the first not printed nonformating character */
  426.     int end;
  427.     int counter; /* counter of printed characters */
  428.     int retval; /* used to store return values from called functions */
  429.     va_list ap;
  430.     char c;
  431.     qualifier_t qualifier;  /* type of argument */
  432.     int base;   /* base in which will be parameter (numbers only) printed */
  433.     __u64 number; /* argument value */
  434.     __native size; /* byte size of integer parameter */
  435.     int width, precision;
  436.     __u64 flags;
  437.    
  438.     counter = 0;
  439.    
  440.     va_start(ap, fmt);
  441.    
  442.     irqpri = interrupts_disable();
  443.     spinlock_lock(&printflock);
  444.  
  445.    
  446.     while ((c = fmt[i])) {
  447.         /* control character */
  448.         if (c == '%' ) {
  449.             /* print common characters if any processed */ 
  450.             if (i > j) {
  451.                 if ((retval = putnchars(&fmt[j], (__native)(i - j))) == EOF) { /* error */
  452.                     counter = -counter;
  453.                     goto out;
  454.                 }
  455.                 counter += retval;
  456.             }
  457.        
  458.             j = i;
  459.             /* parse modifiers */
  460.             flags = 0;
  461.             end = 0;
  462.            
  463.             do {
  464.                 ++i;
  465.                 switch (c = fmt[i]) {
  466.                     case '#': flags |= __PRINTF_FLAG_PREFIX; break;
  467.                     case '-': flags |= __PRINTF_FLAG_LEFTALIGNED; break;
  468.                     case '+': flags |= __PRINTF_FLAG_SHOWPLUS; break;
  469.                     case ' ': flags |= __PRINTF_FLAG_SPACESIGN; break;
  470.                     case '0': flags |= __PRINTF_FLAG_ZEROPADDED; break;
  471.                     default: end = 1;
  472.                 }; 
  473.                
  474.             } while (end == 0);
  475.            
  476.             /* width & '*' operator */
  477.             width = 0;
  478.             if (isdigit(fmt[i])) {
  479.                 while (isdigit(fmt[i])) {
  480.                     width *= 10;
  481.                     width += fmt[i++] - '0';
  482.                 }
  483.             } else if (fmt[i] == '*') {
  484.                 /* get width value from argument list*/
  485.                 i++;
  486.                 width = (int)va_arg(ap, int);
  487.                 if (width < 0) {
  488.                     /* negative width means to set '-' flag */
  489.                     width *= -1;
  490.                     flags |= __PRINTF_FLAG_LEFTALIGNED;
  491.                 }
  492.             }
  493.            
  494.             /* precision and '*' operator */   
  495.             precision = 0;
  496.             if (fmt[i] == '.') {
  497.                 ++i;
  498.                 if (isdigit(fmt[i])) {
  499.                     while (isdigit(fmt[i])) {
  500.                         precision *= 10;
  501.                         precision += fmt[i++] - '0';
  502.                     }
  503.                 } else if (fmt[i] == '*') {
  504.                     /* get precision value from argument list*/
  505.                     i++;
  506.                     precision = (int)va_arg(ap, int);
  507.                     if (precision < 0) {
  508.                         /* negative precision means to ignore it */
  509.                         precision = 0;
  510.                     }
  511.                 }
  512.             }
  513.  
  514.             switch (fmt[i++]) {
  515.                 /** TODO: unimplemented qualifiers:
  516.                  * t ptrdiff_t - ISO C 99
  517.                  */
  518.                 case 'h':   /* char or short */
  519.                     qualifier = PrintfQualifierShort;
  520.                     if (fmt[i] == 'h') {
  521.                         i++;
  522.                         qualifier = PrintfQualifierByte;
  523.                     }
  524.                     break;
  525.                 case 'l':   /* long or long long*/
  526.                     qualifier = PrintfQualifierLong;
  527.                     if (fmt[i] == 'l') {
  528.                         i++;
  529.                         qualifier = PrintfQualifierLongLong;
  530.                     }
  531.                     break;
  532.                 case 'z':   /* __native */
  533.                     qualifier = PrintfQualifierNative;
  534.                     break;
  535.                 default:
  536.                     qualifier = PrintfQualifierInt; /* default type */
  537.                     --i;
  538.             }  
  539.            
  540.             base = 10;
  541.  
  542.             switch (c = fmt[i]) {
  543.  
  544.                 /*
  545.                 * String and character conversions.
  546.                 */
  547.                 case 's':
  548.                     if ((retval = print_string(va_arg(ap, char*), width, precision, flags)) == EOF) {
  549.                         counter = -counter;
  550.                         goto out;
  551.                     };
  552.                    
  553.                     counter += retval;
  554.                     j = i + 1;
  555.                     goto next_char;
  556.                 case 'c':
  557.                     c = va_arg(ap, unsigned int);
  558.                     if ((retval = print_char(c, width, flags )) == EOF) {
  559.                         counter = -counter;
  560.                         goto out;
  561.                     };
  562.                    
  563.                     counter += retval;
  564.                     j = i + 1;
  565.                     goto next_char;
  566.  
  567.                 /*
  568.                  * Integer values
  569.                 */
  570.                 case 'P': /* pointer */
  571.                         flags |= __PRINTF_FLAG_BIGCHARS;
  572.                 case 'p':
  573.                     flags |= __PRINTF_FLAG_PREFIX;
  574.                     base = 16;
  575.                     qualifier = PrintfQualifierPointer;
  576.                     break; 
  577.                 case 'b':
  578.                     base = 2;
  579.                     break;
  580.                 case 'o':
  581.                     base = 8;
  582.                     break;
  583.                 case 'd':
  584.                 case 'i':
  585.                     flags |= __PRINTF_FLAG_SIGNED;  
  586.                 case 'u':
  587.                     break;
  588.                 case 'X':
  589.                     flags |= __PRINTF_FLAG_BIGCHARS;
  590.                 case 'x':
  591.                     base = 16;
  592.                     break;
  593.                 /* percentile itself */
  594.                 case '%':
  595.                     j = i;
  596.                     goto next_char;
  597.                 /*
  598.                 * Bad formatting.
  599.                 */
  600.                 default:
  601.                     /* Unknown format
  602.                      *  now, the j is index of '%' so we will
  603.                      * print whole bad format sequence
  604.                      */
  605.                     goto next_char;    
  606.             }
  607.        
  608.        
  609.         /* Print integers */
  610.             /* print number */
  611.             switch (qualifier) {
  612.                 case PrintfQualifierByte:
  613.                     size = sizeof(unsigned char);
  614.                     number = (__u64)va_arg(ap, unsigned int);
  615.                     break;
  616.                 case PrintfQualifierShort:
  617.                     size = sizeof(unsigned short);
  618.                     number = (__u64)va_arg(ap, unsigned int);
  619.                     break;
  620.                 case PrintfQualifierInt:
  621.                     size = sizeof(unsigned int);
  622.                     number = (__u64)va_arg(ap, unsigned int);
  623.                     break;
  624.                 case PrintfQualifierLong:
  625.                     size = sizeof(unsigned long);
  626.                     number = (__u64)va_arg(ap, unsigned long);
  627.                     break;
  628.                 case PrintfQualifierLongLong:
  629.                     size = sizeof(unsigned long long);
  630.                     number = (__u64)va_arg(ap, unsigned long long);
  631.                     break;
  632.                 case PrintfQualifierPointer:
  633.                     size = sizeof(void *);
  634.                     number = (__u64)(unsigned long)va_arg(ap, void *);
  635.                     break;
  636.                 case PrintfQualifierNative:
  637.                     size = sizeof(__native);
  638.                     number = (__u64)va_arg(ap, __native);
  639.                     break;
  640.                 default: /* Unknown qualifier */
  641.                     counter = -counter;
  642.                     goto out;
  643.                    
  644.             }
  645.            
  646.             if (flags & __PRINTF_FLAG_SIGNED) {
  647.                 if (number & (0x1 << (size*8 - 1))) {
  648.                     flags |= __PRINTF_FLAG_NEGATIVE;
  649.                
  650.                     if (size == sizeof(__u64)) {
  651.                         number = -((__s64)number);
  652.                     } else {
  653.                         number = ~number;
  654.                         number &= (~((0xFFFFFFFFFFFFFFFFll) <<  (size * 8)));
  655.                         number++;
  656.                     }
  657.                 }
  658.             }
  659.  
  660.             if ((retval = print_number(number, width, precision, base, flags)) == EOF ) {
  661.                 counter = -counter;
  662.                 goto out;
  663.             };
  664.  
  665.             counter += retval;
  666.             j = i + 1;
  667.         }  
  668. next_char:
  669.            
  670.         ++i;
  671.     }
  672.    
  673.     if (i > j) {
  674.         if ((retval = putnchars(&fmt[j], (__native)(i - j))) == EOF) { /* error */
  675.             counter = -counter;
  676.             goto out;
  677.         }
  678.         counter += retval;
  679.     }
  680. out:
  681.     spinlock_unlock(&printflock);
  682.     interrupts_restore(irqpri);
  683.    
  684.     va_end(ap);
  685.     return counter;
  686. }
  687.