root/user/printf.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. putc
  2. printint
  3. printptr
  4. vprintf
  5. fprintf
  6. printf

   1 #include "kernel/types.h"
   2 #include "kernel/stat.h"
   3 #include "user/user.h"
   4 
   5 #include <stdarg.h>
   6 
   7 static char digits[] = "0123456789ABCDEF";
   8 
   9 static void
  10 putc(int fd, char c)
  11 {
  12   write(fd, &c, 1);
  13 }
  14 
  15 static void
  16 printint(int fd, int xx, int base, int sgn)
  17 {
  18   char buf[16];
  19   int i, neg;
  20   uint x;
  21 
  22   neg = 0;
  23   if(sgn && xx < 0){
  24     neg = 1;
  25     x = -xx;
  26   } else {
  27     x = xx;
  28   }
  29 
  30   i = 0;
  31   do{
  32     buf[i++] = digits[x % base];
  33   }while((x /= base) != 0);
  34   if(neg)
  35     buf[i++] = '-';
  36 
  37   while(--i >= 0)
  38     putc(fd, buf[i]);
  39 }
  40 
  41 static void
  42 printptr(int fd, uint64 x) {
  43   int i;
  44   putc(fd, '0');
  45   putc(fd, 'x');
  46   for (i = 0; i < (sizeof(uint64) * 2); i++, x <<= 4)
  47     putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]);
  48 }
  49 
  50 // Print to the given fd. Only understands %d, %x, %p, %s.
  51 void
  52 vprintf(int fd, const char *fmt, va_list ap)
  53 {
  54   char *s;
  55   int c, i, state;
  56 
  57   state = 0;
  58   for(i = 0; fmt[i]; i++){
  59     c = fmt[i] & 0xff;
  60     if(state == 0){
  61       if(c == '%'){
  62         state = '%';
  63       } else {
  64         putc(fd, c);
  65       }
  66     } else if(state == '%'){
  67       if(c == 'd'){
  68         printint(fd, va_arg(ap, int), 10, 1);
  69       } else if(c == 'l') {
  70         printint(fd, va_arg(ap, uint64), 10, 0);
  71       } else if(c == 'x') {
  72         printint(fd, va_arg(ap, int), 16, 0);
  73       } else if(c == 'p') {
  74         printptr(fd, va_arg(ap, uint64));
  75       } else if(c == 's'){
  76         s = va_arg(ap, char*);
  77         if(s == 0)
  78           s = "(null)";
  79         while(*s != 0){
  80           putc(fd, *s);
  81           s++;
  82         }
  83       } else if(c == 'c'){
  84         putc(fd, va_arg(ap, uint));
  85       } else if(c == '%'){
  86         putc(fd, c);
  87       } else {
  88         // Unknown % sequence.  Print it to draw attention.
  89         putc(fd, '%');
  90         putc(fd, c);
  91       }
  92       state = 0;
  93     }
  94   }
  95 }
  96 
  97 void
  98 fprintf(int fd, const char *fmt, ...)
  99 {
 100   va_list ap;
 101 
 102   va_start(ap, fmt);
 103   vprintf(fd, fmt, ap);
 104 }
 105 
 106 void
 107 printf(const char *fmt, ...)
 108 {
 109   va_list ap;
 110 
 111   va_start(ap, fmt);
 112   vprintf(1, fmt, ap);
 113 }

/* [<][>][^][v][top][bottom][index][help] */