1 /*
2  * This is the vsnprintf for scummvm/symbian implementation from the original snprintf.c,
3  * all support functions has been removed and vsnprintf renamed to symbian_vsnprintf
4  * snprintf.c - a portable implementation of snprintf
5  * According to the homepage this function could be licensed as either Frontier Aritistic or GPL.
6  *
7  * AUTHOR
8  *   Mark Martinec <mark.martinec@ijs.si>, April 1999.
9  *
10  *   Copyright 1999, Mark Martinec. All rights reserved.
11  *
12  * TERMS AND CONDITIONS
13  *   This program is free software; you can redistribute it and/or modify
14  *   it under the terms of the "Frontier Artistic License" which comes
15  *   with this Kit.
16  *
17  *   This program is distributed in the hope that it will be useful,
18  *   but WITHOUT ANY WARRANTY; without even the implied warranty
19  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20  *   See the Frontier Artistic License for more details.
21  *
22  *   You should have received a copy of the Frontier Artistic License
23  *   with this Kit in the file named LICENSE.txt .
24  *   If not, I'll be glad to provide one.
25  *
26  * FEATURES
27  * - careful adherence to specs regarding flags, field width and precision;
28  * - good performance for large string handling (large format, large
29  *   argument or large paddings). Performance is similar to system's sprintf
30  *   and in several cases significantly better (make sure you compile with
31  *   optimizations turned on, tell the compiler the code is strict ANSI
32  *   if necessary to give it more freedom for optimizations);
33  * - return value semantics per ISO/IEC 9899:1999 ("ISO C99");
34  * - written in standard ISO/ANSI C - requires an ANSI C compiler.
35  *
36  * SUPPORTED CONVERSION SPECIFIERS AND DATA TYPES
37  *
38  * This snprintf only supports the following conversion specifiers:
39  * s, c, d, u, o, x, X, p  (and synonyms: i, D, U, O - see below)
40  * with flags: '-', '+', ' ', '0' and '#'.
41  * An asterisk is supported for field width as well as precision.
42  *
43  * Length modifiers 'h' (short int), 'l' (long int),
44  * and 'll' (long long int) are supported.
45  * NOTE:
46  *   If macro SNPRINTF_LONGLONG_SUPPORT is not defined (default) the
47  *   length modifier 'll' is recognized but treated the same as 'l',
48  *   which may cause argument value truncation! Defining
49  *   SNPRINTF_LONGLONG_SUPPORT requires that your system's sprintf also
50  *   handles length modifier 'll'.  long long int is a language extension
51  *   which may not be portable.
52  *
53  * Conversion of numeric data (conversion specifiers d, u, o, x, X, p)
54  * with length modifiers (none or h, l, ll) is left to the system routine
55  * sprintf, but all handling of flags, field width and precision as well as
56  * c and s conversions is done very carefully by this portable routine.
57  * If a string precision (truncation) is specified (e.g. %.8s) it is
58  * guaranteed the string beyond the specified precision will not be referenced.
59  *
60  * Length modifiers h, l and ll are ignored for c and s conversions (data
61  * types wint_t and wchar_t are not supported).
62  *
63  * The following common synonyms for conversion characters are supported:
64  *   - i is a synonym for d
65  *   - D is a synonym for ld, explicit length modifiers are ignored
66  *   - U is a synonym for lu, explicit length modifiers are ignored
67  *   - O is a synonym for lo, explicit length modifiers are ignored
68  * The D, O and U conversion characters are nonstandard, they are supported
69  * for backward compatibility only, and should not be used for new code.
70  *
71  * The following is specifically NOT supported:
72  *   - flag ' (thousands' grouping character) is recognized but ignored
73  *   - numeric conversion specifiers: f, e, E, g, G and synonym F,
74  *     as well as the new a and A conversion specifiers
75  *   - length modifier 'L' (long double) and 'q' (quad - use 'll' instead)
76  *   - wide character/string conversions: lc, ls, and nonstandard
77  *     synonyms C and S
78  *   - writeback of converted string length: conversion character n
79  *   - the n$ specification for direct reference to n-th argument
80  *   - locales
81  *
82  * It is permitted for str_m to be zero, and it is permitted to specify NULL
83  * pointer for resulting string argument if str_m is zero (as per ISO C99).
84  *
85  * The return value is the number of characters which would be generated
86  * for the given input, excluding the trailing null. If this value
87  * is greater or equal to str_m, not all characters from the result
88  * have been stored in str, output bytes beyond the (str_m-1) -th character
89  * are discarded. If str_m is greater than zero it is guaranteed
90  * the resulting string will be null-terminated.
91  *
92  * NOTE that this matches the ISO C99, OpenBSD, and GNU C library 2.1,
93  * but is different from some older and vendor implementations,
94  * and is also different from XPG, XSH5, SUSv2 specifications.
95  * For historical discussion on changes in the semantics and standards
96  * of snprintf see printf(3) man page in the Linux programmers manual.
97  *
98  * Routines asprintf and vasprintf return a pointer (in the ptr argument)
99  * to a buffer sufficiently large to hold the resulting string. This pointer
100  * should be passed to free(3) to release the allocated storage when it is
101  * no longer needed. If sufficient space cannot be allocated, these functions
102  * will return -1 and set ptr to be a NULL pointer. These two routines are a
103  * GNU C library extensions (glibc).
104  *
105  * Routines asnprintf and vasnprintf are similar to asprintf and vasprintf,
106  * yet, like snprintf and vsnprintf counterparts, will write at most str_m-1
107  * characters into the allocated output string, the last character in the
108  * allocated buffer then gets the terminating null. If the formatted string
109  * length (the return value) is greater than or equal to the str_m argument,
110  * the resulting string was truncated and some of the formatted characters
111  * were discarded. These routines present a handy way to limit the amount
112  * of allocated memory to some sane value.
113  *
114  * AVAILABILITY
115  *   http://www.ijs.si/software/snprintf/
116  *
117  * REVISION HISTORY
118  * 1999-04	V0.9  Mark Martinec
119  *		- initial version, some modifications after comparing printf
120  *		  man pages for Digital Unix 4.0, Solaris 2.6 and HPUX 10,
121  *		  and checking how Perl handles sprintf (differently!);
122  * 1999-04-09	V1.0  Mark Martinec <mark.martinec@ijs.si>
123  *		- added main test program, fixed remaining inconsistencies,
124  *		  added optional (long long int) support;
125  * 1999-04-12	V1.1  Mark Martinec <mark.martinec@ijs.si>
126  *		- support the 'p' conversion (pointer to void);
127  *		- if a string precision is specified
128  *		  make sure the string beyond the specified precision
129  *		  will not be referenced (e.g. by strlen);
130  * 1999-04-13	V1.2  Mark Martinec <mark.martinec@ijs.si>
131  *		- support synonyms %D=%ld, %U=%lu, %O=%lo;
132  *		- speed up the case of long format string with few conversions;
133  * 1999-06-30	V1.3  Mark Martinec <mark.martinec@ijs.si>
134  *		- fixed runaway loop (eventually crashing when str_l wraps
135  *		  beyond 2^31) while copying format string without
136  *		  conversion specifiers to a buffer that is too short
137  *		  (thanks to Edwin Young <edwiny@autonomy.com> for
138  *		  spotting the problem);
139  *		- added macros PORTABLE_SNPRINTF_VERSION_(MAJOR|MINOR)
140  *		  to snprintf.h
141  * 2000-02-14	V2.0 (never released) Mark Martinec <mark.martinec@ijs.si>
142  *		- relaxed license terms: The Artistic License now applies.
143  *		  You may still apply the GNU GENERAL PUBLIC LICENSE
144  *		  as was distributed with previous versions, if you prefer;
145  *		- changed REVISION HISTORY dates to use ISO 8601 date format;
146  *		- added vsnprintf (patch also independently proposed by
147  *		  Caolan McNamara 2000-05-04, and Keith M Willenson 2000-06-01)
148  * 2000-06-27	V2.1  Mark Martinec <mark.martinec@ijs.si>
149  *		- removed POSIX check for str_m<1; value 0 for str_m is
150  *		  allowed by ISO C99 (and GNU C library 2.1) - (pointed out
151  *		  on 2000-05-04 by Caolan McNamara, caolan@ csn dot ul dot ie).
152  *		  Besides relaxed license this change in standards adherence
153  *		  is the main reason to bump up the major version number;
154  *		- added nonstandard routines asnprintf, vasnprintf, asprintf,
155  *		  vasprintf that dynamically allocate storage for the
156  *		  resulting string; these routines are not compiled by default,
157  *		  see comments where NEED_V?ASN?PRINTF macros are defined;
158  *		- autoconf contributed by Caolan McNamara
159  * 2000-10-06	V2.2  Mark Martinec <mark.martinec@ijs.si>
160  *		- BUG FIX: the %c conversion used a temporary variable
161  *		  that was no longer in scope when referenced,
162  *		  possibly causing incorrect resulting character;
163  *		- BUG FIX: make precision and minimal field width unsigned
164  *		  to handle huge values (2^31 <= n < 2^32) correctly;
165  *		  also be more careful in the use of signed/unsigned/size_t
166  *		  internal variables - probably more careful than many
167  *		  vendor implementations, but there may still be a case
168  *		  where huge values of str_m, precision or minimal field
169  *		  could cause incorrect behaviour;
170  *		- use separate variables for signed/unsigned arguments,
171  *		  and for short/int, long, and long long argument lengths
172  *		  to avoid possible incompatibilities on certain
173  *		  computer architectures. Also use separate variable
174  *		  arg_sign to hold sign of a numeric argument,
175  *		  to make code more transparent;
176  *		- some fiddling with zero padding and "0x" to make it
177  *		  Linux compatible;
178  *		- systematically use macros fast_memcpy and fast_memset
179  *		  instead of case-by-case hand optimization; determine some
180  *		  breakeven string lengths for different architectures;
181  *		- terminology change: 'format' -> 'conversion specifier',
182  *		  'C9x' -> 'ISO/IEC 9899:1999 ("ISO C99")',
183  *		  'alternative form' -> 'alternate form',
184  *		  'data type modifier' -> 'length modifier';
185  *		- several comments rephrased and new ones added;
186  *		- make compiler not complain about 'credits' defined but
187  *		  not used;
188  */
189 /* ============================================= */
190 /* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */
191 /* ============================================= */
192 
193 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
194 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
195 #include <sys/types.h>
196 #include <string.h>
197 #include <stdlib.h>
198 #include <stdio.h>
199 #include <stdarg.h>
200 #include <assert.h>
201 #include <errno.h>
202 #ifdef isdigit
203 #undef isdigit
204 #endif
205 #define isdigit(c) ((c) >= '0' && (c) <= '9')
206 
207 #ifndef breakeven_point
208 #  define breakeven_point   6	/* some reasonable one-size-fits-all value */
209 #endif
210 
211 #define fast_memcpy(d,s,n) \
212 { register size_t nn = (size_t)(n); \
213 	if (nn >= breakeven_point) memcpy((d), (s), nn); \
214 	else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
215 	register char *dd; register const char *ss; \
216 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
217 
218 #define fast_memset(d,c,n) \
219 { register size_t nn = (size_t)(n); \
220 	if (nn >= breakeven_point) memset((d), (int)(c), nn); \
221 	else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
222 	register char *dd; register const int cc=(int)(c); \
223 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
224 
225 
226 /* declarations */
227 
228 static char credits[] = "\n\
229 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
230 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
231 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
vsnprintf(char * str,size_t str_m,const char * fmt,va_list ap)232 int vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
233 
234 	size_t str_l = 0;
235 	const char *p = fmt;
236 
237 	/* In contrast with POSIX, the ISO C99 now says
238 	* that str can be NULL and str_m can be 0.
239 	* This is more useful than the old:  if (str_m < 1) return -1; */
240 
241 	if (!p) p = "";
242 	while (*p) {
243 		if (*p != '%') {
244 			/* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
245 			/* but the following code achieves better performance for cases
246 			* where format string is long and contains few conversions */
247 			const char *q = strchr(p+1,'%');
248 			size_t n = !q ? strlen(p) : (q-p);
249 			if (str_l < str_m) {
250 				size_t avail = str_m-str_l;
251 				fast_memcpy(str+str_l, p, (n>avail?avail:n));
252 			}
253 			p += n; str_l += n;
254 		} else {
255 			const char *starting_p;
256 			size_t min_field_width = 0, precision = 0;
257 			int zero_padding = 0, precision_specified = 0, justify_left = 0;
258 			int alternate_form = 0, force_sign = 0;
259 			int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
260 			the ' ' flag should be ignored. */
261 			char length_modifier = '\0';            /* allowed values: \0, h, l, L */
262 			char tmp[32];/* temporary buffer for simple numeric->string conversion */
263 
264 			const char *str_arg;      /* string address in case of string argument */
265 									  size_t str_arg_l;         /* natural field width of arg without padding
266 									  and sign */
267 									  unsigned char uchar_arg;
268 									  /* unsigned char argument value - only defined for c conversion.
269 									  N.B. standard explicitly states the char argument for
270 									  the c conversion is unsigned */
271 
272 									  size_t number_of_zeros_to_pad = 0;
273 									  /* number of zeros to be inserted for numeric conversions
274 									  as required by the precision or minimal field width */
275 
276 									  size_t zero_padding_insertion_ind = 0;
277 									  /* index into tmp where zero padding is to be inserted */
278 
279 									  char fmt_spec = '\0';
280 									  /* current conversion specifier character */
281 
282 									  str_arg = credits;/* just to make compiler happy (defined but not used)*/
283 									  str_arg = NULL;
284 									  starting_p = p; p++;  /* skip '%' */
285 									  /* parse flags */
286 									  while (*p == '0' || *p == '-' || *p == '+' ||
287 										  *p == ' ' || *p == '#' || *p == '\'') {
288 										  switch (*p) {
289 										  case '0': zero_padding = 1; break;
290 										  case '-': justify_left = 1; break;
291 										  case '+': force_sign = 1; space_for_positive = 0; break;
292 										  case ' ': force_sign = 1;
293 											  /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
294 											  break;
295 										  case '#': alternate_form = 1; break;
296 										  case '\'': break;
297 										  }
298 										  p++;
299 									  }
300 									  /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
301 
302 									  /* parse field width */
303 									  if (*p == '*') {
304 										  int j;
305 										  p++; j = va_arg(ap, int);
306 										  if (j >= 0) min_field_width = j;
307 										  else { min_field_width = -j; justify_left = 1; }
308 									  } else if (isdigit((int)(*p))) {
309 									  /* size_t could be wider than unsigned int;
310 										  make sure we treat argument like common implementations do */
311 										  unsigned int uj = *p++ - '0';
312 										  while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
313 										  min_field_width = uj;
314 									  }
315 									  /* parse precision */
316 									  if (*p == '.') {
317 										  p++; precision_specified = 1;
318 										  if (*p == '*') {
319 											  int j = va_arg(ap, int);
320 											  p++;
321 											  if (j >= 0) precision = j;
322 											  else {
323 												  precision_specified = 0; precision = 0;
324 												  /* NOTE:
325 												  *   Solaris 2.6 man page claims that in this case the precision
326 												  *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
327 												  *   claim that this case should be treated as unspecified precision,
328 												  *   which is what we do here.
329 												  */
330 											  }
331 										  } else if (isdigit((int)(*p))) {
332 										  /* size_t could be wider than unsigned int;
333 											  make sure we treat argument like common implementations do */
334 											  unsigned int uj = *p++ - '0';
335 											  while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
336 											  precision = uj;
337 										  }
338 									  }
339 									  /* parse 'h', 'l' and 'll' length modifiers */
340 									  if (*p == 'h' || *p == 'l') {
341 										  length_modifier = *p; p++;
342 										  if (length_modifier == 'l' && *p == 'l') {   /* double l = long long */
343 #ifdef SNPRINTF_LONGLONG_SUPPORT
344 											  length_modifier = '2';                  /* double l encoded as '2' */
345 #else
346 											  length_modifier = 'l';                 /* treat it as a single 'l' */
347 #endif
348 											  p++;
349 										  }
350 									  }
351 									  fmt_spec = *p;
352 									  /* common synonyms: */
353 									  switch (fmt_spec) {
354 									  case 'i': fmt_spec = 'd'; break;
355 									  case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
356 									  case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
357 									  case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
358 									  default: break;
359 									  }
360 									  /* get parameter value, do initial processing */
361 									  switch (fmt_spec) {
362 									  case '%': /* % behaves similar to 's' regarding flags and field widths */
363 									  case 'c': /* c behaves similar to 's' regarding flags and field widths */
364 									  case 's':
365 										  length_modifier = '\0';          /* wint_t and wchar_t not supported */
366 										  /* the result of zero padding flag with non-numeric conversion specifier*/
367 										  /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
368 										  /* Digital Unix and Linux does not. */
369 										  zero_padding = 0;    /* turn zero padding off for string conversions */
370 										  str_arg_l = 1;
371 										  switch (fmt_spec) {
372 										  case '%':
373 											  str_arg = p; break;
374 										  case 'c': {
375 											  int j = va_arg(ap, int);
376 											  uchar_arg = (unsigned char) j;   /* standard demands unsigned char */
377 											  str_arg = (const char *) &uchar_arg;
378 											  break;
379 													}
380 										  case 's':
381 											  str_arg = va_arg(ap, const char *);
382 											  if (!str_arg) str_arg_l = 0;
383 											  /* make sure not to address string beyond the specified precision !!! */
384 											  else if (!precision_specified) str_arg_l = strlen(str_arg);
385 											  /* truncate string if necessary as requested by precision */
386 											  else if (precision == 0) str_arg_l = 0;
387 											  else {
388 												  /* memchr on HP does not like n > 2^31  !!! */
389 												  const char *q = (const char*) memchr(str_arg, '\0',
390 													  precision <= 0x7fffffff ? precision : 0x7fffffff);
391 												  str_arg_l = !q ? precision : (q-str_arg);
392 											  }
393 											  break;
394 										  default: break;
395 										  }
396 										  break;
397 										  case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
398 										  /* NOTE: the u, o, x, X and p conversion specifiers imply
399 											  the value is unsigned;  d implies a signed value */
400 
401 											  int arg_sign = 0;
402 											  /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
403 											  +1 if greater than zero (or nonzero for unsigned arguments),
404 											  -1 if negative (unsigned argument is never negative) */
405 
406 											  int int_arg = 0;  unsigned int uint_arg = 0;
407 											  /* only defined for length modifier h, or for no length modifiers */
408 
409 											  long int long_arg = 0;  unsigned long int ulong_arg = 0;
410 											  /* only defined for length modifier l */
411 
412 											  void *ptr_arg = NULL;
413 											  /* pointer argument value -only defined for p conversion */
414 
415 #ifdef SNPRINTF_LONGLONG_SUPPORT
416 											  long long int long_long_arg = 0;
417 											  unsigned long long int ulong_long_arg = 0;
418 											  /* only defined for length modifier ll */
419 #endif
420 											  if (fmt_spec == 'p') {
421 											  /* HPUX 10: An l, h, ll or L before any other conversion character
422 											  *   (other than d, i, u, o, x, or X) is ignored.
423 											  * Digital Unix:
424 											  *   not specified, but seems to behave as HPUX does.
425 											  * Solaris: If an h, l, or L appears before any other conversion
426 											  *   specifier (other than d, i, u, o, x, or X), the behavior
427 											  *   is undefined. (Actually %hp converts only 16-bits of address
428 											  *   and %llp treats address as 64-bit data which is incompatible
429 											  *   with (void *) argument on a 32-bit system).
430 												  */
431 												  length_modifier = '\0';
432 												  ptr_arg = va_arg(ap, void *);
433 												  if (ptr_arg != NULL) arg_sign = 1;
434 											  } else if (fmt_spec == 'd') {  /* signed */
435 												  switch (length_modifier) {
436 												  case '\0':
437 												  case 'h':
438 												  /* It is non-portable to specify a second argument of char or short
439 												  * to va_arg, because arguments seen by the called function
440 												  * are not char or short.  C converts char and short arguments
441 												  * to int before passing them to a function.
442 													  */
443 													  int_arg = va_arg(ap, int);
444 													  if      (int_arg > 0) arg_sign =  1;
445 													  else if (int_arg < 0) arg_sign = -1;
446 													  break;
447 												  case 'l':
448 													  long_arg = va_arg(ap, long int);
449 													  if      (long_arg > 0) arg_sign =  1;
450 													  else if (long_arg < 0) arg_sign = -1;
451 													  break;
452 #ifdef SNPRINTF_LONGLONG_SUPPORT
453 												  case '2':
454 													  long_long_arg = va_arg(ap, long long int);
455 													  if      (long_long_arg > 0) arg_sign =  1;
456 													  else if (long_long_arg < 0) arg_sign = -1;
457 													  break;
458 #endif
459 												  }
460 											  } else {  /* unsigned */
461 												  switch (length_modifier) {
462 												  case '\0':
463 												  case 'h':
464 													  uint_arg = va_arg(ap, unsigned int);
465 													  if (uint_arg) arg_sign = 1;
466 													  break;
467 												  case 'l':
468 													  ulong_arg = va_arg(ap, unsigned long int);
469 													  if (ulong_arg) arg_sign = 1;
470 													  break;
471 #ifdef SNPRINTF_LONGLONG_SUPPORT
472 												  case '2':
473 													  ulong_long_arg = va_arg(ap, unsigned long long int);
474 													  if (ulong_long_arg) arg_sign = 1;
475 													  break;
476 #endif
477 												  }
478 											  }
479 											  str_arg = tmp; str_arg_l = 0;
480 											  /* NOTE:
481 											  *   For d, i, u, o, x, and X conversions, if precision is specified,
482 											  *   the '0' flag should be ignored. This is so with Solaris 2.6,
483 											  *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
484 											  */
485 											  if (precision_specified) zero_padding = 0;
486 											  if (fmt_spec == 'd') {
487 												  if (force_sign && arg_sign >= 0)
488 													  tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
489 													  /* leave negative numbers for sprintf to handle,
490 												  to avoid handling tricky cases like (short int)(-32768) */
491 											  } else if (alternate_form) {
492 												  if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
493 												  { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
494 												  /* alternate form should have no effect for p conversion, but ... */
495 											  }
496 											  zero_padding_insertion_ind = str_arg_l;
497 											  if (!precision_specified) precision = 1;   /* default precision is 1 */
498 											  if (precision == 0 && arg_sign == 0
499 												  ) {
500 												  /* converted to null string */
501 												  /* When zero value is formatted with an explicit precision 0,
502 												  the resulting formatted string is empty (d, i, u, o, x, X, p).   */
503 											  } else {
504 												  char f[5]; int f_l = 0;
505 												  f[f_l++] = '%';    /* construct a simple format string for sprintf */
506 												  if (!length_modifier) { }
507 												  else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
508 												  else f[f_l++] = length_modifier;
509 												  f[f_l++] = fmt_spec; f[f_l++] = '\0';
510 												  if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
511 												  else if (fmt_spec == 'd') {  /* signed */
512 													  switch (length_modifier) {
513 													  case '\0':
514 													  case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
515 													  case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
516 #ifdef SNPRINTF_LONGLONG_SUPPORT
517 													  case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
518 #endif
519 													  }
520 												  } else {  /* unsigned */
521 													  switch (length_modifier) {
522 													  case '\0':
523 													  case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg);  break;
524 													  case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
525 #ifdef SNPRINTF_LONGLONG_SUPPORT
526 													  case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
527 #endif
528 													  }
529 												  }
530 												  /* include the optional minus sign and possible "0x"
531 												  in the region before the zero padding insertion point */
532 												  if (zero_padding_insertion_ind < str_arg_l &&
533 													  tmp[zero_padding_insertion_ind] == '-') {
534 													  zero_padding_insertion_ind++;
535 												  }
536 												  if (zero_padding_insertion_ind+1 < str_arg_l &&
537 													  tmp[zero_padding_insertion_ind]   == '0' &&
538 													  (tmp[zero_padding_insertion_ind+1] == 'x' ||
539 													  tmp[zero_padding_insertion_ind+1] == 'X') ) {
540 													  zero_padding_insertion_ind += 2;
541 												  }
542 											  }
543 											  { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
544 											  if (alternate_form && fmt_spec == 'o'
545 												  /* unless zero is already the first character */
546 												  && !(zero_padding_insertion_ind < str_arg_l
547 												  && tmp[zero_padding_insertion_ind] == '0')
548 												  ) {        /* assure leading zero for alternate-form octal numbers */
549 												  if (!precision_specified || precision < num_of_digits+1) {
550 												  /* precision is increased to force the first character to be zero,
551 												  except if a zero value is formatted with an explicit precision
552 													  of zero */
553 													  precision = num_of_digits+1; precision_specified = 1;
554 												  }
555 											  }
556 											  /* zero padding to specified precision? */
557 											  if (num_of_digits < precision)
558 												  number_of_zeros_to_pad = precision - num_of_digits;
559 											  }
560 											  /* zero padding to specified minimal field width? */
561 											  if (!justify_left && zero_padding) {
562 												  int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
563 												  if (n > 0) number_of_zeros_to_pad += n;
564 											  }
565 											  break;
566 	  }
567 	  default: /* unrecognized conversion specifier, keep format string as-is*/
568 		  zero_padding = 0;  /* turn zero padding off for non-numeric convers. */
569 		  justify_left = 1; min_field_width = 0;                /* reset flags */
570 																/* discard the unrecognized conversion, just keep *
571 		  * the unrecognized conversion character          */
572 		  str_arg = p; str_arg_l = 0;
573 		  if (*p) str_arg_l++;  /* include invalid conversion specifier unchanged
574 		  if not at end-of-string */
575 		  break;
576 	  }
577 	  if (*p) p++;      /* step over the just processed conversion specifier */
578 						/* insert padding to the left as requested by min_field_width;
579 	  this does not include the zero padding in case of numerical conversions*/
580 	  if (!justify_left) {                /* left padding with blank or zero */
581 		  int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
582 		  if (n > 0) {
583 			  if (str_l < str_m) {
584 				  size_t avail = str_m-str_l;
585 				  fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
586 			  }
587 			  str_l += n;
588 		  }
589 	  }
590 	  /* zero padding as requested by the precision or by the minimal field width
591 	  * for numeric conversions required? */
592 	  if (number_of_zeros_to_pad <= 0) {
593 	  /* will not copy first part of numeric right now, *
594 		  * force it to be copied later in its entirety    */
595 		  zero_padding_insertion_ind = 0;
596 	  } else {
597 		  /* insert first part of numerics (sign or '0x') before zero padding */
598 		  int n = zero_padding_insertion_ind;
599 		  if (n > 0) {
600 			  if (str_l < str_m) {
601 				  size_t avail = str_m-str_l;
602 				  fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
603 			  }
604 			  str_l += n;
605 		  }
606 		  /* insert zero padding as requested by the precision or min field width */
607 		  n = number_of_zeros_to_pad;
608 		  if (n > 0) {
609 			  if (str_l < str_m) {
610 				  size_t avail = str_m-str_l;
611 				  fast_memset(str+str_l, '0', (n>avail?avail:n));
612 			  }
613 			  str_l += n;
614 		  }
615 	  }
616 	  /* insert formatted string
617 	  * (or as-is conversion specifier for unknown conversions) */
618 	  { int n = str_arg_l - zero_padding_insertion_ind;
619 	  if (n > 0) {
620 		  if (str_l < str_m) {
621 			  size_t avail = str_m-str_l;
622 			  fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
623 				  (n>avail?avail:n));
624 		  }
625 		  str_l += n;
626 	  }
627 	  }
628 	  /* insert right padding */
629 	  if (justify_left) {          /* right blank padding to the field width */
630 		  int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
631 		  if (n > 0) {
632 			  if (str_l < str_m) {
633 				  size_t avail = str_m-str_l;
634 				  fast_memset(str+str_l, ' ', (n>avail?avail:n));
635 			  }
636 			  str_l += n;
637 		  }
638 	  }
639 	}
640   }
641   if (str_m > 0) { /* make sure the string is null-terminated
642 				   even at the expense of overwriting the last character
643 	  (shouldn't happen, but just in case) */
644 	  str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
645   }
646   /* Return the number of characters formatted (excluding trailing null
647   * character), that is, the number of characters that would have been
648   * written to the buffer if it were large enough.
649   *
650   * The value of str_l should be returned, but str_l is of unsigned type
651   * size_t, and snprintf is int, possibly leading to an undetected
652   * integer overflow, resulting in a negative return value, which is illegal.
653   * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
654   * Should errno be set to EOVERFLOW and EOF returned in this case???
655   */
656   return (int) str_l;
657 }
658 
snprintf(char * text,size_t maxlen,const char * fmt,...)659 int snprintf(char *text, size_t maxlen, const char *fmt, ...) {
660 	va_list ap;
661 	int retval;
662 
663 	va_start(ap, fmt);
664 	retval = vsnprintf(text, maxlen, fmt, ap);
665 	va_end(ap);
666 
667 	return retval;
668 }
669