Subversion Repositories HelenOS

Rev

Rev 1273 | Go to most recent revision | Details | Last modification | View Log | RSS feed

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