Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
model-checker : get hash of local and global variables which are not pointers
[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 /* ============================================= */
284 /* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */
285 /* ============================================= */
286
287 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
288 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
289
290 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
291 # if defined(NEED_SNPRINTF_ONLY)
292 # undef NEED_SNPRINTF_ONLY
293 # endif
294 # if !defined(PREFER_PORTABLE_SNPRINTF)
295 # define PREFER_PORTABLE_SNPRINTF
296 # endif
297 #endif
298
299 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
300 #define SOLARIS_COMPATIBLE
301 #endif
302
303 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
304 #define HPUX_COMPATIBLE
305 #endif
306
307 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
308 #define DIGITAL_UNIX_COMPATIBLE
309 #endif
310
311 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
312 #define PERL_COMPATIBLE
313 #endif
314
315 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
316 #define LINUX_COMPATIBLE
317 #endif
318
319 #include "portable.h"           /* to get a working stdarg.h */
320
321 #include <sys/types.h>
322 #include <string.h>
323 #include <stdlib.h>
324 #include <stdio.h>
325 #include <stdarg.h>
326
327 #include <assert.h>
328 #include <errno.h>
329 #include "xbt/str.h"
330
331 #ifdef isdigit
332 #undef isdigit
333 #endif
334 #define isdigit(c) ((c) >= '0' && (c) <= '9')
335
336 /* For copying strings longer or equal to 'breakeven_point'
337  * it is more efficient to call memcpy() than to do it inline.
338  * The value depends mostly on the processor architecture,
339  * but also on the compiler and its optimization capabilities.
340  * The value is not critical, some small value greater than zero
341  * will be just fine if you don't care to squeeze every drop
342  * of performance out of the code.
343  *
344  * Small values favor memcpy, large values favor inline code.
345  */
346 #if defined(__alpha__) || defined(__alpha)
347 #  define breakeven_point   2   /* AXP (DEC Alpha)     - gcc or cc or egcs */
348 #endif
349 #if defined(__i386__)  || defined(__i386)
350 #  define breakeven_point  12   /* Intel Pentium/Linux - gcc 2.96 */
351 #endif
352 #if defined(__hppa)
353 #  define breakeven_point  10   /* HP-PA               - gcc */
354 #endif
355 #if defined(__sparc__) || defined(__sparc)
356 #  define breakeven_point  33   /* Sun Sparc 5         - gcc 2.8.1 */
357 #endif
358
359 /* some other values of possible interest: */
360                                                                                                                                                                                                                                                                                                                                                                                                   /* #define breakeven_point  8 *//* VAX 4000          - vaxc */
361                                                                                                                                                                                                                                                                                                                                                                                                   /* #define breakeven_point 19 *//* VAX 4000          - gcc 2.7.0 */
362
363 #ifndef breakeven_point
364 #  define breakeven_point   6   /* some reasonable one-size-fits-all value */
365 #endif
366
367 #define fast_memcpy(d,s,n) \
368   { register size_t nn = (size_t)(n); \
369   if (nn >= breakeven_point) memcpy((d), (s), nn); \
370   else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
371   register char *dd; register const char *ss; \
372   for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
373
374 #define fast_memset(d,c,n) \
375   { register size_t nn = (size_t)(n); \
376   if (nn >= breakeven_point) memset((d), (int)(c), nn); \
377   else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
378   register char *dd; register const int cc=(int)(c); \
379   for (dd=(d); nn>0; nn--) *dd++ = cc; } }
380
381 /* prototypes */
382
383
384 #if defined(NEED_ASPRINTF)
385 int asprintf(char **ptr, const char *fmt, /*args */ ...);
386 #endif
387 #if defined(NEED_VASPRINTF)
388 int vasprintf(char **ptr, const char *fmt, va_list ap);
389 #endif
390
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 #  if defined(_MSC_VER) && (_MSC_VER >= 1400)
402 #    define portable_snprintf  _snprintf
403 #    define portable_vsnprintf  vsnprintf
404 #  else
405 #    define portable_snprintf  snprintf
406 #    define portable_vsnprintf vsnprintf
407 #  endif
408 #else
409 /* declare our portable routines under names snprintf and vsnprintf */
410 #define portable_snprintf snprintf
411 #if !defined(NEED_SNPRINTF_ONLY)
412 #define portable_vsnprintf vsnprintf
413 #endif
414 #endif
415
416 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
417 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
418                       ...);
419 #if !defined(NEED_SNPRINTF_ONLY)
420 int portable_vsnprintf(char *str, size_t str_m, const char *fmt,
421                        va_list ap);
422 #endif
423 #endif
424
425   /* FIXME: better place */
426 #include "xbt/sysdep.h"
427
428 /* declarations */
429
430 static char credits[] = "\n\
431   @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
432   @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
433   @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
434
435 static void __foo__(void)
436 {
437   printf("%s", credits);
438   __foo__();
439 }
440
441 #if defined(NEED_ASPRINTF)
442 int asprintf(char **ptr, const char *fmt, /*args */ ...)
443 {
444   va_list ap;
445   size_t str_m;
446   int str_l;
447
448   *ptr = NULL;
449   va_start(ap, fmt);            /* measure the required size */
450   str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
451   va_end(ap);
452   assert(str_l >= 0);           /* possible integer overflow if str_m > INT_MAX */
453   *ptr = (char *) xbt_malloc(str_m = (size_t) str_l + 1);
454   if (*ptr == NULL) {
455     errno = ENOMEM;
456     str_l = -1;
457   } else {
458     int str_l2;
459     va_start(ap, fmt);
460     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
461     va_end(ap);
462     assert(str_l2 == str_l);
463   }
464   return str_l;
465 }
466 #endif
467
468 #if defined(NEED_VASPRINTF)
469 int vasprintf(char **ptr, const char *fmt, va_list ap)
470 {
471   size_t str_m;
472   int str_l;
473
474   *ptr = NULL;
475   {
476     va_list ap2;
477     va_copy(ap2, ap);           /* don't consume the original ap, we'll need it again */
478     str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2);     /*get required size */
479     va_end(ap2);
480   }
481   assert(str_l >= 0);           /* possible integer overflow if str_m > INT_MAX */
482   *ptr = (char *) xbt_malloc(str_m = (size_t) str_l + 1);
483   if (*ptr == NULL) {
484     errno = ENOMEM;
485     str_l = -1;
486   } else {
487     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
488     assert(str_l2 == str_l);
489   }
490   return str_l;
491 }
492 #endif
493
494 #if defined(NEED_ASNPRINTF)
495 int asnprintf(char **ptr, size_t str_m, const char *fmt, /*args */ ...)
496 {
497   va_list ap;
498   int str_l;
499
500   *ptr = NULL;
501   va_start(ap, fmt);            /* measure the required size */
502   str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
503   va_end(ap);
504   assert(str_l >= 0);           /* possible integer overflow if str_m > INT_MAX */
505   if ((size_t) str_l + 1 < str_m)
506     str_m = (size_t) str_l + 1; /* truncate */
507   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
508   if (str_m == 0) {             /* not interested in resulting string, just return size */
509   } else {
510     *ptr = (char *) xbt_malloc(str_m);
511     if (*ptr == NULL) {
512       errno = ENOMEM;
513       str_l = -1;
514     } else {
515       int str_l2;
516       va_start(ap, fmt);
517       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
518       va_end(ap);
519       assert(str_l2 == str_l);
520     }
521   }
522   return str_l;
523 }
524 #endif
525
526 #if defined(NEED_VASNPRINTF)
527 int vasnprintf(char **ptr, size_t str_m, const char *fmt, va_list ap)
528 {
529   int str_l;
530
531   *ptr = NULL;
532   {
533     va_list ap2;
534     va_copy(ap2, ap);           /* don't consume the original ap, we'll need it again */
535     str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2);     /*get required size */
536     va_end(ap2);
537   }
538   assert(str_l >= 0);           /* possible integer overflow if str_m > INT_MAX */
539   if ((size_t) str_l + 1 < str_m)
540     str_m = (size_t) str_l + 1; /* truncate */
541   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
542   if (str_m == 0) {             /* not interested in resulting string, just return size */
543   } else {
544     *ptr = (char *) xbt_malloc(str_m);
545     if (*ptr == NULL) {
546       errno = ENOMEM;
547       str_l = -1;
548     } else {
549       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
550       assert(str_l2 == str_l);
551     }
552   }
553   return str_l;
554 }
555 #endif
556
557 /*
558  * If the system does have snprintf and the portable routine is not
559  * specifically required, this module produces no code for snprintf/vsnprintf.
560  */
561 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
562
563 #if !defined(NEED_SNPRINTF_ONLY)
564 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
565                       ...)
566 {
567   va_list ap;
568   int str_l;
569
570   va_start(ap, fmt);
571   str_l = portable_vsnprintf(str, str_m, fmt, ap);
572   va_end(ap);
573   return str_l;
574 }
575 #endif
576
577 #if defined(NEED_SNPRINTF_ONLY)
578 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
579                       ...)
580 {
581 #else
582 int portable_vsnprintf(char *str, size_t str_m, const char *fmt,
583                        va_list ap)
584 {
585 #endif
586
587 #if defined(NEED_SNPRINTF_ONLY)
588   va_list ap;
589 #endif
590   size_t str_l = 0;
591   const char *p = fmt;
592
593   /* In contrast with POSIX, the ISO C99 now says
594    * that str can be NULL and str_m can be 0.
595    * This is more useful than the old:  if (str_m < 1) return -1; */
596
597 #if defined(NEED_SNPRINTF_ONLY)
598   va_start(ap, fmt);
599 #endif
600   if (!p)
601     p = "";
602   while (*p) {
603     if (*p != '%') {
604       /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
605       /* but the following code achieves better performance for cases
606        * where format string is long and contains few conversions */
607       const char *q = strchr(p + 1, '%');
608       size_t n = !q ? strlen(p) : (q - p);
609       if (str_l < str_m) {
610         size_t avail = str_m - str_l;
611         fast_memcpy(str + str_l, p, (n > avail ? avail : n));
612       }
613       p += n;
614       str_l += n;
615     } else {
616       const char *starting_p;
617       size_t min_field_width = 0, precision = 0;
618       int zero_padding = 0, precision_specified = 0, justify_left = 0;
619       int alternate_form = 0, force_sign = 0;
620       int space_for_positive = 1;       /* If both the ' ' and '+' flags appear,
621                                            the ' ' flag should be ignored. */
622       char length_modifier = '\0';      /* allowed values: \0, h, l, L */
623       char tmp[32];             /* temporary buffer for simple numeric->string conversion */
624
625       const char *str_arg;      /* string address in case of string argument */
626       size_t str_arg_l;         /* natural field width of arg without padding
627                                    and sign */
628       unsigned char uchar_arg;
629       /* unsigned char argument value - only defined for c conversion.
630          N.B. standard explicitly states the char argument for
631          the c conversion is unsigned */
632
633       size_t number_of_zeros_to_pad = 0;
634       /* number of zeros to be inserted for numeric conversions
635          as required by the precision or minimal field width */
636
637       size_t zero_padding_insertion_ind = 0;
638       /* index into tmp where zero padding is to be inserted */
639
640       char fmt_spec = '\0';
641       /* current conversion specifier character */
642
643       str_arg = credits;        /* just to make compiler happy (defined but not used) */
644       str_arg = NULL;
645       starting_p = p;
646       p++;                      /* skip '%' */
647       /* parse flags */
648       while (*p == '0' || *p == '-' || *p == '+' ||
649              *p == ' ' || *p == '#' || *p == '\'') {
650         switch (*p) {
651         case '0':
652           zero_padding = 1;
653           break;
654         case '-':
655           justify_left = 1;
656           break;
657         case '+':
658           force_sign = 1;
659           space_for_positive = 0;
660           break;
661         case ' ':
662           force_sign = 1;
663           /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
664 #ifdef PERL_COMPATIBLE
665           /* ... but in Perl the last of ' ' and '+' applies */
666           space_for_positive = 1;
667 #endif
668           break;
669         case '#':
670           alternate_form = 1;
671           break;
672         case '\'':
673           break;
674         }
675         p++;
676       }
677       /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
678
679       /* parse field width */
680       if (*p == '*') {
681         int j;
682         p++;
683         j = va_arg(ap, int);
684         if (j >= 0)
685           min_field_width = j;
686         else {
687           min_field_width = -j;
688           justify_left = 1;
689         }
690       } else if (isdigit((int) (*p))) {
691         /* size_t could be wider than unsigned int;
692            make sure we treat argument like common implementations do */
693         unsigned int uj = *p++ - '0';
694         while (isdigit((int) (*p)))
695           uj = 10 * uj + (unsigned int) (*p++ - '0');
696         min_field_width = uj;
697       }
698       /* parse precision */
699       if (*p == '.') {
700         p++;
701         precision_specified = 1;
702         if (*p == '*') {
703           int j = va_arg(ap, int);
704           p++;
705           if (j >= 0)
706             precision = j;
707           else {
708             precision_specified = 0;
709             precision = 0;
710             /* NOTE:
711              *   Solaris 2.6 man page claims that in this case the precision
712              *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
713              *   claim that this case should be treated as unspecified precision,
714              *   which is what we do here.
715              */
716           }
717         } else if (isdigit((int) (*p))) {
718           /* size_t could be wider than unsigned int;
719              make sure we treat argument like common implementations do */
720           unsigned int uj = *p++ - '0';
721           while (isdigit((int) (*p)))
722             uj = 10 * uj + (unsigned int) (*p++ - '0');
723           precision = uj;
724         }
725       }
726       /* parse 'h', 'l' and 'll' length modifiers */
727       if (*p == 'h' || *p == 'l') {
728         length_modifier = *p;
729         p++;
730         if (length_modifier == 'l' && *p == 'l') {      /* double l = long long */
731 #ifdef SNPRINTF_LONGLONG_SUPPORT
732           length_modifier = '2';        /* double l encoded as '2' */
733 #else
734           length_modifier = 'l';        /* treat it as a single 'l' */
735 #endif
736           p++;
737         }
738       }
739       fmt_spec = *p;
740       /* common synonyms: */
741       switch (fmt_spec) {
742       case 'i':
743         fmt_spec = 'd';
744         break;
745       case 'D':
746         fmt_spec = 'd';
747         length_modifier = 'l';
748         break;
749       case 'U':
750         fmt_spec = 'u';
751         length_modifier = 'l';
752         break;
753       case 'O':
754         fmt_spec = 'o';
755         length_modifier = 'l';
756         break;
757       default:
758         break;
759       }
760       /* get parameter value, do initial processing */
761       switch (fmt_spec) {
762       case '%':                /* % behaves similar to 's' regarding flags and field widths */
763       case 'c':                /* c behaves similar to 's' regarding flags and field widths */
764       case 's':
765         length_modifier = '\0'; /* wint_t and wchar_t not supported */
766         /* the result of zero padding flag with non-numeric conversion specifier */
767         /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
768         /* Digital Unix and Linux does not. */
769 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
770         zero_padding = 0;       /* turn zero padding off for string conversions */
771 #endif
772         str_arg_l = 1;
773         switch (fmt_spec) {
774         case '%':
775           str_arg = p;
776           break;
777         case 'c':{
778             int j = va_arg(ap, int);
779             uchar_arg = (unsigned char) j;      /* standard demands unsigned char */
780             str_arg = (const char *) &uchar_arg;
781             break;
782           }
783         case 's':
784           str_arg = va_arg(ap, const char *);
785           if (!str_arg)
786             str_arg_l = 0;
787           /* make sure not to address string beyond the specified precision !!! */
788           else if (!precision_specified)
789             str_arg_l = strlen(str_arg);
790           /* truncate string if necessary as requested by precision */
791           else if (precision == 0)
792             str_arg_l = 0;
793           else {
794             /* memchr on HP does not like n > 2^31  !!! */
795             char *q = (char *) memchr(str_arg, '\0',
796                                       precision <=
797                                       0x7fffffff ? precision : 0x7fffffff);
798             str_arg_l = !q ? precision : (q - str_arg);
799           }
800           break;
801         default:
802           break;
803         }
804         break;
805       case 'd':
806       case 'u':
807       case 'o':
808       case 'x':
809       case 'X':
810       case 'p':{
811           /* NOTE: the u, o, x, X and p conversion specifiers imply
812              the value is unsigned;  d implies a signed value */
813
814           int arg_sign = 0;
815           /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
816              +1 if greater than zero (or nonzero for unsigned arguments),
817              -1 if negative (unsigned argument is never negative) */
818
819           int int_arg = 0;
820           unsigned int uint_arg = 0;
821           /* only defined for length modifier h, or for no length modifiers */
822
823           long int long_arg = 0;
824           unsigned long int ulong_arg = 0;
825           /* only defined for length modifier l */
826
827           void *ptr_arg = NULL;
828           /* pointer argument value -only defined for p conversion */
829
830 #ifdef SNPRINTF_LONGLONG_SUPPORT
831           long long int long_long_arg = 0;
832           unsigned long long int ulong_long_arg = 0;
833           /* only defined for length modifier ll */
834 #endif
835           if (fmt_spec == 'p') {
836             /* HPUX 10: An l, h, ll or L before any other conversion character
837              *   (other than d, i, u, o, x, or X) is ignored.
838              * Digital Unix:
839              *   not specified, but seems to behave as HPUX does.
840              * Solaris: If an h, l, or L appears before any other conversion
841              *   specifier (other than d, i, u, o, x, or X), the behavior
842              *   is undefined. (Actually %hp converts only 16-bits of address
843              *   and %llp treats address as 64-bit data which is incompatible
844              *   with (void *) argument on a 32-bit system).
845              */
846 #ifdef SOLARIS_COMPATIBLE
847 #  ifdef SOLARIS_BUG_COMPATIBLE
848             /* keep length modifiers even if it represents 'll' */
849 #  else
850             if (length_modifier == '2')
851               length_modifier = '\0';
852 #  endif
853 #else
854             length_modifier = '\0';
855 #endif
856             ptr_arg = va_arg(ap, void *);
857             if (ptr_arg != NULL)
858               arg_sign = 1;
859           } else if (fmt_spec == 'd') { /* signed */
860             switch (length_modifier) {
861             case '\0':
862             case 'h':
863               /* It is non-portable to specify a second argument of char or short
864                * to va_arg, because arguments seen by the called function
865                * are not char or short.  C converts char and short arguments
866                * to int before passing them to a function.
867                */
868               int_arg = va_arg(ap, int);
869               if (int_arg > 0)
870                 arg_sign = 1;
871               else if (int_arg < 0)
872                 arg_sign = -1;
873               break;
874             case 'l':
875               long_arg = va_arg(ap, long int);
876               if (long_arg > 0)
877                 arg_sign = 1;
878               else if (long_arg < 0)
879                 arg_sign = -1;
880               break;
881 #ifdef SNPRINTF_LONGLONG_SUPPORT
882             case '2':
883               long_long_arg = va_arg(ap, long long int);
884               if (long_long_arg > 0)
885                 arg_sign = 1;
886               else if (long_long_arg < 0)
887                 arg_sign = -1;
888               break;
889 #endif
890             }
891           } else {              /* unsigned */
892             switch (length_modifier) {
893             case '\0':
894             case 'h':
895               uint_arg = va_arg(ap, unsigned int);
896               if (uint_arg)
897                 arg_sign = 1;
898               break;
899             case 'l':
900               ulong_arg = va_arg(ap, unsigned long int);
901               if (ulong_arg)
902                 arg_sign = 1;
903               break;
904 #ifdef SNPRINTF_LONGLONG_SUPPORT
905             case '2':
906               ulong_long_arg = va_arg(ap, unsigned long long int);
907               if (ulong_long_arg)
908                 arg_sign = 1;
909               break;
910 #endif
911             }
912           }
913           str_arg = tmp;
914           str_arg_l = 0;
915           /* NOTE:
916            *   For d, i, u, o, x, and X conversions, if precision is specified,
917            *   the '0' flag should be ignored. This is so with Solaris 2.6,
918            *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
919            */
920 #ifndef PERL_COMPATIBLE
921           if (precision_specified)
922             zero_padding = 0;
923 #endif
924           if (fmt_spec == 'd') {
925             if (force_sign && arg_sign >= 0)
926               tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
927             /* leave negative numbers for sprintf to handle,
928                to avoid handling tricky cases like (short int)(-32768) */
929 #ifdef LINUX_COMPATIBLE
930           } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
931             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
932 #endif
933           } else if (alternate_form) {
934             if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X')) {
935               tmp[str_arg_l++] = '0';
936               tmp[str_arg_l++] = fmt_spec;
937             }
938             /* alternate form should have no effect for p conversion, but ... */
939 #ifdef HPUX_COMPATIBLE
940             else if (fmt_spec == 'p'
941                      /* HPUX 10: for an alternate form of p conversion,
942                       *          a nonzero result is prefixed by 0x. */
943 #ifndef HPUX_BUG_COMPATIBLE
944                      /* Actually it uses 0x prefix even for a zero value. */
945                      && arg_sign != 0
946 #endif
947                 ) {
948               tmp[str_arg_l++] = '0';
949               tmp[str_arg_l++] = 'x';
950             }
951 #endif
952           }
953           zero_padding_insertion_ind = str_arg_l;
954           if (!precision_specified)
955             precision = 1;      /* default precision is 1 */
956           if (precision == 0 && arg_sign == 0
957 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
958               && fmt_spec != 'p'
959               /* HPUX 10 man page claims: With conversion character p the result of
960                * converting a zero value with a precision of zero is a null string.
961                * Actually HP returns all zeroes, and Linux returns "(nil)". */
962 #endif
963               ) {
964             /* converted to null string */
965             /* When zero value is formatted with an explicit precision 0,
966                the resulting formatted string is empty (d, i, u, o, x, X, p).   */
967           } else {
968             char f[5];
969             int f_l = 0;
970             f[f_l++] = '%';     /* construct a simple format string for sprintf */
971             if (!length_modifier) {
972             } else if (length_modifier == '2') {
973               f[f_l++] = 'l';
974               f[f_l++] = 'l';
975             } else
976               f[f_l++] = length_modifier;
977             f[f_l++] = fmt_spec;
978             f[f_l++] = '\0';
979             if (fmt_spec == 'p')
980               str_arg_l += sprintf(tmp + str_arg_l, f, ptr_arg);
981             else if (fmt_spec == 'd') { /* signed */
982               switch (length_modifier) {
983               case '\0':
984               case 'h':
985                 str_arg_l += sprintf(tmp + str_arg_l, f, int_arg);
986                 break;
987               case 'l':
988                 str_arg_l += sprintf(tmp + str_arg_l, f, long_arg);
989                 break;
990 #ifdef SNPRINTF_LONGLONG_SUPPORT
991               case '2':
992                 str_arg_l += sprintf(tmp + str_arg_l, f, long_long_arg);
993                 break;
994 #endif
995               }
996             } else {            /* unsigned */
997               switch (length_modifier) {
998               case '\0':
999               case 'h':
1000                 str_arg_l += sprintf(tmp + str_arg_l, f, uint_arg);
1001                 break;
1002               case 'l':
1003                 str_arg_l += sprintf(tmp + str_arg_l, f, ulong_arg);
1004                 break;
1005 #ifdef SNPRINTF_LONGLONG_SUPPORT
1006               case '2':
1007                 str_arg_l += sprintf(tmp + str_arg_l, f, ulong_long_arg);
1008                 break;
1009 #endif
1010               }
1011             }
1012             /* include the optional minus sign and possible "0x"
1013                in the region before the zero padding insertion point */
1014             if (zero_padding_insertion_ind < str_arg_l &&
1015                 tmp[zero_padding_insertion_ind] == '-') {
1016               zero_padding_insertion_ind++;
1017             }
1018             if (zero_padding_insertion_ind + 1 < str_arg_l &&
1019                 tmp[zero_padding_insertion_ind] == '0' &&
1020                 (tmp[zero_padding_insertion_ind + 1] == 'x' ||
1021                  tmp[zero_padding_insertion_ind + 1] == 'X')) {
1022               zero_padding_insertion_ind += 2;
1023             }
1024           }
1025           {
1026             size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1027             if (alternate_form && fmt_spec == 'o'
1028 #ifdef HPUX_COMPATIBLE          /* ("%#.o",0) -> ""  */
1029                 && (str_arg_l > 0)
1030 #endif
1031 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE      /* ("%#o",0) -> "00" */
1032 #else
1033                 /* unless zero is already the first character */
1034                 && !(zero_padding_insertion_ind < str_arg_l
1035                      && tmp[zero_padding_insertion_ind] == '0')
1036 #endif
1037                 ) {             /* assure leading zero for alternate-form octal numbers */
1038               if (!precision_specified || precision < num_of_digits + 1) {
1039                 /* precision is increased to force the first character to be zero,
1040                    except if a zero value is formatted with an explicit precision
1041                    of zero */
1042                 precision = num_of_digits + 1;
1043                 precision_specified = 1;
1044               }
1045             }
1046             /* zero padding to specified precision? */
1047             if (num_of_digits < precision)
1048               number_of_zeros_to_pad = precision - num_of_digits;
1049           }
1050           /* zero padding to specified minimal field width? */
1051           if (!justify_left && zero_padding) {
1052             int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1053             if (n > 0)
1054               number_of_zeros_to_pad += n;
1055           }
1056           break;
1057         }
1058       default:                 /* unrecognized conversion specifier, keep format string as-is */
1059         zero_padding = 0;       /* turn zero padding off for non-numeric convers. */
1060 #ifndef DIGITAL_UNIX_COMPATIBLE
1061         justify_left = 1;
1062         min_field_width = 0;    /* reset flags */
1063 #endif
1064 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1065         /* keep the entire format string unchanged */
1066         str_arg = starting_p;
1067         str_arg_l = p - starting_p;
1068         /* well, not exactly so for Linux, which does something inbetween,
1069          * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y"  */
1070 #else
1071         /* discard the unrecognized conversion, just keep *
1072          * the unrecognized conversion character          */
1073         str_arg = p;
1074         str_arg_l = 0;
1075 #endif
1076         if (*p)
1077           str_arg_l++;          /* include invalid conversion specifier unchanged
1078                                    if not at end-of-string */
1079         break;
1080       }
1081       if (*p)
1082         p++;                    /* step over the just processed conversion specifier */
1083       /* insert padding to the left as requested by min_field_width;
1084          this does not include the zero padding in case of numerical conversions */
1085       if (!justify_left) {      /* left padding with blank or zero */
1086         int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1087         if (n > 0) {
1088           if (str_l < str_m) {
1089             int avail = str_m - str_l;
1090             fast_memset(str + str_l, (zero_padding ? '0' : ' '),
1091                         (n > avail ? avail : n));
1092           }
1093           str_l += n;
1094         }
1095       }
1096       /* zero padding as requested by the precision or by the minimal field width
1097        * for numeric conversions required? */
1098       if (number_of_zeros_to_pad <= 0) {
1099         /* will not copy first part of numeric right now, *
1100          * force it to be copied later in its entirety    */
1101         zero_padding_insertion_ind = 0;
1102       } else {
1103         /* insert first part of numerics (sign or '0x') before zero padding */
1104         int n = zero_padding_insertion_ind;
1105         if (n > 0) {
1106           if (str_l < str_m) {
1107             int avail = str_m - str_l;
1108             fast_memcpy(str + str_l, str_arg, (n > avail ? avail : n));
1109           }
1110           str_l += n;
1111         }
1112         /* insert zero padding as requested by the precision or min field width */
1113         n = number_of_zeros_to_pad;
1114         if (n > 0) {
1115           if (str_l < str_m) {
1116             int avail = str_m - str_l;
1117             fast_memset(str + str_l, '0', (n > avail ? avail : n));
1118           }
1119           str_l += n;
1120         }
1121       }
1122       /* insert formatted string
1123        * (or as-is conversion specifier for unknown conversions) */
1124       {
1125         int n = str_arg_l - zero_padding_insertion_ind;
1126         if (n > 0) {
1127           if (str_l < str_m) {
1128             int avail = str_m - str_l;
1129             fast_memcpy(str + str_l, str_arg + zero_padding_insertion_ind,
1130                         (n > avail ? avail : n));
1131           }
1132           str_l += n;
1133         }
1134       }
1135       /* insert right padding */
1136       if (justify_left) {       /* right blank padding to the field width */
1137         int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1138         if (n > 0) {
1139           if (str_l < str_m) {
1140             int avail = str_m - str_l;
1141             fast_memset(str + str_l, ' ', (n > avail ? avail : n));
1142           }
1143           str_l += n;
1144         }
1145       }
1146     }
1147   }
1148 #if defined(NEED_SNPRINTF_ONLY)
1149   va_end(ap);
1150 #endif
1151   if (str_m > 0) {              /* make sure the string is null-terminated
1152                                    even at the expense of overwriting the last character
1153                                    (shouldn't happen, but just in case) */
1154     str[str_l <= str_m - 1 ? str_l : str_m - 1] = '\0';
1155   }
1156   /* Return the number of characters formatted (excluding trailing null
1157    * character), that is, the number of characters that would have been
1158    * written to the buffer if it were large enough.
1159    *
1160    * The value of str_l should be returned, but str_l is of unsigned type
1161    * size_t, and snprintf is int, possibly leading to an undetected
1162    * integer overflow, resulting in a negative return value, which is illegal.
1163    * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1164    * Should errno be set to EOVERFLOW and EOF returned in this case???
1165    */
1166   return (int) str_l;
1167 }
1168 #endif
1169
1170
1171 char *bvprintf(const char *fmt, va_list ap)
1172 {
1173   char *res;
1174
1175   if (vasprintf(&res, fmt, ap) < 0) {
1176     /* Do not want to use xbt_die() here, as it uses the logging
1177      * infrastucture and may fail to allocate memory too. */
1178     fprintf(stderr, "bprintf: vasprintf failed. Aborting.\n");
1179     xbt_abort();
1180   }
1181   return res;
1182 }
1183
1184 char *bprintf(const char *fmt, ...)
1185 {
1186   va_list ap;
1187   char *res;
1188
1189   va_start(ap, fmt);
1190   res = bvprintf(fmt, ap);
1191   va_end(ap);
1192   return res;
1193 }