Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Includes portable.h file header for use of the va_copy macro definition (defined...
[simgrid.git] / src / xbt / snprintf.c
1
2 /*
3  * snprintf.c - a portable implementation of snprintf
4  *
5  * AUTHOR
6  *   Mark Martinec <mark.martinec@ijs.si>, April 1999.
7  *
8  *   Copyright 1999, Mark Martinec. All rights reserved.
9  *
10  * TERMS AND CONDITIONS
11  *   This program is free software; you can redistribute it and/or modify
12  *   it under the terms of the "Frontier Artistic License" which comes
13  *   with this Kit.
14  *
15  *   This program is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty
17  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18  *   See the Frontier Artistic License for more details.
19  *
20  *   You should have received a copy of the Frontier Artistic License
21  *   with this Kit in the file named LICENSE.txt .
22  *   If not, I'll be glad to provide one.
23  *
24  * FEATURES
25  * - careful adherence to specs regarding flags, field width and precision;
26  * - good performance for large string handling (large format, large
27  *   argument or large paddings). Performance is similar to system's sprintf
28  *   and in several cases significantly better (make sure you compile with
29  *   optimizations turned on, tell the compiler the code is strict ANSI
30  *   if necessary to give it more freedom for optimizations);
31  * - return value semantics per ISO/IEC 9899:1999 ("ISO C99");
32  * - written in standard ISO/ANSI C - requires an ANSI C compiler.
33  *
34  * SUPPORTED CONVERSION SPECIFIERS AND DATA TYPES
35  *
36  * This snprintf only supports the following conversion specifiers:
37  * s, c, d, u, o, x, X, p  (and synonyms: i, D, U, O - see below)
38  * with flags: '-', '+', ' ', '0' and '#'.
39  * An asterisk is supported for field width as well as precision.
40  *
41  * Length modifiers 'h' (short int), 'l' (long int),
42  * and 'll' (long long int) are supported.
43  * NOTE:
44  *   If macro SNPRINTF_LONGLONG_SUPPORT is not defined (default) the
45  *   length modifier 'll' is recognized but treated the same as 'l',
46  *   which may cause argument value truncation! Defining
47  *   SNPRINTF_LONGLONG_SUPPORT requires that your system's sprintf also
48  *   handles length modifier 'll'.  long long int is a language extension
49  *   which may not be portable.
50  *
51  * Conversion of numeric data (conversion specifiers d, u, o, x, X, p)
52  * with length modifiers (none or h, l, ll) is left to the system routine
53  * sprintf, but all handling of flags, field width and precision as well as
54  * c and s conversions is done very carefully by this portable routine.
55  * If a string precision (truncation) is specified (e.g. %.8s) it is
56  * guaranteed the string beyond the specified precision will not be referenced.
57  *
58  * Length modifiers h, l and ll are ignored for c and s conversions (data
59  * types wint_t and wchar_t are not supported).
60  *
61  * The following common synonyms for conversion characters are supported:
62  *   - i is a synonym for d
63  *   - D is a synonym for ld, explicit length modifiers are ignored
64  *   - U is a synonym for lu, explicit length modifiers are ignored
65  *   - O is a synonym for lo, explicit length modifiers are ignored
66  * The D, O and U conversion characters are nonstandard, they are supported
67  * for backward compatibility only, and should not be used for new code.
68  *
69  * The following is specifically NOT supported:
70  *   - flag ' (thousands' grouping character) is recognized but ignored
71  *   - numeric conversion specifiers: f, e, E, g, G and synonym F,
72  *     as well as the new a and A conversion specifiers
73  *   - length modifier 'L' (long double) and 'q' (quad - use 'll' instead)
74  *   - wide character/string conversions: lc, ls, and nonstandard
75  *     synonyms C and S
76  *   - writeback of converted string length: conversion character n
77  *   - the n$ specification for direct reference to n-th argument
78  *   - locales
79  *
80  * It is permitted for str_m to be zero, and it is permitted to specify NULL
81  * pointer for resulting string argument if str_m is zero (as per ISO C99).
82  *
83  * The return value is the number of characters which would be generated
84  * for the given input, excluding the trailing null. If this value
85  * is greater or equal to str_m, not all characters from the result
86  * have been stored in str, output bytes beyond the (str_m-1) -th character
87  * are discarded. If str_m is greater than zero it is guaranteed
88  * the resulting string will be null-terminated.
89  *
90  * NOTE that this matches the ISO C99, OpenBSD, and GNU C library 2.1,
91  * but is different from some older and vendor implementations,
92  * and is also different from XPG, XSH5, SUSv2 specifications.
93  * For historical discussion on changes in the semantics and standards
94  * of snprintf see printf(3) man page in the Linux programmers manual.
95  *
96  * Routines asprintf and vasprintf return a pointer (in the ptr argument)
97  * to a buffer sufficiently large to hold the resulting string. This pointer
98  * should be passed to free(3) to release the allocated storage when it is
99  * no longer needed. If sufficient space cannot be allocated, these functions
100  * will return -1 and set ptr to be a NULL pointer. These two routines are a
101  * GNU C library extensions (glibc).
102  *
103  * Routines asnprintf and vasnprintf are similar to asprintf and vasprintf,
104  * yet, like snprintf and vsnprintf counterparts, will write at most str_m-1
105  * characters into the allocated output string, the last character in the
106  * allocated buffer then gets the terminating null. If the formatted string
107  * length (the return value) is greater than or equal to the str_m argument,
108  * the resulting string was truncated and some of the formatted characters
109  * were discarded. These routines present a handy way to limit the amount
110  * of allocated memory to some sane value.
111  *
112  * AVAILABILITY
113  *   http://www.ijs.si/software/snprintf/
114  *
115  * REVISION HISTORY
116  * 1999-04      V0.9  Mark Martinec
117  *              - initial version, some modifications after comparing printf
118  *                man pages for Digital Unix 4.0, Solaris 2.6 and HPUX 10,
119  *                and checking how Perl handles sprintf (differently!);
120  * 1999-04-09   V1.0  Mark Martinec <mark.martinec@ijs.si>
121  *              - added main test program, fixed remaining inconsistencies,
122  *                added optional (long long int) support;
123  * 1999-04-12   V1.1  Mark Martinec <mark.martinec@ijs.si>
124  *              - support the 'p' conversion (pointer to void);
125  *              - if a string precision is specified
126  *                make sure the string beyond the specified precision
127  *                will not be referenced (e.g. by strlen);
128  * 1999-04-13   V1.2  Mark Martinec <mark.martinec@ijs.si>
129  *              - support synonyms %D=%ld, %U=%lu, %O=%lo;
130  *              - speed up the case of long format string with few conversions;
131  * 1999-06-30   V1.3  Mark Martinec <mark.martinec@ijs.si>
132  *              - fixed runaway loop (eventually crashing when str_l wraps
133  *                beyond 2^31) while copying format string without
134  *                conversion specifiers to a buffer that is too short
135  *                (thanks to Edwin Young <edwiny@autonomy.com> for
136  *                spotting the problem);
137  *              - added macros PORTABLE_SNPRINTF_VERSION_(MAJOR|MINOR)
138  *                to snprintf.h
139  * 2000-02-14   V2.0 (never released) Mark Martinec <mark.martinec@ijs.si>
140  *              - relaxed license terms: The Artistic License now applies.
141  *                You may still apply the GNU GENERAL PUBLIC LICENSE
142  *                as was distributed with previous versions, if you prefer;
143  *              - changed REVISION HISTORY dates to use ISO 8601 date format;
144  *              - added vsnprintf (patch also independently proposed by
145  *                Caolan McNamara 2000-05-04, and Keith M Willenson 2000-06-01)
146  * 2000-06-27   V2.1  Mark Martinec <mark.martinec@ijs.si>
147  *              - removed POSIX check for str_m<1; value 0 for str_m is
148  *                allowed by ISO C99 (and GNU C library 2.1) - (pointed out
149  *                on 2000-05-04 by Caolan McNamara, caolan@ csn dot ul dot ie).
150  *                Besides relaxed license this change in standards adherence
151  *                is the main reason to bump up the major version number;
152  *              - added nonstandard routines asnprintf, vasnprintf, asprintf,
153  *                vasprintf that dynamically allocate storage for the
154  *                resulting string; these routines are not compiled by default,
155  *                see comments where NEED_V?ASN?PRINTF macros are defined;
156  *              - autoconf contributed by Caolan McNamara
157  * 2000-10-06   V2.2  Mark Martinec <mark.martinec@ijs.si>
158  *              - BUG FIX: the %c conversion used a temporary variable
159  *                that was no longer in scope when referenced,
160  *                possibly causing incorrect resulting character;
161  *              - BUG FIX: make precision and minimal field width unsigned
162  *                to handle huge values (2^31 <= n < 2^32) correctly;
163  *                also be more careful in the use of signed/unsigned/size_t
164  *                internal variables - probably more careful than many
165  *                vendor implementations, but there may still be a case
166  *                where huge values of str_m, precision or minimal field
167  *                could cause incorrect behaviour;
168  *              - use separate variables for signed/unsigned arguments,
169  *                and for short/int, long, and long long argument lengths
170  *                to avoid possible incompatibilities on certain
171  *                computer architectures. Also use separate variable
172  *                arg_sign to hold sign of a numeric argument,
173  *                to make code more transparent;
174  *              - some fiddling with zero padding and "0x" to make it
175  *                Linux compatible;
176  *              - systematically use macros fast_memcpy and fast_memset
177  *                instead of case-by-case hand optimization; determine some
178  *                breakeven string lengths for different architectures;
179  *              - terminology change: 'format' -> 'conversion specifier',
180  *                'C9x' -> 'ISO/IEC 9899:1999 ("ISO C99")',
181  *                'alternative form' -> 'alternate form',
182  *                'data type modifier' -> 'length modifier';
183  *              - several comments rephrased and new ones added;
184  *              - make compiler not complain about 'credits' defined but
185  *                not used;
186  */
187
188
189 /* Define HAVE_SNPRINTF if your system already has snprintf and vsnprintf.
190  *
191  * If HAVE_SNPRINTF is defined this module will not produce code for
192  * snprintf and vsnprintf, unless PREFER_PORTABLE_SNPRINTF is defined as well,
193  * causing this portable version of snprintf to be called portable_snprintf
194  * (and portable_vsnprintf).
195  */
196 /* #define HAVE_SNPRINTF */
197
198 /* Define PREFER_PORTABLE_SNPRINTF if your system does have snprintf and
199  * vsnprintf but you would prefer to use the portable routine(s) instead.
200  * In this case the portable routine is declared as portable_snprintf
201  * (and portable_vsnprintf) and a macro 'snprintf' (and 'vsnprintf')
202  * is defined to expand to 'portable_v?snprintf' - see file snprintf.h .
203  * Defining this macro is only useful if HAVE_SNPRINTF is also defined,
204  * but does does no harm if defined nevertheless.
205  */
206 /* #define PREFER_PORTABLE_SNPRINTF */
207
208 /* Define SNPRINTF_LONGLONG_SUPPORT if you want to support
209  * data type (long long int) and length modifier 'll' (e.g. %lld).
210  * If undefined, 'll' is recognized but treated as a single 'l'.
211  *
212  * If the system's sprintf does not handle 'll'
213  * the SNPRINTF_LONGLONG_SUPPORT must not be defined!
214  *
215  * This is off by default as (long long int) is a language extension.
216  */
217 /* #define SNPRINTF_LONGLONG_SUPPORT */
218
219 /* Define NEED_SNPRINTF_ONLY if you only need snprintf, and not vsnprintf.
220  * If NEED_SNPRINTF_ONLY is defined, the snprintf will be defined directly,
221  * otherwise both snprintf and vsnprintf routines will be defined
222  * and snprintf will be a simple wrapper around vsnprintf, at the expense
223  * of an extra procedure call.
224  */
225 /* #define NEED_SNPRINTF_ONLY */
226
227 /* Define NEED_V?ASN?PRINTF macros if you need library extension
228  * routines asprintf, vasprintf, asnprintf, vasnprintf respectively,
229  * and your system library does not provide them. They are all small
230  * wrapper routines around portable_vsnprintf. Defining any of the four
231  * NEED_V?ASN?PRINTF macros automatically turns off NEED_SNPRINTF_ONLY
232  * and turns on PREFER_PORTABLE_SNPRINTF.
233  *
234  * Watch for name conflicts with the system library if these routines
235  * are already present there.
236  *
237  * NOTE: vasprintf and vasnprintf routines need va_copy() from stdarg.h, as
238  * specified by C99, to be able to traverse the same list of arguments twice.
239  * I don't know of any other standard and portable way of achieving the same.
240  * With some versions of gcc you may use __va_copy(). You might even get away
241  * with "ap2 = ap", in this case you must not call va_end(ap2) !
242  *   #define va_copy(ap2,ap) ap2 = ap
243  */
244 /* #define NEED_ASPRINTF   */
245 /* #define NEED_ASNPRINTF  */
246 /* #define NEED_VASPRINTF  */
247 /* #define NEED_VASNPRINTF */
248
249
250 /* Define the following macros if desired:
251  *   SOLARIS_COMPATIBLE, SOLARIS_BUG_COMPATIBLE,
252  *   HPUX_COMPATIBLE, HPUX_BUG_COMPATIBLE, LINUX_COMPATIBLE,
253  *   DIGITAL_UNIX_COMPATIBLE, DIGITAL_UNIX_BUG_COMPATIBLE,
254  *   PERL_COMPATIBLE, PERL_BUG_COMPATIBLE,
255  *
256  * - For portable applications it is best not to rely on peculiarities
257  *   of a given implementation so it may be best not to define any
258  *   of the macros that select compatibility and to avoid features
259  *   that vary among the systems.
260  *
261  * - Selecting compatibility with more than one operating system
262  *   is not strictly forbidden but is not recommended.
263  *
264  * - 'x'_BUG_COMPATIBLE implies 'x'_COMPATIBLE .
265  *
266  * - 'x'_COMPATIBLE refers to (and enables) a behaviour that is
267  *   documented in a sprintf man page on a given operating system
268  *   and actually adhered to by the system's sprintf (but not on
269  *   most other operating systems). It may also refer to and enable
270  *   a behaviour that is declared 'undefined' or 'implementation specific'
271  *   in the man page but a given implementation behaves predictably
272  *   in a certain way.
273  *
274  * - 'x'_BUG_COMPATIBLE refers to (and enables) a behaviour of system's sprintf
275  *   that contradicts the sprintf man page on the same operating system.
276  *
277  * - I do not claim that the 'x'_COMPATIBLE and 'x'_BUG_COMPATIBLE
278  *   conditionals take into account all idiosyncrasies of a particular
279  *   implementation, there may be other incompatibilities.
280  */
281
282
283 \f
284 /* ============================================= */
285 /* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */
286 /* ============================================= */
287
288 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
289 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
290
291 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
292 # if defined(NEED_SNPRINTF_ONLY)
293 # undef NEED_SNPRINTF_ONLY
294 # endif
295 # if !defined(PREFER_PORTABLE_SNPRINTF)
296 # define PREFER_PORTABLE_SNPRINTF
297 # endif
298 #endif
299
300 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
301 #define SOLARIS_COMPATIBLE
302 #endif
303
304 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
305 #define HPUX_COMPATIBLE
306 #endif
307
308 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
309 #define DIGITAL_UNIX_COMPATIBLE
310 #endif
311
312 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
313 #define PERL_COMPATIBLE
314 #endif
315
316 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
317 #define LINUX_COMPATIBLE
318 #endif
319
320 #include <sys/types.h>
321 #include <string.h>
322 #include <stdlib.h>
323 #include <stdio.h>
324 #include <stdarg.h>
325 /* to get a working stdarg.h */
326
327
328 #include "portable.h"
329
330 #include <assert.h>
331 #include <errno.h>
332
333 #ifdef isdigit
334 #undef isdigit
335 #endif
336 #define isdigit(c) ((c) >= '0' && (c) <= '9')
337
338 /* For copying strings longer or equal to 'breakeven_point'
339  * it is more efficient to call memcpy() than to do it inline.
340  * The value depends mostly on the processor architecture,
341  * but also on the compiler and its optimization capabilities.
342  * The value is not critical, some small value greater than zero
343  * will be just fine if you don't care to squeeze every drop
344  * of performance out of the code.
345  *
346  * Small values favor memcpy, large values favor inline code.
347  */
348 #if defined(__alpha__) || defined(__alpha)
349 #  define breakeven_point   2   /* AXP (DEC Alpha)     - gcc or cc or egcs */
350 #endif
351 #if defined(__i386__)  || defined(__i386)
352 #  define breakeven_point  12   /* Intel Pentium/Linux - gcc 2.96 */
353 #endif
354 #if defined(__hppa)
355 #  define breakeven_point  10   /* HP-PA               - gcc */
356 #endif
357 #if defined(__sparc__) || defined(__sparc)
358 #  define breakeven_point  33   /* Sun Sparc 5         - gcc 2.8.1 */
359 #endif
360
361 /* some other values of possible interest: */
362 /* #define breakeven_point  8 */  /* VAX 4000          - vaxc */
363 /* #define breakeven_point 19 */  /* VAX 4000          - gcc 2.7.0 */
364
365 #ifndef breakeven_point
366 #  define breakeven_point   6   /* some reasonable one-size-fits-all value */
367 #endif
368
369 #define fast_memcpy(d,s,n) \
370   { register size_t nn = (size_t)(n); \
371     if (nn >= breakeven_point) memcpy((d), (s), nn); \
372     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
373       register char *dd; register const char *ss; \
374       for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
375
376 #define fast_memset(d,c,n) \
377   { register size_t nn = (size_t)(n); \
378     if (nn >= breakeven_point) memset((d), (int)(c), nn); \
379     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
380       register char *dd; register const int cc=(int)(c); \
381       for (dd=(d); nn>0; nn--) *dd++ = cc; } }
382
383 /* prototypes */
384
385 #if defined(NEED_ASPRINTF)
386 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
387 #endif
388 #if defined(NEED_VASPRINTF)
389 int vasprintf  (char **ptr, const char *fmt, va_list ap);
390 #endif
391 #if defined(NEED_ASNPRINTF)
392 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
393 #endif
394 #if defined(NEED_VASNPRINTF)
395 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
396 #endif
397
398 #if defined(HAVE_SNPRINTF)
399 /* declare our portable snprintf  routine under name portable_snprintf  */
400 /* declare our portable vsnprintf routine under name portable_vsnprintf */
401 #else
402 /* declare our portable routines under names snprintf and vsnprintf */
403 #define portable_snprintf snprintf
404 #if !defined(NEED_SNPRINTF_ONLY)
405 #define portable_vsnprintf vsnprintf
406 #endif
407 #endif
408
409 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
410 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
411 #if !defined(NEED_SNPRINTF_ONLY)
412 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
413 #endif
414 #endif
415
416 /* declarations */
417
418 static char credits[] = "\n\
419 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
420 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
421 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
422
423 static void __foo__(void) 
424 {
425    printf("%s",credits);
426    __foo__();
427 }
428
429 #if defined(NEED_ASPRINTF)
430 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
431   va_list ap;
432   size_t str_m;
433   int str_l;
434
435   *ptr = NULL;
436   va_start(ap, fmt);                            /* measure the required size */
437   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
438   va_end(ap);
439   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
440   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
441   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
442   else {
443     int str_l2;
444     va_start(ap, fmt);
445     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
446     va_end(ap);
447     assert(str_l2 == str_l);
448   }
449   return str_l;
450 }
451 #endif
452
453 #if defined(NEED_VASPRINTF)
454 int vasprintf(char **ptr, const char *fmt, va_list ap) {
455   size_t str_m;
456   int str_l;
457
458   *ptr = NULL;
459   { va_list ap2;
460     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
461     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
462     va_end(ap2);
463   }
464   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
465   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
466   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
467   else {
468     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
469     assert(str_l2 == str_l);
470   }
471   return str_l;
472 }
473 #endif
474
475 #if defined(NEED_ASNPRINTF)
476 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
477   va_list ap;
478   int str_l;
479
480   *ptr = NULL;
481   va_start(ap, fmt);                            /* measure the required size */
482   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
483   va_end(ap);
484   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
485   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
486   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
487   if (str_m == 0) {  /* not interested in resulting string, just return size */
488   } else {
489     *ptr = (char *) malloc(str_m);
490     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
491     else {
492       int str_l2;
493       va_start(ap, fmt);
494       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
495       va_end(ap);
496       assert(str_l2 == str_l);
497     }
498   }
499   return str_l;
500 }
501 #endif
502
503 #if defined(NEED_VASNPRINTF)
504 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
505   int str_l;
506
507   *ptr = NULL;
508   { va_list ap2;
509     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
510     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
511     va_end(ap2);
512   }
513   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
514   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
515   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
516   if (str_m == 0) {  /* not interested in resulting string, just return size */
517   } else {
518     *ptr = (char *) malloc(str_m);
519     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
520     else {
521       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
522       assert(str_l2 == str_l);
523     }
524   }
525   return str_l;
526 }
527 #endif
528
529 /*
530  * If the system does have snprintf and the portable routine is not
531  * specifically required, this module produces no code for snprintf/vsnprintf.
532  */
533 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
534
535 #if !defined(NEED_SNPRINTF_ONLY)
536 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
537   va_list ap;
538   int str_l;
539
540   va_start(ap, fmt);
541   str_l = portable_vsnprintf(str, str_m, fmt, ap);
542   va_end(ap);
543   return str_l;
544 }
545 #endif
546
547 #if defined(NEED_SNPRINTF_ONLY)
548 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
549 #else
550 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
551 #endif
552
553 #if defined(NEED_SNPRINTF_ONLY)
554   va_list ap;
555 #endif
556   size_t str_l = 0;
557   const char *p = fmt;
558
559 /* In contrast with POSIX, the ISO C99 now says
560  * that str can be NULL and str_m can be 0.
561  * This is more useful than the old:  if (str_m < 1) return -1; */
562
563 #if defined(NEED_SNPRINTF_ONLY)
564   va_start(ap, fmt);
565 #endif
566   if (!p) p = "";
567   while (*p) {
568     if (*p != '%') {
569    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
570    /* but the following code achieves better performance for cases
571     * where format string is long and contains few conversions */
572       const char *q = strchr(p+1,'%');
573       size_t n = !q ? strlen(p) : (q-p);
574       if (str_l < str_m) {
575         size_t avail = str_m-str_l;
576         fast_memcpy(str+str_l, p, (n>avail?avail:n));
577       }
578       p += n; str_l += n;
579     } else {
580       const char *starting_p;
581       size_t min_field_width = 0, precision = 0;
582       int zero_padding = 0, precision_specified = 0, justify_left = 0;
583       int alternate_form = 0, force_sign = 0;
584       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
585                                      the ' ' flag should be ignored. */
586       char length_modifier = '\0';            /* allowed values: \0, h, l, L */
587       char tmp[32];/* temporary buffer for simple numeric->string conversion */
588
589       const char *str_arg;      /* string address in case of string argument */
590       size_t str_arg_l;         /* natural field width of arg without padding
591                                    and sign */
592       unsigned char uchar_arg;
593         /* unsigned char argument value - only defined for c conversion.
594            N.B. standard explicitly states the char argument for
595            the c conversion is unsigned */
596
597       size_t number_of_zeros_to_pad = 0;
598         /* number of zeros to be inserted for numeric conversions
599            as required by the precision or minimal field width */
600
601       size_t zero_padding_insertion_ind = 0;
602         /* index into tmp where zero padding is to be inserted */
603
604       char fmt_spec = '\0';
605         /* current conversion specifier character */
606
607       str_arg = credits;/* just to make compiler happy (defined but not used)*/
608       str_arg = NULL;
609       starting_p = p; p++;  /* skip '%' */
610    /* parse flags */
611       while (*p == '0' || *p == '-' || *p == '+' ||
612              *p == ' ' || *p == '#' || *p == '\'') {
613         switch (*p) {
614         case '0': zero_padding = 1; break;
615         case '-': justify_left = 1; break;
616         case '+': force_sign = 1; space_for_positive = 0; break;
617         case ' ': force_sign = 1;
618      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
619 #ifdef PERL_COMPATIBLE
620      /* ... but in Perl the last of ' ' and '+' applies */
621                   space_for_positive = 1;
622 #endif
623                   break;
624         case '#': alternate_form = 1; break;
625         case '\'': break;
626         }
627         p++;
628       }
629    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
630
631    /* parse field width */
632       if (*p == '*') {
633         int j;
634         p++; j = va_arg(ap, int);
635         if (j >= 0) min_field_width = j;
636         else { min_field_width = -j; justify_left = 1; }
637       } else if (isdigit((int)(*p))) {
638         /* size_t could be wider than unsigned int;
639            make sure we treat argument like common implementations do */
640         unsigned int uj = *p++ - '0';
641         while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
642         min_field_width = uj;
643       }
644    /* parse precision */
645       if (*p == '.') {
646         p++; precision_specified = 1;
647         if (*p == '*') {
648           int j = va_arg(ap, int);
649           p++;
650           if (j >= 0) precision = j;
651           else {
652             precision_specified = 0; precision = 0;
653          /* NOTE:
654           *   Solaris 2.6 man page claims that in this case the precision
655           *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
656           *   claim that this case should be treated as unspecified precision,
657           *   which is what we do here.
658           */
659           }
660         } else if (isdigit((int)(*p))) {
661           /* size_t could be wider than unsigned int;
662              make sure we treat argument like common implementations do */
663           unsigned int uj = *p++ - '0';
664           while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
665           precision = uj;
666         }
667       }
668    /* parse 'h', 'l' and 'll' length modifiers */
669       if (*p == 'h' || *p == 'l') {
670         length_modifier = *p; p++;
671         if (length_modifier == 'l' && *p == 'l') {   /* double l = long long */
672 #ifdef SNPRINTF_LONGLONG_SUPPORT
673           length_modifier = '2';                  /* double l encoded as '2' */
674 #else
675           length_modifier = 'l';                 /* treat it as a single 'l' */
676 #endif
677           p++;
678         }
679       }
680       fmt_spec = *p;
681    /* common synonyms: */
682       switch (fmt_spec) {
683       case 'i': fmt_spec = 'd'; break;
684       case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
685       case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
686       case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
687       default: break;
688       }
689    /* get parameter value, do initial processing */
690       switch (fmt_spec) {
691       case '%': /* % behaves similar to 's' regarding flags and field widths */
692       case 'c': /* c behaves similar to 's' regarding flags and field widths */
693       case 's':
694         length_modifier = '\0';          /* wint_t and wchar_t not supported */
695      /* the result of zero padding flag with non-numeric conversion specifier*/
696      /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
697      /* Digital Unix and Linux does not. */
698 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
699         zero_padding = 0;    /* turn zero padding off for string conversions */
700 #endif
701         str_arg_l = 1;
702         switch (fmt_spec) {
703         case '%':
704           str_arg = p; break;
705         case 'c': {
706           int j = va_arg(ap, int);
707           uchar_arg = (unsigned char) j;   /* standard demands unsigned char */
708           str_arg = (const char *) &uchar_arg;
709           break;
710         }
711         case 's':
712           str_arg = va_arg(ap, const char *);
713           if (!str_arg) str_arg_l = 0;
714        /* make sure not to address string beyond the specified precision !!! */
715           else if (!precision_specified) str_arg_l = strlen(str_arg);
716        /* truncate string if necessary as requested by precision */
717           else if (precision == 0) str_arg_l = 0;
718           else {
719        /* memchr on HP does not like n > 2^31  !!! */
720             char *q = (char *) memchr(str_arg, '\0',
721                              precision <= 0x7fffffff ? precision : 0x7fffffff);
722             str_arg_l = !q ? precision : (q-str_arg);
723           }
724           break;
725         default: break;
726         }
727         break;
728       case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
729         /* NOTE: the u, o, x, X and p conversion specifiers imply
730                  the value is unsigned;  d implies a signed value */
731
732         int arg_sign = 0;
733           /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
734             +1 if greater than zero (or nonzero for unsigned arguments),
735             -1 if negative (unsigned argument is never negative) */
736
737         int int_arg = 0;  unsigned int uint_arg = 0;
738           /* only defined for length modifier h, or for no length modifiers */
739
740         long int long_arg = 0;  unsigned long int ulong_arg = 0;
741           /* only defined for length modifier l */
742
743         void *ptr_arg = NULL;
744           /* pointer argument value -only defined for p conversion */
745
746 #ifdef SNPRINTF_LONGLONG_SUPPORT
747         long long int long_long_arg = 0;
748         unsigned long long int ulong_long_arg = 0;
749           /* only defined for length modifier ll */
750 #endif
751         if (fmt_spec == 'p') {
752         /* HPUX 10: An l, h, ll or L before any other conversion character
753          *   (other than d, i, u, o, x, or X) is ignored.
754          * Digital Unix:
755          *   not specified, but seems to behave as HPUX does.
756          * Solaris: If an h, l, or L appears before any other conversion
757          *   specifier (other than d, i, u, o, x, or X), the behavior
758          *   is undefined. (Actually %hp converts only 16-bits of address
759          *   and %llp treats address as 64-bit data which is incompatible
760          *   with (void *) argument on a 32-bit system).
761          */
762 #ifdef SOLARIS_COMPATIBLE
763 #  ifdef SOLARIS_BUG_COMPATIBLE
764           /* keep length modifiers even if it represents 'll' */
765 #  else
766           if (length_modifier == '2') length_modifier = '\0';
767 #  endif
768 #else
769           length_modifier = '\0';
770 #endif
771           ptr_arg = va_arg(ap, void *);
772           if (ptr_arg != NULL) arg_sign = 1;
773         } else if (fmt_spec == 'd') {  /* signed */
774           switch (length_modifier) {
775           case '\0':
776           case 'h':
777          /* It is non-portable to specify a second argument of char or short
778           * to va_arg, because arguments seen by the called function
779           * are not char or short.  C converts char and short arguments
780           * to int before passing them to a function.
781           */
782             int_arg = va_arg(ap, int);
783             if      (int_arg > 0) arg_sign =  1;
784             else if (int_arg < 0) arg_sign = -1;
785             break;
786           case 'l':
787             long_arg = va_arg(ap, long int);
788             if      (long_arg > 0) arg_sign =  1;
789             else if (long_arg < 0) arg_sign = -1;
790             break;
791 #ifdef SNPRINTF_LONGLONG_SUPPORT
792           case '2':
793             long_long_arg = va_arg(ap, long long int);
794             if      (long_long_arg > 0) arg_sign =  1;
795             else if (long_long_arg < 0) arg_sign = -1;
796             break;
797 #endif
798           }
799         } else {  /* unsigned */
800           switch (length_modifier) {
801           case '\0':
802           case 'h':
803             uint_arg = va_arg(ap, unsigned int);
804             if (uint_arg) arg_sign = 1;
805             break;
806           case 'l':
807             ulong_arg = va_arg(ap, unsigned long int);
808             if (ulong_arg) arg_sign = 1;
809             break;
810 #ifdef SNPRINTF_LONGLONG_SUPPORT
811           case '2':
812             ulong_long_arg = va_arg(ap, unsigned long long int);
813             if (ulong_long_arg) arg_sign = 1;
814             break;
815 #endif
816           }
817         }
818         str_arg = tmp; str_arg_l = 0;
819      /* NOTE:
820       *   For d, i, u, o, x, and X conversions, if precision is specified,
821       *   the '0' flag should be ignored. This is so with Solaris 2.6,
822       *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
823       */
824 #ifndef PERL_COMPATIBLE
825         if (precision_specified) zero_padding = 0;
826 #endif
827         if (fmt_spec == 'd') {
828           if (force_sign && arg_sign >= 0)
829             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
830          /* leave negative numbers for sprintf to handle,
831             to avoid handling tricky cases like (short int)(-32768) */
832 #ifdef LINUX_COMPATIBLE
833         } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
834           tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
835 #endif
836         } else if (alternate_form) {
837           if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
838             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
839          /* alternate form should have no effect for p conversion, but ... */
840 #ifdef HPUX_COMPATIBLE
841           else if (fmt_spec == 'p'
842          /* HPUX 10: for an alternate form of p conversion,
843           *          a nonzero result is prefixed by 0x. */
844 #ifndef HPUX_BUG_COMPATIBLE
845          /* Actually it uses 0x prefix even for a zero value. */
846                    && arg_sign != 0
847 #endif
848                   ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
849 #endif
850         }
851         zero_padding_insertion_ind = str_arg_l;
852         if (!precision_specified) precision = 1;   /* default precision is 1 */
853         if (precision == 0 && arg_sign == 0
854 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
855             && fmt_spec != 'p'
856          /* HPUX 10 man page claims: With conversion character p the result of
857           * converting a zero value with a precision of zero is a null string.
858           * Actually HP returns all zeroes, and Linux returns "(nil)". */
859 #endif
860         ) {
861          /* converted to null string */
862          /* When zero value is formatted with an explicit precision 0,
863             the resulting formatted string is empty (d, i, u, o, x, X, p).   */
864         } else {
865           char f[5]; int f_l = 0;
866           f[f_l++] = '%';    /* construct a simple format string for sprintf */
867           if (!length_modifier) { }
868           else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
869           else f[f_l++] = length_modifier;
870           f[f_l++] = fmt_spec; f[f_l++] = '\0';
871           if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
872           else if (fmt_spec == 'd') {  /* signed */
873             switch (length_modifier) {
874             case '\0':
875             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
876             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
877 #ifdef SNPRINTF_LONGLONG_SUPPORT
878             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
879 #endif
880             }
881           } else {  /* unsigned */
882             switch (length_modifier) {
883             case '\0':
884             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg);  break;
885             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
886 #ifdef SNPRINTF_LONGLONG_SUPPORT
887             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
888 #endif
889             }
890           }
891          /* include the optional minus sign and possible "0x"
892             in the region before the zero padding insertion point */
893           if (zero_padding_insertion_ind < str_arg_l &&
894               tmp[zero_padding_insertion_ind] == '-') {
895             zero_padding_insertion_ind++;
896           }
897           if (zero_padding_insertion_ind+1 < str_arg_l &&
898               tmp[zero_padding_insertion_ind]   == '0' &&
899              (tmp[zero_padding_insertion_ind+1] == 'x' ||
900               tmp[zero_padding_insertion_ind+1] == 'X') ) {
901             zero_padding_insertion_ind += 2;
902           }
903         }
904         { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
905           if (alternate_form && fmt_spec == 'o'
906 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
907               && (str_arg_l > 0)
908 #endif
909 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
910 #else
911               /* unless zero is already the first character */
912               && !(zero_padding_insertion_ind < str_arg_l
913                    && tmp[zero_padding_insertion_ind] == '0')
914 #endif
915           ) {        /* assure leading zero for alternate-form octal numbers */
916             if (!precision_specified || precision < num_of_digits+1) {
917              /* precision is increased to force the first character to be zero,
918                 except if a zero value is formatted with an explicit precision
919                 of zero */
920               precision = num_of_digits+1; precision_specified = 1;
921             }
922           }
923        /* zero padding to specified precision? */
924           if (num_of_digits < precision) 
925             number_of_zeros_to_pad = precision - num_of_digits;
926         }
927      /* zero padding to specified minimal field width? */
928         if (!justify_left && zero_padding) {
929           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
930           if (n > 0) number_of_zeros_to_pad += n;
931         }
932         break;
933       }
934       default: /* unrecognized conversion specifier, keep format string as-is*/
935         zero_padding = 0;  /* turn zero padding off for non-numeric convers. */
936 #ifndef DIGITAL_UNIX_COMPATIBLE
937         justify_left = 1; min_field_width = 0;                /* reset flags */
938 #endif
939 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
940      /* keep the entire format string unchanged */
941         str_arg = starting_p; str_arg_l = p - starting_p;
942      /* well, not exactly so for Linux, which does something inbetween,
943       * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y"  */
944 #else
945      /* discard the unrecognized conversion, just keep *
946       * the unrecognized conversion character          */
947         str_arg = p; str_arg_l = 0;
948 #endif
949         if (*p) str_arg_l++;  /* include invalid conversion specifier unchanged
950                                  if not at end-of-string */
951         break;
952       }
953       if (*p) p++;      /* step over the just processed conversion specifier */
954    /* insert padding to the left as requested by min_field_width;
955       this does not include the zero padding in case of numerical conversions*/
956       if (!justify_left) {                /* left padding with blank or zero */
957         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
958         if (n > 0) {
959           if (str_l < str_m) {
960             int avail = str_m-str_l;
961             fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
962           }
963           str_l += n;
964         }
965       }
966    /* zero padding as requested by the precision or by the minimal field width
967     * for numeric conversions required? */
968       if (number_of_zeros_to_pad <= 0) {
969      /* will not copy first part of numeric right now, *
970       * force it to be copied later in its entirety    */
971         zero_padding_insertion_ind = 0;
972       } else {
973      /* insert first part of numerics (sign or '0x') before zero padding */
974         int n = zero_padding_insertion_ind;
975         if (n > 0) {
976           if (str_l < str_m) {
977             int avail = str_m-str_l;
978             fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
979           }
980           str_l += n;
981         }
982      /* insert zero padding as requested by the precision or min field width */
983         n = number_of_zeros_to_pad;
984         if (n > 0) {
985           if (str_l < str_m) {
986             int avail = str_m-str_l;
987             fast_memset(str+str_l, '0', (n>avail?avail:n));
988           }
989           str_l += n;
990         }
991       }
992    /* insert formatted string
993     * (or as-is conversion specifier for unknown conversions) */
994       { int n = str_arg_l - zero_padding_insertion_ind;
995         if (n > 0) {
996           if (str_l < str_m) {
997             int avail = str_m-str_l;
998             fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
999                         (n>avail?avail:n));
1000           }
1001           str_l += n;
1002         }
1003       }
1004    /* insert right padding */
1005       if (justify_left) {          /* right blank padding to the field width */
1006         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1007         if (n > 0) {
1008           if (str_l < str_m) {
1009             int avail = str_m-str_l;
1010             fast_memset(str+str_l, ' ', (n>avail?avail:n));
1011           }
1012           str_l += n;
1013         }
1014       }
1015     }
1016   }
1017 #if defined(NEED_SNPRINTF_ONLY)
1018   va_end(ap);
1019 #endif
1020   if (str_m > 0) { /* make sure the string is null-terminated
1021                       even at the expense of overwriting the last character
1022                       (shouldn't happen, but just in case) */
1023     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1024   }
1025   /* Return the number of characters formatted (excluding trailing null
1026    * character), that is, the number of characters that would have been
1027    * written to the buffer if it were large enough.
1028    *
1029    * The value of str_l should be returned, but str_l is of unsigned type
1030    * size_t, and snprintf is int, possibly leading to an undetected
1031    * integer overflow, resulting in a negative return value, which is illegal.
1032    * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1033    * Should errno be set to EOVERFLOW and EOF returned in this case???
1034    */
1035   return (int) str_l;
1036 }
1037 #endif
1038
1039
1040 /* FIXME: better place */
1041 #include "xbt/sysdep.h"
1042
1043 char *bprintf(const char*fmt, ...) {
1044   va_list ap;
1045   char *res;
1046   
1047   va_start(ap, fmt);
1048   vasprintf(&res,fmt,ap);
1049   va_end(ap);
1050   return res;
1051 }