summaryrefslogtreecommitdiff
path: root/sys/kern/printf.c
blob: 89add9e6e3942a02069d4781b09325927e729215 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <printf.h>
#include <stdint.h>
#include <spinlock.h>
#include <sbi.h>
#include <stdarg.h>

static char digits[] = "0123456789abcdef";

struct spinlock mutex;
int locked = 0;

int
puts(const char *str)
{
	do {
		sbi_console_putchar(*str);
	} while (*(str++) != '\0');
}

#define PUTCHAR(c)      sbi_console_putchar(c)

static void
printint(int xx, int base, int sign)
{
        char buf[16];
        int i;
        unsigned int x;

        if (sign && (sign = xx < 0))
                x = -xx;
        else 
                x = xx; 

        i = 0;
        do {
                buf[i++] = digits[x % base];
        } while ((x /= base) != 0);

        if (sign)
                buf[i++] = '-';
        while (--i >= 0)
                PUTCHAR(buf[i]);

}

static void 
printptr(uint64_t x)
{
        int i;
        puts("0x");
        for (i = 0; i < (sizeof(uint64_t) * 2); i++, x <<= 4)
                PUTCHAR(digits[x >> (sizeof(int64_t) * 8 - 4)]);
}

void
printf(const char *fmt, ...) 
{
        va_list ap;
        int i, c, _locked;
        char *s;

	_locked = locked;
	if (_locked)
		acquire(&mutex);

        va_start(ap, fmt);

        for (i = 0; (c = fmt[i] & 0xff) != 0; i++) {
                if (c != '%') {
                        PUTCHAR(c);
                        continue;
                }
                c = fmt[++i] & 0xff;
                if (!c) 
                        break;

                switch (c) {
                        case 'd':
                        case 'i':
                                printint(va_arg(ap, int), 10, 1);
                                break;
                        case 'x':
                                printint(va_arg(ap, int), 16, 1);
                                break;
                        case 'p':
                                printptr(va_arg(ap, uint64_t));
                                break;
                        case '%':
                                PUTCHAR('%');
                                break;
                }
        }
	if (_locked)
		release(&mutex);
}

void printf_init(void)
{
	initlock(&mutex);
	locked = 1;
}