Subversion Repositories HelenOS

Rev

Rev 1224 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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