xref: /linux/drivers/firmware/efi/libstub/vsprintf.c (revision 1b8b67503725fa6deb3a4f00ea61f982bd00c152)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* -*- linux-c -*- ------------------------------------------------------- *
3  *
4  *   Copyright (C) 1991, 1992 Linus Torvalds
5  *   Copyright 2007 rPath, Inc. - All Rights Reserved
6  *
7  * ----------------------------------------------------------------------- */
8 
9 /*
10  * Oh, it's a waste of space, but oh-so-yummy for debugging.
11  */
12 
13 #include <linux/stdarg.h>
14 
15 #include <linux/compiler.h>
16 #include <linux/ctype.h>
17 #include <linux/efi.h>
18 #include <linux/kernel.h>
19 #include <linux/limits.h>
20 #include <linux/string.h>
21 #include <linux/types.h>
22 #include <linux/ucs2_string.h>
23 
24 #include "efistub.h"
25 
26 static
27 int skip_atoi(const char **s)
28 {
29 	int i = 0;
30 
31 	while (isdigit(**s))
32 		i = i * 10 + *((*s)++) - '0';
33 	return i;
34 }
35 
36 /*
37  * put_dec_full4 handles numbers in the range 0 <= r < 10000.
38  * The multiplier 0xccd is round(2^15/10), and the approximation
39  * r/10 == (r * 0xccd) >> 15 is exact for all r < 16389.
40  */
41 static
42 void put_dec_full4(char *end, unsigned int r)
43 {
44 	int i;
45 
46 	for (i = 0; i < 3; i++) {
47 		unsigned int q = (r * 0xccd) >> 15;
48 		*--end = '0' + (r - q * 10);
49 		r = q;
50 	}
51 	*--end = '0' + r;
52 }
53 
54 /* put_dec is copied from lib/vsprintf.c with small modifications */
55 
56 /*
57  * Call put_dec_full4 on x % 10000, return x / 10000.
58  * The approximation x/10000 == (x * 0x346DC5D7) >> 43
59  * holds for all x < 1,128,869,999.  The largest value this
60  * helper will ever be asked to convert is 1,125,520,955.
61  * (second call in the put_dec code, assuming n is all-ones).
62  */
63 static
64 unsigned int put_dec_helper4(char *end, unsigned int x)
65 {
66 	unsigned int q = (x * 0x346DC5D7ULL) >> 43;
67 
68 	put_dec_full4(end, x - q * 10000);
69 	return q;
70 }
71 
72 /* Based on code by Douglas W. Jones found at
73  * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
74  * (with permission from the author).
75  * Performs no 64-bit division and hence should be fast on 32-bit machines.
76  */
77 static
78 char *put_dec(char *end, unsigned long long n)
79 {
80 	unsigned int d3, d2, d1, q, h;
81 	char *p = end;
82 
83 	d1  = ((unsigned int)n >> 16); /* implicit "& 0xffff" */
84 	h   = (n >> 32);
85 	d2  = (h      ) & 0xffff;
86 	d3  = (h >> 16); /* implicit "& 0xffff" */
87 
88 	/* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
89 	     = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
90 	q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((unsigned int)n & 0xffff);
91 	q = put_dec_helper4(p, q);
92 	p -= 4;
93 
94 	q += 7671 * d3 + 9496 * d2 + 6 * d1;
95 	q = put_dec_helper4(p, q);
96 	p -= 4;
97 
98 	q += 4749 * d3 + 42 * d2;
99 	q = put_dec_helper4(p, q);
100 	p -= 4;
101 
102 	q += 281 * d3;
103 	q = put_dec_helper4(p, q);
104 	p -= 4;
105 
106 	put_dec_full4(p, q);
107 	p -= 4;
108 
109 	/* strip off the extra 0's we printed */
110 	while (p < end && *p == '0')
111 		++p;
112 
113 	return p;
114 }
115 
116 /* we are called with base 8, 10 or 16, only, thus don't need "G..."  */
117 static const char digits[16] = "0123456789ABCDEF"; /* "GHIJKLMNOPQRSTUVWXYZ"; */
118 
119 static
120 char *number(char *end, unsigned long long num, int base, char locase)
121 {
122 	/*
123 	 * locase = 0 or 0x20. ORing digits or letters with 'locase'
124 	 * produces same digits or (maybe lowercased) letters
125 	 */
126 
127 	switch (base) {
128 	case 10:
129 		if (num != 0)
130 			end = put_dec(end, num);
131 		break;
132 	case 8:
133 		for (; num != 0; num >>= 3)
134 			*--end = '0' + (num & 07);
135 		break;
136 	case 16:
137 		for (; num != 0; num >>= 4)
138 			*--end = digits[num & 0xf] | locase;
139 		break;
140 	default:
141 		unreachable();
142 	}
143 
144 	return end;
145 }
146 
147 static char *guid_to_str(const efi_guid_t *guid, char *out, char locase)
148 {
149 	static const u8 guid_index[UUID_SIZE] = {
150 		3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15,
151 	};
152 
153 	for (int i = 0, p = 0; i < ARRAY_SIZE(guid_index); i++) {
154 		u8 byte = guid->b[guid_index[i]];
155 
156 		out[p++] = locase | digits[byte >> 4];
157 		out[p++] = locase | digits[byte & 0xf];
158 
159 		switch (i) {
160 		case 3:
161 		case 5:
162 		case 7:
163 		case 9:
164 			out[p++] = '-';
165 		}
166 	}
167 	return out;
168 }
169 
170 #define ZEROPAD	1		/* pad with zero */
171 #define SIGN	2		/* unsigned/signed long */
172 #define PLUS	4		/* show plus */
173 #define SPACE	8		/* space if plus */
174 #define LEFT	16		/* left justified */
175 #define SMALL	32		/* Must be 32 == 0x20 */
176 #define SPECIAL	64		/* 0x */
177 #define WIDE	128		/* UTF-16 string */
178 
179 static
180 int get_flags(const char **fmt)
181 {
182 	int flags = 0;
183 
184 	do {
185 		switch (**fmt) {
186 		case '-':
187 			flags |= LEFT;
188 			break;
189 		case '+':
190 			flags |= PLUS;
191 			break;
192 		case ' ':
193 			flags |= SPACE;
194 			break;
195 		case '#':
196 			flags |= SPECIAL;
197 			break;
198 		case '0':
199 			flags |= ZEROPAD;
200 			break;
201 		default:
202 			return flags;
203 		}
204 		++(*fmt);
205 	} while (1);
206 }
207 
208 static
209 int get_int(const char **fmt, va_list *ap)
210 {
211 	if (isdigit(**fmt))
212 		return skip_atoi(fmt);
213 	if (**fmt == '*') {
214 		++(*fmt);
215 		/* it's the next argument */
216 		return va_arg(*ap, int);
217 	}
218 	return 0;
219 }
220 
221 static
222 unsigned long long get_number(int sign, int qualifier, va_list *ap)
223 {
224 	if (sign) {
225 		switch (qualifier) {
226 		case 'L':
227 			return va_arg(*ap, long long);
228 		case 'l':
229 			return va_arg(*ap, long);
230 		case 'h':
231 			return (short)va_arg(*ap, int);
232 		case 'H':
233 			return (signed char)va_arg(*ap, int);
234 		default:
235 			return va_arg(*ap, int);
236 		};
237 	} else {
238 		switch (qualifier) {
239 		case 'L':
240 			return va_arg(*ap, unsigned long long);
241 		case 'l':
242 			return va_arg(*ap, unsigned long);
243 		case 'h':
244 			return (unsigned short)va_arg(*ap, int);
245 		case 'H':
246 			return (unsigned char)va_arg(*ap, int);
247 		default:
248 			return va_arg(*ap, unsigned int);
249 		}
250 	}
251 }
252 
253 static
254 char get_sign(long long *num, int flags)
255 {
256 	if (!(flags & SIGN))
257 		return 0;
258 	if (*num < 0) {
259 		*num = -(*num);
260 		return '-';
261 	}
262 	if (flags & PLUS)
263 		return '+';
264 	if (flags & SPACE)
265 		return ' ';
266 	return 0;
267 }
268 
269 #define PUTC(c) \
270 do {				\
271 	if (pos < size)		\
272 		buf[pos] = (c);	\
273 	++pos;			\
274 } while (0);
275 
276 int efi_vsnprintf(efi_char16_t *buf, size_t size, const char *fmt, va_list ap,
277 		  bool crlf)
278 {
279 	char tmp[UUID_STRING_LEN];
280 	char *tmp_end = &tmp[ARRAY_SIZE(tmp)];
281 	long long num;
282 	int base;
283 	const char *s;
284 	size_t len, pos;
285 	char sign;
286 
287 	int flags;		/* flags to number() */
288 
289 	int field_width;	/* width of output field */
290 	int precision;		/* min. # of digits for integers; max
291 				   number of chars for from string */
292 	int qualifier;		/* 'h', 'hh', 'l' or 'll' for integer fields */
293 
294 	va_list args;
295 
296 	/*
297 	 * We want to pass our input va_list to helper functions by reference,
298 	 * but there's an annoying edge case. If va_list was originally passed
299 	 * to us by value, we could just pass &ap down to the helpers. This is
300 	 * the case on, for example, X86_32.
301 	 * However, on X86_64 (and possibly others), va_list is actually a
302 	 * size-1 array containing a structure. Our function parameter ap has
303 	 * decayed from T[1] to T*, and &ap has type T** rather than T(*)[1],
304 	 * which is what will be expected by a function taking a va_list *
305 	 * parameter.
306 	 * One standard way to solve this mess is by creating a copy in a local
307 	 * variable of type va_list and then passing a pointer to that local
308 	 * copy instead, which is what we do here.
309 	 */
310 	va_copy(args, ap);
311 
312 	for (pos = 0; *fmt; ++fmt) {
313 		if (*fmt != '%' || *++fmt == '%') {
314 			if (crlf && *fmt == '\n')
315 				PUTC('\r');
316 			PUTC(*fmt);
317 			continue;
318 		}
319 
320 		/* process flags */
321 		flags = get_flags(&fmt);
322 
323 		/* get field width */
324 		field_width = get_int(&fmt, &args);
325 		if (field_width < 0) {
326 			field_width = -field_width;
327 			flags |= LEFT;
328 		}
329 
330 		if (flags & LEFT)
331 			flags &= ~ZEROPAD;
332 
333 		/* get the precision */
334 		precision = -1;
335 		if (*fmt == '.') {
336 			++fmt;
337 			precision = get_int(&fmt, &args);
338 			if (precision >= 0)
339 				flags &= ~ZEROPAD;
340 		}
341 
342 		/* get the conversion qualifier */
343 		qualifier = -1;
344 		if (*fmt == 'h' || *fmt == 'l') {
345 			qualifier = *fmt;
346 			++fmt;
347 			if (qualifier == *fmt) {
348 				qualifier -= 'a'-'A';
349 				++fmt;
350 			}
351 		}
352 
353 		sign = 0;
354 
355 		switch (*fmt) {
356 		case 'c':
357 			flags &= LEFT;
358 			s = tmp;
359 			if (qualifier == 'l') {
360 				((u16 *)tmp)[0] = (u16)va_arg(args, unsigned int);
361 				((u16 *)tmp)[1] = L'\0';
362 				precision = INT_MAX;
363 				goto wstring;
364 			} else {
365 				tmp[0] = (unsigned char)va_arg(args, int);
366 				precision = len = 1;
367 			}
368 			goto output;
369 
370 		case 's':
371 			flags &= LEFT;
372 			if (precision < 0)
373 				precision = INT_MAX;
374 			s = va_arg(args, void *);
375 			if (!s)
376 				s = precision < 6 ? "" : "(null)";
377 			else if (qualifier == 'l') {
378 		wstring:
379 				flags |= WIDE;
380 				precision = len = ucs2_strnlen((const u16 *)s, precision);
381 				goto output;
382 			}
383 			precision = len = strnlen(s, precision);
384 			goto output;
385 
386 			/* integer number formats - set up the flags and "break" */
387 		case 'o':
388 			base = 8;
389 			break;
390 
391 		case 'p':
392 			if (fmt[1] == 'U' && (fmt[2] | 0x20) == 'l') {
393 				flags &= LEFT;
394 				s = guid_to_str(va_arg(args, efi_guid_t *), tmp, fmt[2] & 0x20);
395 				precision = len = UUID_STRING_LEN;
396 				fmt += 2;
397 				goto output;
398 			}
399 
400 			if (precision < 0)
401 				precision = 2 * sizeof(void *);
402 			fallthrough;
403 		case 'x':
404 			flags |= SMALL;
405 			fallthrough;
406 		case 'X':
407 			base = 16;
408 			break;
409 
410 		case 'd':
411 		case 'i':
412 			flags |= SIGN;
413 			fallthrough;
414 		case 'u':
415 			flags &= ~SPECIAL;
416 			base = 10;
417 			break;
418 
419 		default:
420 			/*
421 			 * Bail out if the conversion specifier is invalid.
422 			 * There's probably a typo in the format string and the
423 			 * remaining specifiers are unlikely to match up with
424 			 * the arguments.
425 			 */
426 			goto fail;
427 		}
428 		if (*fmt == 'p') {
429 			num = (unsigned long)va_arg(args, void *);
430 		} else {
431 			num = get_number(flags & SIGN, qualifier, &args);
432 		}
433 
434 		sign = get_sign(&num, flags);
435 		if (sign)
436 			--field_width;
437 
438 		s = number(tmp_end, num, base, flags & SMALL);
439 		len = tmp_end - s;
440 		/* default precision is 1 */
441 		if (precision < 0)
442 			precision = 1;
443 		/* precision is minimum number of digits to print */
444 		if (precision < len)
445 			precision = len;
446 		if (flags & SPECIAL) {
447 			/*
448 			 * For octal, a leading 0 is printed only if necessary,
449 			 * i.e. if it's not already there because of the
450 			 * precision.
451 			 */
452 			if (base == 8 && precision == len)
453 				++precision;
454 			/*
455 			 * For hexadecimal, the leading 0x is skipped if the
456 			 * output is empty, i.e. both the number and the
457 			 * precision are 0.
458 			 */
459 			if (base == 16 && precision > 0)
460 				field_width -= 2;
461 			else
462 				flags &= ~SPECIAL;
463 		}
464 		/*
465 		 * For zero padding, increase the precision to fill the field
466 		 * width.
467 		 */
468 		if ((flags & ZEROPAD) && field_width > precision)
469 			precision = field_width;
470 
471 output:
472 		/* Calculate the padding necessary */
473 		field_width -= precision;
474 		/* Leading padding with ' ' */
475 		if (!(flags & LEFT))
476 			while (field_width-- > 0)
477 				PUTC(' ');
478 		/* sign */
479 		if (sign)
480 			PUTC(sign);
481 		/* 0x/0X for hexadecimal */
482 		if (flags & SPECIAL) {
483 			PUTC('0');
484 			PUTC( 'X' | (flags & SMALL));
485 		}
486 		/* Zero padding and excess precision */
487 		while (precision-- > len)
488 			PUTC('0');
489 		/* Actual output */
490 		if (flags & WIDE) {
491 			const u16 *ws = (const u16 *)s;
492 
493 			if (pos < size)
494 				memcpy(&buf[pos], ws, min(len, size - pos) * sizeof(*ws));
495 			pos += len;
496 		} else {
497 			while (len-- > 0)
498 				PUTC(*s++);
499 		}
500 		/* Trailing padding with ' ' */
501 		while (field_width-- > 0)
502 			PUTC(' ');
503 	}
504 fail:
505 	va_end(args);
506 
507 	if (size)
508 		buf[min(pos, size-1)] = '\0';
509 
510 	return pos;
511 }
512 
513 int efi_snprintf(efi_char16_t *buf, size_t size, const char *fmt, ...)
514 {
515 	va_list args;
516 	int i;
517 
518 	va_start(args, fmt);
519 	i = efi_vsnprintf(buf, size, fmt, args, false);
520 	va_end(args);
521 	return i;
522 }
523