Path: blob/master/drivers/firmware/efi/libstub/vsprintf.c
26483 views
// SPDX-License-Identifier: GPL-2.0-only1/* -*- linux-c -*- ------------------------------------------------------- *2*3* Copyright (C) 1991, 1992 Linus Torvalds4* Copyright 2007 rPath, Inc. - All Rights Reserved5*6* ----------------------------------------------------------------------- */78/*9* Oh, it's a waste of space, but oh-so-yummy for debugging.10*/1112#include <linux/stdarg.h>1314#include <linux/compiler.h>15#include <linux/ctype.h>16#include <linux/kernel.h>17#include <linux/limits.h>18#include <linux/string.h>19#include <linux/types.h>2021static22int skip_atoi(const char **s)23{24int i = 0;2526while (isdigit(**s))27i = i * 10 + *((*s)++) - '0';28return i;29}3031/*32* put_dec_full4 handles numbers in the range 0 <= r < 10000.33* The multiplier 0xccd is round(2^15/10), and the approximation34* r/10 == (r * 0xccd) >> 15 is exact for all r < 16389.35*/36static37void put_dec_full4(char *end, unsigned int r)38{39int i;4041for (i = 0; i < 3; i++) {42unsigned int q = (r * 0xccd) >> 15;43*--end = '0' + (r - q * 10);44r = q;45}46*--end = '0' + r;47}4849/* put_dec is copied from lib/vsprintf.c with small modifications */5051/*52* Call put_dec_full4 on x % 10000, return x / 10000.53* The approximation x/10000 == (x * 0x346DC5D7) >> 4354* holds for all x < 1,128,869,999. The largest value this55* helper will ever be asked to convert is 1,125,520,955.56* (second call in the put_dec code, assuming n is all-ones).57*/58static59unsigned int put_dec_helper4(char *end, unsigned int x)60{61unsigned int q = (x * 0x346DC5D7ULL) >> 43;6263put_dec_full4(end, x - q * 10000);64return q;65}6667/* Based on code by Douglas W. Jones found at68* <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>69* (with permission from the author).70* Performs no 64-bit division and hence should be fast on 32-bit machines.71*/72static73char *put_dec(char *end, unsigned long long n)74{75unsigned int d3, d2, d1, q, h;76char *p = end;7778d1 = ((unsigned int)n >> 16); /* implicit "& 0xffff" */79h = (n >> 32);80d2 = (h ) & 0xffff;81d3 = (h >> 16); /* implicit "& 0xffff" */8283/* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d084= 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */85q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((unsigned int)n & 0xffff);86q = put_dec_helper4(p, q);87p -= 4;8889q += 7671 * d3 + 9496 * d2 + 6 * d1;90q = put_dec_helper4(p, q);91p -= 4;9293q += 4749 * d3 + 42 * d2;94q = put_dec_helper4(p, q);95p -= 4;9697q += 281 * d3;98q = put_dec_helper4(p, q);99p -= 4;100101put_dec_full4(p, q);102p -= 4;103104/* strip off the extra 0's we printed */105while (p < end && *p == '0')106++p;107108return p;109}110111static112char *number(char *end, unsigned long long num, int base, char locase)113{114/*115* locase = 0 or 0x20. ORing digits or letters with 'locase'116* produces same digits or (maybe lowercased) letters117*/118119/* we are called with base 8, 10 or 16, only, thus don't need "G..." */120static const char digits[16] = "0123456789ABCDEF"; /* "GHIJKLMNOPQRSTUVWXYZ"; */121122switch (base) {123case 10:124if (num != 0)125end = put_dec(end, num);126break;127case 8:128for (; num != 0; num >>= 3)129*--end = '0' + (num & 07);130break;131case 16:132for (; num != 0; num >>= 4)133*--end = digits[num & 0xf] | locase;134break;135default:136unreachable();137}138139return end;140}141142#define ZEROPAD 1 /* pad with zero */143#define SIGN 2 /* unsigned/signed long */144#define PLUS 4 /* show plus */145#define SPACE 8 /* space if plus */146#define LEFT 16 /* left justified */147#define SMALL 32 /* Must be 32 == 0x20 */148#define SPECIAL 64 /* 0x */149#define WIDE 128 /* UTF-16 string */150151static152int get_flags(const char **fmt)153{154int flags = 0;155156do {157switch (**fmt) {158case '-':159flags |= LEFT;160break;161case '+':162flags |= PLUS;163break;164case ' ':165flags |= SPACE;166break;167case '#':168flags |= SPECIAL;169break;170case '0':171flags |= ZEROPAD;172break;173default:174return flags;175}176++(*fmt);177} while (1);178}179180static181int get_int(const char **fmt, va_list *ap)182{183if (isdigit(**fmt))184return skip_atoi(fmt);185if (**fmt == '*') {186++(*fmt);187/* it's the next argument */188return va_arg(*ap, int);189}190return 0;191}192193static194unsigned long long get_number(int sign, int qualifier, va_list *ap)195{196if (sign) {197switch (qualifier) {198case 'L':199return va_arg(*ap, long long);200case 'l':201return va_arg(*ap, long);202case 'h':203return (short)va_arg(*ap, int);204case 'H':205return (signed char)va_arg(*ap, int);206default:207return va_arg(*ap, int);208};209} else {210switch (qualifier) {211case 'L':212return va_arg(*ap, unsigned long long);213case 'l':214return va_arg(*ap, unsigned long);215case 'h':216return (unsigned short)va_arg(*ap, int);217case 'H':218return (unsigned char)va_arg(*ap, int);219default:220return va_arg(*ap, unsigned int);221}222}223}224225static226char get_sign(long long *num, int flags)227{228if (!(flags & SIGN))229return 0;230if (*num < 0) {231*num = -(*num);232return '-';233}234if (flags & PLUS)235return '+';236if (flags & SPACE)237return ' ';238return 0;239}240241static242size_t utf16s_utf8nlen(const u16 *s16, size_t maxlen)243{244size_t len, clen;245246for (len = 0; len < maxlen && *s16; len += clen) {247u16 c0 = *s16++;248249/* First, get the length for a BMP character */250clen = 1 + (c0 >= 0x80) + (c0 >= 0x800);251if (len + clen > maxlen)252break;253/*254* If this is a high surrogate, and we're already at maxlen, we255* can't include the character if it's a valid surrogate pair.256* Avoid accessing one extra word just to check if it's valid257* or not.258*/259if ((c0 & 0xfc00) == 0xd800) {260if (len + clen == maxlen)261break;262if ((*s16 & 0xfc00) == 0xdc00) {263++s16;264++clen;265}266}267}268269return len;270}271272static273u32 utf16_to_utf32(const u16 **s16)274{275u16 c0, c1;276277c0 = *(*s16)++;278/* not a surrogate */279if ((c0 & 0xf800) != 0xd800)280return c0;281/* invalid: low surrogate instead of high */282if (c0 & 0x0400)283return 0xfffd;284c1 = **s16;285/* invalid: missing low surrogate */286if ((c1 & 0xfc00) != 0xdc00)287return 0xfffd;288/* valid surrogate pair */289++(*s16);290return (0x10000 - (0xd800 << 10) - 0xdc00) + (c0 << 10) + c1;291}292293#define PUTC(c) \294do { \295if (pos < size) \296buf[pos] = (c); \297++pos; \298} while (0);299300int vsnprintf(char *buf, size_t size, const char *fmt, va_list ap)301{302/* The maximum space required is to print a 64-bit number in octal */303char tmp[(sizeof(unsigned long long) * 8 + 2) / 3];304char *tmp_end = &tmp[ARRAY_SIZE(tmp)];305long long num;306int base;307const char *s;308size_t len, pos;309char sign;310311int flags; /* flags to number() */312313int field_width; /* width of output field */314int precision; /* min. # of digits for integers; max315number of chars for from string */316int qualifier; /* 'h', 'hh', 'l' or 'll' for integer fields */317318va_list args;319320/*321* We want to pass our input va_list to helper functions by reference,322* but there's an annoying edge case. If va_list was originally passed323* to us by value, we could just pass &ap down to the helpers. This is324* the case on, for example, X86_32.325* However, on X86_64 (and possibly others), va_list is actually a326* size-1 array containing a structure. Our function parameter ap has327* decayed from T[1] to T*, and &ap has type T** rather than T(*)[1],328* which is what will be expected by a function taking a va_list *329* parameter.330* One standard way to solve this mess is by creating a copy in a local331* variable of type va_list and then passing a pointer to that local332* copy instead, which is what we do here.333*/334va_copy(args, ap);335336for (pos = 0; *fmt; ++fmt) {337if (*fmt != '%' || *++fmt == '%') {338PUTC(*fmt);339continue;340}341342/* process flags */343flags = get_flags(&fmt);344345/* get field width */346field_width = get_int(&fmt, &args);347if (field_width < 0) {348field_width = -field_width;349flags |= LEFT;350}351352if (flags & LEFT)353flags &= ~ZEROPAD;354355/* get the precision */356precision = -1;357if (*fmt == '.') {358++fmt;359precision = get_int(&fmt, &args);360if (precision >= 0)361flags &= ~ZEROPAD;362}363364/* get the conversion qualifier */365qualifier = -1;366if (*fmt == 'h' || *fmt == 'l') {367qualifier = *fmt;368++fmt;369if (qualifier == *fmt) {370qualifier -= 'a'-'A';371++fmt;372}373}374375sign = 0;376377switch (*fmt) {378case 'c':379flags &= LEFT;380s = tmp;381if (qualifier == 'l') {382((u16 *)tmp)[0] = (u16)va_arg(args, unsigned int);383((u16 *)tmp)[1] = L'\0';384precision = INT_MAX;385goto wstring;386} else {387tmp[0] = (unsigned char)va_arg(args, int);388precision = len = 1;389}390goto output;391392case 's':393flags &= LEFT;394if (precision < 0)395precision = INT_MAX;396s = va_arg(args, void *);397if (!s)398s = precision < 6 ? "" : "(null)";399else if (qualifier == 'l') {400wstring:401flags |= WIDE;402precision = len = utf16s_utf8nlen((const u16 *)s, precision);403goto output;404}405precision = len = strnlen(s, precision);406goto output;407408/* integer number formats - set up the flags and "break" */409case 'o':410base = 8;411break;412413case 'p':414if (precision < 0)415precision = 2 * sizeof(void *);416fallthrough;417case 'x':418flags |= SMALL;419fallthrough;420case 'X':421base = 16;422break;423424case 'd':425case 'i':426flags |= SIGN;427fallthrough;428case 'u':429flags &= ~SPECIAL;430base = 10;431break;432433default:434/*435* Bail out if the conversion specifier is invalid.436* There's probably a typo in the format string and the437* remaining specifiers are unlikely to match up with438* the arguments.439*/440goto fail;441}442if (*fmt == 'p') {443num = (unsigned long)va_arg(args, void *);444} else {445num = get_number(flags & SIGN, qualifier, &args);446}447448sign = get_sign(&num, flags);449if (sign)450--field_width;451452s = number(tmp_end, num, base, flags & SMALL);453len = tmp_end - s;454/* default precision is 1 */455if (precision < 0)456precision = 1;457/* precision is minimum number of digits to print */458if (precision < len)459precision = len;460if (flags & SPECIAL) {461/*462* For octal, a leading 0 is printed only if necessary,463* i.e. if it's not already there because of the464* precision.465*/466if (base == 8 && precision == len)467++precision;468/*469* For hexadecimal, the leading 0x is skipped if the470* output is empty, i.e. both the number and the471* precision are 0.472*/473if (base == 16 && precision > 0)474field_width -= 2;475else476flags &= ~SPECIAL;477}478/*479* For zero padding, increase the precision to fill the field480* width.481*/482if ((flags & ZEROPAD) && field_width > precision)483precision = field_width;484485output:486/* Calculate the padding necessary */487field_width -= precision;488/* Leading padding with ' ' */489if (!(flags & LEFT))490while (field_width-- > 0)491PUTC(' ');492/* sign */493if (sign)494PUTC(sign);495/* 0x/0X for hexadecimal */496if (flags & SPECIAL) {497PUTC('0');498PUTC( 'X' | (flags & SMALL));499}500/* Zero padding and excess precision */501while (precision-- > len)502PUTC('0');503/* Actual output */504if (flags & WIDE) {505const u16 *ws = (const u16 *)s;506507while (len-- > 0) {508u32 c32 = utf16_to_utf32(&ws);509u8 *s8;510size_t clen;511512if (c32 < 0x80) {513PUTC(c32);514continue;515}516517/* Number of trailing octets */518clen = 1 + (c32 >= 0x800) + (c32 >= 0x10000);519520len -= clen;521s8 = (u8 *)&buf[pos];522523/* Avoid writing partial character */524PUTC('\0');525pos += clen;526if (pos >= size)527continue;528529/* Set high bits of leading octet */530*s8 = (0xf00 >> 1) >> clen;531/* Write trailing octets in reverse order */532for (s8 += clen; clen; --clen, c32 >>= 6)533*s8-- = 0x80 | (c32 & 0x3f);534/* Set low bits of leading octet */535*s8 |= c32;536}537} else {538while (len-- > 0)539PUTC(*s++);540}541/* Trailing padding with ' ' */542while (field_width-- > 0)543PUTC(' ');544}545fail:546va_end(args);547548if (size)549buf[min(pos, size-1)] = '\0';550551return pos;552}553554int snprintf(char *buf, size_t size, const char *fmt, ...)555{556va_list args;557int i;558559va_start(args, fmt);560i = vsnprintf(buf, size, fmt, args);561va_end(args);562return i;563}564565566