1 const char miscutil_rcs[] = "$Id: miscutil.c,v 1.79 2015/08/12 10:34:38 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/miscutil.c,v $
6 * Purpose : zalloc, hash_string, strcmpic, strncmpic, and
7 * MinGW32 strdup functions. These are each too small
8 * to deserve their own file but don't really fit in
11 * Copyright : Written by and Copyright (C) 2001-2016 the
12 * Privoxy team. http://www.privoxy.org/
14 * Based on the Internet Junkbuster originally written
15 * by and Copyright (C) 1997 Anonymous Coders and
16 * Junkbusters Corporation. http://www.junkbusters.com
18 * The timegm replacement function was taken from GnuPG,
19 * Copyright (C) 2004 Free Software Foundation, Inc.
21 * The snprintf replacement function is written by
22 * Mark Martinec who also holds the copyright. It can be
23 * used under the terms of the GPL or the terms of the
24 * "Frontier Artistic License".
26 * This program is free software; you can redistribute it
27 * and/or modify it under the terms of the GNU General
28 * Public License as published by the Free Software
29 * Foundation; either version 2 of the License, or (at
30 * your option) any later version.
32 * This program is distributed in the hope that it will
33 * be useful, but WITHOUT ANY WARRANTY; without even the
34 * implied warranty of MERCHANTABILITY or FITNESS FOR A
35 * PARTICULAR PURPOSE. See the GNU General Public
36 * License for more details.
38 * The GNU General Public License should be included with
39 * this file. If not, you can view it at
40 * http://www.gnu.org/copyleft/gpl.html
41 * or write to the Free Software Foundation, Inc., 59
42 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
44 *********************************************************************/
50 #include <sys/types.h>
52 #if !defined(_WIN32) && !defined(__OS2__)
54 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
59 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
61 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
68 const char miscutil_h_rcs[] = MISCUTIL_H_VERSION;
70 /*********************************************************************
74 * Description : Malloc some memory and set it to '\0'.
77 * 1 : size = Size of memory chunk to return.
79 * Returns : Pointer to newly malloc'd memory chunk.
81 *********************************************************************/
82 void *zalloc(size_t size)
86 if ((ret = (void *)malloc(size)) != NULL)
96 /*********************************************************************
98 * Function : strdup_or_die
100 * Description : strdup wrapper that either succeeds or causes
101 * program termination.
103 * Useful in situations were the string length is
104 * "small" and strdup() failures couldn't be handled
105 * better anyway. In case of debug builds, failures
106 * trigger an assert().
109 * 1 : str = String to duplicate
111 * Returns : Pointer to newly strdup'd copy of the string.
113 *********************************************************************/
114 char *strdup_or_die(const char *str)
118 new_str = strdup(str);
122 assert(new_str != NULL);
123 log_error(LOG_LEVEL_FATAL, "Out of memory in strdup_or_die().");
132 /*********************************************************************
134 * Function : malloc_or_die
136 * Description : malloc wrapper that either succeeds or causes
137 * program termination.
139 * Useful in situations were the buffer size is "small"
140 * and malloc() failures couldn't be handled better
141 * anyway. In case of debug builds, failures trigger
145 * 1 : buffer_size = Size of the space to allocate
147 * Returns : Pointer to newly malloc'd memory
149 *********************************************************************/
150 void *malloc_or_die(size_t buffer_size)
154 if (buffer_size == 0)
156 log_error(LOG_LEVEL_ERROR,
157 "malloc_or_die() called with buffer size 0");
158 assert(buffer_size != 0);
162 new_buf = malloc(buffer_size);
166 assert(new_buf != NULL);
167 log_error(LOG_LEVEL_FATAL, "Out of memory in malloc_or_die().");
177 /*********************************************************************
179 * Function : write_pid_file
181 * Description : Writes a pid file with the pid of the main process
187 *********************************************************************/
188 void write_pid_file(void)
193 * If no --pidfile option was given,
194 * we can live without one.
196 if (pidfile == NULL) return;
198 if ((fp = fopen(pidfile, "w")) == NULL)
200 log_error(LOG_LEVEL_INFO, "can't open pidfile '%s': %E", pidfile);
204 fprintf(fp, "%u\n", (unsigned int) getpid());
210 #endif /* def unix */
213 /*********************************************************************
215 * Function : hash_string
217 * Description : Take a string and compute a (hopefuly) unique numeric
218 * integer value. This is useful to "switch" a string.
221 * 1 : s : string to be hashed.
223 * Returns : The string's hash
225 *********************************************************************/
226 unsigned int hash_string(const char* s)
232 h = 5 * h + (unsigned int)*s;
240 /*********************************************************************
242 * Function : strcmpic
244 * Description : Case insensitive string comparison
247 * 1 : s1 = string 1 to compare
248 * 2 : s2 = string 2 to compare
250 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
252 *********************************************************************/
253 int strcmpic(const char *s1, const char *s2)
260 if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
266 return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
271 /*********************************************************************
273 * Function : strncmpic
275 * Description : Case insensitive string comparison (up to n characters)
278 * 1 : s1 = string 1 to compare
279 * 2 : s2 = string 2 to compare
280 * 3 : n = maximum characters to compare
282 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
284 *********************************************************************/
285 int strncmpic(const char *s1, const char *s2, size_t n)
287 if (n <= (size_t)0) return(0);
293 if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
298 if (--n <= (size_t)0) break;
302 return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
307 /*********************************************************************
311 * Description : In-situ-eliminate all leading and trailing whitespace
315 * 1 : s : string to be chomped.
317 * Returns : chomped string
319 *********************************************************************/
320 char *chomp(char *string)
325 * strip trailing whitespace
327 p = string + strlen(string);
328 while (p > string && privoxy_isspace(*(p-1)))
335 * find end of leading whitespace
338 while (*q && privoxy_isspace(*q))
344 * if there was any, move the rest forwards
359 /*********************************************************************
361 * Function : string_append
363 * Description : Reallocate target_string and append text to it.
364 * This makes it easier to append to malloc'd strings.
365 * This is similar to the (removed) strsav(), but
366 * running out of memory isn't catastrophic.
370 * The following style provides sufficient error
371 * checking for this routine, with minimal clutter
372 * in the source code. It is recommended if you
373 * have many calls to this function:
375 * char * s = strdup(...); // don't check for error
376 * string_append(&s, ...); // don't check for error
377 * string_append(&s, ...); // don't check for error
378 * string_append(&s, ...); // don't check for error
379 * if (NULL == s) { ... handle error ... }
383 * char * s = strdup(...); // don't check for error
384 * string_append(&s, ...); // don't check for error
385 * string_append(&s, ...); // don't check for error
386 * if (string_append(&s, ...)) {... handle error ...}
389 * 1 : target_string = Pointer to old text that is to be
390 * extended. *target_string will be free()d by this
391 * routine. target_string must be non-NULL.
392 * If *target_string is NULL, this routine will
393 * do nothing and return with an error - this allows
394 * you to make many calls to this routine and only
395 * check for errors after the last one.
396 * 2 : text_to_append = Text to be appended to old.
399 * Returns : JB_ERR_OK on success, and sets *target_string
400 * to newly malloc'ed appended string. Caller
401 * must free(*target_string).
402 * JB_ERR_MEMORY on out-of-memory. (And free()s
403 * *target_string and sets it to NULL).
404 * JB_ERR_MEMORY if *target_string is NULL.
406 *********************************************************************/
407 jb_err string_append(char **target_string, const char *text_to_append)
413 assert(target_string);
414 assert(text_to_append);
416 if (*target_string == NULL)
418 return JB_ERR_MEMORY;
421 if (*text_to_append == '\0')
426 old_len = strlen(*target_string);
428 new_size = strlen(text_to_append) + old_len + 1;
430 if (NULL == (new_string = realloc(*target_string, new_size)))
432 free(*target_string);
434 *target_string = NULL;
435 return JB_ERR_MEMORY;
438 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
440 *target_string = new_string;
445 /*********************************************************************
447 * Function : string_join
449 * Description : Join two strings together. Frees BOTH the original
450 * strings. If either or both input strings are NULL,
451 * fails as if it had run out of memory.
453 * For comparison, string_append requires that the
454 * second string is non-NULL, and doesn't free it.
456 * Rationale: Too often, we want to do
457 * string_append(s, html_encode(s2)). That assert()s
458 * if s2 is NULL or if html_encode() runs out of memory.
459 * It also leaks memory. Proper checking is cumbersome.
460 * The solution: string_join(s, html_encode(s2)) is safe,
461 * and will free the memory allocated by html_encode().
464 * 1 : target_string = Pointer to old text that is to be
465 * extended. *target_string will be free()d by this
466 * routine. target_string must be non-NULL.
467 * 2 : text_to_append = Text to be appended to old.
469 * Returns : JB_ERR_OK on success, and sets *target_string
470 * to newly malloc'ed appended string. Caller
471 * must free(*target_string).
472 * JB_ERR_MEMORY on out-of-memory, or if
473 * *target_string or text_to_append is NULL. (In
474 * this case, frees *target_string and text_to_append,
475 * sets *target_string to NULL).
477 *********************************************************************/
478 jb_err string_join(char **target_string, char *text_to_append)
482 assert(target_string);
484 if (text_to_append == NULL)
486 freez(*target_string);
487 return JB_ERR_MEMORY;
490 err = string_append(target_string, text_to_append);
492 freez(text_to_append);
498 /*********************************************************************
500 * Function : string_toupper
502 * Description : Produce a copy of string with all convertible
503 * characters converted to uppercase.
506 * 1 : string = string to convert
508 * Returns : Uppercase copy of string if possible,
509 * NULL on out-of-memory or if string was NULL.
511 *********************************************************************/
512 char *string_toupper(const char *string)
517 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
527 *p++ = (char)toupper((int) *q++);
535 /*********************************************************************
537 * Function : string_move
539 * Description : memmove wrapper to move the last part of a string
540 * towards the beginning, overwriting the part in
541 * the middle. strlcpy() can't be used here as the
545 * 1 : dst = Destination to overwrite
546 * 2 : src = Source to move.
550 *********************************************************************/
551 void string_move(char *dst, char *src)
555 /* +1 to copy the terminating nul as well. */
556 memmove(dst, src, strlen(src)+1);
560 /*********************************************************************
564 * Description : Duplicate the first n characters of a string that may
565 * contain '\0' characters.
568 * 1 : string = string to be duplicated
569 * 2 : len = number of bytes to duplicate
571 * Returns : pointer to copy, or NULL if failiure
573 *********************************************************************/
574 char *bindup(const char *string, size_t len)
578 duplicate = (char *)malloc(len);
579 if (NULL != duplicate)
581 memcpy(duplicate, string, len);
589 /*********************************************************************
591 * Function : make_path
593 * Description : Takes a directory name and a file name, returns
594 * the complete path. Handles windows/unix differences.
595 * If the file name is already an absolute path, or if
596 * the directory name is NULL or empty, it returns
600 * 1 : dir: Name of directory or NULL for none.
601 * 2 : file: Name of file. Should not be NULL or empty.
603 * Returns : "dir/file" (Or on windows, "dir\file").
604 * It allocates the string on the heap. Caller frees.
605 * Returns NULL in error (i.e. NULL file or out of
608 *********************************************************************/
609 char * make_path(const char * dir, const char * file)
620 strncpy(path,dir+2,512);
624 strncpy(path,dir+1,512);
629 strncpy(path,dir,512);
637 if (AddPart(path,file,512))
645 #else /* ndef AMIGA */
647 if ((file == NULL) || (*file == '\0'))
649 return NULL; /* Error */
652 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
653 #if defined(_WIN32) || defined(__OS2__)
654 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
655 #else /* ifndef _WIN32 || __OS2__ */
656 || (*file == '/') /* Absolute path (U*ix) */
657 #endif /* ifndef _WIN32 || __OS2__ */
665 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
668 if (*dir != '/' && basedir && *basedir)
671 * Relative path, so start with the base directory.
673 path_size += strlen(basedir) + 1; /* +1 for the slash */
674 path = malloc(path_size);
675 if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
676 strlcpy(path, basedir, path_size);
677 strlcat(path, "/", path_size);
678 strlcat(path, dir, path_size);
681 #endif /* defined unix */
683 path = malloc(path_size);
684 if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
685 strlcpy(path, dir, path_size);
688 assert(NULL != path);
689 #if defined(_WIN32) || defined(__OS2__)
690 if (path[strlen(path)-1] != '\\')
692 strlcat(path, "\\", path_size);
694 #else /* ifndef _WIN32 || __OS2__ */
695 if (path[strlen(path)-1] != '/')
697 strlcat(path, "/", path_size);
699 #endif /* ifndef _WIN32 || __OS2__ */
700 strlcat(path, file, path_size);
704 #endif /* ndef AMIGA */
708 /*********************************************************************
710 * Function : pick_from_range
712 * Description : Pick a positive number out of a given range.
713 * Should only be used if randomness would be nice,
714 * but isn't really necessary.
717 * 1 : range: Highest possible number to pick.
719 * Returns : Picked number.
721 *********************************************************************/
722 long int pick_from_range(long int range)
726 static unsigned long seed = 0;
727 #endif /* def _WIN32 */
732 if (range <= 0) return 0;
735 number = random() % range + 1;
736 #elif defined(MUTEX_LOCKS_AVAILABLE)
737 privoxy_mutex_lock(&rand_mutex);
741 seed = (unsigned long)(GetCurrentThreadId()+GetTickCount());
744 seed = (unsigned long)((rand() << 16) + rand());
745 #endif /* def _WIN32 */
746 number = (unsigned long)((rand() << 16) + (rand())) % (unsigned long)(range + 1);
747 privoxy_mutex_unlock(&rand_mutex);
750 * XXX: Which platforms reach this and are there
751 * better options than just using rand() and hoping
754 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization "
755 "might cause crashes, predictable results or even combine these fine options.");
756 number = rand() % (long int)(range + 1);
758 #endif /* (def HAVE_RANDOM) */
764 #ifdef USE_PRIVOXY_STRLCPY
765 /*********************************************************************
767 * Function : privoxy_strlcpy
769 * Description : strlcpy(3) look-alike for those without decent libc.
772 * 1 : destination: buffer to copy into.
773 * 2 : source: String to copy.
774 * 3 : size: Size of destination buffer.
776 * Returns : The length of the string that privoxy_strlcpy() tried to create.
778 *********************************************************************/
779 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
783 snprintf(destination, size, "%s", source);
785 * Platforms that lack strlcpy() also tend to have
786 * a broken snprintf implementation that doesn't
787 * guarantee nul termination.
789 * XXX: the configure script should detect and reject those.
791 destination[size-1] = '\0';
793 return strlen(source);
795 #endif /* def USE_PRIVOXY_STRLCPY */
799 /*********************************************************************
801 * Function : privoxy_strlcat
803 * Description : strlcat(3) look-alike for those without decent libc.
806 * 1 : destination: C string.
807 * 2 : source: String to copy.
808 * 3 : size: Size of destination buffer.
810 * Returns : The length of the string that privoxy_strlcat() tried to create.
812 *********************************************************************/
813 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
815 const size_t old_length = strlen(destination);
816 return old_length + strlcpy(destination + old_length, source, size - old_length);
818 #endif /* ndef HAVE_STRLCAT */
821 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
822 /*********************************************************************
826 * Description : libc replacement function for the inverse of gmtime().
827 * Copyright (C) 2004 Free Software Foundation, Inc.
829 * Code originally copied from GnuPG, modifications done
830 * for Privoxy: style changed, #ifdefs for _WIN32 added
831 * to have it work on mingw32.
833 * XXX: It's very unlikely to happen, but if the malloc()
834 * call fails the time zone will be permanently set to UTC.
837 * 1 : tm: Broken-down time struct.
839 * Returns : tm converted into time_t seconds.
841 *********************************************************************/
842 time_t timegm(struct tm *tm)
855 old_zone = malloc(3 + strlen(zone) + 1);
858 strcpy(old_zone, "TZ=");
859 strcat(old_zone, zone);
863 #endif /* def _WIN32 */
870 #elif defined(_WIN32)
880 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
883 #ifndef HAVE_SNPRINTF
885 * What follows is a portable snprintf routine, written by Mark Martinec.
886 * See: http://www.ijs.si/software/snprintf/
889 - a portable implementation of snprintf,
890 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
892 snprintf is a routine to convert numeric and string arguments to
893 formatted strings. It is similar to sprintf(3) provided in a system's
894 C library, yet it requires an additional argument - the buffer size -
895 and it guarantees never to store anything beyond the given buffer,
896 regardless of the format or arguments to be formatted. Some newer
897 operating systems do provide snprintf in their C library, but many do
898 not or do provide an inadequate (slow or idiosyncratic) version, which
899 calls for a portable implementation of this routine.
903 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
904 Copyright © 1999, Mark Martinec
908 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
909 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
911 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
912 # if defined(NEED_SNPRINTF_ONLY)
913 # undef NEED_SNPRINTF_ONLY
915 # if !defined(PREFER_PORTABLE_SNPRINTF)
916 # define PREFER_PORTABLE_SNPRINTF
920 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
921 #define SOLARIS_COMPATIBLE
924 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
925 #define HPUX_COMPATIBLE
928 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
929 #define DIGITAL_UNIX_COMPATIBLE
932 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
933 #define PERL_COMPATIBLE
936 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
937 #define LINUX_COMPATIBLE
940 #include <sys/types.h>
951 #define isdigit(c) ((c) >= '0' && (c) <= '9')
953 /* For copying strings longer or equal to 'breakeven_point'
954 * it is more efficient to call memcpy() than to do it inline.
955 * The value depends mostly on the processor architecture,
956 * but also on the compiler and its optimization capabilities.
957 * The value is not critical, some small value greater than zero
958 * will be just fine if you don't care to squeeze every drop
959 * of performance out of the code.
961 * Small values favor memcpy, large values favor inline code.
963 #if defined(__alpha__) || defined(__alpha)
964 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
966 #if defined(__i386__) || defined(__i386)
967 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
970 # define breakeven_point 10 /* HP-PA - gcc */
972 #if defined(__sparc__) || defined(__sparc)
973 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
976 /* some other values of possible interest: */
977 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
978 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
980 #ifndef breakeven_point
981 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
984 #define fast_memcpy(d,s,n) \
985 { register size_t nn = (size_t)(n); \
986 if (nn >= breakeven_point) memcpy((d), (s), nn); \
987 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
988 register char *dd; register const char *ss; \
989 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
991 #define fast_memset(d,c,n) \
992 { register size_t nn = (size_t)(n); \
993 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
994 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
995 register char *dd; register const int cc=(int)(c); \
996 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1000 #if defined(NEED_ASPRINTF)
1001 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1003 #if defined(NEED_VASPRINTF)
1004 int vasprintf (char **ptr, const char *fmt, va_list ap);
1006 #if defined(NEED_ASNPRINTF)
1007 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1009 #if defined(NEED_VASNPRINTF)
1010 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1013 #if defined(HAVE_SNPRINTF)
1014 /* declare our portable snprintf routine under name portable_snprintf */
1015 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1017 /* declare our portable routines under names snprintf and vsnprintf */
1018 #define portable_snprintf snprintf
1019 #if !defined(NEED_SNPRINTF_ONLY)
1020 #define portable_vsnprintf vsnprintf
1024 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1025 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1026 #if !defined(NEED_SNPRINTF_ONLY)
1027 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1033 static char credits[] = "\n\
1034 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1035 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1036 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1038 #if defined(NEED_ASPRINTF)
1039 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1045 va_start(ap, fmt); /* measure the required size */
1046 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1048 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1049 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1050 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1054 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1056 assert(str_l2 == str_l);
1062 #if defined(NEED_VASPRINTF)
1063 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1069 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1070 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1073 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1074 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1075 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1077 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1078 assert(str_l2 == str_l);
1084 #if defined(NEED_ASNPRINTF)
1085 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1090 va_start(ap, fmt); /* measure the required size */
1091 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1093 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1094 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1095 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1096 if (str_m == 0) { /* not interested in resulting string, just return size */
1098 *ptr = (char *) malloc(str_m);
1099 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1103 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1105 assert(str_l2 == str_l);
1112 #if defined(NEED_VASNPRINTF)
1113 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1118 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1119 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1122 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1123 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1124 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1125 if (str_m == 0) { /* not interested in resulting string, just return size */
1127 *ptr = (char *) malloc(str_m);
1128 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1130 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1131 assert(str_l2 == str_l);
1139 * If the system does have snprintf and the portable routine is not
1140 * specifically required, this module produces no code for snprintf/vsnprintf.
1142 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1144 #if !defined(NEED_SNPRINTF_ONLY)
1145 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1150 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1156 #if defined(NEED_SNPRINTF_ONLY)
1157 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1159 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1162 #if defined(NEED_SNPRINTF_ONLY)
1166 const char *p = fmt;
1168 /* In contrast with POSIX, the ISO C99 now says
1169 * that str can be NULL and str_m can be 0.
1170 * This is more useful than the old: if (str_m < 1) return -1; */
1172 #if defined(NEED_SNPRINTF_ONLY)
1178 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1179 /* but the following code achieves better performance for cases
1180 * where format string is long and contains few conversions */
1181 const char *q = strchr(p+1,'%');
1182 size_t n = !q ? strlen(p) : (q-p);
1183 if (str_l < str_m) {
1184 size_t avail = str_m-str_l;
1185 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1189 const char *starting_p;
1190 size_t min_field_width = 0, precision = 0;
1191 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1192 int alternate_form = 0, force_sign = 0;
1193 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1194 the ' ' flag should be ignored. */
1195 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1196 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1198 const char *str_arg; /* string address in case of string argument */
1199 size_t str_arg_l; /* natural field width of arg without padding
1201 unsigned char uchar_arg;
1202 /* unsigned char argument value - only defined for c conversion.
1203 N.B. standard explicitly states the char argument for
1204 the c conversion is unsigned */
1206 size_t number_of_zeros_to_pad = 0;
1207 /* number of zeros to be inserted for numeric conversions
1208 as required by the precision or minimal field width */
1210 size_t zero_padding_insertion_ind = 0;
1211 /* index into tmp where zero padding is to be inserted */
1213 char fmt_spec = '\0';
1214 /* current conversion specifier character */
1216 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1218 starting_p = p; p++; /* skip '%' */
1220 while (*p == '0' || *p == '-' || *p == '+' ||
1221 *p == ' ' || *p == '#' || *p == '\'') {
1223 case '0': zero_padding = 1; break;
1224 case '-': justify_left = 1; break;
1225 case '+': force_sign = 1; space_for_positive = 0; break;
1226 case ' ': force_sign = 1;
1227 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1228 #ifdef PERL_COMPATIBLE
1229 /* ... but in Perl the last of ' ' and '+' applies */
1230 space_for_positive = 1;
1233 case '#': alternate_form = 1; break;
1238 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1240 /* parse field width */
1243 p++; j = va_arg(ap, int);
1244 if (j >= 0) min_field_width = j;
1245 else { min_field_width = -j; justify_left = 1; }
1246 } else if (isdigit((int)(*p))) {
1247 /* size_t could be wider than unsigned int;
1248 make sure we treat argument like common implementations do */
1249 unsigned int uj = *p++ - '0';
1250 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1251 min_field_width = uj;
1253 /* parse precision */
1255 p++; precision_specified = 1;
1257 int j = va_arg(ap, int);
1259 if (j >= 0) precision = j;
1261 precision_specified = 0; precision = 0;
1263 * Solaris 2.6 man page claims that in this case the precision
1264 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1265 * claim that this case should be treated as unspecified precision,
1266 * which is what we do here.
1269 } else if (isdigit((int)(*p))) {
1270 /* size_t could be wider than unsigned int;
1271 make sure we treat argument like common implementations do */
1272 unsigned int uj = *p++ - '0';
1273 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1277 /* parse 'h', 'l' and 'll' length modifiers */
1278 if (*p == 'h' || *p == 'l') {
1279 length_modifier = *p; p++;
1280 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1281 #ifdef SNPRINTF_LONGLONG_SUPPORT
1282 length_modifier = '2'; /* double l encoded as '2' */
1284 length_modifier = 'l'; /* treat it as a single 'l' */
1290 /* common synonyms: */
1292 case 'i': fmt_spec = 'd'; break;
1293 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1294 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1295 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1298 /* get parameter value, do initial processing */
1300 case '%': /* % behaves similar to 's' regarding flags and field widths */
1301 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1303 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1304 /* the result of zero padding flag with non-numeric conversion specifier*/
1305 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1306 /* Digital Unix and Linux does not. */
1307 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1308 zero_padding = 0; /* turn zero padding off for string conversions */
1315 int j = va_arg(ap, int);
1316 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1317 str_arg = (const char *) &uchar_arg;
1321 str_arg = va_arg(ap, const char *);
1322 if (!str_arg) str_arg_l = 0;
1323 /* make sure not to address string beyond the specified precision !!! */
1324 else if (!precision_specified) str_arg_l = strlen(str_arg);
1325 /* truncate string if necessary as requested by precision */
1326 else if (precision == 0) str_arg_l = 0;
1328 /* memchr on HP does not like n > 2^31 !!! */
1329 const char *q = memchr(str_arg, '\0',
1330 precision <= 0x7fffffff ? precision : 0x7fffffff);
1331 str_arg_l = !q ? precision : (q-str_arg);
1337 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1338 /* NOTE: the u, o, x, X and p conversion specifiers imply
1339 the value is unsigned; d implies a signed value */
1342 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1343 +1 if greater than zero (or nonzero for unsigned arguments),
1344 -1 if negative (unsigned argument is never negative) */
1346 int int_arg = 0; unsigned int uint_arg = 0;
1347 /* only defined for length modifier h, or for no length modifiers */
1349 long int long_arg = 0; unsigned long int ulong_arg = 0;
1350 /* only defined for length modifier l */
1352 void *ptr_arg = NULL;
1353 /* pointer argument value -only defined for p conversion */
1355 #ifdef SNPRINTF_LONGLONG_SUPPORT
1356 long long int long_long_arg = 0;
1357 unsigned long long int ulong_long_arg = 0;
1358 /* only defined for length modifier ll */
1360 if (fmt_spec == 'p') {
1361 /* HPUX 10: An l, h, ll or L before any other conversion character
1362 * (other than d, i, u, o, x, or X) is ignored.
1364 * not specified, but seems to behave as HPUX does.
1365 * Solaris: If an h, l, or L appears before any other conversion
1366 * specifier (other than d, i, u, o, x, or X), the behavior
1367 * is undefined. (Actually %hp converts only 16-bits of address
1368 * and %llp treats address as 64-bit data which is incompatible
1369 * with (void *) argument on a 32-bit system).
1371 #ifdef SOLARIS_COMPATIBLE
1372 # ifdef SOLARIS_BUG_COMPATIBLE
1373 /* keep length modifiers even if it represents 'll' */
1375 if (length_modifier == '2') length_modifier = '\0';
1378 length_modifier = '\0';
1380 ptr_arg = va_arg(ap, void *);
1381 if (ptr_arg != NULL) arg_sign = 1;
1382 } else if (fmt_spec == 'd') { /* signed */
1383 switch (length_modifier) {
1386 /* It is non-portable to specify a second argument of char or short
1387 * to va_arg, because arguments seen by the called function
1388 * are not char or short. C converts char and short arguments
1389 * to int before passing them to a function.
1391 int_arg = va_arg(ap, int);
1392 if (int_arg > 0) arg_sign = 1;
1393 else if (int_arg < 0) arg_sign = -1;
1396 long_arg = va_arg(ap, long int);
1397 if (long_arg > 0) arg_sign = 1;
1398 else if (long_arg < 0) arg_sign = -1;
1400 #ifdef SNPRINTF_LONGLONG_SUPPORT
1402 long_long_arg = va_arg(ap, long long int);
1403 if (long_long_arg > 0) arg_sign = 1;
1404 else if (long_long_arg < 0) arg_sign = -1;
1408 } else { /* unsigned */
1409 switch (length_modifier) {
1412 uint_arg = va_arg(ap, unsigned int);
1413 if (uint_arg) arg_sign = 1;
1416 ulong_arg = va_arg(ap, unsigned long int);
1417 if (ulong_arg) arg_sign = 1;
1419 #ifdef SNPRINTF_LONGLONG_SUPPORT
1421 ulong_long_arg = va_arg(ap, unsigned long long int);
1422 if (ulong_long_arg) arg_sign = 1;
1427 str_arg = tmp; str_arg_l = 0;
1429 * For d, i, u, o, x, and X conversions, if precision is specified,
1430 * the '0' flag should be ignored. This is so with Solaris 2.6,
1431 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1433 #ifndef PERL_COMPATIBLE
1434 if (precision_specified) zero_padding = 0;
1436 if (fmt_spec == 'd') {
1437 if (force_sign && arg_sign >= 0)
1438 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1439 /* leave negative numbers for sprintf to handle,
1440 to avoid handling tricky cases like (short int)(-32768) */
1441 #ifdef LINUX_COMPATIBLE
1442 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1443 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1445 } else if (alternate_form) {
1446 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1447 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1448 /* alternate form should have no effect for p conversion, but ... */
1449 #ifdef HPUX_COMPATIBLE
1450 else if (fmt_spec == 'p'
1451 /* HPUX 10: for an alternate form of p conversion,
1452 * a nonzero result is prefixed by 0x. */
1453 #ifndef HPUX_BUG_COMPATIBLE
1454 /* Actually it uses 0x prefix even for a zero value. */
1457 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1460 zero_padding_insertion_ind = str_arg_l;
1461 if (!precision_specified) precision = 1; /* default precision is 1 */
1462 if (precision == 0 && arg_sign == 0
1463 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1465 /* HPUX 10 man page claims: With conversion character p the result of
1466 * converting a zero value with a precision of zero is a null string.
1467 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1470 /* converted to null string */
1471 /* When zero value is formatted with an explicit precision 0,
1472 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1474 char f[5]; int f_l = 0;
1475 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1476 if (!length_modifier) { }
1477 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1478 else f[f_l++] = length_modifier;
1479 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1480 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1481 else if (fmt_spec == 'd') { /* signed */
1482 switch (length_modifier) {
1484 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1485 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1486 #ifdef SNPRINTF_LONGLONG_SUPPORT
1487 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1490 } else { /* unsigned */
1491 switch (length_modifier) {
1493 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1494 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1495 #ifdef SNPRINTF_LONGLONG_SUPPORT
1496 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1500 /* include the optional minus sign and possible "0x"
1501 in the region before the zero padding insertion point */
1502 if (zero_padding_insertion_ind < str_arg_l &&
1503 tmp[zero_padding_insertion_ind] == '-') {
1504 zero_padding_insertion_ind++;
1506 if (zero_padding_insertion_ind+1 < str_arg_l &&
1507 tmp[zero_padding_insertion_ind] == '0' &&
1508 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1509 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1510 zero_padding_insertion_ind += 2;
1513 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1514 if (alternate_form && fmt_spec == 'o'
1515 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1518 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1520 /* unless zero is already the first character */
1521 && !(zero_padding_insertion_ind < str_arg_l
1522 && tmp[zero_padding_insertion_ind] == '0')
1524 ) { /* assure leading zero for alternate-form octal numbers */
1525 if (!precision_specified || precision < num_of_digits+1) {
1526 /* precision is increased to force the first character to be zero,
1527 except if a zero value is formatted with an explicit precision
1529 precision = num_of_digits+1; precision_specified = 1;
1532 /* zero padding to specified precision? */
1533 if (num_of_digits < precision)
1534 number_of_zeros_to_pad = precision - num_of_digits;
1536 /* zero padding to specified minimal field width? */
1537 if (!justify_left && zero_padding) {
1538 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1539 if (n > 0) number_of_zeros_to_pad += n;
1543 default: /* unrecognized conversion specifier, keep format string as-is*/
1544 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1545 #ifndef DIGITAL_UNIX_COMPATIBLE
1546 justify_left = 1; min_field_width = 0; /* reset flags */
1548 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1549 /* keep the entire format string unchanged */
1550 str_arg = starting_p; str_arg_l = p - starting_p;
1551 /* well, not exactly so for Linux, which does something between,
1552 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1554 /* discard the unrecognized conversion, just keep *
1555 * the unrecognized conversion character */
1556 str_arg = p; str_arg_l = 0;
1558 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1559 if not at end-of-string */
1562 if (*p) p++; /* step over the just processed conversion specifier */
1563 /* insert padding to the left as requested by min_field_width;
1564 this does not include the zero padding in case of numerical conversions*/
1565 if (!justify_left) { /* left padding with blank or zero */
1566 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1568 if (str_l < str_m) {
1569 size_t avail = str_m-str_l;
1570 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1575 /* zero padding as requested by the precision or by the minimal field width
1576 * for numeric conversions required? */
1577 if (number_of_zeros_to_pad <= 0) {
1578 /* will not copy first part of numeric right now, *
1579 * force it to be copied later in its entirety */
1580 zero_padding_insertion_ind = 0;
1582 /* insert first part of numerics (sign or '0x') before zero padding */
1583 int n = zero_padding_insertion_ind;
1585 if (str_l < str_m) {
1586 size_t avail = str_m-str_l;
1587 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1591 /* insert zero padding as requested by the precision or min field width */
1592 n = number_of_zeros_to_pad;
1594 if (str_l < str_m) {
1595 size_t avail = str_m-str_l;
1596 fast_memset(str+str_l, '0', (n>avail?avail:n));
1601 /* insert formatted string
1602 * (or as-is conversion specifier for unknown conversions) */
1603 { int n = str_arg_l - zero_padding_insertion_ind;
1605 if (str_l < str_m) {
1606 size_t avail = str_m-str_l;
1607 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1613 /* insert right padding */
1614 if (justify_left) { /* right blank padding to the field width */
1615 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1617 if (str_l < str_m) {
1618 size_t avail = str_m-str_l;
1619 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1626 #if defined(NEED_SNPRINTF_ONLY)
1629 if (str_m > 0) { /* make sure the string is null-terminated
1630 even at the expense of overwriting the last character
1631 (shouldn't happen, but just in case) */
1632 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1634 /* Return the number of characters formatted (excluding trailing null
1635 * character), that is, the number of characters that would have been
1636 * written to the buffer if it were large enough.
1638 * The value of str_l should be returned, but str_l is of unsigned type
1639 * size_t, and snprintf is int, possibly leading to an undetected
1640 * integer overflow, resulting in a negative return value, which is illegal.
1641 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1642 * Should errno be set to EOVERFLOW and EOF returned in this case???
1647 #endif /* ndef HAVE_SNPRINTF */