/*1* Copyright (c) 1997, 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2008, 20092* The President and Fellows of Harvard College.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12* 3. Neither the name of the University nor the names of its contributors13* may be used to endorse or promote products derived from this software14* without specific prior written permission.15*16* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND17* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE18* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE19* ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE20* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL21* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS22* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)23* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT24* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY25* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF26* SUCH DAMAGE.27*/2829/*30* Guts of printf.31*32* This file is used in both libc and the kernel and needs to work in both33* contexts. This makes a few things a bit awkward.34*35* This is a slightly simplified version of the real-life printf36* originally used in the VINO kernel.37*/3839#ifdef _KERNEL40#include <types.h>41#include <lib.h>42#define assert KASSERT43#else4445#include <sys/types.h>46#include <assert.h>47#include <stdint.h>48#include <stdio.h>49#include <string.h>50#endif5152#include <stdarg.h>535455/*56* Do we want to support "long long" types with %lld?57*58* Using 64-bit types with gcc causes gcc to emit calls to functions59* like __moddi3 and __divdi3. These need to be provided at link time,60* which can be a hassle; this switch is provided to help avoid61* needing them.62*/63#define USE_LONGLONG6465/*66* Define a type that holds the longest signed integer we intend to support.67*/68#ifdef USE_LONGLONG69#define INTTYPE long long70#else71#define INTTYPE long72#endif737475/*76* Space for a long long in base 8, plus a NUL, plus one77* character extra for slop.78*79* CHAR_BIT is the number of bits in a char; thus sizeof(long long)*CHAR_BIT80* is the number of bits in a long long. Each octal digit prints 3 bits.81* Values printed in larger bases will be shorter strings.82*/83#define NUMBER_BUF_SIZE ((sizeof(INTTYPE) * CHAR_BIT) / 3 + 2)8485/*86* Structure holding the state for printf.87*/88typedef struct {89/* Callback for sending printed string data */90void (*sendfunc)(void *clientdata, const char *str, size_t len);91void *clientdata;9293/* The varargs argument pointer */94va_list ap;9596/* Total count of characters printed */97int charcount;9899/* Flag that's true if we are currently looking in a %-format */100int in_pct;101102/* Size of the integer argument to retrieve */103enum {104INTSZ,105LONGSZ,106#ifdef USE_LONGLONG107LLONGSZ,108#endif109} size;110111/* The value of the integer argument retrieved */112unsigned INTTYPE num;113114/* Sign of the integer argument (0 = positive; -1 = negative) */115int sign;116117/* Field width (number of spaces) */118int spacing;119120/* Flag: align to left in field instead of right */121int rightspc;122123/* Character to pad to field size with (space or 0) */124int fillchar;125126/* Number base to print the integer argument in (8, 10, 16) */127int base;128129/* Flag: if set, print 0x before hex and 0 before octal numbers */130int baseprefix;131132/* Flag: alternative output format selected with %#... */133int altformat;134} PF;135136/*137* Send some text onward to the output.138*139* We count the total length we send out so we can return it from __vprintf,140* since that's what most printf-like functions want to return.141*/142static143void144__pf_print(PF *pf, const char *txt, size_t len)145{146pf->sendfunc(pf->clientdata, txt, len);147pf->charcount += len;148}149150/*151* Reset the state for the next %-field.152*/153static154void155__pf_endfield(PF *pf)156{157pf->in_pct = 0;158pf->size = INTSZ;159pf->num = 0;160pf->sign = 0;161pf->spacing = 0;162pf->rightspc = 0;163pf->fillchar = ' ';164pf->base = 0;165pf->baseprefix = 0;166pf->altformat = 0;167}168169/*170* Process modifier chars (between the % and the type specifier)171* # use "alternate display format"172* - left align in field instead of right align173* l value is long (ll = long long)174* 0-9 field width175* leading 0 pad with zeros instead of spaces176*/177static178void179__pf_modifier(PF *pf, int ch)180{181switch (ch) {182case '#':183pf->altformat = 1;184break;185case '-':186pf->rightspc = 1;187break;188case 'l':189if (pf->size==LONGSZ) {190#ifdef USE_LONGLONG191pf->size = LLONGSZ;192#endif193}194else {195pf->size = LONGSZ;196}197break;198case '0':199if (pf->spacing>0) {200/*201* Already seen some digits; this is part of the202* field size.203*/204pf->spacing = pf->spacing*10;205}206else {207/*208* Leading zero; set the padding character to 0.209*/210pf->fillchar = '0';211}212break;213default:214/*215* Invalid characters should be filtered out by a216* higher-level function, so if this assert goes off217* it's our fault.218*/219assert(ch>'0' && ch<='9');220221/*222* Got a digit; accumulate the field size.223*/224pf->spacing = pf->spacing*10 + (ch-'0');225break;226}227}228229/*230* Retrieve a numeric argument from the argument list and store it231* in pf->num, according to the size recorded in pf->size and using232* the numeric type specified by ch.233*/234static235void236__pf_getnum(PF *pf, int ch)237{238if (ch=='p') {239/*240* Pointer.241*242* uintptr_t is a C99 standard type that's an unsigned243* integer the same size as a pointer.244*/245pf->num = (uintptr_t) va_arg(pf->ap, void *);246}247else if (ch=='d') {248/* signed integer */249INTTYPE signednum=0;250switch (pf->size) {251case INTSZ:252/* %d */253signednum = va_arg(pf->ap, int);254break;255case LONGSZ:256/* %ld */257signednum = va_arg(pf->ap, long);258break;259#ifdef USE_LONGLONG260case LLONGSZ:261/* %lld */262signednum = va_arg(pf->ap, long long);263break;264#endif265}266267/*268* Check for negative numbers.269*/270if (signednum < 0) {271pf->sign = -1;272pf->num = -signednum;273}274else {275pf->num = signednum;276}277}278else {279/* unsigned integer */280switch (pf->size) {281case INTSZ:282/* %u (or %o, %x) */283pf->num = va_arg(pf->ap, unsigned int);284break;285case LONGSZ:286/* %lu (or %lo, %lx) */287pf->num = va_arg(pf->ap, unsigned long);288break;289#ifdef USE_LONGLONG290case LLONGSZ:291/* %llu, %llo, %llx */292pf->num = va_arg(pf->ap, unsigned long long);293break;294#endif295}296}297}298299/*300* Set the printing base based on the numeric type specified in ch.301* %o octal302* %d,%u decimal303* %x hex304* %p pointer (print as hex)305*306* If the "alternate format" was requested, or always for pointers,307* note to print the C prefix for the type.308*/309static310void311__pf_setbase(PF *pf, int ch)312{313switch (ch) {314case 'd':315case 'u':316pf->base = 10;317break;318case 'x':319case 'p':320pf->base = 16;321break;322case 'o':323pf->base = 8;324break;325}326if (pf->altformat || ch=='p') {327pf->baseprefix = 1;328}329}330331/*332* Function to print "spc" instances of the fill character.333*/334static335void336__pf_fill(PF *pf, int spc)337{338char f = pf->fillchar;339int i;340for (i=0; i<spc; i++) {341__pf_print(pf, &f, 1);342}343}344345/*346* General printing function. Prints the string "stuff".347* The two prefixes (in practice one is a type prefix, such as "0x",348* and the other is the sign) get printed *after* space padding but349* *before* zero padding, if padding is on the left.350*/351static352void353__pf_printstuff(PF *pf,354const char *prefix, const char *prefix2,355const char *stuff)356{357/* Total length to print. */358int len = strlen(prefix)+strlen(prefix2)+strlen(stuff);359360/* Get field width and compute amount of padding in "spc". */361int spc = pf->spacing;362if (spc > len) {363spc -= len;364}365else {366spc = 0;367}368369/* If padding on left and the fill char is not 0, pad first. */370if (spc > 0 && pf->rightspc==0 && pf->fillchar!='0') {371__pf_fill(pf, spc);372}373374/* Print the prefixes. */375__pf_print(pf, prefix, strlen(prefix));376__pf_print(pf, prefix2, strlen(prefix2));377378/* If padding on left and the fill char *is* 0, pad here. */379if (spc > 0 && pf->rightspc==0 && pf->fillchar=='0') {380__pf_fill(pf, spc);381}382383/* Print the actual string. */384__pf_print(pf, stuff, strlen(stuff));385386/* If padding on the right, pad afterwards. */387if (spc > 0 && pf->rightspc!=0) {388__pf_fill(pf, spc);389}390}391392/*393* Function to convert a number to ascii and then print it.394*395* Works from right to left in a buffer of NUMBER_BUF_SIZE bytes.396* NUMBER_BUF_SIZE is set so that the longest number string we can397* generate (a long long printed in octal) will fit. See above.398*/399static400void401__pf_printnum(PF *pf)402{403/* Digits to print with. */404const char *const digits = "0123456789abcdef";405406char buf[NUMBER_BUF_SIZE]; /* Accumulation buffer for string. */407char *x; /* Current pointer into buf. */408unsigned INTTYPE xnum; /* Current value to print. */409const char *bprefix; /* Base prefix (0, 0x, or nothing) */410const char *sprefix; /* Sign prefix (- or nothing) */411412/* Start in the last slot of the buffer. */413x = buf+sizeof(buf)-1;414415/* Insert null terminator. */416*x-- = 0;417418/* Initialize value. */419xnum = pf->num;420421/*422* Convert a single digit.423* Do this loop at least once - that way 0 prints as 0 and not "".424*/425do {426/*427* Get the digit character for the least significant428* part of xnum.429*/430*x = digits[xnum % pf->base];431432/*433* Back up the pointer to point to the next space to the left.434*/435x--;436437/*438* Drop the value of the digit we just printed from xnum.439*/440xnum = xnum / pf->base;441442/*443* If xnum hits 0 there's no more number left.444*/445} while (xnum > 0);446447/*448* x points to the *next* slot in the buffer to use.449* However, we're done printing the number. So it's pointing450* one slot *before* the start of the actual number text.451* So advance it by one so it actually points at the number.452*/453x++;454455/*456* If a base prefix was requested, select it.457*/458if (pf->baseprefix && pf->base==16) {459bprefix = "0x";460}461else if (pf->baseprefix && pf->base==8) {462bprefix = "0";463}464else {465bprefix = "";466}467468/*469* Choose the sign prefix.470*/471sprefix = pf->sign ? "-" : "";472473/*474* Now actually print the string we just generated.475*/476__pf_printstuff(pf, sprefix, bprefix, x);477}478479/*480* Process a single character out of the format string.481*/482static483void484__pf_send(PF *pf, int ch)485{486/* Cannot get NULs here. */487assert(ch!=0);488489if (pf->in_pct==0 && ch!='%') {490/*491* Not currently in a format, and not a %. Just send492* the character on through.493*/494char c = ch;495__pf_print(pf, &c, 1);496}497else if (pf->in_pct==0) {498/*499* Not in a format, but got a %. Start a format.500*/501pf->in_pct = 1;502}503else if (strchr("#-l0123456789", ch)) {504/*505* These are the modifier characters we recognize.506* (These are the characters between the % and the type.)507*/508__pf_modifier(pf, ch);509}510else if (strchr("doupx", ch)) {511/*512* Integer types.513* Fetch the number, set the base, print it, then514* reset for the next format.515*/516__pf_getnum(pf, ch);517__pf_setbase(pf, ch);518__pf_printnum(pf);519__pf_endfield(pf);520}521else if (ch=='s') {522/*523* Print a string.524*/525const char *str = va_arg(pf->ap, const char *);526if (str==NULL) {527str = "(null)";528}529__pf_printstuff(pf, "", "", str);530__pf_endfield(pf);531}532else {533/*534* %%, %c, or illegal character.535* Illegal characters are printed like %%.536* for example, %5k prints " k".537*/538char x[2];539if (ch=='c') {540x[0] = va_arg(pf->ap, int);541}542else {543x[0] = ch;544}545x[1] = 0;546__pf_printstuff(pf, "", "", x);547__pf_endfield(pf);548}549}550551/*552* Do a whole printf session.553* Create and initialize a printf state object,554* then send it each character from the format string.555*/556int557__vprintf(void (*func)(void *clientdata, const char *str, size_t len),558void *clientdata, const char *format, va_list ap)559{560PF pf;561int i;562563pf.sendfunc = func;564pf.clientdata = clientdata;565pf.ap = ap;566pf.charcount = 0;567__pf_endfield(&pf);568569for (i=0; format[i]; i++) {570__pf_send(&pf, format[i]);571}572573return pf.charcount;574}575576577