Logo AND Algorithmique Numérique Distribuée

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