1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/miscutil.c,v $
5 * Purpose : zalloc, hash_string, strcmpic, strncmpic, and
6 * MinGW32 strdup functions. These are each too small
7 * to deserve their own file but don't really fit in
10 * Copyright : Written by and Copyright (C) 2001-2020 the
11 * Privoxy team. https://www.privoxy.org/
13 * Based on the Internet Junkbuster originally written
14 * by and Copyright (C) 1997 Anonymous Coders and
15 * Junkbusters Corporation. http://www.junkbusters.com
17 * The timegm replacement function was taken from GnuPG,
18 * Copyright (C) 2004 Free Software Foundation, Inc.
20 * The snprintf replacement function is written by
21 * Mark Martinec who also holds the copyright. It can be
22 * used under the terms of the GPL or the terms of the
23 * "Frontier Artistic License".
25 * This program is free software; you can redistribute it
26 * and/or modify it under the terms of the GNU General
27 * Public License as published by the Free Software
28 * Foundation; either version 2 of the License, or (at
29 * your option) any later version.
31 * This program is distributed in the hope that it will
32 * be useful, but WITHOUT ANY WARRANTY; without even the
33 * implied warranty of MERCHANTABILITY or FITNESS FOR A
34 * PARTICULAR PURPOSE. See the GNU General Public
35 * License for more details.
37 * The GNU General Public License should be included with
38 * this file. If not, you can view it at
39 * http://www.gnu.org/copyleft/gpl.html
40 * or write to the Free Software Foundation, Inc., 59
41 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
43 *********************************************************************/
49 #include <sys/types.h>
51 #if !defined(_WIN32) && !defined(__OS2__)
53 #endif /* #if !defined(_WIN32) && !defined(__OS2__) */
58 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
60 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
67 /*********************************************************************
71 * Description : Returns allocated memory that is initialized
75 * 1 : size = Size of memory chunk to return.
77 * Returns : Pointer to newly alloc'd memory chunk.
79 *********************************************************************/
80 void *zalloc(size_t size)
85 ret = calloc(1, size);
87 #warning calloc appears to be unavailable. Your platform will become unsupported in the future
88 if ((ret = (void *)malloc(size)) != NULL)
99 /*********************************************************************
101 * Function : zalloc_or_die
103 * Description : zalloc wrapper that either succeeds or causes
104 * program termination.
106 * Useful in situations were the string length is
107 * "small" and zalloc() failures couldn't be handled
108 * better anyway. In case of debug builds, failures
109 * trigger an assert().
112 * 1 : size = Size of memory chunk to return.
114 * Returns : Pointer to newly malloc'd memory chunk.
116 *********************************************************************/
117 void *zalloc_or_die(size_t size)
121 buffer = zalloc(size);
124 assert(buffer != NULL);
125 log_error(LOG_LEVEL_FATAL, "Out of memory in zalloc_or_die().");
133 /*********************************************************************
135 * Function : strdup_or_die
137 * Description : strdup wrapper that either succeeds or causes
138 * program termination.
140 * Useful in situations were the string length is
141 * "small" and strdup() failures couldn't be handled
142 * better anyway. In case of debug builds, failures
143 * trigger an assert().
146 * 1 : str = String to duplicate
148 * Returns : Pointer to newly strdup'd copy of the string.
150 *********************************************************************/
151 char *strdup_or_die(const char *str)
155 new_str = strdup(str);
159 assert(new_str != NULL);
160 log_error(LOG_LEVEL_FATAL, "Out of memory in strdup_or_die().");
169 /*********************************************************************
171 * Function : malloc_or_die
173 * Description : malloc wrapper that either succeeds or causes
174 * program termination.
176 * Useful in situations were the buffer size is "small"
177 * and malloc() failures couldn't be handled better
178 * anyway. In case of debug builds, failures trigger
182 * 1 : buffer_size = Size of the space to allocate
184 * Returns : Pointer to newly malloc'd memory
186 *********************************************************************/
187 void *malloc_or_die(size_t buffer_size)
191 if (buffer_size == 0)
193 log_error(LOG_LEVEL_ERROR,
194 "malloc_or_die() called with buffer size 0");
195 assert(buffer_size != 0);
199 new_buf = malloc(buffer_size);
203 assert(new_buf != NULL);
204 log_error(LOG_LEVEL_FATAL, "Out of memory in malloc_or_die().");
214 /*********************************************************************
216 * Function : write_pid_file
218 * Description : Writes a pid file with the pid of the main process.
219 * Exits if the file can't be opened
222 * 1 : pid_file = Path of the pid file that gets created.
226 *********************************************************************/
227 void write_pid_file(const char *pid_file)
231 if ((fp = fopen(pid_file, "w")) == NULL)
233 log_error(LOG_LEVEL_FATAL, "can't open pid file '%s': %E", pid_file);
237 fprintf(fp, "%u\n", (unsigned int) getpid());
243 #endif /* def unix */
246 /*********************************************************************
248 * Function : hash_string
250 * Description : Take a string and compute a (hopefuly) unique numeric
251 * integer value. This is useful to "switch" a string.
254 * 1 : s : string to be hashed.
256 * Returns : The string's hash
258 *********************************************************************/
259 unsigned int hash_string(const char* s)
265 h = 5 * h + (unsigned int)*s;
273 /*********************************************************************
275 * Function : strcmpic
277 * Description : Case insensitive string comparison
280 * 1 : s1 = string 1 to compare
281 * 2 : s2 = string 2 to compare
283 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
285 *********************************************************************/
286 int strcmpic(const char *s1, const char *s2)
293 if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
299 return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
304 /*********************************************************************
306 * Function : strncmpic
308 * Description : Case insensitive string comparison (up to n characters)
311 * 1 : s1 = string 1 to compare
312 * 2 : s2 = string 2 to compare
313 * 3 : n = maximum characters to compare
315 * Returns : 0 if s1==s2, Negative if s1<s2, Positive if s1>s2
317 *********************************************************************/
318 int strncmpic(const char *s1, const char *s2, size_t n)
320 if (n <= (size_t)0) return(0);
326 if ((*s1 != *s2) && (privoxy_tolower(*s1) != privoxy_tolower(*s2)))
331 if (--n <= (size_t)0) break;
335 return(privoxy_tolower(*s1) - privoxy_tolower(*s2));
340 /*********************************************************************
344 * Description : In-situ-eliminate all leading and trailing whitespace
348 * 1 : s : string to be chomped.
350 * Returns : chomped string
352 *********************************************************************/
353 char *chomp(char *string)
358 * strip trailing whitespace
360 p = string + strlen(string);
361 while (p > string && privoxy_isspace(*(p-1)))
368 * find end of leading whitespace
371 while (*q && privoxy_isspace(*q))
377 * if there was any, move the rest forwards
392 /*********************************************************************
394 * Function : string_append
396 * Description : Reallocate target_string and append text to it.
397 * This makes it easier to append to malloc'd strings.
398 * This is similar to the (removed) strsav(), but
399 * running out of memory isn't catastrophic.
403 * The following style provides sufficient error
404 * checking for this routine, with minimal clutter
405 * in the source code. It is recommended if you
406 * have many calls to this function:
408 * char * s = strdup(...); // don't check for error
409 * string_append(&s, ...); // don't check for error
410 * string_append(&s, ...); // don't check for error
411 * string_append(&s, ...); // don't check for error
412 * if (NULL == s) { ... handle error ... }
416 * char * s = strdup(...); // don't check for error
417 * string_append(&s, ...); // don't check for error
418 * string_append(&s, ...); // don't check for error
419 * if (string_append(&s, ...)) {... handle error ...}
422 * 1 : target_string = Pointer to old text that is to be
423 * extended. *target_string will be free()d by this
424 * routine. target_string must be non-NULL.
425 * If *target_string is NULL, this routine will
426 * do nothing and return with an error - this allows
427 * you to make many calls to this routine and only
428 * check for errors after the last one.
429 * 2 : text_to_append = Text to be appended to old.
432 * Returns : JB_ERR_OK on success, and sets *target_string
433 * to newly malloc'ed appended string. Caller
434 * must free(*target_string).
435 * JB_ERR_MEMORY on out-of-memory. (And free()s
436 * *target_string and sets it to NULL).
437 * JB_ERR_MEMORY if *target_string is NULL.
439 *********************************************************************/
440 jb_err string_append(char **target_string, const char *text_to_append)
446 assert(target_string);
447 assert(text_to_append);
449 if (*target_string == NULL)
451 return JB_ERR_MEMORY;
454 if (*text_to_append == '\0')
459 old_len = strlen(*target_string);
461 new_size = strlen(text_to_append) + old_len + 1;
463 if (NULL == (new_string = realloc(*target_string, new_size)))
465 free(*target_string);
467 *target_string = NULL;
468 return JB_ERR_MEMORY;
471 strlcpy(new_string + old_len, text_to_append, new_size - old_len);
473 *target_string = new_string;
478 /*********************************************************************
480 * Function : string_join
482 * Description : Join two strings together. Frees BOTH the original
483 * strings. If either or both input strings are NULL,
484 * fails as if it had run out of memory.
486 * For comparison, string_append requires that the
487 * second string is non-NULL, and doesn't free it.
489 * Rationale: Too often, we want to do
490 * string_append(s, html_encode(s2)). That assert()s
491 * if s2 is NULL or if html_encode() runs out of memory.
492 * It also leaks memory. Proper checking is cumbersome.
493 * The solution: string_join(s, html_encode(s2)) is safe,
494 * and will free the memory allocated by html_encode().
497 * 1 : target_string = Pointer to old text that is to be
498 * extended. *target_string will be free()d by this
499 * routine. target_string must be non-NULL.
500 * 2 : text_to_append = Text to be appended to old.
502 * Returns : JB_ERR_OK on success, and sets *target_string
503 * to newly malloc'ed appended string. Caller
504 * must free(*target_string).
505 * JB_ERR_MEMORY on out-of-memory, or if
506 * *target_string or text_to_append is NULL. (In
507 * this case, frees *target_string and text_to_append,
508 * sets *target_string to NULL).
510 *********************************************************************/
511 jb_err string_join(char **target_string, char *text_to_append)
515 assert(target_string);
517 if (text_to_append == NULL)
519 freez(*target_string);
520 return JB_ERR_MEMORY;
523 err = string_append(target_string, text_to_append);
525 freez(text_to_append);
531 /*********************************************************************
533 * Function : string_toupper
535 * Description : Produce a copy of string with all convertible
536 * characters converted to uppercase.
539 * 1 : string = string to convert
541 * Returns : Uppercase copy of string if possible,
542 * NULL on out-of-memory or if string was NULL.
544 *********************************************************************/
545 char *string_toupper(const char *string)
550 if (!string || ((result = (char *) zalloc(strlen(string) + 1)) == NULL))
560 *p++ = (char)toupper((int) *q++);
568 /*********************************************************************
570 * Function : string_move
572 * Description : memmove wrapper to move the last part of a string
573 * towards the beginning, overwriting the part in
574 * the middle. strlcpy() can't be used here as the
578 * 1 : dst = Destination to overwrite
579 * 2 : src = Source to move.
583 *********************************************************************/
584 void string_move(char *dst, char *src)
588 /* +1 to copy the terminating nul as well. */
589 memmove(dst, src, strlen(src)+1);
593 /*********************************************************************
597 * Description : Duplicate the first n characters of a string that may
598 * contain '\0' characters.
601 * 1 : string = string to be duplicated
602 * 2 : len = number of bytes to duplicate
604 * Returns : pointer to copy, or NULL if failiure
606 *********************************************************************/
607 char *bindup(const char *string, size_t len)
611 duplicate = (char *)malloc(len);
612 if (NULL != duplicate)
614 memcpy(duplicate, string, len);
622 /*********************************************************************
624 * Function : make_path
626 * Description : Takes a directory name and a file name, returns
627 * the complete path. Handles windows/unix differences.
628 * If the file name is already an absolute path, or if
629 * the directory name is NULL or empty, it returns
633 * 1 : dir: Name of directory or NULL for none.
634 * 2 : file: Name of file. Should not be NULL or empty.
636 * Returns : "dir/file" (Or on windows, "dir\file").
637 * It allocates the string on the heap. Caller frees.
638 * Returns NULL in error (i.e. NULL file or out of
641 *********************************************************************/
642 char * make_path(const char * dir, const char * file)
644 if ((file == NULL) || (*file == '\0'))
646 return NULL; /* Error */
649 if ((dir == NULL) || (*dir == '\0') /* No directory specified */
650 #if defined(_WIN32) || defined(__OS2__)
651 || (*file == '\\') || (file[1] == ':') /* Absolute path (DOS) */
652 #else /* ifndef _WIN32 || __OS2__ */
653 || (*file == '/') /* Absolute path (U*ix) */
654 #endif /* ifndef _WIN32 || __OS2__ */
662 size_t path_size = strlen(dir) + strlen(file) + 2; /* +2 for trailing (back)slash and \0 */
665 if (*dir != '/' && basedir && *basedir)
668 * Relative path, so start with the base directory.
670 path_size += strlen(basedir) + 1; /* +1 for the slash */
671 path = malloc(path_size);
672 if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
673 strlcpy(path, basedir, path_size);
674 strlcat(path, "/", path_size);
675 strlcat(path, dir, path_size);
678 #endif /* defined unix */
680 path = malloc(path_size);
681 if (!path) log_error(LOG_LEVEL_FATAL, "malloc failed!");
682 strlcpy(path, dir, path_size);
685 assert(NULL != path);
686 #if defined(_WIN32) || defined(__OS2__)
687 if (path[strlen(path)-1] != '\\')
689 strlcat(path, "\\", path_size);
691 #else /* ifndef _WIN32 || __OS2__ */
692 if (path[strlen(path)-1] != '/')
694 strlcat(path, "/", path_size);
696 #endif /* ifndef _WIN32 || __OS2__ */
697 strlcat(path, file, path_size);
704 /*********************************************************************
706 * Function : pick_from_range
708 * Description : Pick a positive number out of a given range.
709 * Should only be used if randomness would be nice,
710 * but isn't really necessary.
713 * 1 : range: Highest possible number to pick.
715 * Returns : Picked number.
717 *********************************************************************/
718 long int pick_from_range(long int range)
722 static unsigned long seed = 0;
723 #endif /* def _WIN32 */
728 if (range <= 0) return 0;
730 #ifdef HAVE_ARC4RANDOM
731 number = arc4random() % range + 1;
732 #elif defined(HAVE_RANDOM)
733 number = random() % range + 1;
734 #elif defined(MUTEX_LOCKS_AVAILABLE)
735 privoxy_mutex_lock(&rand_mutex);
739 seed = (unsigned long)(GetCurrentThreadId()+GetTickCount());
742 seed = (unsigned long)((rand() << 16) + rand());
743 #endif /* def _WIN32 */
744 number = (unsigned long)((rand() << 16) + (rand())) % (unsigned long)(range + 1);
745 privoxy_mutex_unlock(&rand_mutex);
748 * XXX: Which platforms reach this and are there
749 * better options than just using rand() and hoping
752 log_error(LOG_LEVEL_INFO, "No thread-safe PRNG available? Header time randomization "
753 "might cause crashes, predictable results or even combine these fine options.");
754 number = rand() % (long int)(range + 1);
756 #endif /* (def HAVE_ARC4RANDOM) */
762 #ifdef USE_PRIVOXY_STRLCPY
763 /*********************************************************************
765 * Function : privoxy_strlcpy
767 * Description : strlcpy(3) look-alike for those without decent libc.
770 * 1 : destination: buffer to copy into.
771 * 2 : source: String to copy.
772 * 3 : size: Size of destination buffer.
774 * Returns : The length of the string that privoxy_strlcpy() tried to create.
776 *********************************************************************/
777 size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
781 snprintf(destination, size, "%s", source);
783 * Platforms that lack strlcpy() also tend to have
784 * a broken snprintf implementation that doesn't
785 * guarantee nul termination.
787 * XXX: the configure script should detect and reject those.
789 destination[size-1] = '\0';
791 return strlen(source);
793 #endif /* def USE_PRIVOXY_STRLCPY */
797 /*********************************************************************
799 * Function : privoxy_strlcat
801 * Description : strlcat(3) look-alike for those without decent libc.
804 * 1 : destination: C string.
805 * 2 : source: String to copy.
806 * 3 : size: Size of destination buffer.
808 * Returns : The length of the string that privoxy_strlcat() tried to create.
810 *********************************************************************/
811 size_t privoxy_strlcat(char *destination, const char *source, const size_t size)
813 const size_t old_length = strlen(destination);
814 return old_length + strlcpy(destination + old_length, source, size - old_length);
816 #endif /* ndef HAVE_STRLCAT */
819 /*********************************************************************
821 * Function : privoxy_millisleep
823 * Description : Sleep a number of milliseconds
826 * 1 : delay: Number of milliseconds to sleep
828 * Returns : -1 on error, 0 otherwise
830 *********************************************************************/
831 int privoxy_millisleep(unsigned milliseconds)
833 #ifdef HAVE_NANOSLEEP
834 struct timespec rqtp = {0};
835 struct timespec rmtp = {0};
837 rqtp.tv_sec = milliseconds / 1000;
838 rqtp.tv_nsec = (milliseconds % 1000) * 1000 * 1000;
840 return nanosleep(&rqtp, &rmtp);
841 #elif defined (_WIN32)
845 #elif defined(__OS2__)
846 DosSleep(milliseconds * 10);
850 #warning Missing privoxy_milisleep() implementation. delay-response{} will not work.
853 #endif /* def HAVE_NANOSLEEP */
858 /*********************************************************************
860 * Function : privoxy_gmtime_r
862 * Description : Behave like gmtime_r() and convert a
863 * time_t to a struct tm.
866 * 1 : time_spec: The time to convert
867 * 2 : result: The struct tm to use as storage
869 * Returns : Pointer to the result or NULL on error.
871 *********************************************************************/
872 struct tm *privoxy_gmtime_r(const time_t *time_spec, struct tm *result)
877 timeptr = gmtime_r(time_spec, result);
878 #elif defined(MUTEX_LOCKS_AVAILABLE)
879 privoxy_mutex_lock(&gmtime_mutex);
880 timeptr = gmtime(time_spec);
882 #warning Using unlocked gmtime()
883 timeptr = gmtime(time_spec);
888 #if !defined(HAVE_GMTIME_R) && defined(MUTEX_LOCKS_AVAILABLE)
889 privoxy_mutex_unlock(&gmtime_mutex);
894 #if !defined(HAVE_GMTIME_R)
897 #ifdef MUTEX_LOCKS_AVAILABLE
898 privoxy_mutex_unlock(&gmtime_mutex);
905 #if !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV)
906 /*********************************************************************
910 * Description : libc replacement function for the inverse of gmtime().
911 * Copyright (C) 2004 Free Software Foundation, Inc.
913 * Code originally copied from GnuPG, modifications done
914 * for Privoxy: style changed, #ifdefs for _WIN32 added
915 * to have it work on mingw32.
917 * XXX: It's very unlikely to happen, but if the malloc()
918 * call fails the time zone will be permanently set to UTC.
921 * 1 : tm: Broken-down time struct.
923 * Returns : tm converted into time_t seconds.
925 *********************************************************************/
926 time_t timegm(struct tm *tm)
939 old_zone = malloc(3 + strlen(zone) + 1);
942 strcpy(old_zone, "TZ=");
943 strcat(old_zone, zone);
946 /* http://man7.org/linux/man-pages/man3/putenv.3.html
947 * int putenv(char *string);
948 * The string pointed to by string becomes part of the environment, so altering the
949 * string changes the environment.
950 * In other words, the memory pointed to by *string is used until
951 * a) another call to putenv() with the same e-var name
952 * b) the program exits
954 * Windows e-vars don't work that way, so let's not leak memory.
957 #endif /* def _WIN32 */
964 #elif defined(_WIN32)
974 #endif /* !defined(HAVE_TIMEGM) && defined(HAVE_TZSET) && defined(HAVE_PUTENV) */
977 #ifndef HAVE_SNPRINTF
979 * What follows is a portable snprintf routine, written by Mark Martinec.
980 * See: http://www.ijs.si/software/snprintf/
983 - a portable implementation of snprintf,
984 including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf
986 snprintf is a routine to convert numeric and string arguments to
987 formatted strings. It is similar to sprintf(3) provided in a system's
988 C library, yet it requires an additional argument - the buffer size -
989 and it guarantees never to store anything beyond the given buffer,
990 regardless of the format or arguments to be formatted. Some newer
991 operating systems do provide snprintf in their C library, but many do
992 not or do provide an inadequate (slow or idiosyncratic) version, which
993 calls for a portable implementation of this routine.
997 Mark Martinec <mark.martinec@ijs.si>, April 1999, June 2000
998 Copyright © 1999, Mark Martinec
1002 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
1003 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
1005 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
1006 # if defined(NEED_SNPRINTF_ONLY)
1007 # undef NEED_SNPRINTF_ONLY
1009 # if !defined(PREFER_PORTABLE_SNPRINTF)
1010 # define PREFER_PORTABLE_SNPRINTF
1014 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
1015 #define SOLARIS_COMPATIBLE
1018 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1019 #define HPUX_COMPATIBLE
1022 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
1023 #define DIGITAL_UNIX_COMPATIBLE
1026 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
1027 #define PERL_COMPATIBLE
1030 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
1031 #define LINUX_COMPATIBLE
1034 #include <sys/types.h>
1045 #define isdigit(c) ((c) >= '0' && (c) <= '9')
1047 /* For copying strings longer or equal to 'breakeven_point'
1048 * it is more efficient to call memcpy() than to do it inline.
1049 * The value depends mostly on the processor architecture,
1050 * but also on the compiler and its optimization capabilities.
1051 * The value is not critical, some small value greater than zero
1052 * will be just fine if you don't care to squeeze every drop
1053 * of performance out of the code.
1055 * Small values favor memcpy, large values favor inline code.
1057 #if defined(__alpha__) || defined(__alpha)
1058 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
1060 #if defined(__i386__) || defined(__i386)
1061 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
1064 # define breakeven_point 10 /* HP-PA - gcc */
1066 #if defined(__sparc__) || defined(__sparc)
1067 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
1070 /* some other values of possible interest: */
1071 /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */
1072 /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */
1074 #ifndef breakeven_point
1075 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
1078 #define fast_memcpy(d,s,n) \
1079 { register size_t nn = (size_t)(n); \
1080 if (nn >= breakeven_point) memcpy((d), (s), nn); \
1081 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1082 register char *dd; register const char *ss; \
1083 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
1085 #define fast_memset(d,c,n) \
1086 { register size_t nn = (size_t)(n); \
1087 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
1088 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
1089 register char *dd; register const int cc=(int)(c); \
1090 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
1094 #if defined(NEED_ASPRINTF)
1095 int asprintf (char **ptr, const char *fmt, /*args*/ ...);
1097 #if defined(NEED_VASPRINTF)
1098 int vasprintf (char **ptr, const char *fmt, va_list ap);
1100 #if defined(NEED_ASNPRINTF)
1101 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
1103 #if defined(NEED_VASNPRINTF)
1104 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
1107 #if defined(HAVE_SNPRINTF)
1108 /* declare our portable snprintf routine under name portable_snprintf */
1109 /* declare our portable vsnprintf routine under name portable_vsnprintf */
1111 /* declare our portable routines under names snprintf and vsnprintf */
1112 #define portable_snprintf snprintf
1113 #if !defined(NEED_SNPRINTF_ONLY)
1114 #define portable_vsnprintf vsnprintf
1118 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1119 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
1120 #if !defined(NEED_SNPRINTF_ONLY)
1121 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
1127 static char credits[] = "\n\
1128 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
1129 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
1130 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
1132 #if defined(NEED_ASPRINTF)
1133 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
1139 va_start(ap, fmt); /* measure the required size */
1140 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1142 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1143 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1144 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1148 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1150 assert(str_l2 == str_l);
1156 #if defined(NEED_VASPRINTF)
1157 int vasprintf(char **ptr, const char *fmt, va_list ap) {
1163 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1164 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1167 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1168 *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
1169 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1171 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1172 assert(str_l2 == str_l);
1178 #if defined(NEED_ASNPRINTF)
1179 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
1184 va_start(ap, fmt); /* measure the required size */
1185 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
1187 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1188 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1189 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1190 if (str_m == 0) { /* not interested in resulting string, just return size */
1192 *ptr = (char *) malloc(str_m);
1193 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1197 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1199 assert(str_l2 == str_l);
1206 #if defined(NEED_VASNPRINTF)
1207 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
1212 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
1213 str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
1216 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
1217 if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */
1218 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
1219 if (str_m == 0) { /* not interested in resulting string, just return size */
1221 *ptr = (char *) malloc(str_m);
1222 if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
1224 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
1225 assert(str_l2 == str_l);
1233 * If the system does have snprintf and the portable routine is not
1234 * specifically required, this module produces no code for snprintf/vsnprintf.
1236 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
1238 #if !defined(NEED_SNPRINTF_ONLY)
1239 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1244 str_l = portable_vsnprintf(str, str_m, fmt, ap);
1250 #if defined(NEED_SNPRINTF_ONLY)
1251 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
1253 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
1256 #if defined(NEED_SNPRINTF_ONLY)
1260 const char *p = fmt;
1262 /* In contrast with POSIX, the ISO C99 now says
1263 * that str can be NULL and str_m can be 0.
1264 * This is more useful than the old: if (str_m < 1) return -1; */
1266 #if defined(NEED_SNPRINTF_ONLY)
1272 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
1273 /* but the following code achieves better performance for cases
1274 * where format string is long and contains few conversions */
1275 const char *q = strchr(p+1,'%');
1276 size_t n = !q ? strlen(p) : (q-p);
1277 if (str_l < str_m) {
1278 size_t avail = str_m-str_l;
1279 fast_memcpy(str+str_l, p, (n>avail?avail:n));
1283 const char *starting_p;
1284 size_t min_field_width = 0, precision = 0;
1285 int zero_padding = 0, precision_specified = 0, justify_left = 0;
1286 int alternate_form = 0, force_sign = 0;
1287 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
1288 the ' ' flag should be ignored. */
1289 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
1290 char tmp[32];/* temporary buffer for simple numeric->string conversion */
1292 const char *str_arg; /* string address in case of string argument */
1293 size_t str_arg_l; /* natural field width of arg without padding
1295 unsigned char uchar_arg;
1296 /* unsigned char argument value - only defined for c conversion.
1297 N.B. standard explicitly states the char argument for
1298 the c conversion is unsigned */
1300 size_t number_of_zeros_to_pad = 0;
1301 /* number of zeros to be inserted for numeric conversions
1302 as required by the precision or minimal field width */
1304 size_t zero_padding_insertion_ind = 0;
1305 /* index into tmp where zero padding is to be inserted */
1307 char fmt_spec = '\0';
1308 /* current conversion specifier character */
1310 str_arg = credits;/* just to make compiler happy (defined but not used)*/
1312 starting_p = p; p++; /* skip '%' */
1314 while (*p == '0' || *p == '-' || *p == '+' ||
1315 *p == ' ' || *p == '#' || *p == '\'') {
1317 case '0': zero_padding = 1; break;
1318 case '-': justify_left = 1; break;
1319 case '+': force_sign = 1; space_for_positive = 0; break;
1320 case ' ': force_sign = 1;
1321 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
1322 #ifdef PERL_COMPATIBLE
1323 /* ... but in Perl the last of ' ' and '+' applies */
1324 space_for_positive = 1;
1327 case '#': alternate_form = 1; break;
1332 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
1334 /* parse field width */
1337 p++; j = va_arg(ap, int);
1338 if (j >= 0) min_field_width = j;
1339 else { min_field_width = -j; justify_left = 1; }
1340 } else if (isdigit((int)(*p))) {
1341 /* size_t could be wider than unsigned int;
1342 make sure we treat argument like common implementations do */
1343 unsigned int uj = *p++ - '0';
1344 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1345 min_field_width = uj;
1347 /* parse precision */
1349 p++; precision_specified = 1;
1351 int j = va_arg(ap, int);
1353 if (j >= 0) precision = j;
1355 precision_specified = 0; precision = 0;
1357 * Solaris 2.6 man page claims that in this case the precision
1358 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
1359 * claim that this case should be treated as unspecified precision,
1360 * which is what we do here.
1363 } else if (isdigit((int)(*p))) {
1364 /* size_t could be wider than unsigned int;
1365 make sure we treat argument like common implementations do */
1366 unsigned int uj = *p++ - '0';
1367 while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
1371 /* parse 'h', 'l' and 'll' length modifiers */
1372 if (*p == 'h' || *p == 'l') {
1373 length_modifier = *p; p++;
1374 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
1375 #ifdef SNPRINTF_LONGLONG_SUPPORT
1376 length_modifier = '2'; /* double l encoded as '2' */
1378 length_modifier = 'l'; /* treat it as a single 'l' */
1384 /* common synonyms: */
1386 case 'i': fmt_spec = 'd'; break;
1387 case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
1388 case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
1389 case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
1392 /* get parameter value, do initial processing */
1394 case '%': /* % behaves similar to 's' regarding flags and field widths */
1395 case 'c': /* c behaves similar to 's' regarding flags and field widths */
1397 length_modifier = '\0'; /* wint_t and wchar_t not supported */
1398 /* the result of zero padding flag with non-numeric conversion specifier*/
1399 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
1400 /* Digital Unix and Linux does not. */
1401 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
1402 zero_padding = 0; /* turn zero padding off for string conversions */
1409 int j = va_arg(ap, int);
1410 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
1411 str_arg = (const char *) &uchar_arg;
1415 str_arg = va_arg(ap, const char *);
1416 if (!str_arg) str_arg_l = 0;
1417 /* make sure not to address string beyond the specified precision !!! */
1418 else if (!precision_specified) str_arg_l = strlen(str_arg);
1419 /* truncate string if necessary as requested by precision */
1420 else if (precision == 0) str_arg_l = 0;
1422 /* memchr on HP does not like n > 2^31 !!! */
1423 const char *q = memchr(str_arg, '\0',
1424 precision <= 0x7fffffff ? precision : 0x7fffffff);
1425 str_arg_l = !q ? precision : (q-str_arg);
1431 case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
1432 /* NOTE: the u, o, x, X and p conversion specifiers imply
1433 the value is unsigned; d implies a signed value */
1436 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
1437 +1 if greater than zero (or nonzero for unsigned arguments),
1438 -1 if negative (unsigned argument is never negative) */
1440 int int_arg = 0; unsigned int uint_arg = 0;
1441 /* only defined for length modifier h, or for no length modifiers */
1443 long int long_arg = 0; unsigned long int ulong_arg = 0;
1444 /* only defined for length modifier l */
1446 void *ptr_arg = NULL;
1447 /* pointer argument value -only defined for p conversion */
1449 #ifdef SNPRINTF_LONGLONG_SUPPORT
1450 long long int long_long_arg = 0;
1451 unsigned long long int ulong_long_arg = 0;
1452 /* only defined for length modifier ll */
1454 if (fmt_spec == 'p') {
1455 /* HPUX 10: An l, h, ll or L before any other conversion character
1456 * (other than d, i, u, o, x, or X) is ignored.
1458 * not specified, but seems to behave as HPUX does.
1459 * Solaris: If an h, l, or L appears before any other conversion
1460 * specifier (other than d, i, u, o, x, or X), the behavior
1461 * is undefined. (Actually %hp converts only 16-bits of address
1462 * and %llp treats address as 64-bit data which is incompatible
1463 * with (void *) argument on a 32-bit system).
1465 #ifdef SOLARIS_COMPATIBLE
1466 # ifdef SOLARIS_BUG_COMPATIBLE
1467 /* keep length modifiers even if it represents 'll' */
1469 if (length_modifier == '2') length_modifier = '\0';
1472 length_modifier = '\0';
1474 ptr_arg = va_arg(ap, void *);
1475 if (ptr_arg != NULL) arg_sign = 1;
1476 } else if (fmt_spec == 'd') { /* signed */
1477 switch (length_modifier) {
1480 /* It is non-portable to specify a second argument of char or short
1481 * to va_arg, because arguments seen by the called function
1482 * are not char or short. C converts char and short arguments
1483 * to int before passing them to a function.
1485 int_arg = va_arg(ap, int);
1486 if (int_arg > 0) arg_sign = 1;
1487 else if (int_arg < 0) arg_sign = -1;
1490 long_arg = va_arg(ap, long int);
1491 if (long_arg > 0) arg_sign = 1;
1492 else if (long_arg < 0) arg_sign = -1;
1494 #ifdef SNPRINTF_LONGLONG_SUPPORT
1496 long_long_arg = va_arg(ap, long long int);
1497 if (long_long_arg > 0) arg_sign = 1;
1498 else if (long_long_arg < 0) arg_sign = -1;
1502 } else { /* unsigned */
1503 switch (length_modifier) {
1506 uint_arg = va_arg(ap, unsigned int);
1507 if (uint_arg) arg_sign = 1;
1510 ulong_arg = va_arg(ap, unsigned long int);
1511 if (ulong_arg) arg_sign = 1;
1513 #ifdef SNPRINTF_LONGLONG_SUPPORT
1515 ulong_long_arg = va_arg(ap, unsigned long long int);
1516 if (ulong_long_arg) arg_sign = 1;
1521 str_arg = tmp; str_arg_l = 0;
1523 * For d, i, u, o, x, and X conversions, if precision is specified,
1524 * the '0' flag should be ignored. This is so with Solaris 2.6,
1525 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
1527 #ifndef PERL_COMPATIBLE
1528 if (precision_specified) zero_padding = 0;
1530 if (fmt_spec == 'd') {
1531 if (force_sign && arg_sign >= 0)
1532 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1533 /* leave negative numbers for sprintf to handle,
1534 to avoid handling tricky cases like (short int)(-32768) */
1535 #ifdef LINUX_COMPATIBLE
1536 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
1537 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
1539 } else if (alternate_form) {
1540 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
1541 { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
1542 /* alternate form should have no effect for p conversion, but ... */
1543 #ifdef HPUX_COMPATIBLE
1544 else if (fmt_spec == 'p'
1545 /* HPUX 10: for an alternate form of p conversion,
1546 * a nonzero result is prefixed by 0x. */
1547 #ifndef HPUX_BUG_COMPATIBLE
1548 /* Actually it uses 0x prefix even for a zero value. */
1551 ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
1554 zero_padding_insertion_ind = str_arg_l;
1555 if (!precision_specified) precision = 1; /* default precision is 1 */
1556 if (precision == 0 && arg_sign == 0
1557 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1559 /* HPUX 10 man page claims: With conversion character p the result of
1560 * converting a zero value with a precision of zero is a null string.
1561 * Actually HP returns all zeroes, and Linux returns "(nil)". */
1564 /* converted to null string */
1565 /* When zero value is formatted with an explicit precision 0,
1566 the resulting formatted string is empty (d, i, u, o, x, X, p). */
1568 char f[5]; int f_l = 0;
1569 f[f_l++] = '%'; /* construct a simple format string for sprintf */
1570 if (!length_modifier) { }
1571 else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
1572 else f[f_l++] = length_modifier;
1573 f[f_l++] = fmt_spec; f[f_l++] = '\0';
1574 if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
1575 else if (fmt_spec == 'd') { /* signed */
1576 switch (length_modifier) {
1578 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break;
1579 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
1580 #ifdef SNPRINTF_LONGLONG_SUPPORT
1581 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
1584 } else { /* unsigned */
1585 switch (length_modifier) {
1587 case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break;
1588 case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
1589 #ifdef SNPRINTF_LONGLONG_SUPPORT
1590 case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
1594 /* include the optional minus sign and possible "0x"
1595 in the region before the zero padding insertion point */
1596 if (zero_padding_insertion_ind < str_arg_l &&
1597 tmp[zero_padding_insertion_ind] == '-') {
1598 zero_padding_insertion_ind++;
1600 if (zero_padding_insertion_ind+1 < str_arg_l &&
1601 tmp[zero_padding_insertion_ind] == '0' &&
1602 (tmp[zero_padding_insertion_ind+1] == 'x' ||
1603 tmp[zero_padding_insertion_ind+1] == 'X') ) {
1604 zero_padding_insertion_ind += 2;
1607 { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1608 if (alternate_form && fmt_spec == 'o'
1609 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1612 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1614 /* unless zero is already the first character */
1615 && !(zero_padding_insertion_ind < str_arg_l
1616 && tmp[zero_padding_insertion_ind] == '0')
1618 ) { /* assure leading zero for alternate-form octal numbers */
1619 if (!precision_specified || precision < num_of_digits+1) {
1620 /* precision is increased to force the first character to be zero,
1621 except if a zero value is formatted with an explicit precision
1623 precision = num_of_digits+1; precision_specified = 1;
1626 /* zero padding to specified precision? */
1627 if (num_of_digits < precision)
1628 number_of_zeros_to_pad = precision - num_of_digits;
1630 /* zero padding to specified minimal field width? */
1631 if (!justify_left && zero_padding) {
1632 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1633 if (n > 0) number_of_zeros_to_pad += n;
1637 default: /* unrecognized conversion specifier, keep format string as-is*/
1638 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1639 #ifndef DIGITAL_UNIX_COMPATIBLE
1640 justify_left = 1; min_field_width = 0; /* reset flags */
1642 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1643 /* keep the entire format string unchanged */
1644 str_arg = starting_p; str_arg_l = p - starting_p;
1645 /* well, not exactly so for Linux, which does something between,
1646 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1648 /* discard the unrecognized conversion, just keep *
1649 * the unrecognized conversion character */
1650 str_arg = p; str_arg_l = 0;
1652 if (*p) str_arg_l++; /* include invalid conversion specifier unchanged
1653 if not at end-of-string */
1656 if (*p) p++; /* step over the just processed conversion specifier */
1657 /* insert padding to the left as requested by min_field_width;
1658 this does not include the zero padding in case of numerical conversions*/
1659 if (!justify_left) { /* left padding with blank or zero */
1660 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1662 if (str_l < str_m) {
1663 size_t avail = str_m-str_l;
1664 fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
1669 /* zero padding as requested by the precision or by the minimal field width
1670 * for numeric conversions required? */
1671 if (number_of_zeros_to_pad <= 0) {
1672 /* will not copy first part of numeric right now, *
1673 * force it to be copied later in its entirety */
1674 zero_padding_insertion_ind = 0;
1676 /* insert first part of numerics (sign or '0x') before zero padding */
1677 int n = zero_padding_insertion_ind;
1679 if (str_l < str_m) {
1680 size_t avail = str_m-str_l;
1681 fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
1685 /* insert zero padding as requested by the precision or min field width */
1686 n = number_of_zeros_to_pad;
1688 if (str_l < str_m) {
1689 size_t avail = str_m-str_l;
1690 fast_memset(str+str_l, '0', (n>avail?avail:n));
1695 /* insert formatted string
1696 * (or as-is conversion specifier for unknown conversions) */
1697 { int n = str_arg_l - zero_padding_insertion_ind;
1699 if (str_l < str_m) {
1700 size_t avail = str_m-str_l;
1701 fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
1707 /* insert right padding */
1708 if (justify_left) { /* right blank padding to the field width */
1709 int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1711 if (str_l < str_m) {
1712 size_t avail = str_m-str_l;
1713 fast_memset(str+str_l, ' ', (n>avail?avail:n));
1720 #if defined(NEED_SNPRINTF_ONLY)
1723 if (str_m > 0) { /* make sure the string is null-terminated
1724 even at the expense of overwriting the last character
1725 (shouldn't happen, but just in case) */
1726 str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1728 /* Return the number of characters formatted (excluding trailing null
1729 * character), that is, the number of characters that would have been
1730 * written to the buffer if it were large enough.
1732 * The value of str_l should be returned, but str_l is of unsigned type
1733 * size_t, and snprintf is int, possibly leading to an undetected
1734 * integer overflow, resulting in a negative return value, which is illegal.
1735 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1736 * Should errno be set to EOVERFLOW and EOF returned in this case???
1741 #endif /* ndef HAVE_SNPRINTF */