]> jfr.im git - solanum.git/blob - libratbox/src/snprintf.c
Fix a couple more string leaks.
[solanum.git] / libratbox / src / snprintf.c
1
2 /*
3 * Modified and hacked into libratbox by Aaron Sethman <androsyn@ratbox.org>
4 * The original headers are below..
5 * Note that this implementation does not process floating point numbers so
6 * you will likely need to fall back to using sprintf yourself to do those...
7 * $Id: snprintf.c 26092 2008-09-19 15:13:52Z androsyn $
8 */
9
10 /*
11 * linux/lib/vsprintf.c
12 *
13 * Copyright (C) 1991, 1992 Linus Torvalds
14 */
15
16 /* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
17 /*
18 * Wirzenius wrote this portably, Torvalds fucked it up :-)
19 */
20
21 /*
22 * Fri Jul 13 2001 Crutcher Dunnavant <crutcher+kernel@datastacks.com>
23 * - changed to provide snprintf and vsnprintf functions
24 * So Feb 1 16:51:32 CET 2004 Juergen Quade <quade@hsnr.de>
25 * - scnprintf and vscnprintf
26 */
27 #include <libratbox_config.h>
28 #include <ratbox_lib.h>
29
30 static int
31 skip_atoi(const char **s)
32 {
33 int i = 0;
34
35 while(isdigit(**s))
36 i = i * 10 + *((*s)++) - '0';
37 return i;
38 }
39
40 /* Decimal conversion is by far the most typical, and is used
41 * for /proc and /sys data. This directly impacts e.g. top performance
42 * with many processes running. We optimize it for speed
43 * using code from
44 * http://www.cs.uiowa.edu/~jones/bcd/decimal.html
45 * (with permission from the author, Douglas W. Jones). */
46
47 /* Formats correctly any integer in [0,99999].
48 * Outputs from one to five digits depending on input.
49 * On i386 gcc 4.1.2 -O2: ~250 bytes of code. */
50 static char *
51 put_dec_trunc(char *buf, unsigned q)
52 {
53 unsigned d3, d2, d1, d0;
54 d1 = (q >> 4) & 0xf;
55 d2 = (q >> 8) & 0xf;
56 d3 = (q >> 12);
57
58 d0 = 6 * (d3 + d2 + d1) + (q & 0xf);
59 q = (d0 * 0xcd) >> 11;
60 d0 = d0 - 10 * q;
61 *buf++ = d0 + '0'; /* least significant digit */
62 d1 = q + 9 * d3 + 5 * d2 + d1;
63 if(d1 != 0)
64 {
65 q = (d1 * 0xcd) >> 11;
66 d1 = d1 - 10 * q;
67 *buf++ = d1 + '0'; /* next digit */
68
69 d2 = q + 2 * d2;
70 if((d2 != 0) || (d3 != 0))
71 {
72 q = (d2 * 0xd) >> 7;
73 d2 = d2 - 10 * q;
74 *buf++ = d2 + '0'; /* next digit */
75
76 d3 = q + 4 * d3;
77 if(d3 != 0)
78 {
79 q = (d3 * 0xcd) >> 11;
80 d3 = d3 - 10 * q;
81 *buf++ = d3 + '0'; /* next digit */
82 if(q != 0)
83 *buf++ = q + '0'; /* most sign. digit */
84 }
85 }
86 }
87 return buf;
88 }
89
90 /* Same with if's removed. Always emits five digits */
91 static char *
92 put_dec_full(char *buf, unsigned q)
93 {
94 /* BTW, if q is in [0,9999], 8-bit ints will be enough, */
95 /* but anyway, gcc produces better code with full-sized ints */
96 unsigned d3, d2, d1, d0;
97 d1 = (q >> 4) & 0xf;
98 d2 = (q >> 8) & 0xf;
99 d3 = (q >> 12);
100
101 /* Possible ways to approx. divide by 10 */
102 /* gcc -O2 replaces multiply with shifts and adds */
103 // (x * 0xcd) >> 11: 11001101 - shorter code than * 0x67 (on i386)
104 // (x * 0x67) >> 10: 1100111
105 // (x * 0x34) >> 9: 110100 - same
106 // (x * 0x1a) >> 8: 11010 - same
107 // (x * 0x0d) >> 7: 1101 - same, shortest code (on i386)
108
109 d0 = 6 * (d3 + d2 + d1) + (q & 0xf);
110 q = (d0 * 0xcd) >> 11;
111 d0 = d0 - 10 * q;
112 *buf++ = d0 + '0';
113 d1 = q + 9 * d3 + 5 * d2 + d1;
114 q = (d1 * 0xcd) >> 11;
115 d1 = d1 - 10 * q;
116 *buf++ = d1 + '0';
117
118 d2 = q + 2 * d2;
119 q = (d2 * 0xd) >> 7;
120 d2 = d2 - 10 * q;
121 *buf++ = d2 + '0';
122
123 d3 = q + 4 * d3;
124 q = (d3 * 0xcd) >> 11; /* - shorter code */
125 /* q = (d3 * 0x67) >> 10; - would also work */
126 d3 = d3 - 10 * q;
127 *buf++ = d3 + '0';
128 *buf++ = q + '0';
129 return buf;
130 }
131
132 static char *
133 put_dec(char *buf, unsigned long long int num)
134 {
135 while(1)
136 {
137 unsigned rem;
138 if(num < 100000)
139 return put_dec_trunc(buf, num);
140 rem = num % 100000;
141 num = num / 100000;
142 buf = put_dec_full(buf, rem);
143 }
144 }
145
146 #define ZEROPAD 1 /* pad with zero */
147 #define SIGN 2 /* unsigned/signed long */
148 #define PLUS 4 /* show plus */
149 #define SPACE 8 /* space if plus */
150 #define LEFT 16 /* left justified */
151 #define SPECIAL 32 /* 0x */
152 #define LARGE 64 /* use 'ABCDEF' instead of 'abcdef' */
153
154 static size_t
155 number(char *const buf, const size_t size, size_t idx, unsigned long long int num, int base, int field_width, int precision,
156 int type)
157 {
158 char sign, tmp[66];
159 const char *digits;
160 /* we are called with base 8, 10 or 16, only, thus don't need "g..." */
161 static const char small_digits[] = "0123456789abcdefx"; /* "ghijklmnopqrstuvwxyz"; */
162 static const char large_digits[] = "0123456789ABCDEFX"; /* "GHIJKLMNOPQRSTUVWXYZ"; */
163 int need_pfx = ((type & SPECIAL) && base != 10);
164 int i;
165
166 digits = (type & LARGE) ? large_digits : small_digits;
167 if(type & LEFT)
168 type &= ~ZEROPAD;
169 if(base < 2 || base > 36)
170 return idx;
171 sign = 0;
172 if(type & SIGN)
173 {
174 if((signed long long int)num < 0)
175 {
176 sign = '-';
177 num = -(signed long long int)num;
178 field_width--;
179 }
180 else if(type & PLUS)
181 {
182 sign = '+';
183 field_width--;
184 }
185 else if(type & SPACE)
186 {
187 sign = ' ';
188 field_width--;
189 }
190 }
191 if(need_pfx)
192 {
193 field_width--;
194 if(base == 16)
195 field_width--;
196 }
197
198 /* generate full string in tmp[], in reverse order */
199 i = 0;
200 if(num == 0)
201 tmp[i++] = '0';
202 /* Generic code, for any base:
203 else do {
204 tmp[i++] = digits[do_div(num,base)];
205 } while (num != 0);
206 */
207 else if(base != 10)
208 { /* 8 or 16 */
209 int mask = base - 1;
210 int shift = 3;
211 if(base == 16)
212 shift = 4;
213 do
214 {
215 tmp[i++] = digits[((unsigned char)num) & mask];
216 num >>= shift;
217 }
218 while(num);
219 }
220 else
221 { /* base 10 */
222 i = put_dec(tmp, num) - tmp;
223 }
224
225 /* printing 100 using %2d gives "100", not "00" */
226 if(i > precision)
227 precision = i;
228 /* leading space padding */
229 field_width -= precision;
230 if(!(type & (ZEROPAD + LEFT)))
231 {
232 while(--field_width >= 0)
233 {
234 if(idx < size)
235 buf[idx] = ' ';
236 ++idx;
237 }
238 }
239 /* sign */
240 if(sign)
241 {
242 if(idx < size)
243 buf[idx] = sign;
244 ++idx;
245 }
246 /* "0x" / "0" prefix */
247 if(need_pfx)
248 {
249 if(idx < size)
250 buf[idx] = '0';
251 ++idx;
252 if(base == 16)
253 {
254 if(idx < size)
255 buf[idx] = digits[16]; /* for arbitrary base: digits[33]; */
256 ++idx;
257 }
258 }
259 /* zero or space padding */
260 if(!(type & LEFT))
261 {
262 char c = (type & ZEROPAD) ? '0' : ' ';
263 while(--field_width >= 0)
264 {
265 if(idx < size)
266 buf[idx] = c;
267 ++idx;
268 }
269 }
270 /* hmm even more zero padding? */
271 while(i <= --precision)
272 {
273 if(idx < size)
274 buf[idx] = '0';
275 ++idx;
276 }
277 /* actual digits of result */
278 while(--i >= 0)
279 {
280 if(idx < size)
281 buf[idx] = tmp[i];
282 ++idx;
283 }
284 /* trailing space padding */
285 while(--field_width >= 0)
286 {
287 if(idx < size)
288 buf[idx] = ' ';
289 ++idx;
290 }
291 return idx;
292 }
293
294 /**
295 * vsnprintf - Format a string and place it in a buffer
296 * @buf: The buffer to place the result into
297 * @size: The size of the buffer, including the trailing null space
298 * @fmt: The format string to use
299 * @args: Arguments for the format string
300 *
301 * The return value is the number of characters which would
302 * be generated for the given input, excluding the trailing
303 * '\0', as per ISO C99. If you want to have the exact
304 * number of characters written into @buf as return value
305 * (not including the trailing '\0'), use vscnprintf(). If the
306 * return is greater than or equal to @size, the resulting
307 * string is truncated.
308 *
309 * Call this function if you are already dealing with a va_list.
310 * You probably want snprintf() instead.
311 */
312 int
313 rb_vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
314 {
315 int len;
316 unsigned long long int num;
317 int i, base;
318 char c;
319 size_t idx;
320 const char *s;
321
322 int flags; /* flags to number() */
323
324 int field_width; /* width of output field */
325 int precision; /* min. # of digits for integers; max
326 number of chars for from string */
327 int qualifier; /* 'h', 'l', or 'L' for integer fields */
328 /* 'z' support added 23/7/1999 S.H. */
329 /* 'z' changed to 'Z' --davidm 1/25/99 */
330 /* 't' added for ptrdiff_t */
331
332 /* Reject out-of-range values early. Large positive sizes are
333 used for unknown buffer sizes. */
334 if(rb_unlikely(size > INT_MAX))
335 {
336 return 0;
337 }
338
339 idx = 0;
340
341 for(; *fmt; ++fmt)
342 {
343 if(*fmt != '%')
344 {
345 if(idx < size)
346 buf[idx] = *fmt;
347 ++idx;
348 continue;
349 }
350
351 /* process flags */
352 flags = 0;
353 repeat:
354 ++fmt; /* this also skips first '%' */
355 switch (*fmt)
356 {
357 case '-':
358 flags |= LEFT;
359 goto repeat;
360 case '+':
361 flags |= PLUS;
362 goto repeat;
363 case ' ':
364 flags |= SPACE;
365 goto repeat;
366 case '#':
367 flags |= SPECIAL;
368 goto repeat;
369 case '0':
370 flags |= ZEROPAD;
371 goto repeat;
372 }
373
374 /* get field width */
375 field_width = -1;
376 if(isdigit(*fmt))
377 field_width = skip_atoi(&fmt);
378 else if(*fmt == '*')
379 {
380 ++fmt;
381 /* it's the next argument */
382 field_width = va_arg(args, int);
383 if(field_width < 0)
384 {
385 field_width = -field_width;
386 flags |= LEFT;
387 }
388 }
389
390 /* get the precision */
391 precision = -1;
392 if(*fmt == '.')
393 {
394 ++fmt;
395 if(isdigit(*fmt))
396 precision = skip_atoi(&fmt);
397 else if(*fmt == '*')
398 {
399 ++fmt;
400 /* it's the next argument */
401 precision = va_arg(args, int);
402 }
403 if(precision < 0)
404 precision = 0;
405 }
406
407 /* get the conversion qualifier */
408 qualifier = -1;
409 if(*fmt == 'h' || *fmt == 'l' || *fmt == 'L' ||
410 *fmt == 'Z' || *fmt == 'z' || *fmt == 't')
411 {
412 qualifier = *fmt;
413 ++fmt;
414 if(qualifier == 'l' && *fmt == 'l')
415 {
416 qualifier = 'L';
417 ++fmt;
418 }
419 }
420
421 /* default base */
422 base = 10;
423
424 switch (*fmt)
425 {
426 case 'c':
427 if(!(flags & LEFT))
428 {
429 while(--field_width > 0)
430 {
431 if(idx < size)
432 buf[idx] = ' ';
433 ++idx;
434 }
435 }
436 c = (unsigned char)va_arg(args, int);
437 if(idx < size)
438 buf[idx] = c;
439 ++idx;
440 while(--field_width > 0)
441 {
442 if(idx < size)
443 buf[idx] = ' ';
444 ++idx;
445 }
446 continue;
447
448 case 's':
449 s = va_arg(args, char *);
450 if(s == NULL)
451 {
452 abort(); /* prefer blowing up vs corrupt data */
453 }
454 len = rb_strnlen(s, precision);
455
456 if(!(flags & LEFT))
457 {
458 while(len < field_width--)
459 {
460 if(idx < size)
461 buf[idx] = ' ';
462 ++idx;
463 }
464 }
465 for(i = 0; i < len; ++i)
466 {
467 if(idx < size)
468 buf[idx] = *s;
469 ++idx;
470 ++s;
471 }
472 while(len < field_width--)
473 {
474 if(idx < size)
475 buf[idx] = ' ';
476 ++idx;
477 }
478 continue;
479
480 case 'p':
481 if(field_width == -1)
482 {
483 field_width = 2 * sizeof(void *);
484 flags |= ZEROPAD;
485 }
486 idx = number(buf, size, idx,
487 (unsigned long)va_arg(args, void *),
488 16, field_width, precision, flags);
489 continue;
490
491
492 case 'n':
493 /* FIXME:
494 * What does C99 say about the overflow case here? */
495 if(qualifier == 'l')
496 {
497 long *ip = va_arg(args, long *);
498 *ip = idx;
499 }
500 else if(qualifier == 'Z' || qualifier == 'z')
501 {
502 size_t *ip = va_arg(args, size_t *);
503 *ip = idx;
504 }
505 else
506 {
507 int *ip = va_arg(args, int *);
508 *ip = idx;
509 }
510 continue;
511
512 case '%':
513 if(idx < size)
514 buf[idx] = '%';
515 ++idx;
516 continue;
517
518 /* integer number formats - set up the flags and "break" */
519 case 'o':
520 base = 8;
521 break;
522
523 case 'X':
524 flags |= LARGE;
525 case 'x':
526 base = 16;
527 break;
528
529 case 'd':
530 case 'i':
531 flags |= SIGN;
532 case 'u':
533 break;
534
535 default:
536 if(idx < size)
537 buf[idx] = '%';
538 ++idx;
539 if(*fmt)
540 {
541 if(idx < size)
542 buf[idx] = *fmt;
543 ++idx;
544 }
545 else
546 {
547 --fmt;
548 }
549 continue;
550 }
551 if(qualifier == 'L')
552 num = va_arg(args, long long int);
553 else if(qualifier == 'l')
554 {
555 num = va_arg(args, unsigned long);
556 if(flags & SIGN)
557 num = (signed long)num;
558 }
559 else if(qualifier == 'Z' || qualifier == 'z')
560 {
561 num = va_arg(args, size_t);
562 }
563 else if(qualifier == 't')
564 {
565 num = va_arg(args, ptrdiff_t);
566 }
567 else if(qualifier == 'h')
568 {
569 num = (unsigned short)va_arg(args, int);
570 if(flags & SIGN)
571 num = (signed short)num;
572 }
573 else
574 {
575 num = va_arg(args, unsigned int);
576 if(flags & SIGN)
577 num = (signed int)num;
578 }
579 idx = number(buf, size, idx, num, base, field_width, precision, flags);
580 }
581 if(size > 0)
582 {
583 if(idx < size)
584 buf[idx] = '\0';
585 else
586 buf[size - 1] = '\0';
587 }
588 /* the trailing null byte doesn't count towards the total */
589 return idx;
590 }
591
592 /**
593 * snprintf - Format a string and place it in a buffer
594 * @buf: The buffer to place the result into
595 * @size: The size of the buffer, including the trailing null space
596 * @fmt: The format string to use
597 * @...: Arguments for the format string
598 *
599 * The return value is the number of characters which would be
600 * generated for the given input, excluding the trailing null,
601 * as per ISO C99. If the return is greater than or equal to
602 * @size, the resulting string is truncated.
603 */
604 int
605 rb_snprintf(char *buf, size_t size, const char *fmt, ...)
606 {
607 va_list args;
608 int i;
609
610 va_start(args, fmt);
611 i = rb_vsnprintf(buf, size, fmt, args);
612 va_end(args);
613 return i;
614 }
615
616 /**
617 * vsprintf - Format a string and place it in a buffer
618 * @buf: The buffer to place the result into
619 * @fmt: The format string to use
620 * @args: Arguments for the format string
621 *
622 * The function returns the number of characters written
623 * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
624 * buffer overflows.
625 *
626 * Call this function if you are already dealing with a va_list.
627 * You probably want sprintf() instead.
628 */
629 int
630 rb_vsprintf(char *buf, const char *fmt, va_list args)
631 {
632 return rb_vsnprintf(buf, INT_MAX, fmt, args);
633 }
634
635 /**
636 * sprintf - Format a string and place it in a buffer
637 * @buf: The buffer to place the result into
638 * @fmt: The format string to use
639 * @...: Arguments for the format string
640 *
641 * The function returns the number of characters written
642 * into @buf. Use snprintf() or scnprintf() in order to avoid
643 * buffer overflows.
644 */
645 int
646 rb_sprintf(char *buf, const char *fmt, ...)
647 {
648 va_list args;
649 int i;
650
651 va_start(args, fmt);
652 i = rb_vsnprintf(buf, INT_MAX, fmt, args);
653 va_end(args);
654 return i;
655 }
656
657 /*
658 * rb_vsprintf_append()
659 * appends sprintf formatted string to the end of the buffer
660 */
661
662 int
663 rb_vsprintf_append(char *str, const char *format, va_list ap)
664 {
665 size_t x = strlen(str);
666 return (rb_vsprintf(str + x, format, ap) + x);
667 }
668
669 /*
670 * rb_sprintf_append()
671 * appends sprintf formatted string to the end of the buffer
672 */
673 int
674 rb_sprintf_append(char *str, const char *format, ...)
675 {
676 int x;
677 va_list ap;
678 va_start(ap, format);
679 x = rb_vsprintf_append(str, format, ap);
680 va_end(ap);
681 return (x);
682 }
683
684 /*
685 * rb_vsnprintf_append()
686 * appends sprintf formatted string to the end of the buffer but not
687 * exceeding len
688 */
689
690 int
691 rb_vsnprintf_append(char *str, size_t len, const char *format, va_list ap)
692 {
693 size_t x;
694 if(len == 0)
695 return 0;
696 x = strlen(str);
697
698 if(len < x)
699 {
700 str[len - 1] = '\0';
701 return len - 1;
702 }
703 return (rb_vsnprintf(str + x, len - x, format, ap) + x);
704 }
705
706 /*
707 * rb_snprintf_append()
708 * appends snprintf formatted string to the end of the buffer but not
709 * exceeding len
710 */
711
712 int
713 rb_snprintf_append(char *str, size_t len, const char *format, ...)
714 {
715 int x;
716 va_list ap;
717 va_start(ap, format);
718 x = rb_vsnprintf_append(str, len, format, ap);
719 va_end(ap);
720 return (x);
721 }