Logo AND Algorithmique Numérique Distribuée

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